id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,900
|
mdasberg/ng-apimock
|
templates/protractor.mock.js
|
echoRequest
|
function echoRequest(data, echo) {
return _execute('PUT', '/mocks', {
identifier: _getIdentifier(data),
echo: echo || false
}, 'Could not echo the request');
}
|
javascript
|
function echoRequest(data, echo) {
return _execute('PUT', '/mocks', {
identifier: _getIdentifier(data),
echo: echo || false
}, 'Could not echo the request');
}
|
[
"function",
"echoRequest",
"(",
"data",
",",
"echo",
")",
"{",
"return",
"_execute",
"(",
"'PUT'",
",",
"'/mocks'",
",",
"{",
"identifier",
":",
"_getIdentifier",
"(",
"data",
")",
",",
"echo",
":",
"echo",
"||",
"false",
"}",
",",
"'Could not echo the request'",
")",
";",
"}"
] |
Sets the given echo indicator for the mock matching the identifier.
@param {Object | String} data The data object containing all the information for an expression or the name of the mock.
@param {boolean} echo The indicator echo request.
@return {Promise} the promise.
|
[
"Sets",
"the",
"given",
"echo",
"indicator",
"for",
"the",
"mock",
"matching",
"the",
"identifier",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/protractor.mock.js#L109-L114
|
14,901
|
mdasberg/ng-apimock
|
templates/protractor.mock.js
|
_execute
|
function _execute(httpMethod, urlSuffix, options, errorMessage) {
const opts = {
headers: {
'Content-Type': 'application/json',
'ngapimockid': ngapimockid
}
};
if (options !== undefined) {
opts.json = options;
}
return _handleRequest(httpMethod, urlSuffix, opts, errorMessage);
}
|
javascript
|
function _execute(httpMethod, urlSuffix, options, errorMessage) {
const opts = {
headers: {
'Content-Type': 'application/json',
'ngapimockid': ngapimockid
}
};
if (options !== undefined) {
opts.json = options;
}
return _handleRequest(httpMethod, urlSuffix, opts, errorMessage);
}
|
[
"function",
"_execute",
"(",
"httpMethod",
",",
"urlSuffix",
",",
"options",
",",
"errorMessage",
")",
"{",
"const",
"opts",
"=",
"{",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'ngapimockid'",
":",
"ngapimockid",
"}",
"}",
";",
"if",
"(",
"options",
"!==",
"undefined",
")",
"{",
"opts",
".",
"json",
"=",
"options",
";",
"}",
"return",
"_handleRequest",
"(",
"httpMethod",
",",
"urlSuffix",
",",
"opts",
",",
"errorMessage",
")",
";",
"}"
] |
Executes the api call with the provided information.
@param httpMethod The http method.
@param urlSuffix The url suffix.
@param options The options object.
@param errorMessage The error message.
@return {Promise} The promise.
@private
|
[
"Executes",
"the",
"api",
"call",
"with",
"the",
"provided",
"information",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/protractor.mock.js#L176-L189
|
14,902
|
mdasberg/ng-apimock
|
templates/protractor.mock.js
|
_getIdentifier
|
function _getIdentifier(data) {
let identifier;
if (typeof data === 'string') { // name of the mock
identifier = data;
} else if (data.name) { // the data containing the name of the mock
identifier = data.name;
} else {
identifier = data.expression + '$$' + data.method;
}
return identifier;
}
|
javascript
|
function _getIdentifier(data) {
let identifier;
if (typeof data === 'string') { // name of the mock
identifier = data;
} else if (data.name) { // the data containing the name of the mock
identifier = data.name;
} else {
identifier = data.expression + '$$' + data.method;
}
return identifier;
}
|
[
"function",
"_getIdentifier",
"(",
"data",
")",
"{",
"let",
"identifier",
";",
"if",
"(",
"typeof",
"data",
"===",
"'string'",
")",
"{",
"// name of the mock",
"identifier",
"=",
"data",
";",
"}",
"else",
"if",
"(",
"data",
".",
"name",
")",
"{",
"// the data containing the name of the mock",
"identifier",
"=",
"data",
".",
"name",
";",
"}",
"else",
"{",
"identifier",
"=",
"data",
".",
"expression",
"+",
"'$$'",
"+",
"data",
".",
"method",
";",
"}",
"return",
"identifier",
";",
"}"
] |
Gets the identifier from the provided data object.
@param data The data object.
@return {string} identifier The identifier.
@private
|
[
"Gets",
"the",
"identifier",
"from",
"the",
"provided",
"data",
"object",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/protractor.mock.js#L240-L250
|
14,903
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
fetchMocks
|
function fetchMocks() {
mockService.get({}, function (response) {
vm.mocks = response.mocks.map(function(mock){
Object.keys(mock.responses).forEach(function(response) {
mock.responses[response].name = response;
});
return mock;
});
vm.selections = response.selections;
vm.delays = response.delays;
vm.echos = response.echos;
vm.recordings = response.recordings;
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
}
});
}
|
javascript
|
function fetchMocks() {
mockService.get({}, function (response) {
vm.mocks = response.mocks.map(function(mock){
Object.keys(mock.responses).forEach(function(response) {
mock.responses[response].name = response;
});
return mock;
});
vm.selections = response.selections;
vm.delays = response.delays;
vm.echos = response.echos;
vm.recordings = response.recordings;
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
}
});
}
|
[
"function",
"fetchMocks",
"(",
")",
"{",
"mockService",
".",
"get",
"(",
"{",
"}",
",",
"function",
"(",
"response",
")",
"{",
"vm",
".",
"mocks",
"=",
"response",
".",
"mocks",
".",
"map",
"(",
"function",
"(",
"mock",
")",
"{",
"Object",
".",
"keys",
"(",
"mock",
".",
"responses",
")",
".",
"forEach",
"(",
"function",
"(",
"response",
")",
"{",
"mock",
".",
"responses",
"[",
"response",
"]",
".",
"name",
"=",
"response",
";",
"}",
")",
";",
"return",
"mock",
";",
"}",
")",
";",
"vm",
".",
"selections",
"=",
"response",
".",
"selections",
";",
"vm",
".",
"delays",
"=",
"response",
".",
"delays",
";",
"vm",
".",
"echos",
"=",
"response",
".",
"echos",
";",
"vm",
".",
"recordings",
"=",
"response",
".",
"recordings",
";",
"vm",
".",
"record",
"=",
"response",
".",
"record",
";",
"if",
"(",
"vm",
".",
"record",
")",
"{",
"interval",
"=",
"$interval",
"(",
"refreshMocks",
",",
"5000",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Fetch all the mocks and make them available.
|
[
"Fetch",
"all",
"the",
"mocks",
"and",
"make",
"them",
"available",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L30-L47
|
14,904
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
refreshMocks
|
function refreshMocks() {
mockService.get({}, function (response) {
angular.merge(vm.mocks, response.mocks);
vm.selections = response.selections;
});
}
|
javascript
|
function refreshMocks() {
mockService.get({}, function (response) {
angular.merge(vm.mocks, response.mocks);
vm.selections = response.selections;
});
}
|
[
"function",
"refreshMocks",
"(",
")",
"{",
"mockService",
".",
"get",
"(",
"{",
"}",
",",
"function",
"(",
"response",
")",
"{",
"angular",
".",
"merge",
"(",
"vm",
".",
"mocks",
",",
"response",
".",
"mocks",
")",
";",
"vm",
".",
"selections",
"=",
"response",
".",
"selections",
";",
"}",
")",
";",
"}"
] |
Refresh the mocks from the connect server
|
[
"Refresh",
"the",
"mocks",
"from",
"the",
"connect",
"server"
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L59-L64
|
14,905
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
echoMock
|
function echoMock(mock, echo) {
mockService.update({'identifier': mock.identifier, 'echo': echo}, function () {
vm.echos[mock.identifier] = echo;
});
}
|
javascript
|
function echoMock(mock, echo) {
mockService.update({'identifier': mock.identifier, 'echo': echo}, function () {
vm.echos[mock.identifier] = echo;
});
}
|
[
"function",
"echoMock",
"(",
"mock",
",",
"echo",
")",
"{",
"mockService",
".",
"update",
"(",
"{",
"'identifier'",
":",
"mock",
".",
"identifier",
",",
"'echo'",
":",
"echo",
"}",
",",
"function",
"(",
")",
"{",
"vm",
".",
"echos",
"[",
"mock",
".",
"identifier",
"]",
"=",
"echo",
";",
"}",
")",
";",
"}"
] |
Update the given Echo indicator.
@param mock The mock.
@param echo The echo.
|
[
"Update",
"the",
"given",
"Echo",
"indicator",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L71-L75
|
14,906
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
delayMock
|
function delayMock(mock, delay) {
mockService.update({'identifier': mock.identifier, 'delay': delay}, function () {
vm.delays[mock.identifier] = delay;
});
}
|
javascript
|
function delayMock(mock, delay) {
mockService.update({'identifier': mock.identifier, 'delay': delay}, function () {
vm.delays[mock.identifier] = delay;
});
}
|
[
"function",
"delayMock",
"(",
"mock",
",",
"delay",
")",
"{",
"mockService",
".",
"update",
"(",
"{",
"'identifier'",
":",
"mock",
".",
"identifier",
",",
"'delay'",
":",
"delay",
"}",
",",
"function",
"(",
")",
"{",
"vm",
".",
"delays",
"[",
"mock",
".",
"identifier",
"]",
"=",
"delay",
";",
"}",
")",
";",
"}"
] |
Update the given Delay time.
@param mock The mock.
@param delay The delay.
|
[
"Update",
"the",
"given",
"Delay",
"time",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L82-L86
|
14,907
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
toggleRecording
|
function toggleRecording() {
mockService.toggleRecord({}, function (response) {
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
} else {
$interval.cancel(interval);
refreshMocks();
}
});
}
|
javascript
|
function toggleRecording() {
mockService.toggleRecord({}, function (response) {
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
} else {
$interval.cancel(interval);
refreshMocks();
}
});
}
|
[
"function",
"toggleRecording",
"(",
")",
"{",
"mockService",
".",
"toggleRecord",
"(",
"{",
"}",
",",
"function",
"(",
"response",
")",
"{",
"vm",
".",
"record",
"=",
"response",
".",
"record",
";",
"if",
"(",
"vm",
".",
"record",
")",
"{",
"interval",
"=",
"$interval",
"(",
"refreshMocks",
",",
"5000",
")",
";",
"}",
"else",
"{",
"$interval",
".",
"cancel",
"(",
"interval",
")",
";",
"refreshMocks",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Toggle the recording.
|
[
"Toggle",
"the",
"recording",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L89-L99
|
14,908
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
selectMock
|
function selectMock(mock, selection) {
mockService.update({'identifier': mock.identifier, 'scenario': selection || 'passThrough'}, function () {
vm.selections[mock.identifier] = selection;
});
}
|
javascript
|
function selectMock(mock, selection) {
mockService.update({'identifier': mock.identifier, 'scenario': selection || 'passThrough'}, function () {
vm.selections[mock.identifier] = selection;
});
}
|
[
"function",
"selectMock",
"(",
"mock",
",",
"selection",
")",
"{",
"mockService",
".",
"update",
"(",
"{",
"'identifier'",
":",
"mock",
".",
"identifier",
",",
"'scenario'",
":",
"selection",
"||",
"'passThrough'",
"}",
",",
"function",
"(",
")",
"{",
"vm",
".",
"selections",
"[",
"mock",
".",
"identifier",
"]",
"=",
"selection",
";",
"}",
")",
";",
"}"
] |
Select the given response.
@param mock The mock.
@param selection The selection.
|
[
"Select",
"the",
"given",
"response",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L106-L110
|
14,909
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
addVariable
|
function addVariable() {
variableService.addOrUpdate(vm.variable, function () {
vm.variables[vm.variable.key] = vm.variable.value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
javascript
|
function addVariable() {
variableService.addOrUpdate(vm.variable, function () {
vm.variables[vm.variable.key] = vm.variable.value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
[
"function",
"addVariable",
"(",
")",
"{",
"variableService",
".",
"addOrUpdate",
"(",
"vm",
".",
"variable",
",",
"function",
"(",
")",
"{",
"vm",
".",
"variables",
"[",
"vm",
".",
"variable",
".",
"key",
"]",
"=",
"vm",
".",
"variable",
".",
"value",
";",
"vm",
".",
"variable",
"=",
"{",
"key",
":",
"undefined",
",",
"value",
":",
"undefined",
"}",
";",
"}",
")",
";",
"}"
] |
Adds the given variable.
|
[
"Adds",
"the",
"given",
"variable",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L127-L135
|
14,910
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
updateVariable
|
function updateVariable(key, value) {
variableService.addOrUpdate({key: key, value: value}, function () {
vm.variables[key] = value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
javascript
|
function updateVariable(key, value) {
variableService.addOrUpdate({key: key, value: value}, function () {
vm.variables[key] = value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
[
"function",
"updateVariable",
"(",
"key",
",",
"value",
")",
"{",
"variableService",
".",
"addOrUpdate",
"(",
"{",
"key",
":",
"key",
",",
"value",
":",
"value",
"}",
",",
"function",
"(",
")",
"{",
"vm",
".",
"variables",
"[",
"key",
"]",
"=",
"value",
";",
"vm",
".",
"variable",
"=",
"{",
"key",
":",
"undefined",
",",
"value",
":",
"undefined",
"}",
";",
"}",
")",
";",
"}"
] |
Update the given variable.
@param key The key.
@param value The value.
|
[
"Update",
"the",
"given",
"variable",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L142-L150
|
14,911
|
mdasberg/ng-apimock
|
templates/interface/js/ngapimock.controller.js
|
searchFilter
|
function searchFilter(mock) {
if (!vm.searchUrl || !mock.expression) {
return true;
}
return vm.searchUrl.match(mock.expression);
}
|
javascript
|
function searchFilter(mock) {
if (!vm.searchUrl || !mock.expression) {
return true;
}
return vm.searchUrl.match(mock.expression);
}
|
[
"function",
"searchFilter",
"(",
"mock",
")",
"{",
"if",
"(",
"!",
"vm",
".",
"searchUrl",
"||",
"!",
"mock",
".",
"expression",
")",
"{",
"return",
"true",
";",
"}",
"return",
"vm",
".",
"searchUrl",
".",
"match",
"(",
"mock",
".",
"expression",
")",
";",
"}"
] |
Check if the expression of the mock matches the searchUrl.
@param mock A mock.
|
[
"Check",
"if",
"the",
"expression",
"of",
"the",
"mock",
"matches",
"the",
"searchUrl",
"."
] |
f547e64a6bb719d2f03e5ce18fc658f70d40bf07
|
https://github.com/mdasberg/ng-apimock/blob/f547e64a6bb719d2f03e5ce18fc658f70d40bf07/templates/interface/js/ngapimock.controller.js#L166-L172
|
14,912
|
vervallsweg/cast-web-api
|
lib/legacy/legacy-discovery.js
|
discover
|
function discover(target) {
var both = false;
if (!target) {
target = 'googlecast';
both = true;
}
return new Promise( function(resolve, reject) {
var updateCounter=0;
var discovered = [];
try {
if (getNetworkIp) {
var browser = mdns.createBrowser(mdns.tcp(target));
var exception;
browser.on('error', function(error) {
log('debug', 'discover()', 'mdns browser error: ' + error);
})
browser.on('ready', function(){
browser.discover();
});
browser.on('update', function(service){
//try {
updateCounter++;
log('debug', 'discover()', 'update received, service: ' + JSON.stringify(service));
if (target=='googlecast' && service.type[0].name==target) {
var currentDevice = {
id: getId(service.txt[0]),
name: getFriendlyName(service.txt),
address: {
host: service.addresses[0],
port: service.port
}
}
if (!duplicateDevice(discovered, currentDevice) && currentDevice.name!=null ) {
log('debug', 'discover()', 'found device: '+ JSON.stringify(currentDevice));
discovered.push(currentDevice);
updateExistingCastDeviceAddress(currentDevice);
if ( !deviceExists(currentDevice.id) ) {
log('info', 'discover()', 'added device name: '+ currentDevice.name +', address: '+ JSON.stringify(currentDevice.address), currentDevice.id);
devices.push( new CastDevice( currentDevice.id, currentDevice.address, currentDevice.name ) ); //TODO: addDevice
}
} else {
log('debug', 'discover()', 'duplicate, googlezone device or empy name: ' + JSON.stringify(currentDevice));
}
}
if (target=='googlezone' && service.type[0].name==target) {
var currentGroupMembership = {
id: getId(service.txt[0]).replace(/-/g, ''),
groups: getGroupIds(service.txt)
}
log('debug', 'discover()', 'found googlezone: ' + JSON.stringify(currentGroupMembership) );
discovered.push(currentGroupMembership);
}
// } catch (e) {
// log('error', 'discover()', 'exception while prcessing service: '+e);
// }
});
}
} catch (e) {
reject('Exception caught: ' + e);
}
setTimeout(() => {
try{
browser.stop();
} catch (e) {
//reject('Exception caught: ' + e)
}
log('debug', 'discover()', 'updateCounter: ' + updateCounter);
resolve(discovered);
}, timeoutDiscovery);
});
}
|
javascript
|
function discover(target) {
var both = false;
if (!target) {
target = 'googlecast';
both = true;
}
return new Promise( function(resolve, reject) {
var updateCounter=0;
var discovered = [];
try {
if (getNetworkIp) {
var browser = mdns.createBrowser(mdns.tcp(target));
var exception;
browser.on('error', function(error) {
log('debug', 'discover()', 'mdns browser error: ' + error);
})
browser.on('ready', function(){
browser.discover();
});
browser.on('update', function(service){
//try {
updateCounter++;
log('debug', 'discover()', 'update received, service: ' + JSON.stringify(service));
if (target=='googlecast' && service.type[0].name==target) {
var currentDevice = {
id: getId(service.txt[0]),
name: getFriendlyName(service.txt),
address: {
host: service.addresses[0],
port: service.port
}
}
if (!duplicateDevice(discovered, currentDevice) && currentDevice.name!=null ) {
log('debug', 'discover()', 'found device: '+ JSON.stringify(currentDevice));
discovered.push(currentDevice);
updateExistingCastDeviceAddress(currentDevice);
if ( !deviceExists(currentDevice.id) ) {
log('info', 'discover()', 'added device name: '+ currentDevice.name +', address: '+ JSON.stringify(currentDevice.address), currentDevice.id);
devices.push( new CastDevice( currentDevice.id, currentDevice.address, currentDevice.name ) ); //TODO: addDevice
}
} else {
log('debug', 'discover()', 'duplicate, googlezone device or empy name: ' + JSON.stringify(currentDevice));
}
}
if (target=='googlezone' && service.type[0].name==target) {
var currentGroupMembership = {
id: getId(service.txt[0]).replace(/-/g, ''),
groups: getGroupIds(service.txt)
}
log('debug', 'discover()', 'found googlezone: ' + JSON.stringify(currentGroupMembership) );
discovered.push(currentGroupMembership);
}
// } catch (e) {
// log('error', 'discover()', 'exception while prcessing service: '+e);
// }
});
}
} catch (e) {
reject('Exception caught: ' + e);
}
setTimeout(() => {
try{
browser.stop();
} catch (e) {
//reject('Exception caught: ' + e)
}
log('debug', 'discover()', 'updateCounter: ' + updateCounter);
resolve(discovered);
}, timeoutDiscovery);
});
}
|
[
"function",
"discover",
"(",
"target",
")",
"{",
"var",
"both",
"=",
"false",
";",
"if",
"(",
"!",
"target",
")",
"{",
"target",
"=",
"'googlecast'",
";",
"both",
"=",
"true",
";",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"updateCounter",
"=",
"0",
";",
"var",
"discovered",
"=",
"[",
"]",
";",
"try",
"{",
"if",
"(",
"getNetworkIp",
")",
"{",
"var",
"browser",
"=",
"mdns",
".",
"createBrowser",
"(",
"mdns",
".",
"tcp",
"(",
"target",
")",
")",
";",
"var",
"exception",
";",
"browser",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'mdns browser error: '",
"+",
"error",
")",
";",
"}",
")",
"browser",
".",
"on",
"(",
"'ready'",
",",
"function",
"(",
")",
"{",
"browser",
".",
"discover",
"(",
")",
";",
"}",
")",
";",
"browser",
".",
"on",
"(",
"'update'",
",",
"function",
"(",
"service",
")",
"{",
"//try {",
"updateCounter",
"++",
";",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'update received, service: '",
"+",
"JSON",
".",
"stringify",
"(",
"service",
")",
")",
";",
"if",
"(",
"target",
"==",
"'googlecast'",
"&&",
"service",
".",
"type",
"[",
"0",
"]",
".",
"name",
"==",
"target",
")",
"{",
"var",
"currentDevice",
"=",
"{",
"id",
":",
"getId",
"(",
"service",
".",
"txt",
"[",
"0",
"]",
")",
",",
"name",
":",
"getFriendlyName",
"(",
"service",
".",
"txt",
")",
",",
"address",
":",
"{",
"host",
":",
"service",
".",
"addresses",
"[",
"0",
"]",
",",
"port",
":",
"service",
".",
"port",
"}",
"}",
"if",
"(",
"!",
"duplicateDevice",
"(",
"discovered",
",",
"currentDevice",
")",
"&&",
"currentDevice",
".",
"name",
"!=",
"null",
")",
"{",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'found device: '",
"+",
"JSON",
".",
"stringify",
"(",
"currentDevice",
")",
")",
";",
"discovered",
".",
"push",
"(",
"currentDevice",
")",
";",
"updateExistingCastDeviceAddress",
"(",
"currentDevice",
")",
";",
"if",
"(",
"!",
"deviceExists",
"(",
"currentDevice",
".",
"id",
")",
")",
"{",
"log",
"(",
"'info'",
",",
"'discover()'",
",",
"'added device name: '",
"+",
"currentDevice",
".",
"name",
"+",
"', address: '",
"+",
"JSON",
".",
"stringify",
"(",
"currentDevice",
".",
"address",
")",
",",
"currentDevice",
".",
"id",
")",
";",
"devices",
".",
"push",
"(",
"new",
"CastDevice",
"(",
"currentDevice",
".",
"id",
",",
"currentDevice",
".",
"address",
",",
"currentDevice",
".",
"name",
")",
")",
";",
"//TODO: addDevice",
"}",
"}",
"else",
"{",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'duplicate, googlezone device or empy name: '",
"+",
"JSON",
".",
"stringify",
"(",
"currentDevice",
")",
")",
";",
"}",
"}",
"if",
"(",
"target",
"==",
"'googlezone'",
"&&",
"service",
".",
"type",
"[",
"0",
"]",
".",
"name",
"==",
"target",
")",
"{",
"var",
"currentGroupMembership",
"=",
"{",
"id",
":",
"getId",
"(",
"service",
".",
"txt",
"[",
"0",
"]",
")",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"''",
")",
",",
"groups",
":",
"getGroupIds",
"(",
"service",
".",
"txt",
")",
"}",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'found googlezone: '",
"+",
"JSON",
".",
"stringify",
"(",
"currentGroupMembership",
")",
")",
";",
"discovered",
".",
"push",
"(",
"currentGroupMembership",
")",
";",
"}",
"// \t} catch (e) {",
"// \tlog('error', 'discover()', 'exception while prcessing service: '+e);",
"// }",
"}",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"'Exception caught: '",
"+",
"e",
")",
";",
"}",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"try",
"{",
"browser",
".",
"stop",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"//reject('Exception caught: ' + e)",
"}",
"log",
"(",
"'debug'",
",",
"'discover()'",
",",
"'updateCounter: '",
"+",
"updateCounter",
")",
";",
"resolve",
"(",
"discovered",
")",
";",
"}",
",",
"timeoutDiscovery",
")",
";",
"}",
")",
";",
"}"
] |
GOOGLE CAST FUNCTIONS 'googlecast' 'googlezone'
|
[
"GOOGLE",
"CAST",
"FUNCTIONS",
"googlecast",
"googlezone"
] |
94d253c74b93a45ed9a3582318281978ba84fafa
|
https://github.com/vervallsweg/cast-web-api/blob/94d253c74b93a45ed9a3582318281978ba84fafa/lib/legacy/legacy-discovery.js#L83-L158
|
14,913
|
Crypho/cordova-plugin-secure-storage
|
www/securestorage.js
|
function (success, error, nativeMethodName, args) {
var fail;
// args checking
_checkCallbacks(success, error);
// By convention a failure callback should always receive an instance
// of a JavaScript Error object.
fail = function(err) {
// provide default message if no details passed to callback
if (typeof err === 'undefined') {
error(new Error('Error occured while executing native method.'));
} else {
// wrap string to Error instance if necessary
error(_isString(err) ? new Error(err) : err);
}
};
cordova.exec(success, fail, 'SecureStorage', nativeMethodName, args);
}
|
javascript
|
function (success, error, nativeMethodName, args) {
var fail;
// args checking
_checkCallbacks(success, error);
// By convention a failure callback should always receive an instance
// of a JavaScript Error object.
fail = function(err) {
// provide default message if no details passed to callback
if (typeof err === 'undefined') {
error(new Error('Error occured while executing native method.'));
} else {
// wrap string to Error instance if necessary
error(_isString(err) ? new Error(err) : err);
}
};
cordova.exec(success, fail, 'SecureStorage', nativeMethodName, args);
}
|
[
"function",
"(",
"success",
",",
"error",
",",
"nativeMethodName",
",",
"args",
")",
"{",
"var",
"fail",
";",
"// args checking",
"_checkCallbacks",
"(",
"success",
",",
"error",
")",
";",
"// By convention a failure callback should always receive an instance",
"// of a JavaScript Error object.",
"fail",
"=",
"function",
"(",
"err",
")",
"{",
"// provide default message if no details passed to callback",
"if",
"(",
"typeof",
"err",
"===",
"'undefined'",
")",
"{",
"error",
"(",
"new",
"Error",
"(",
"'Error occured while executing native method.'",
")",
")",
";",
"}",
"else",
"{",
"// wrap string to Error instance if necessary",
"error",
"(",
"_isString",
"(",
"err",
")",
"?",
"new",
"Error",
"(",
"err",
")",
":",
"err",
")",
";",
"}",
"}",
";",
"cordova",
".",
"exec",
"(",
"success",
",",
"fail",
",",
"'SecureStorage'",
",",
"nativeMethodName",
",",
"args",
")",
";",
"}"
] |
Helper method to execute Cordova native method
@param {String} nativeMethodName Method to execute.
@param {Array} args Execution arguments.
@param {Function} success Called when returning successful result from an action.
@param {Function} error Called when returning error result from an action.
|
[
"Helper",
"method",
"to",
"execute",
"Cordova",
"native",
"method"
] |
3b2f0b10f680b8c1505868d39dbdf22a545edea5
|
https://github.com/Crypho/cordova-plugin-secure-storage/blob/3b2f0b10f680b8c1505868d39dbdf22a545edea5/www/securestorage.js#L28-L46
|
|
14,914
|
iddan/react-spreadsheet
|
__fixtures__/Filter.js
|
filterMatrix
|
function filterMatrix(matrix, filter) {
const filtered = [];
if (matrix.length === 0) {
return matrix;
}
for (let row = 0; row < matrix.length; row++) {
if (matrix.length !== 0) {
for (let column = 0; column < matrix[0].length; column++) {
const cell = matrix[row][column];
if (cell && cell.value.includes(filter)) {
if (!filtered[0]) {
filtered[0] = [];
}
if (filtered[0].length < column) {
filtered[0].length = column + 1;
}
if (!filtered[row]) {
filtered[row] = [];
}
filtered[row][column] = cell;
}
}
}
}
return filtered;
}
|
javascript
|
function filterMatrix(matrix, filter) {
const filtered = [];
if (matrix.length === 0) {
return matrix;
}
for (let row = 0; row < matrix.length; row++) {
if (matrix.length !== 0) {
for (let column = 0; column < matrix[0].length; column++) {
const cell = matrix[row][column];
if (cell && cell.value.includes(filter)) {
if (!filtered[0]) {
filtered[0] = [];
}
if (filtered[0].length < column) {
filtered[0].length = column + 1;
}
if (!filtered[row]) {
filtered[row] = [];
}
filtered[row][column] = cell;
}
}
}
}
return filtered;
}
|
[
"function",
"filterMatrix",
"(",
"matrix",
",",
"filter",
")",
"{",
"const",
"filtered",
"=",
"[",
"]",
";",
"if",
"(",
"matrix",
".",
"length",
"===",
"0",
")",
"{",
"return",
"matrix",
";",
"}",
"for",
"(",
"let",
"row",
"=",
"0",
";",
"row",
"<",
"matrix",
".",
"length",
";",
"row",
"++",
")",
"{",
"if",
"(",
"matrix",
".",
"length",
"!==",
"0",
")",
"{",
"for",
"(",
"let",
"column",
"=",
"0",
";",
"column",
"<",
"matrix",
"[",
"0",
"]",
".",
"length",
";",
"column",
"++",
")",
"{",
"const",
"cell",
"=",
"matrix",
"[",
"row",
"]",
"[",
"column",
"]",
";",
"if",
"(",
"cell",
"&&",
"cell",
".",
"value",
".",
"includes",
"(",
"filter",
")",
")",
"{",
"if",
"(",
"!",
"filtered",
"[",
"0",
"]",
")",
"{",
"filtered",
"[",
"0",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"filtered",
"[",
"0",
"]",
".",
"length",
"<",
"column",
")",
"{",
"filtered",
"[",
"0",
"]",
".",
"length",
"=",
"column",
"+",
"1",
";",
"}",
"if",
"(",
"!",
"filtered",
"[",
"row",
"]",
")",
"{",
"filtered",
"[",
"row",
"]",
"=",
"[",
"]",
";",
"}",
"filtered",
"[",
"row",
"]",
"[",
"column",
"]",
"=",
"cell",
";",
"}",
"}",
"}",
"}",
"return",
"filtered",
";",
"}"
] |
Removes cells not matching the filter from matrix while maintaining the
minimum size that includes all of the matching cells.
|
[
"Removes",
"cells",
"not",
"matching",
"the",
"filter",
"from",
"matrix",
"while",
"maintaining",
"the",
"minimum",
"size",
"that",
"includes",
"all",
"of",
"the",
"matching",
"cells",
"."
] |
a859681313ece3e38f1998d9d0e8f53c1500c38d
|
https://github.com/iddan/react-spreadsheet/blob/a859681313ece3e38f1998d9d0e8f53c1500c38d/__fixtures__/Filter.js#L15-L40
|
14,915
|
apache/cordova-plugin-device-motion
|
www/accelerometer.js
|
start
|
function start() {
exec(function (a) {
var tempListeners = listeners.slice(0);
accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].win(accel);
}
}, function (e) {
var tempListeners = listeners.slice(0);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].fail(e);
}
}, "Accelerometer", "start", []);
running = true;
}
|
javascript
|
function start() {
exec(function (a) {
var tempListeners = listeners.slice(0);
accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].win(accel);
}
}, function (e) {
var tempListeners = listeners.slice(0);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].fail(e);
}
}, "Accelerometer", "start", []);
running = true;
}
|
[
"function",
"start",
"(",
")",
"{",
"exec",
"(",
"function",
"(",
"a",
")",
"{",
"var",
"tempListeners",
"=",
"listeners",
".",
"slice",
"(",
"0",
")",
";",
"accel",
"=",
"new",
"Acceleration",
"(",
"a",
".",
"x",
",",
"a",
".",
"y",
",",
"a",
".",
"z",
",",
"a",
".",
"timestamp",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"tempListeners",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"tempListeners",
"[",
"i",
"]",
".",
"win",
"(",
"accel",
")",
";",
"}",
"}",
",",
"function",
"(",
"e",
")",
"{",
"var",
"tempListeners",
"=",
"listeners",
".",
"slice",
"(",
"0",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"tempListeners",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"tempListeners",
"[",
"i",
"]",
".",
"fail",
"(",
"e",
")",
";",
"}",
"}",
",",
"\"Accelerometer\"",
",",
"\"start\"",
",",
"[",
"]",
")",
";",
"running",
"=",
"true",
";",
"}"
] |
Tells native to start.
|
[
"Tells",
"native",
"to",
"start",
"."
] |
aa939cd2715d059c10fa338cb760127d0cead0ae
|
https://github.com/apache/cordova-plugin-device-motion/blob/aa939cd2715d059c10fa338cb760127d0cead0ae/www/accelerometer.js#L47-L61
|
14,916
|
benmajor/jQuery-Touch-Events
|
src/1.0.8/jquery.mobile-events.js
|
touchStart
|
function touchStart(e) {
$this = $(e.currentTarget);
$this.data('callee1', touchStart);
originalCoord.x = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageX : e.pageX;
originalCoord.y = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageY : e.pageY;
finalCoord.x = originalCoord.x;
finalCoord.y = originalCoord.y;
started = true;
var origEvent = e.originalEvent;
// Read event data into our startEvt:
startEvnt = {
'position': {
'x': (settings.touch_capable) ? origEvent.touches[0].screenX : e.screenX,
'y': (settings.touch_capable) ? origEvent.touches[0].screenY : e.screenY
},
'offset': {
'x': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageX - ($this.offset() ? $this.offset().left : 0)) : Math.round(e.pageX - ($this.offset() ? $this.offset().left : 0)),
'y': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageY - ($this.offset() ? $this.offset().top : 0)) : Math.round(e.pageY - ($this.offset() ? $this.offset().top : 0))
},
'time': Date.now(),
'target': e.target
};
}
|
javascript
|
function touchStart(e) {
$this = $(e.currentTarget);
$this.data('callee1', touchStart);
originalCoord.x = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageX : e.pageX;
originalCoord.y = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageY : e.pageY;
finalCoord.x = originalCoord.x;
finalCoord.y = originalCoord.y;
started = true;
var origEvent = e.originalEvent;
// Read event data into our startEvt:
startEvnt = {
'position': {
'x': (settings.touch_capable) ? origEvent.touches[0].screenX : e.screenX,
'y': (settings.touch_capable) ? origEvent.touches[0].screenY : e.screenY
},
'offset': {
'x': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageX - ($this.offset() ? $this.offset().left : 0)) : Math.round(e.pageX - ($this.offset() ? $this.offset().left : 0)),
'y': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageY - ($this.offset() ? $this.offset().top : 0)) : Math.round(e.pageY - ($this.offset() ? $this.offset().top : 0))
},
'time': Date.now(),
'target': e.target
};
}
|
[
"function",
"touchStart",
"(",
"e",
")",
"{",
"$this",
"=",
"$",
"(",
"e",
".",
"currentTarget",
")",
";",
"$this",
".",
"data",
"(",
"'callee1'",
",",
"touchStart",
")",
";",
"originalCoord",
".",
"x",
"=",
"(",
"e",
".",
"originalEvent",
".",
"targetTouches",
")",
"?",
"e",
".",
"originalEvent",
".",
"targetTouches",
"[",
"0",
"]",
".",
"pageX",
":",
"e",
".",
"pageX",
";",
"originalCoord",
".",
"y",
"=",
"(",
"e",
".",
"originalEvent",
".",
"targetTouches",
")",
"?",
"e",
".",
"originalEvent",
".",
"targetTouches",
"[",
"0",
"]",
".",
"pageY",
":",
"e",
".",
"pageY",
";",
"finalCoord",
".",
"x",
"=",
"originalCoord",
".",
"x",
";",
"finalCoord",
".",
"y",
"=",
"originalCoord",
".",
"y",
";",
"started",
"=",
"true",
";",
"var",
"origEvent",
"=",
"e",
".",
"originalEvent",
";",
"// Read event data into our startEvt:",
"startEvnt",
"=",
"{",
"'position'",
":",
"{",
"'x'",
":",
"(",
"settings",
".",
"touch_capable",
")",
"?",
"origEvent",
".",
"touches",
"[",
"0",
"]",
".",
"screenX",
":",
"e",
".",
"screenX",
",",
"'y'",
":",
"(",
"settings",
".",
"touch_capable",
")",
"?",
"origEvent",
".",
"touches",
"[",
"0",
"]",
".",
"screenY",
":",
"e",
".",
"screenY",
"}",
",",
"'offset'",
":",
"{",
"'x'",
":",
"(",
"settings",
".",
"touch_capable",
")",
"?",
"Math",
".",
"round",
"(",
"origEvent",
".",
"changedTouches",
"[",
"0",
"]",
".",
"pageX",
"-",
"(",
"$this",
".",
"offset",
"(",
")",
"?",
"$this",
".",
"offset",
"(",
")",
".",
"left",
":",
"0",
")",
")",
":",
"Math",
".",
"round",
"(",
"e",
".",
"pageX",
"-",
"(",
"$this",
".",
"offset",
"(",
")",
"?",
"$this",
".",
"offset",
"(",
")",
".",
"left",
":",
"0",
")",
")",
",",
"'y'",
":",
"(",
"settings",
".",
"touch_capable",
")",
"?",
"Math",
".",
"round",
"(",
"origEvent",
".",
"changedTouches",
"[",
"0",
"]",
".",
"pageY",
"-",
"(",
"$this",
".",
"offset",
"(",
")",
"?",
"$this",
".",
"offset",
"(",
")",
".",
"top",
":",
"0",
")",
")",
":",
"Math",
".",
"round",
"(",
"e",
".",
"pageY",
"-",
"(",
"$this",
".",
"offset",
"(",
")",
"?",
"$this",
".",
"offset",
"(",
")",
".",
"top",
":",
"0",
")",
")",
"}",
",",
"'time'",
":",
"Date",
".",
"now",
"(",
")",
",",
"'target'",
":",
"e",
".",
"target",
"}",
";",
"}"
] |
Screen touched, store the original coordinate
|
[
"Screen",
"touched",
"store",
"the",
"original",
"coordinate"
] |
05c3931d207069e324aaf908ca87f12257310392
|
https://github.com/benmajor/jQuery-Touch-Events/blob/05c3931d207069e324aaf908ca87f12257310392/src/1.0.8/jquery.mobile-events.js#L537-L559
|
14,917
|
dhleong/ps4-waker
|
lib/ps4socket.js
|
function(packet) {
packet.status = packet.readInt(8);
packet.oskType = packet.readInt(12);
// TODO: for some reason, the way we decode it
// gives an extra 16 bytes of garbage here. We
// should really figure out why that's happening
// ... and fix it
if (packet.buf.length > 36) {
packet.max = packet.readInt(32);
packet.initial = packet.readString(36);
}
this.emit('start_osk_result', packet);
}
|
javascript
|
function(packet) {
packet.status = packet.readInt(8);
packet.oskType = packet.readInt(12);
// TODO: for some reason, the way we decode it
// gives an extra 16 bytes of garbage here. We
// should really figure out why that's happening
// ... and fix it
if (packet.buf.length > 36) {
packet.max = packet.readInt(32);
packet.initial = packet.readString(36);
}
this.emit('start_osk_result', packet);
}
|
[
"function",
"(",
"packet",
")",
"{",
"packet",
".",
"status",
"=",
"packet",
".",
"readInt",
"(",
"8",
")",
";",
"packet",
".",
"oskType",
"=",
"packet",
".",
"readInt",
"(",
"12",
")",
";",
"// TODO: for some reason, the way we decode it",
"// gives an extra 16 bytes of garbage here. We",
"// should really figure out why that's happening",
"// ... and fix it",
"if",
"(",
"packet",
".",
"buf",
".",
"length",
">",
"36",
")",
"{",
"packet",
".",
"max",
"=",
"packet",
".",
"readInt",
"(",
"32",
")",
";",
"packet",
".",
"initial",
"=",
"packet",
".",
"readString",
"(",
"36",
")",
";",
"}",
"this",
".",
"emit",
"(",
"'start_osk_result'",
",",
"packet",
")",
";",
"}"
] |
osk start result
|
[
"osk",
"start",
"result"
] |
12630615300aa770def3949a6076bd25a76debce
|
https://github.com/dhleong/ps4-waker/blob/12630615300aa770def3949a6076bd25a76debce/lib/ps4socket.js#L494-L506
|
|
14,918
|
dhleong/ps4-waker
|
lib/ps4socket.js
|
function(packet) {
packet._index = 8;
packet.preEditIndex = packet.readInt();
packet.preEditLength = packet.readInt();
// TODO: see above about how how we're skipping
// 16 bytes here for some reason and how hacky
// this is
if (packet.buf.length > 36) {
packet._index += 16;
packet.editIndex = packet.readInt();
packet.editLength = packet.readInt();
packet.caretIndex = packet.readInt();
packet.string = packet.readString(packet._index);
}
this.emit('osk_string_changed', packet);
}
|
javascript
|
function(packet) {
packet._index = 8;
packet.preEditIndex = packet.readInt();
packet.preEditLength = packet.readInt();
// TODO: see above about how how we're skipping
// 16 bytes here for some reason and how hacky
// this is
if (packet.buf.length > 36) {
packet._index += 16;
packet.editIndex = packet.readInt();
packet.editLength = packet.readInt();
packet.caretIndex = packet.readInt();
packet.string = packet.readString(packet._index);
}
this.emit('osk_string_changed', packet);
}
|
[
"function",
"(",
"packet",
")",
"{",
"packet",
".",
"_index",
"=",
"8",
";",
"packet",
".",
"preEditIndex",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"packet",
".",
"preEditLength",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"// TODO: see above about how how we're skipping",
"// 16 bytes here for some reason and how hacky",
"// this is",
"if",
"(",
"packet",
".",
"buf",
".",
"length",
">",
"36",
")",
"{",
"packet",
".",
"_index",
"+=",
"16",
";",
"packet",
".",
"editIndex",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"packet",
".",
"editLength",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"packet",
".",
"caretIndex",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"packet",
".",
"string",
"=",
"packet",
".",
"readString",
"(",
"packet",
".",
"_index",
")",
";",
"}",
"this",
".",
"emit",
"(",
"'osk_string_changed'",
",",
"packet",
")",
";",
"}"
] |
osk string changed
|
[
"osk",
"string",
"changed"
] |
12630615300aa770def3949a6076bd25a76debce
|
https://github.com/dhleong/ps4-waker/blob/12630615300aa770def3949a6076bd25a76debce/lib/ps4socket.js#L509-L524
|
|
14,919
|
dhleong/ps4-waker
|
lib/ps4socket.js
|
function(packet) {
packet.commandId = packet.readInt();
packet.command = packet.commandId === 0
? 'return'
: 'close';
this.emit('osk_command', packet);
}
|
javascript
|
function(packet) {
packet.commandId = packet.readInt();
packet.command = packet.commandId === 0
? 'return'
: 'close';
this.emit('osk_command', packet);
}
|
[
"function",
"(",
"packet",
")",
"{",
"packet",
".",
"commandId",
"=",
"packet",
".",
"readInt",
"(",
")",
";",
"packet",
".",
"command",
"=",
"packet",
".",
"commandId",
"===",
"0",
"?",
"'return'",
":",
"'close'",
";",
"this",
".",
"emit",
"(",
"'osk_command'",
",",
"packet",
")",
";",
"}"
] |
osk command received
|
[
"osk",
"command",
"received"
] |
12630615300aa770def3949a6076bd25a76debce
|
https://github.com/dhleong/ps4-waker/blob/12630615300aa770def3949a6076bd25a76debce/lib/ps4socket.js#L527-L533
|
|
14,920
|
dhleong/ps4-waker
|
lib/packets.js
|
Packet
|
function Packet(length) {
this._index = 0;
if (length instanceof Buffer) {
this.buf = length;
} else {
this.buf = Buffer.alloc(length, 0);
this.writeInt32LE(length);
}
}
|
javascript
|
function Packet(length) {
this._index = 0;
if (length instanceof Buffer) {
this.buf = length;
} else {
this.buf = Buffer.alloc(length, 0);
this.writeInt32LE(length);
}
}
|
[
"function",
"Packet",
"(",
"length",
")",
"{",
"this",
".",
"_index",
"=",
"0",
";",
"if",
"(",
"length",
"instanceof",
"Buffer",
")",
"{",
"this",
".",
"buf",
"=",
"length",
";",
"}",
"else",
"{",
"this",
".",
"buf",
"=",
"Buffer",
".",
"alloc",
"(",
"length",
",",
"0",
")",
";",
"this",
".",
"writeInt32LE",
"(",
"length",
")",
";",
"}",
"}"
] |
Utility for creating and reading TCP packets
|
[
"Utility",
"for",
"creating",
"and",
"reading",
"TCP",
"packets"
] |
12630615300aa770def3949a6076bd25a76debce
|
https://github.com/dhleong/ps4-waker/blob/12630615300aa770def3949a6076bd25a76debce/lib/packets.js#L30-L39
|
14,921
|
cornerstonejs/cornerstoneMath
|
src/point.js
|
findClosestPoint
|
function findClosestPoint (sources, target) {
const distances = [];
let minDistance;
sources.forEach(function (source, index) {
const d = distance(source, target);
distances.push(d);
if (index === 0) {
minDistance = d;
} else {
minDistance = Math.min(d, minDistance);
}
});
const index = distances.indexOf(minDistance);
return sources[index];
}
|
javascript
|
function findClosestPoint (sources, target) {
const distances = [];
let minDistance;
sources.forEach(function (source, index) {
const d = distance(source, target);
distances.push(d);
if (index === 0) {
minDistance = d;
} else {
minDistance = Math.min(d, minDistance);
}
});
const index = distances.indexOf(minDistance);
return sources[index];
}
|
[
"function",
"findClosestPoint",
"(",
"sources",
",",
"target",
")",
"{",
"const",
"distances",
"=",
"[",
"]",
";",
"let",
"minDistance",
";",
"sources",
".",
"forEach",
"(",
"function",
"(",
"source",
",",
"index",
")",
"{",
"const",
"d",
"=",
"distance",
"(",
"source",
",",
"target",
")",
";",
"distances",
".",
"push",
"(",
"d",
")",
";",
"if",
"(",
"index",
"===",
"0",
")",
"{",
"minDistance",
"=",
"d",
";",
"}",
"else",
"{",
"minDistance",
"=",
"Math",
".",
"min",
"(",
"d",
",",
"minDistance",
")",
";",
"}",
"}",
")",
";",
"const",
"index",
"=",
"distances",
".",
"indexOf",
"(",
"minDistance",
")",
";",
"return",
"sources",
"[",
"index",
"]",
";",
"}"
] |
Returns the closest source point to a target point
given an array of source points.
@param sources An Array of source Points
@param target The target Point
@returns Point The closest point from the points array
|
[
"Returns",
"the",
"closest",
"source",
"point",
"to",
"a",
"target",
"point",
"given",
"an",
"array",
"of",
"source",
"points",
"."
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/point.js#L52-L72
|
14,922
|
cornerstonejs/cornerstoneMath
|
src/rect.js
|
rectToPoints
|
function rectToPoints (rect) {
const rectPoints = {
topLeft: {
x: rect.left,
y: rect.top
},
bottomRight: {
x: rect.left + rect.width,
y: rect.top + rect.height
}
};
return rectPoints;
}
|
javascript
|
function rectToPoints (rect) {
const rectPoints = {
topLeft: {
x: rect.left,
y: rect.top
},
bottomRight: {
x: rect.left + rect.width,
y: rect.top + rect.height
}
};
return rectPoints;
}
|
[
"function",
"rectToPoints",
"(",
"rect",
")",
"{",
"const",
"rectPoints",
"=",
"{",
"topLeft",
":",
"{",
"x",
":",
"rect",
".",
"left",
",",
"y",
":",
"rect",
".",
"top",
"}",
",",
"bottomRight",
":",
"{",
"x",
":",
"rect",
".",
"left",
"+",
"rect",
".",
"width",
",",
"y",
":",
"rect",
".",
"top",
"+",
"rect",
".",
"height",
"}",
"}",
";",
"return",
"rectPoints",
";",
"}"
] |
Returns top-left and bottom-right points of the rectangle
|
[
"Returns",
"top",
"-",
"left",
"and",
"bottom",
"-",
"right",
"points",
"of",
"the",
"rectangle"
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/rect.js#L70-L83
|
14,923
|
cornerstonejs/cornerstoneMath
|
src/rect.js
|
doesIntersect
|
function doesIntersect (rect1, rect2) {
let intersectLeftRight;
let intersectTopBottom;
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.topLeft.x));
} else {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.topLeft.x));
}
} else if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.bottomRight.x));
} else {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.bottomRight.x));
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.topLeft.y));
} else {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.bottomRight.y) || (rect2Points.topLeft.y <= rect1Points.topLeft.y));
}
} else if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.bottomRight.y));
} else {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.bottomRight.y) || (rect2Points.top <= rect1Points.bottomRight.y));
}
return intersectLeftRight && intersectTopBottom;
}
|
javascript
|
function doesIntersect (rect1, rect2) {
let intersectLeftRight;
let intersectTopBottom;
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.topLeft.x));
} else {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.topLeft.x));
}
} else if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.bottomRight.x));
} else {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.bottomRight.x));
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.topLeft.y));
} else {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.bottomRight.y) || (rect2Points.topLeft.y <= rect1Points.topLeft.y));
}
} else if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.bottomRight.y));
} else {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.bottomRight.y) || (rect2Points.top <= rect1Points.bottomRight.y));
}
return intersectLeftRight && intersectTopBottom;
}
|
[
"function",
"doesIntersect",
"(",
"rect1",
",",
"rect2",
")",
"{",
"let",
"intersectLeftRight",
";",
"let",
"intersectTopBottom",
";",
"const",
"rect1Points",
"=",
"rectToPoints",
"(",
"rect1",
")",
";",
"const",
"rect2Points",
"=",
"rectToPoints",
"(",
"rect2",
")",
";",
"if",
"(",
"rect1",
".",
"width",
">=",
"0",
")",
"{",
"if",
"(",
"rect2",
".",
"width",
">=",
"0",
")",
"{",
"intersectLeftRight",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
"<=",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
"||",
"(",
"rect2Points",
".",
"bottomRight",
".",
"x",
"<=",
"rect1Points",
".",
"topLeft",
".",
"x",
")",
")",
";",
"}",
"else",
"{",
"intersectLeftRight",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
"<=",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
"||",
"(",
"rect2Points",
".",
"topLeft",
".",
"x",
"<=",
"rect1Points",
".",
"topLeft",
".",
"x",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"rect2",
".",
"width",
">=",
"0",
")",
"{",
"intersectLeftRight",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
"<=",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
"||",
"(",
"rect2Points",
".",
"bottomRight",
".",
"x",
"<=",
"rect1Points",
".",
"bottomRight",
".",
"x",
")",
")",
";",
"}",
"else",
"{",
"intersectLeftRight",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
"<=",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
"||",
"(",
"rect2Points",
".",
"topLeft",
".",
"x",
"<=",
"rect1Points",
".",
"bottomRight",
".",
"x",
")",
")",
";",
"}",
"if",
"(",
"rect1",
".",
"height",
">=",
"0",
")",
"{",
"if",
"(",
"rect2",
".",
"height",
">=",
"0",
")",
"{",
"intersectTopBottom",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
"<=",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
"||",
"(",
"rect2Points",
".",
"bottomRight",
".",
"y",
"<=",
"rect1Points",
".",
"topLeft",
".",
"y",
")",
")",
";",
"}",
"else",
"{",
"intersectTopBottom",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
"<=",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
"||",
"(",
"rect2Points",
".",
"topLeft",
".",
"y",
"<=",
"rect1Points",
".",
"topLeft",
".",
"y",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"rect2",
".",
"height",
">=",
"0",
")",
"{",
"intersectTopBottom",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
"<=",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
"||",
"(",
"rect2Points",
".",
"bottomRight",
".",
"y",
"<=",
"rect1Points",
".",
"bottomRight",
".",
"y",
")",
")",
";",
"}",
"else",
"{",
"intersectTopBottom",
"=",
"!",
"(",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
"<=",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
"||",
"(",
"rect2Points",
".",
"top",
"<=",
"rect1Points",
".",
"bottomRight",
".",
"y",
")",
")",
";",
"}",
"return",
"intersectLeftRight",
"&&",
"intersectTopBottom",
";",
"}"
] |
Returns whether two non-rotated rectangles are intersected
|
[
"Returns",
"whether",
"two",
"non",
"-",
"rotated",
"rectangles",
"are",
"intersected"
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/rect.js#L86-L118
|
14,924
|
cornerstonejs/cornerstoneMath
|
src/rect.js
|
getIntersectionRect
|
function getIntersectionRect (rect1, rect2) {
const intersectRect = {
topLeft: {},
bottomRight: {}
};
if (!doesIntersect(rect1, rect2)) {
return;
}
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
} else {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.topLeft.x);
}
} else if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.topLeft.x);
} else {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
} else {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.topLeft.y);
}
} else if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.topLeft.y);
} else {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
}
// Returns top-left and bottom-right points of intersected rectangle
return intersectRect;
}
|
javascript
|
function getIntersectionRect (rect1, rect2) {
const intersectRect = {
topLeft: {},
bottomRight: {}
};
if (!doesIntersect(rect1, rect2)) {
return;
}
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
} else {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.topLeft.x);
}
} else if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.topLeft.x);
} else {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
} else {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.topLeft.y);
}
} else if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.topLeft.y);
} else {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
}
// Returns top-left and bottom-right points of intersected rectangle
return intersectRect;
}
|
[
"function",
"getIntersectionRect",
"(",
"rect1",
",",
"rect2",
")",
"{",
"const",
"intersectRect",
"=",
"{",
"topLeft",
":",
"{",
"}",
",",
"bottomRight",
":",
"{",
"}",
"}",
";",
"if",
"(",
"!",
"doesIntersect",
"(",
"rect1",
",",
"rect2",
")",
")",
"{",
"return",
";",
"}",
"const",
"rect1Points",
"=",
"rectToPoints",
"(",
"rect1",
")",
";",
"const",
"rect2Points",
"=",
"rectToPoints",
"(",
"rect2",
")",
";",
"if",
"(",
"rect1",
".",
"width",
">=",
"0",
")",
"{",
"if",
"(",
"rect2",
".",
"width",
">=",
"0",
")",
"{",
"intersectRect",
".",
"topLeft",
".",
"x",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
",",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"x",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
",",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
";",
"}",
"else",
"{",
"intersectRect",
".",
"topLeft",
".",
"x",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
",",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"x",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
",",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
";",
"}",
"}",
"else",
"if",
"(",
"rect2",
".",
"width",
">=",
"0",
")",
"{",
"intersectRect",
".",
"topLeft",
".",
"x",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
",",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"x",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
",",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
";",
"}",
"else",
"{",
"intersectRect",
".",
"topLeft",
".",
"x",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"topLeft",
".",
"x",
",",
"rect2Points",
".",
"topLeft",
".",
"x",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"x",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"bottomRight",
".",
"x",
",",
"rect2Points",
".",
"bottomRight",
".",
"x",
")",
";",
"}",
"if",
"(",
"rect1",
".",
"height",
">=",
"0",
")",
"{",
"if",
"(",
"rect2",
".",
"height",
">=",
"0",
")",
"{",
"intersectRect",
".",
"topLeft",
".",
"y",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
",",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"y",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
",",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
";",
"}",
"else",
"{",
"intersectRect",
".",
"topLeft",
".",
"y",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
",",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"y",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
",",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
";",
"}",
"}",
"else",
"if",
"(",
"rect2",
".",
"height",
">=",
"0",
")",
"{",
"intersectRect",
".",
"topLeft",
".",
"y",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
",",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"y",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
",",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
";",
"}",
"else",
"{",
"intersectRect",
".",
"topLeft",
".",
"y",
"=",
"Math",
".",
"min",
"(",
"rect1Points",
".",
"topLeft",
".",
"y",
",",
"rect2Points",
".",
"topLeft",
".",
"y",
")",
";",
"intersectRect",
".",
"bottomRight",
".",
"y",
"=",
"Math",
".",
"max",
"(",
"rect1Points",
".",
"bottomRight",
".",
"y",
",",
"rect2Points",
".",
"bottomRight",
".",
"y",
")",
";",
"}",
"// Returns top-left and bottom-right points of intersected rectangle",
"return",
"intersectRect",
";",
"}"
] |
Returns intersection points of two non-rotated rectangles
|
[
"Returns",
"intersection",
"points",
"of",
"two",
"non",
"-",
"rotated",
"rectangles"
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/rect.js#L121-L169
|
14,925
|
cornerstonejs/cornerstoneMath
|
src/math.js
|
clamp
|
function clamp (x, a, b) {
return (x < a) ? a : ((x > b) ? b : x);
}
|
javascript
|
function clamp (x, a, b) {
return (x < a) ? a : ((x > b) ? b : x);
}
|
[
"function",
"clamp",
"(",
"x",
",",
"a",
",",
"b",
")",
"{",
"return",
"(",
"x",
"<",
"a",
")",
"?",
"a",
":",
"(",
"(",
"x",
">",
"b",
")",
"?",
"b",
":",
"x",
")",
";",
"}"
] |
Based on THREE.JS
|
[
"Based",
"on",
"THREE",
".",
"JS"
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/math.js#L2-L4
|
14,926
|
cornerstonejs/cornerstoneMath
|
src/lineSegment.js
|
intersectLine
|
function intersectLine (lineSegment1, lineSegment2) {
const intersectionPoint = {};
let x1 = lineSegment1.start.x,
y1 = lineSegment1.start.y,
x2 = lineSegment1.end.x,
y2 = lineSegment1.end.y,
x3 = lineSegment2.start.x,
y3 = lineSegment2.start.y,
x4 = lineSegment2.end.x,
y4 = lineSegment2.end.y;
// Coefficients of line equations
let a1, a2, b1, b2, c1, c2;
// Sign values
let r1, r2, r3, r4;
// Intermediate values
let denom, num;
// Compute a1, b1, c1, where line joining points 1 and 2 is "a1 x + b1 y + c1 = 0"
a1 = y2 - y1;
b1 = x1 - x2;
c1 = x2 * y1 - x1 * y2;
// Compute r3 and r4
r3 = a1 * x3 + b1 * y3 + c1;
r4 = a1 * x4 + b1 * y4 + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 !== 0 &&
r4 !== 0 &&
sign(r3) === sign(r4)) {
return;
}
// Compute a2, b2, c2
a2 = y4 - y3;
b2 = x3 - x4;
c2 = x4 * y3 - x3 * y4;
// Compute r1 and r2
r1 = a2 * x1 + b2 * y1 + c2;
r2 = a2 * x2 + b2 * y2 + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 !== 0 &&
r2 !== 0 &&
sign(r1) === sign(r2)) {
return;
}
/* Line segments intersect: compute intersection point.
*/
denom = (a1 * b2) - (a2 * b1);
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
num = (b1 * c2) - (b2 * c1);
const x = parseFloat(num / denom);
num = (a2 * c1) - (a1 * c2);
const y = parseFloat(num / denom);
intersectionPoint.x = x;
intersectionPoint.y = y;
return intersectionPoint;
}
|
javascript
|
function intersectLine (lineSegment1, lineSegment2) {
const intersectionPoint = {};
let x1 = lineSegment1.start.x,
y1 = lineSegment1.start.y,
x2 = lineSegment1.end.x,
y2 = lineSegment1.end.y,
x3 = lineSegment2.start.x,
y3 = lineSegment2.start.y,
x4 = lineSegment2.end.x,
y4 = lineSegment2.end.y;
// Coefficients of line equations
let a1, a2, b1, b2, c1, c2;
// Sign values
let r1, r2, r3, r4;
// Intermediate values
let denom, num;
// Compute a1, b1, c1, where line joining points 1 and 2 is "a1 x + b1 y + c1 = 0"
a1 = y2 - y1;
b1 = x1 - x2;
c1 = x2 * y1 - x1 * y2;
// Compute r3 and r4
r3 = a1 * x3 + b1 * y3 + c1;
r4 = a1 * x4 + b1 * y4 + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 !== 0 &&
r4 !== 0 &&
sign(r3) === sign(r4)) {
return;
}
// Compute a2, b2, c2
a2 = y4 - y3;
b2 = x3 - x4;
c2 = x4 * y3 - x3 * y4;
// Compute r1 and r2
r1 = a2 * x1 + b2 * y1 + c2;
r2 = a2 * x2 + b2 * y2 + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 !== 0 &&
r2 !== 0 &&
sign(r1) === sign(r2)) {
return;
}
/* Line segments intersect: compute intersection point.
*/
denom = (a1 * b2) - (a2 * b1);
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
num = (b1 * c2) - (b2 * c1);
const x = parseFloat(num / denom);
num = (a2 * c1) - (a1 * c2);
const y = parseFloat(num / denom);
intersectionPoint.x = x;
intersectionPoint.y = y;
return intersectionPoint;
}
|
[
"function",
"intersectLine",
"(",
"lineSegment1",
",",
"lineSegment2",
")",
"{",
"const",
"intersectionPoint",
"=",
"{",
"}",
";",
"let",
"x1",
"=",
"lineSegment1",
".",
"start",
".",
"x",
",",
"y1",
"=",
"lineSegment1",
".",
"start",
".",
"y",
",",
"x2",
"=",
"lineSegment1",
".",
"end",
".",
"x",
",",
"y2",
"=",
"lineSegment1",
".",
"end",
".",
"y",
",",
"x3",
"=",
"lineSegment2",
".",
"start",
".",
"x",
",",
"y3",
"=",
"lineSegment2",
".",
"start",
".",
"y",
",",
"x4",
"=",
"lineSegment2",
".",
"end",
".",
"x",
",",
"y4",
"=",
"lineSegment2",
".",
"end",
".",
"y",
";",
"// Coefficients of line equations",
"let",
"a1",
",",
"a2",
",",
"b1",
",",
"b2",
",",
"c1",
",",
"c2",
";",
"// Sign values",
"let",
"r1",
",",
"r2",
",",
"r3",
",",
"r4",
";",
"// Intermediate values",
"let",
"denom",
",",
"num",
";",
"// Compute a1, b1, c1, where line joining points 1 and 2 is \"a1 x + b1 y + c1 = 0\"",
"a1",
"=",
"y2",
"-",
"y1",
";",
"b1",
"=",
"x1",
"-",
"x2",
";",
"c1",
"=",
"x2",
"*",
"y1",
"-",
"x1",
"*",
"y2",
";",
"// Compute r3 and r4",
"r3",
"=",
"a1",
"*",
"x3",
"+",
"b1",
"*",
"y3",
"+",
"c1",
";",
"r4",
"=",
"a1",
"*",
"x4",
"+",
"b1",
"*",
"y4",
"+",
"c1",
";",
"/* Check signs of r3 and r4. If both point 3 and point 4 lie on\n * same side of line 1, the line segments do not intersect.\n */",
"if",
"(",
"r3",
"!==",
"0",
"&&",
"r4",
"!==",
"0",
"&&",
"sign",
"(",
"r3",
")",
"===",
"sign",
"(",
"r4",
")",
")",
"{",
"return",
";",
"}",
"// Compute a2, b2, c2",
"a2",
"=",
"y4",
"-",
"y3",
";",
"b2",
"=",
"x3",
"-",
"x4",
";",
"c2",
"=",
"x4",
"*",
"y3",
"-",
"x3",
"*",
"y4",
";",
"// Compute r1 and r2",
"r1",
"=",
"a2",
"*",
"x1",
"+",
"b2",
"*",
"y1",
"+",
"c2",
";",
"r2",
"=",
"a2",
"*",
"x2",
"+",
"b2",
"*",
"y2",
"+",
"c2",
";",
"/* Check signs of r1 and r2. If both point 1 and point 2 lie\n * on same side of second line segment, the line segments do\n * not intersect.\n */",
"if",
"(",
"r1",
"!==",
"0",
"&&",
"r2",
"!==",
"0",
"&&",
"sign",
"(",
"r1",
")",
"===",
"sign",
"(",
"r2",
")",
")",
"{",
"return",
";",
"}",
"/* Line segments intersect: compute intersection point.\n */",
"denom",
"=",
"(",
"a1",
"*",
"b2",
")",
"-",
"(",
"a2",
"*",
"b1",
")",
";",
"/* The denom/2 is to get rounding instead of truncating. It\n * is added or subtracted to the numerator, depending upon the\n * sign of the numerator.\n */",
"num",
"=",
"(",
"b1",
"*",
"c2",
")",
"-",
"(",
"b2",
"*",
"c1",
")",
";",
"const",
"x",
"=",
"parseFloat",
"(",
"num",
"/",
"denom",
")",
";",
"num",
"=",
"(",
"a2",
"*",
"c1",
")",
"-",
"(",
"a1",
"*",
"c2",
")",
";",
"const",
"y",
"=",
"parseFloat",
"(",
"num",
"/",
"denom",
")",
";",
"intersectionPoint",
".",
"x",
"=",
"x",
";",
"intersectionPoint",
".",
"y",
"=",
"y",
";",
"return",
"intersectionPoint",
";",
"}"
] |
Returns intersection points of two lines
|
[
"Returns",
"intersection",
"points",
"of",
"two",
"lines"
] |
c89342021539339cfb9e0a908e0453216b8e460f
|
https://github.com/cornerstonejs/cornerstoneMath/blob/c89342021539339cfb9e0a908e0453216b8e460f/src/lineSegment.js#L42-L121
|
14,927
|
kekee000/fonteditor-core
|
src/ttf/util/string.js
|
function (bytes) {
var s = '';
for (var i = 0, l = bytes.length; i < l; i++) {
s += String.fromCharCode(bytes[i]);
}
return s;
}
|
javascript
|
function (bytes) {
var s = '';
for (var i = 0, l = bytes.length; i < l; i++) {
s += String.fromCharCode(bytes[i]);
}
return s;
}
|
[
"function",
"(",
"bytes",
")",
"{",
"var",
"s",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"bytes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"s",
"+=",
"String",
".",
"fromCharCode",
"(",
"bytes",
"[",
"i",
"]",
")",
";",
"}",
"return",
"s",
";",
"}"
] |
bytes to string
@param {Array} bytes 字节数组
@return {string} string
|
[
"bytes",
"to",
"string"
] |
e6b82f9d55dcc472ec0644681c7d33dd995b9364
|
https://github.com/kekee000/fonteditor-core/blob/e6b82f9d55dcc472ec0644681c7d33dd995b9364/src/ttf/util/string.js#L63-L69
|
|
14,928
|
kekee000/fonteditor-core
|
src/ttf/table/CFF.js
|
calcCFFSubroutineBias
|
function calcCFFSubroutineBias(subrs) {
var bias;
if (subrs.length < 1240) {
bias = 107;
}
else if (subrs.length < 33900) {
bias = 1131;
}
else {
bias = 32768;
}
return bias;
}
|
javascript
|
function calcCFFSubroutineBias(subrs) {
var bias;
if (subrs.length < 1240) {
bias = 107;
}
else if (subrs.length < 33900) {
bias = 1131;
}
else {
bias = 32768;
}
return bias;
}
|
[
"function",
"calcCFFSubroutineBias",
"(",
"subrs",
")",
"{",
"var",
"bias",
";",
"if",
"(",
"subrs",
".",
"length",
"<",
"1240",
")",
"{",
"bias",
"=",
"107",
";",
"}",
"else",
"if",
"(",
"subrs",
".",
"length",
"<",
"33900",
")",
"{",
"bias",
"=",
"1131",
";",
"}",
"else",
"{",
"bias",
"=",
"32768",
";",
"}",
"return",
"bias",
";",
"}"
] |
Subroutines are encoded using the negative half of the number space. See type 2 chapter 4.7 "Subroutine operators".
|
[
"Subroutines",
"are",
"encoded",
"using",
"the",
"negative",
"half",
"of",
"the",
"number",
"space",
".",
"See",
"type",
"2",
"chapter",
"4",
".",
"7",
"Subroutine",
"operators",
"."
] |
e6b82f9d55dcc472ec0644681c7d33dd995b9364
|
https://github.com/kekee000/fonteditor-core/blob/e6b82f9d55dcc472ec0644681c7d33dd995b9364/src/ttf/table/CFF.js#L97-L110
|
14,929
|
spiritree/vue-orgchart
|
dist/vue-orgchart.esm.js
|
getRawTag
|
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag$1),
tag = value[symToStringTag$1];
try {
value[symToStringTag$1] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag$1] = tag;
} else {
delete value[symToStringTag$1];
}
}
return result;
}
|
javascript
|
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag$1),
tag = value[symToStringTag$1];
try {
value[symToStringTag$1] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag$1] = tag;
} else {
delete value[symToStringTag$1];
}
}
return result;
}
|
[
"function",
"getRawTag",
"(",
"value",
")",
"{",
"var",
"isOwn",
"=",
"hasOwnProperty$1",
".",
"call",
"(",
"value",
",",
"symToStringTag$1",
")",
",",
"tag",
"=",
"value",
"[",
"symToStringTag$1",
"]",
";",
"try",
"{",
"value",
"[",
"symToStringTag$1",
"]",
"=",
"undefined",
";",
"var",
"unmasked",
"=",
"true",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"var",
"result",
"=",
"nativeObjectToString",
".",
"call",
"(",
"value",
")",
";",
"if",
"(",
"unmasked",
")",
"{",
"if",
"(",
"isOwn",
")",
"{",
"value",
"[",
"symToStringTag$1",
"]",
"=",
"tag",
";",
"}",
"else",
"{",
"delete",
"value",
"[",
"symToStringTag$1",
"]",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
@private
@param {*} value The value to query.
@returns {string} Returns the raw `toStringTag`.
|
[
"A",
"specialized",
"version",
"of",
"baseGetTag",
"which",
"ignores",
"Symbol",
".",
"toStringTag",
"values",
"."
] |
c8de4152e2839e28af5561bcce9b4af0d3f046a4
|
https://github.com/spiritree/vue-orgchart/blob/c8de4152e2839e28af5561bcce9b4af0d3f046a4/dist/vue-orgchart.esm.js#L2458-L2476
|
14,930
|
tyrasd/osmtogeojson
|
index.js
|
default_deduplicator
|
function default_deduplicator(objectA, objectB) {
// default deduplication handler:
// if object versions differ, use highest available version
if ((objectA.version || objectB.version) &&
(objectA.version !== objectB.version)) {
return (+objectA.version || 0) > (+objectB.version || 0)
? objectA
: objectB;
}
// otherwise: return merged obj properties
return _.merge(objectA, objectB);
}
|
javascript
|
function default_deduplicator(objectA, objectB) {
// default deduplication handler:
// if object versions differ, use highest available version
if ((objectA.version || objectB.version) &&
(objectA.version !== objectB.version)) {
return (+objectA.version || 0) > (+objectB.version || 0)
? objectA
: objectB;
}
// otherwise: return merged obj properties
return _.merge(objectA, objectB);
}
|
[
"function",
"default_deduplicator",
"(",
"objectA",
",",
"objectB",
")",
"{",
"// default deduplication handler:",
"// if object versions differ, use highest available version",
"if",
"(",
"(",
"objectA",
".",
"version",
"||",
"objectB",
".",
"version",
")",
"&&",
"(",
"objectA",
".",
"version",
"!==",
"objectB",
".",
"version",
")",
")",
"{",
"return",
"(",
"+",
"objectA",
".",
"version",
"||",
"0",
")",
">",
"(",
"+",
"objectB",
".",
"version",
"||",
"0",
")",
"?",
"objectA",
":",
"objectB",
";",
"}",
"// otherwise: return merged obj properties",
"return",
"_",
".",
"merge",
"(",
"objectA",
",",
"objectB",
")",
";",
"}"
] |
default deduplication helper function
|
[
"default",
"deduplication",
"helper",
"function"
] |
0d6190a2c3d23b3ce0ab9b302199834894334727
|
https://github.com/tyrasd/osmtogeojson/blob/0d6190a2c3d23b3ce0ab9b302199834894334727/index.js#L19-L30
|
14,931
|
tyrasd/osmtogeojson
|
index.js
|
has_interesting_tags
|
function has_interesting_tags(t, ignore_tags) {
if (typeof ignore_tags !== "object")
ignore_tags={};
if (typeof options.uninterestingTags === "function")
return !options.uninterestingTags(t, ignore_tags);
for (var k in t)
if (!(options.uninterestingTags[k]===true) &&
!(ignore_tags[k]===true || ignore_tags[k]===t[k]))
return true;
return false;
}
|
javascript
|
function has_interesting_tags(t, ignore_tags) {
if (typeof ignore_tags !== "object")
ignore_tags={};
if (typeof options.uninterestingTags === "function")
return !options.uninterestingTags(t, ignore_tags);
for (var k in t)
if (!(options.uninterestingTags[k]===true) &&
!(ignore_tags[k]===true || ignore_tags[k]===t[k]))
return true;
return false;
}
|
[
"function",
"has_interesting_tags",
"(",
"t",
",",
"ignore_tags",
")",
"{",
"if",
"(",
"typeof",
"ignore_tags",
"!==",
"\"object\"",
")",
"ignore_tags",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"options",
".",
"uninterestingTags",
"===",
"\"function\"",
")",
"return",
"!",
"options",
".",
"uninterestingTags",
"(",
"t",
",",
"ignore_tags",
")",
";",
"for",
"(",
"var",
"k",
"in",
"t",
")",
"if",
"(",
"!",
"(",
"options",
".",
"uninterestingTags",
"[",
"k",
"]",
"===",
"true",
")",
"&&",
"!",
"(",
"ignore_tags",
"[",
"k",
"]",
"===",
"true",
"||",
"ignore_tags",
"[",
"k",
"]",
"===",
"t",
"[",
"k",
"]",
")",
")",
"return",
"true",
";",
"return",
"false",
";",
"}"
] |
helper function that checks if there are any tags other than "created_by", "source", etc. or any tag provided in ignore_tags
|
[
"helper",
"function",
"that",
"checks",
"if",
"there",
"are",
"any",
"tags",
"other",
"than",
"created_by",
"source",
"etc",
".",
"or",
"any",
"tag",
"provided",
"in",
"ignore_tags"
] |
0d6190a2c3d23b3ce0ab9b302199834894334727
|
https://github.com/tyrasd/osmtogeojson/blob/0d6190a2c3d23b3ce0ab9b302199834894334727/index.js#L460-L470
|
14,932
|
tyrasd/osmtogeojson
|
index.js
|
build_meta_information
|
function build_meta_information(object) {
var res = {
"timestamp": object.timestamp,
"version": object.version,
"changeset": object.changeset,
"user": object.user,
"uid": object.uid
};
for (var k in res)
if (res[k] === undefined)
delete res[k];
return res;
}
|
javascript
|
function build_meta_information(object) {
var res = {
"timestamp": object.timestamp,
"version": object.version,
"changeset": object.changeset,
"user": object.user,
"uid": object.uid
};
for (var k in res)
if (res[k] === undefined)
delete res[k];
return res;
}
|
[
"function",
"build_meta_information",
"(",
"object",
")",
"{",
"var",
"res",
"=",
"{",
"\"timestamp\"",
":",
"object",
".",
"timestamp",
",",
"\"version\"",
":",
"object",
".",
"version",
",",
"\"changeset\"",
":",
"object",
".",
"changeset",
",",
"\"user\"",
":",
"object",
".",
"user",
",",
"\"uid\"",
":",
"object",
".",
"uid",
"}",
";",
"for",
"(",
"var",
"k",
"in",
"res",
")",
"if",
"(",
"res",
"[",
"k",
"]",
"===",
"undefined",
")",
"delete",
"res",
"[",
"k",
"]",
";",
"return",
"res",
";",
"}"
] |
helper function to extract meta information
|
[
"helper",
"function",
"to",
"extract",
"meta",
"information"
] |
0d6190a2c3d23b3ce0ab9b302199834894334727
|
https://github.com/tyrasd/osmtogeojson/blob/0d6190a2c3d23b3ce0ab9b302199834894334727/index.js#L472-L484
|
14,933
|
tyrasd/osmtogeojson
|
index.js
|
join
|
function join(ways) {
var _first = function(arr) {return arr[0]};
var _last = function(arr) {return arr[arr.length-1]};
var _fitTogether = function(n1, n2) {
return n1 !== undefined && n2 !== undefined && n1.id === n2.id;
}
// stolen from iD/relation.js
var joined = [], current, first, last, i, how, what;
while (ways.length) {
current = ways.pop().nodes.slice();
joined.push(current);
while (ways.length && !_fitTogether(_first(current), _last(current))) {
first = _first(current);
last = _last(current);
for (i = 0; i < ways.length; i++) {
what = ways[i].nodes;
if (_fitTogether(last, _first(what))) {
how = current.push;
what = what.slice(1);
break;
} else if (_fitTogether(last, _last(what))) {
how = current.push;
what = what.slice(0, -1).reverse();
break;
} else if (_fitTogether(first, _last(what))) {
how = current.unshift;
what = what.slice(0, -1);
break;
} else if (_fitTogether(first, _first(what))) {
how = current.unshift;
what = what.slice(1).reverse();
break;
} else {
what = how = null;
}
}
if (!what)
break; // Invalid geometry (dangling way, unclosed ring)
ways.splice(i, 1);
how.apply(current, what);
}
}
return joined;
}
|
javascript
|
function join(ways) {
var _first = function(arr) {return arr[0]};
var _last = function(arr) {return arr[arr.length-1]};
var _fitTogether = function(n1, n2) {
return n1 !== undefined && n2 !== undefined && n1.id === n2.id;
}
// stolen from iD/relation.js
var joined = [], current, first, last, i, how, what;
while (ways.length) {
current = ways.pop().nodes.slice();
joined.push(current);
while (ways.length && !_fitTogether(_first(current), _last(current))) {
first = _first(current);
last = _last(current);
for (i = 0; i < ways.length; i++) {
what = ways[i].nodes;
if (_fitTogether(last, _first(what))) {
how = current.push;
what = what.slice(1);
break;
} else if (_fitTogether(last, _last(what))) {
how = current.push;
what = what.slice(0, -1).reverse();
break;
} else if (_fitTogether(first, _last(what))) {
how = current.unshift;
what = what.slice(0, -1);
break;
} else if (_fitTogether(first, _first(what))) {
how = current.unshift;
what = what.slice(1).reverse();
break;
} else {
what = how = null;
}
}
if (!what)
break; // Invalid geometry (dangling way, unclosed ring)
ways.splice(i, 1);
how.apply(current, what);
}
}
return joined;
}
|
[
"function",
"join",
"(",
"ways",
")",
"{",
"var",
"_first",
"=",
"function",
"(",
"arr",
")",
"{",
"return",
"arr",
"[",
"0",
"]",
"}",
";",
"var",
"_last",
"=",
"function",
"(",
"arr",
")",
"{",
"return",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
"}",
";",
"var",
"_fitTogether",
"=",
"function",
"(",
"n1",
",",
"n2",
")",
"{",
"return",
"n1",
"!==",
"undefined",
"&&",
"n2",
"!==",
"undefined",
"&&",
"n1",
".",
"id",
"===",
"n2",
".",
"id",
";",
"}",
"// stolen from iD/relation.js",
"var",
"joined",
"=",
"[",
"]",
",",
"current",
",",
"first",
",",
"last",
",",
"i",
",",
"how",
",",
"what",
";",
"while",
"(",
"ways",
".",
"length",
")",
"{",
"current",
"=",
"ways",
".",
"pop",
"(",
")",
".",
"nodes",
".",
"slice",
"(",
")",
";",
"joined",
".",
"push",
"(",
"current",
")",
";",
"while",
"(",
"ways",
".",
"length",
"&&",
"!",
"_fitTogether",
"(",
"_first",
"(",
"current",
")",
",",
"_last",
"(",
"current",
")",
")",
")",
"{",
"first",
"=",
"_first",
"(",
"current",
")",
";",
"last",
"=",
"_last",
"(",
"current",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"ways",
".",
"length",
";",
"i",
"++",
")",
"{",
"what",
"=",
"ways",
"[",
"i",
"]",
".",
"nodes",
";",
"if",
"(",
"_fitTogether",
"(",
"last",
",",
"_first",
"(",
"what",
")",
")",
")",
"{",
"how",
"=",
"current",
".",
"push",
";",
"what",
"=",
"what",
".",
"slice",
"(",
"1",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"_fitTogether",
"(",
"last",
",",
"_last",
"(",
"what",
")",
")",
")",
"{",
"how",
"=",
"current",
".",
"push",
";",
"what",
"=",
"what",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
".",
"reverse",
"(",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"_fitTogether",
"(",
"first",
",",
"_last",
"(",
"what",
")",
")",
")",
"{",
"how",
"=",
"current",
".",
"unshift",
";",
"what",
"=",
"what",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"_fitTogether",
"(",
"first",
",",
"_first",
"(",
"what",
")",
")",
")",
"{",
"how",
"=",
"current",
".",
"unshift",
";",
"what",
"=",
"what",
".",
"slice",
"(",
"1",
")",
".",
"reverse",
"(",
")",
";",
"break",
";",
"}",
"else",
"{",
"what",
"=",
"how",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"!",
"what",
")",
"break",
";",
"// Invalid geometry (dangling way, unclosed ring)",
"ways",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"how",
".",
"apply",
"(",
"current",
",",
"what",
")",
";",
"}",
"}",
"return",
"joined",
";",
"}"
] |
helper that joins adjacent osm ways into linestrings or linear rings
|
[
"helper",
"that",
"joins",
"adjacent",
"osm",
"ways",
"into",
"linestrings",
"or",
"linear",
"rings"
] |
0d6190a2c3d23b3ce0ab9b302199834894334727
|
https://github.com/tyrasd/osmtogeojson/blob/0d6190a2c3d23b3ce0ab9b302199834894334727/index.js#L1017-L1060
|
14,934
|
AlexDisler/cordova-splash
|
index.js
|
function () {
var deferred = Q.defer();
var parser = new xml2js.Parser();
fs.readFile(settings.CONFIG_FILE, function (err, data) {
if (err) {
deferred.reject(err);
}
parser.parseString(data, function (err, result) {
if (err) {
deferred.reject(err);
}
var projectName = result.widget.name[0];
deferred.resolve(projectName);
});
});
return deferred.promise;
}
|
javascript
|
function () {
var deferred = Q.defer();
var parser = new xml2js.Parser();
fs.readFile(settings.CONFIG_FILE, function (err, data) {
if (err) {
deferred.reject(err);
}
parser.parseString(data, function (err, result) {
if (err) {
deferred.reject(err);
}
var projectName = result.widget.name[0];
deferred.resolve(projectName);
});
});
return deferred.promise;
}
|
[
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"parser",
"=",
"new",
"xml2js",
".",
"Parser",
"(",
")",
";",
"fs",
".",
"readFile",
"(",
"settings",
".",
"CONFIG_FILE",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"parser",
".",
"parseString",
"(",
"data",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"var",
"projectName",
"=",
"result",
".",
"widget",
".",
"name",
"[",
"0",
"]",
";",
"deferred",
".",
"resolve",
"(",
"projectName",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
read the config file and get the project name
@return {Promise} resolves to a string - the project's name
|
[
"read",
"the",
"config",
"file",
"and",
"get",
"the",
"project",
"name"
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L126-L142
|
|
14,935
|
AlexDisler/cordova-splash
|
index.js
|
function (platform, splash) {
var deferred = Q.defer();
var srcPath = settings.SPLASH_FILE;
var platformPath = srcPath.replace(/\.png$/, '-' + platform.name + '.png');
if (fs.existsSync(platformPath)) {
srcPath = platformPath;
}
var dstPath = platform.splashPath + splash.name;
var dst = path.dirname(dstPath);
if (!fs.existsSync(dst)) {
fs.mkdirsSync(dst);
}
ig.crop({
srcPath: srcPath,
dstPath: dstPath,
quality: 1,
format: 'png',
width: splash.width,
height: splash.height
} , function(err, stdout, stderr){
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
display.success(splash.name + ' created');
}
});
return deferred.promise;
}
|
javascript
|
function (platform, splash) {
var deferred = Q.defer();
var srcPath = settings.SPLASH_FILE;
var platformPath = srcPath.replace(/\.png$/, '-' + platform.name + '.png');
if (fs.existsSync(platformPath)) {
srcPath = platformPath;
}
var dstPath = platform.splashPath + splash.name;
var dst = path.dirname(dstPath);
if (!fs.existsSync(dst)) {
fs.mkdirsSync(dst);
}
ig.crop({
srcPath: srcPath,
dstPath: dstPath,
quality: 1,
format: 'png',
width: splash.width,
height: splash.height
} , function(err, stdout, stderr){
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
display.success(splash.name + ' created');
}
});
return deferred.promise;
}
|
[
"function",
"(",
"platform",
",",
"splash",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"srcPath",
"=",
"settings",
".",
"SPLASH_FILE",
";",
"var",
"platformPath",
"=",
"srcPath",
".",
"replace",
"(",
"/",
"\\.png$",
"/",
",",
"'-'",
"+",
"platform",
".",
"name",
"+",
"'.png'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"platformPath",
")",
")",
"{",
"srcPath",
"=",
"platformPath",
";",
"}",
"var",
"dstPath",
"=",
"platform",
".",
"splashPath",
"+",
"splash",
".",
"name",
";",
"var",
"dst",
"=",
"path",
".",
"dirname",
"(",
"dstPath",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dst",
")",
")",
"{",
"fs",
".",
"mkdirsSync",
"(",
"dst",
")",
";",
"}",
"ig",
".",
"crop",
"(",
"{",
"srcPath",
":",
"srcPath",
",",
"dstPath",
":",
"dstPath",
",",
"quality",
":",
"1",
",",
"format",
":",
"'png'",
",",
"width",
":",
"splash",
".",
"width",
",",
"height",
":",
"splash",
".",
"height",
"}",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"display",
".",
"success",
"(",
"splash",
".",
"name",
"+",
"' created'",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Crops and creates a new splash in the platform's folder.
@param {Object} platform
@param {Object} splash
@return {Promise}
|
[
"Crops",
"and",
"creates",
"a",
"new",
"splash",
"in",
"the",
"platform",
"s",
"folder",
"."
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L151-L179
|
|
14,936
|
AlexDisler/cordova-splash
|
index.js
|
function (platform) {
var deferred = Q.defer();
display.header('Generating splash screen for ' + platform.name);
var all = [];
var splashes = platform.splash;
splashes.forEach(function (splash) {
all.push(generateSplash(platform, splash));
});
Q.all(all).then(function () {
deferred.resolve();
}).catch(function (err) {
console.log(err);
});
return deferred.promise;
}
|
javascript
|
function (platform) {
var deferred = Q.defer();
display.header('Generating splash screen for ' + platform.name);
var all = [];
var splashes = platform.splash;
splashes.forEach(function (splash) {
all.push(generateSplash(platform, splash));
});
Q.all(all).then(function () {
deferred.resolve();
}).catch(function (err) {
console.log(err);
});
return deferred.promise;
}
|
[
"function",
"(",
"platform",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"display",
".",
"header",
"(",
"'Generating splash screen for '",
"+",
"platform",
".",
"name",
")",
";",
"var",
"all",
"=",
"[",
"]",
";",
"var",
"splashes",
"=",
"platform",
".",
"splash",
";",
"splashes",
".",
"forEach",
"(",
"function",
"(",
"splash",
")",
"{",
"all",
".",
"push",
"(",
"generateSplash",
"(",
"platform",
",",
"splash",
")",
")",
";",
"}",
")",
";",
"Q",
".",
"all",
"(",
"all",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Generates splash based on the platform object
@param {Object} platform
@return {Promise}
|
[
"Generates",
"splash",
"based",
"on",
"the",
"platform",
"object"
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L187-L201
|
|
14,937
|
AlexDisler/cordova-splash
|
index.js
|
function (platforms) {
var deferred = Q.defer();
var sequence = Q();
var all = [];
_(platforms).where({ isAdded : true }).forEach(function (platform) {
sequence = sequence.then(function () {
return generateSplashForPlatform(platform);
});
all.push(sequence);
});
Q.all(all).then(function () {
deferred.resolve();
});
return deferred.promise;
}
|
javascript
|
function (platforms) {
var deferred = Q.defer();
var sequence = Q();
var all = [];
_(platforms).where({ isAdded : true }).forEach(function (platform) {
sequence = sequence.then(function () {
return generateSplashForPlatform(platform);
});
all.push(sequence);
});
Q.all(all).then(function () {
deferred.resolve();
});
return deferred.promise;
}
|
[
"function",
"(",
"platforms",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"sequence",
"=",
"Q",
"(",
")",
";",
"var",
"all",
"=",
"[",
"]",
";",
"_",
"(",
"platforms",
")",
".",
"where",
"(",
"{",
"isAdded",
":",
"true",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"platform",
")",
"{",
"sequence",
"=",
"sequence",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"generateSplashForPlatform",
"(",
"platform",
")",
";",
"}",
")",
";",
"all",
".",
"push",
"(",
"sequence",
")",
";",
"}",
")",
";",
"Q",
".",
"all",
"(",
"all",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Goes over all the platforms and triggers splash screen generation
@param {Array} platforms
@return {Promise}
|
[
"Goes",
"over",
"all",
"the",
"platforms",
"and",
"triggers",
"splash",
"screen",
"generation"
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L209-L223
|
|
14,938
|
AlexDisler/cordova-splash
|
index.js
|
function () {
var deferred = Q.defer();
getPlatforms().then(function (platforms) {
var activePlatforms = _(platforms).where({ isAdded : true });
if (activePlatforms.length > 0) {
display.success('platforms found: ' + _(activePlatforms).pluck('name').join(', '));
deferred.resolve();
} else {
display.error(
'No cordova platforms found. ' +
'Make sure you are in the root folder of your Cordova project ' +
'and add platforms with \'cordova platform add\''
);
deferred.reject();
}
});
return deferred.promise;
}
|
javascript
|
function () {
var deferred = Q.defer();
getPlatforms().then(function (platforms) {
var activePlatforms = _(platforms).where({ isAdded : true });
if (activePlatforms.length > 0) {
display.success('platforms found: ' + _(activePlatforms).pluck('name').join(', '));
deferred.resolve();
} else {
display.error(
'No cordova platforms found. ' +
'Make sure you are in the root folder of your Cordova project ' +
'and add platforms with \'cordova platform add\''
);
deferred.reject();
}
});
return deferred.promise;
}
|
[
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"getPlatforms",
"(",
")",
".",
"then",
"(",
"function",
"(",
"platforms",
")",
"{",
"var",
"activePlatforms",
"=",
"_",
"(",
"platforms",
")",
".",
"where",
"(",
"{",
"isAdded",
":",
"true",
"}",
")",
";",
"if",
"(",
"activePlatforms",
".",
"length",
">",
"0",
")",
"{",
"display",
".",
"success",
"(",
"'platforms found: '",
"+",
"_",
"(",
"activePlatforms",
")",
".",
"pluck",
"(",
"'name'",
")",
".",
"join",
"(",
"', '",
")",
")",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"display",
".",
"error",
"(",
"'No cordova platforms found. '",
"+",
"'Make sure you are in the root folder of your Cordova project '",
"+",
"'and add platforms with \\'cordova platform add\\''",
")",
";",
"deferred",
".",
"reject",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Checks if at least one platform was added to the project
@return {Promise} resolves if at least one platform was found, rejects otherwise
|
[
"Checks",
"if",
"at",
"least",
"one",
"platform",
"was",
"added",
"to",
"the",
"project"
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L230-L247
|
|
14,939
|
AlexDisler/cordova-splash
|
index.js
|
function () {
var deferred = Q.defer();
fs.exists(settings.SPLASH_FILE, function (exists) {
if (exists) {
display.success(settings.SPLASH_FILE + ' exists');
deferred.resolve();
} else {
display.error(settings.SPLASH_FILE + ' does not exist');
deferred.reject();
}
});
return deferred.promise;
}
|
javascript
|
function () {
var deferred = Q.defer();
fs.exists(settings.SPLASH_FILE, function (exists) {
if (exists) {
display.success(settings.SPLASH_FILE + ' exists');
deferred.resolve();
} else {
display.error(settings.SPLASH_FILE + ' does not exist');
deferred.reject();
}
});
return deferred.promise;
}
|
[
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"fs",
".",
"exists",
"(",
"settings",
".",
"SPLASH_FILE",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"display",
".",
"success",
"(",
"settings",
".",
"SPLASH_FILE",
"+",
"' exists'",
")",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"display",
".",
"error",
"(",
"settings",
".",
"SPLASH_FILE",
"+",
"' does not exist'",
")",
";",
"deferred",
".",
"reject",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Checks if a valid splash file exists
@return {Promise} resolves if exists, rejects otherwise
|
[
"Checks",
"if",
"a",
"valid",
"splash",
"file",
"exists"
] |
2368a5cb843a6ad89bf1944b213acc0e93732df8
|
https://github.com/AlexDisler/cordova-splash/blob/2368a5cb843a6ad89bf1944b213acc0e93732df8/index.js#L254-L266
|
|
14,940
|
mapbox/mapbox-gl-sync-move
|
index.js
|
syncMaps
|
function syncMaps () {
var maps;
var argLen = arguments.length;
if (argLen === 1) {
maps = arguments[0];
} else {
maps = [];
for (var i = 0; i < argLen; i++) {
maps.push(arguments[i]);
}
}
// Create all the movement functions, because if they're created every time
// they wouldn't be the same and couldn't be removed.
var fns = [];
maps.forEach(function (map, index) {
fns[index] = sync.bind(null, map, maps.filter(function (o, i) { return i !== index; }));
});
function on () {
maps.forEach(function (map, index) {
map.on('move', fns[index]);
});
}
function off () {
maps.forEach(function (map, index) {
map.off('move', fns[index]);
});
}
// When one map moves, we turn off the movement listeners
// on all the maps, move it, then turn the listeners on again
function sync (master, clones) {
off();
moveToMapPosition(master, clones);
on();
}
on();
}
|
javascript
|
function syncMaps () {
var maps;
var argLen = arguments.length;
if (argLen === 1) {
maps = arguments[0];
} else {
maps = [];
for (var i = 0; i < argLen; i++) {
maps.push(arguments[i]);
}
}
// Create all the movement functions, because if they're created every time
// they wouldn't be the same and couldn't be removed.
var fns = [];
maps.forEach(function (map, index) {
fns[index] = sync.bind(null, map, maps.filter(function (o, i) { return i !== index; }));
});
function on () {
maps.forEach(function (map, index) {
map.on('move', fns[index]);
});
}
function off () {
maps.forEach(function (map, index) {
map.off('move', fns[index]);
});
}
// When one map moves, we turn off the movement listeners
// on all the maps, move it, then turn the listeners on again
function sync (master, clones) {
off();
moveToMapPosition(master, clones);
on();
}
on();
}
|
[
"function",
"syncMaps",
"(",
")",
"{",
"var",
"maps",
";",
"var",
"argLen",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"argLen",
"===",
"1",
")",
"{",
"maps",
"=",
"arguments",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"maps",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argLen",
";",
"i",
"++",
")",
"{",
"maps",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"}",
"// Create all the movement functions, because if they're created every time",
"// they wouldn't be the same and couldn't be removed.",
"var",
"fns",
"=",
"[",
"]",
";",
"maps",
".",
"forEach",
"(",
"function",
"(",
"map",
",",
"index",
")",
"{",
"fns",
"[",
"index",
"]",
"=",
"sync",
".",
"bind",
"(",
"null",
",",
"map",
",",
"maps",
".",
"filter",
"(",
"function",
"(",
"o",
",",
"i",
")",
"{",
"return",
"i",
"!==",
"index",
";",
"}",
")",
")",
";",
"}",
")",
";",
"function",
"on",
"(",
")",
"{",
"maps",
".",
"forEach",
"(",
"function",
"(",
"map",
",",
"index",
")",
"{",
"map",
".",
"on",
"(",
"'move'",
",",
"fns",
"[",
"index",
"]",
")",
";",
"}",
")",
";",
"}",
"function",
"off",
"(",
")",
"{",
"maps",
".",
"forEach",
"(",
"function",
"(",
"map",
",",
"index",
")",
"{",
"map",
".",
"off",
"(",
"'move'",
",",
"fns",
"[",
"index",
"]",
")",
";",
"}",
")",
";",
"}",
"// When one map moves, we turn off the movement listeners",
"// on all the maps, move it, then turn the listeners on again",
"function",
"sync",
"(",
"master",
",",
"clones",
")",
"{",
"off",
"(",
")",
";",
"moveToMapPosition",
"(",
"master",
",",
"clones",
")",
";",
"on",
"(",
")",
";",
"}",
"on",
"(",
")",
";",
"}"
] |
Sync movements of two maps. All interactions that result in movement end up firing a "move" event. The trick here, though, is to ensure that movements don't cycle from one map to the other and back again, because such a cycle - could cause an infinite loop - prematurely halts prolonged movements like double-click zooming, box-zooming, and flying
|
[
"Sync",
"movements",
"of",
"two",
"maps",
".",
"All",
"interactions",
"that",
"result",
"in",
"movement",
"end",
"up",
"firing",
"a",
"move",
"event",
".",
"The",
"trick",
"here",
"though",
"is",
"to",
"ensure",
"that",
"movements",
"don",
"t",
"cycle",
"from",
"one",
"map",
"to",
"the",
"other",
"and",
"back",
"again",
"because",
"such",
"a",
"cycle",
"-",
"could",
"cause",
"an",
"infinite",
"loop",
"-",
"prematurely",
"halts",
"prolonged",
"movements",
"like",
"double",
"-",
"click",
"zooming",
"box",
"-",
"zooming",
"and",
"flying"
] |
9b3cb748d21c8785037c1830330ec33842cc0ce0
|
https://github.com/mapbox/mapbox-gl-sync-move/blob/9b3cb748d21c8785037c1830330ec33842cc0ce0/index.js#L26-L66
|
14,941
|
NGRP/node-red-contrib-viseo
|
node-red-viseo-storage-plugin/index.js
|
writeFile
|
function writeFile(path,content) {
return when.promise(function(resolve,reject) {
var stream = fs.createWriteStream(path);
stream.on('open',function(fd) {
stream.end(content,'utf8',function() {
fs.fsync(fd,resolve);
});
});
stream.on('error',function(err) {
reject(err);
});
});
}
|
javascript
|
function writeFile(path,content) {
return when.promise(function(resolve,reject) {
var stream = fs.createWriteStream(path);
stream.on('open',function(fd) {
stream.end(content,'utf8',function() {
fs.fsync(fd,resolve);
});
});
stream.on('error',function(err) {
reject(err);
});
});
}
|
[
"function",
"writeFile",
"(",
"path",
",",
"content",
")",
"{",
"return",
"when",
".",
"promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"stream",
"=",
"fs",
".",
"createWriteStream",
"(",
"path",
")",
";",
"stream",
".",
"on",
"(",
"'open'",
",",
"function",
"(",
"fd",
")",
"{",
"stream",
".",
"end",
"(",
"content",
",",
"'utf8'",
",",
"function",
"(",
")",
"{",
"fs",
".",
"fsync",
"(",
"fd",
",",
"resolve",
")",
";",
"}",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Write content to a file using UTF8 encoding.
This forces a fsync before completing to ensure
the write hits disk.
|
[
"Write",
"content",
"to",
"a",
"file",
"using",
"UTF8",
"encoding",
".",
"This",
"forces",
"a",
"fsync",
"before",
"completing",
"to",
"ensure",
"the",
"write",
"hits",
"disk",
"."
] |
1f41bd43c93efa4047062efb5ca956518b0b0fd2
|
https://github.com/NGRP/node-red-contrib-viseo/blob/1f41bd43c93efa4047062efb5ca956518b0b0fd2/node-red-viseo-storage-plugin/index.js#L110-L122
|
14,942
|
jsor/jcarousel
|
vendor/qunit/qunit.js
|
function( result, message ) {
message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
QUnit.dump.parse( result ) );
if ( !!result ) {
this.push( true, result, true, message );
} else {
this.test.pushFailure( message, null, result );
}
}
|
javascript
|
function( result, message ) {
message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
QUnit.dump.parse( result ) );
if ( !!result ) {
this.push( true, result, true, message );
} else {
this.test.pushFailure( message, null, result );
}
}
|
[
"function",
"(",
"result",
",",
"message",
")",
"{",
"message",
"=",
"message",
"||",
"(",
"result",
"?",
"\"okay\"",
":",
"\"failed, expected argument to be truthy, was: \"",
"+",
"QUnit",
".",
"dump",
".",
"parse",
"(",
"result",
")",
")",
";",
"if",
"(",
"!",
"!",
"result",
")",
"{",
"this",
".",
"push",
"(",
"true",
",",
"result",
",",
"true",
",",
"message",
")",
";",
"}",
"else",
"{",
"this",
".",
"test",
".",
"pushFailure",
"(",
"message",
",",
"null",
",",
"result",
")",
";",
"}",
"}"
] |
Asserts rough true-ish result.
@name ok
@function
@example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
|
[
"Asserts",
"rough",
"true",
"-",
"ish",
"result",
"."
] |
2265c2f189c6400e0df2f782cc078d439a20217a
|
https://github.com/jsor/jcarousel/blob/2265c2f189c6400e0df2f782cc078d439a20217a/vendor/qunit/qunit.js#L1005-L1013
|
|
14,943
|
vue-bulma/click-outside
|
index.js
|
handler
|
function handler(e) {
if (!vNode.context) return
// some components may have related popup item, on which we shall prevent the click outside event handler.
var elements = e.path || (e.composedPath && e.composedPath())
elements && elements.length > 0 && elements.unshift(e.target)
if (el.contains(e.target) || isPopup(vNode.context.popupItem, elements)) return
el.__vueClickOutside__.callback(e)
}
|
javascript
|
function handler(e) {
if (!vNode.context) return
// some components may have related popup item, on which we shall prevent the click outside event handler.
var elements = e.path || (e.composedPath && e.composedPath())
elements && elements.length > 0 && elements.unshift(e.target)
if (el.contains(e.target) || isPopup(vNode.context.popupItem, elements)) return
el.__vueClickOutside__.callback(e)
}
|
[
"function",
"handler",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"vNode",
".",
"context",
")",
"return",
"// some components may have related popup item, on which we shall prevent the click outside event handler.",
"var",
"elements",
"=",
"e",
".",
"path",
"||",
"(",
"e",
".",
"composedPath",
"&&",
"e",
".",
"composedPath",
"(",
")",
")",
"elements",
"&&",
"elements",
".",
"length",
">",
"0",
"&&",
"elements",
".",
"unshift",
"(",
"e",
".",
"target",
")",
"if",
"(",
"el",
".",
"contains",
"(",
"e",
".",
"target",
")",
"||",
"isPopup",
"(",
"vNode",
".",
"context",
".",
"popupItem",
",",
"elements",
")",
")",
"return",
"el",
".",
"__vueClickOutside__",
".",
"callback",
"(",
"e",
")",
"}"
] |
Define Handler and cache it on the element
|
[
"Define",
"Handler",
"and",
"cache",
"it",
"on",
"the",
"element"
] |
45629f43911abfe9bcba3172e2a3f723a0fa7ce5
|
https://github.com/vue-bulma/click-outside/blob/45629f43911abfe9bcba3172e2a3f723a0fa7ce5/index.js#L39-L49
|
14,944
|
eggjs/egg-core
|
lib/loader/mixin/controller.js
|
wrapClass
|
function wrapClass(Controller) {
let proto = Controller.prototype;
const ret = {};
// tracing the prototype chain
while (proto !== Object.prototype) {
const keys = Object.getOwnPropertyNames(proto);
for (const key of keys) {
// getOwnPropertyNames will return constructor
// that should be ignored
if (key === 'constructor') {
continue;
}
// skip getter, setter & non-function properties
const d = Object.getOwnPropertyDescriptor(proto, key);
// prevent to override sub method
if (is.function(d.value) && !ret.hasOwnProperty(key)) {
ret[key] = methodToMiddleware(Controller, key);
ret[key][FULLPATH] = Controller.prototype.fullPath + '#' + Controller.name + '.' + key + '()';
}
}
proto = Object.getPrototypeOf(proto);
}
return ret;
function methodToMiddleware(Controller, key) {
return function classControllerMiddleware(...args) {
const controller = new Controller(this);
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return utils.callFn(controller[key], args, controller);
};
}
}
|
javascript
|
function wrapClass(Controller) {
let proto = Controller.prototype;
const ret = {};
// tracing the prototype chain
while (proto !== Object.prototype) {
const keys = Object.getOwnPropertyNames(proto);
for (const key of keys) {
// getOwnPropertyNames will return constructor
// that should be ignored
if (key === 'constructor') {
continue;
}
// skip getter, setter & non-function properties
const d = Object.getOwnPropertyDescriptor(proto, key);
// prevent to override sub method
if (is.function(d.value) && !ret.hasOwnProperty(key)) {
ret[key] = methodToMiddleware(Controller, key);
ret[key][FULLPATH] = Controller.prototype.fullPath + '#' + Controller.name + '.' + key + '()';
}
}
proto = Object.getPrototypeOf(proto);
}
return ret;
function methodToMiddleware(Controller, key) {
return function classControllerMiddleware(...args) {
const controller = new Controller(this);
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return utils.callFn(controller[key], args, controller);
};
}
}
|
[
"function",
"wrapClass",
"(",
"Controller",
")",
"{",
"let",
"proto",
"=",
"Controller",
".",
"prototype",
";",
"const",
"ret",
"=",
"{",
"}",
";",
"// tracing the prototype chain",
"while",
"(",
"proto",
"!==",
"Object",
".",
"prototype",
")",
"{",
"const",
"keys",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"proto",
")",
";",
"for",
"(",
"const",
"key",
"of",
"keys",
")",
"{",
"// getOwnPropertyNames will return constructor",
"// that should be ignored",
"if",
"(",
"key",
"===",
"'constructor'",
")",
"{",
"continue",
";",
"}",
"// skip getter, setter & non-function properties",
"const",
"d",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"proto",
",",
"key",
")",
";",
"// prevent to override sub method",
"if",
"(",
"is",
".",
"function",
"(",
"d",
".",
"value",
")",
"&&",
"!",
"ret",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"ret",
"[",
"key",
"]",
"=",
"methodToMiddleware",
"(",
"Controller",
",",
"key",
")",
";",
"ret",
"[",
"key",
"]",
"[",
"FULLPATH",
"]",
"=",
"Controller",
".",
"prototype",
".",
"fullPath",
"+",
"'#'",
"+",
"Controller",
".",
"name",
"+",
"'.'",
"+",
"key",
"+",
"'()'",
";",
"}",
"}",
"proto",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"proto",
")",
";",
"}",
"return",
"ret",
";",
"function",
"methodToMiddleware",
"(",
"Controller",
",",
"key",
")",
"{",
"return",
"function",
"classControllerMiddleware",
"(",
"...",
"args",
")",
"{",
"const",
"controller",
"=",
"new",
"Controller",
"(",
"this",
")",
";",
"if",
"(",
"!",
"this",
".",
"app",
".",
"config",
".",
"controller",
"||",
"!",
"this",
".",
"app",
".",
"config",
".",
"controller",
".",
"supportParams",
")",
"{",
"args",
"=",
"[",
"this",
"]",
";",
"}",
"return",
"utils",
".",
"callFn",
"(",
"controller",
"[",
"key",
"]",
",",
"args",
",",
"controller",
")",
";",
"}",
";",
"}",
"}"
] |
wrap the class, yield a object with middlewares
|
[
"wrap",
"the",
"class",
"yield",
"a",
"object",
"with",
"middlewares"
] |
afa89c1b2ce89a2f8994943905172ee1bab6f77e
|
https://github.com/eggjs/egg-core/blob/afa89c1b2ce89a2f8994943905172ee1bab6f77e/lib/loader/mixin/controller.js#L57-L90
|
14,945
|
eggjs/egg-core
|
lib/loader/mixin/controller.js
|
wrapObject
|
function wrapObject(obj, path, prefix) {
const keys = Object.keys(obj);
const ret = {};
for (const key of keys) {
if (is.function(obj[key])) {
const names = utility.getParamNames(obj[key]);
if (names[0] === 'next') {
throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
}
ret[key] = functionToMiddleware(obj[key]);
ret[key][FULLPATH] = `${path}#${prefix || ''}${key}()`;
} else if (is.object(obj[key])) {
ret[key] = wrapObject(obj[key], path, `${prefix || ''}${key}.`);
}
}
return ret;
function functionToMiddleware(func) {
const objectControllerMiddleware = async function(...args) {
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return await utils.callFn(func, args, this);
};
for (const key in func) {
objectControllerMiddleware[key] = func[key];
}
return objectControllerMiddleware;
}
}
|
javascript
|
function wrapObject(obj, path, prefix) {
const keys = Object.keys(obj);
const ret = {};
for (const key of keys) {
if (is.function(obj[key])) {
const names = utility.getParamNames(obj[key]);
if (names[0] === 'next') {
throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
}
ret[key] = functionToMiddleware(obj[key]);
ret[key][FULLPATH] = `${path}#${prefix || ''}${key}()`;
} else if (is.object(obj[key])) {
ret[key] = wrapObject(obj[key], path, `${prefix || ''}${key}.`);
}
}
return ret;
function functionToMiddleware(func) {
const objectControllerMiddleware = async function(...args) {
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return await utils.callFn(func, args, this);
};
for (const key in func) {
objectControllerMiddleware[key] = func[key];
}
return objectControllerMiddleware;
}
}
|
[
"function",
"wrapObject",
"(",
"obj",
",",
"path",
",",
"prefix",
")",
"{",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"const",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"key",
"of",
"keys",
")",
"{",
"if",
"(",
"is",
".",
"function",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"const",
"names",
"=",
"utility",
".",
"getParamNames",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"if",
"(",
"names",
"[",
"0",
"]",
"===",
"'next'",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"\\`",
"${",
"prefix",
"||",
"''",
"}",
"${",
"key",
"}",
"\\`",
"${",
"path",
"}",
"`",
")",
";",
"}",
"ret",
"[",
"key",
"]",
"=",
"functionToMiddleware",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"ret",
"[",
"key",
"]",
"[",
"FULLPATH",
"]",
"=",
"`",
"${",
"path",
"}",
"${",
"prefix",
"||",
"''",
"}",
"${",
"key",
"}",
"`",
";",
"}",
"else",
"if",
"(",
"is",
".",
"object",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"ret",
"[",
"key",
"]",
"=",
"wrapObject",
"(",
"obj",
"[",
"key",
"]",
",",
"path",
",",
"`",
"${",
"prefix",
"||",
"''",
"}",
"${",
"key",
"}",
"`",
")",
";",
"}",
"}",
"return",
"ret",
";",
"function",
"functionToMiddleware",
"(",
"func",
")",
"{",
"const",
"objectControllerMiddleware",
"=",
"async",
"function",
"(",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"this",
".",
"app",
".",
"config",
".",
"controller",
"||",
"!",
"this",
".",
"app",
".",
"config",
".",
"controller",
".",
"supportParams",
")",
"{",
"args",
"=",
"[",
"this",
"]",
";",
"}",
"return",
"await",
"utils",
".",
"callFn",
"(",
"func",
",",
"args",
",",
"this",
")",
";",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"func",
")",
"{",
"objectControllerMiddleware",
"[",
"key",
"]",
"=",
"func",
"[",
"key",
"]",
";",
"}",
"return",
"objectControllerMiddleware",
";",
"}",
"}"
] |
wrap the method of the object, method can receive ctx as it's first argument
|
[
"wrap",
"the",
"method",
"of",
"the",
"object",
"method",
"can",
"receive",
"ctx",
"as",
"it",
"s",
"first",
"argument"
] |
afa89c1b2ce89a2f8994943905172ee1bab6f77e
|
https://github.com/eggjs/egg-core/blob/afa89c1b2ce89a2f8994943905172ee1bab6f77e/lib/loader/mixin/controller.js#L93-L122
|
14,946
|
austintgriffith/clevis
|
commands/update.js
|
getGasPrice
|
function getGasPrice(toWei) {
return axios.get("https://ethgasstation.info/json/ethgasAPI.json").then(response => {
//ethgasstation returns 10x the actual average for some odd reason
let actualAverage = response.data.average / 10
winston.debug(`gas price actualAverage: ${actualAverage}`)
//We want to just add a bit more than average to be speedy
let safeAmount = actualAverage + 0.1
winston.debug(`gas price safeAmount: ${safeAmount}`)
//We want to round to the tenthousandth precision
let rounded = Math.round(safeAmount * 10000) / 10000
winston.debug(`gas price rounded: ${rounded}`)
//Lets save the gas price in wei, rather than gwei, since that is how web3 expects it.
let wei = toWei(`${rounded}`, 'gwei')
winston.debug(`gas price wei: ${wei}`)
return parseInt(wei)
})
}
|
javascript
|
function getGasPrice(toWei) {
return axios.get("https://ethgasstation.info/json/ethgasAPI.json").then(response => {
//ethgasstation returns 10x the actual average for some odd reason
let actualAverage = response.data.average / 10
winston.debug(`gas price actualAverage: ${actualAverage}`)
//We want to just add a bit more than average to be speedy
let safeAmount = actualAverage + 0.1
winston.debug(`gas price safeAmount: ${safeAmount}`)
//We want to round to the tenthousandth precision
let rounded = Math.round(safeAmount * 10000) / 10000
winston.debug(`gas price rounded: ${rounded}`)
//Lets save the gas price in wei, rather than gwei, since that is how web3 expects it.
let wei = toWei(`${rounded}`, 'gwei')
winston.debug(`gas price wei: ${wei}`)
return parseInt(wei)
})
}
|
[
"function",
"getGasPrice",
"(",
"toWei",
")",
"{",
"return",
"axios",
".",
"get",
"(",
"\"https://ethgasstation.info/json/ethgasAPI.json\"",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"//ethgasstation returns 10x the actual average for some odd reason",
"let",
"actualAverage",
"=",
"response",
".",
"data",
".",
"average",
"/",
"10",
"winston",
".",
"debug",
"(",
"`",
"${",
"actualAverage",
"}",
"`",
")",
"//We want to just add a bit more than average to be speedy",
"let",
"safeAmount",
"=",
"actualAverage",
"+",
"0.1",
"winston",
".",
"debug",
"(",
"`",
"${",
"safeAmount",
"}",
"`",
")",
"//We want to round to the tenthousandth precision",
"let",
"rounded",
"=",
"Math",
".",
"round",
"(",
"safeAmount",
"*",
"10000",
")",
"/",
"10000",
"winston",
".",
"debug",
"(",
"`",
"${",
"rounded",
"}",
"`",
")",
"//Lets save the gas price in wei, rather than gwei, since that is how web3 expects it.",
"let",
"wei",
"=",
"toWei",
"(",
"`",
"${",
"rounded",
"}",
"`",
",",
"'gwei'",
")",
"winston",
".",
"debug",
"(",
"`",
"${",
"wei",
"}",
"`",
")",
"return",
"parseInt",
"(",
"wei",
")",
"}",
")",
"}"
] |
This function is way more verbose than needed on purpose The logic is not easy to understand when done as a one-liner Returns the gas price in wei
|
[
"This",
"function",
"is",
"way",
"more",
"verbose",
"than",
"needed",
"on",
"purpose",
"The",
"logic",
"is",
"not",
"easy",
"to",
"understand",
"when",
"done",
"as",
"a",
"one",
"-",
"liner",
"Returns",
"the",
"gas",
"price",
"in",
"wei"
] |
82fd29d01c5c9c5daea92acd1aa4706aa83a1dbe
|
https://github.com/austintgriffith/clevis/blob/82fd29d01c5c9c5daea92acd1aa4706aa83a1dbe/commands/update.js#L26-L46
|
14,947
|
riot/examples
|
rollup/rollup.config.js
|
cssnext
|
function cssnext (tagName, css) {
// A small hack: it passes :scope as :root to PostCSS.
// This make it easy to use css variables inside tags.
css = css.replace(/:scope/g, ':root')
css = postcss([postcssCssnext]).process(css).css
css = css.replace(/:root/g, ':scope')
return css
}
|
javascript
|
function cssnext (tagName, css) {
// A small hack: it passes :scope as :root to PostCSS.
// This make it easy to use css variables inside tags.
css = css.replace(/:scope/g, ':root')
css = postcss([postcssCssnext]).process(css).css
css = css.replace(/:root/g, ':scope')
return css
}
|
[
"function",
"cssnext",
"(",
"tagName",
",",
"css",
")",
"{",
"// A small hack: it passes :scope as :root to PostCSS.",
"// This make it easy to use css variables inside tags.",
"css",
"=",
"css",
".",
"replace",
"(",
"/",
":scope",
"/",
"g",
",",
"':root'",
")",
"css",
"=",
"postcss",
"(",
"[",
"postcssCssnext",
"]",
")",
".",
"process",
"(",
"css",
")",
".",
"css",
"css",
"=",
"css",
".",
"replace",
"(",
"/",
":root",
"/",
"g",
",",
"':scope'",
")",
"return",
"css",
"}"
] |
Transforms new CSS specs into more compatible CSS
|
[
"Transforms",
"new",
"CSS",
"specs",
"into",
"more",
"compatible",
"CSS"
] |
1d53dd949682538e194f91a64f174e421e78596a
|
https://github.com/riot/examples/blob/1d53dd949682538e194f91a64f174e421e78596a/rollup/rollup.config.js#L29-L36
|
14,948
|
webpack-contrib/i18n-webpack-plugin
|
src/MakeLocalizeFunction.js
|
makeLocalizeFunction
|
function makeLocalizeFunction(localization, nested) {
return function localizeFunction(key) {
return nested ? byString(localization, key) : localization[key];
};
}
|
javascript
|
function makeLocalizeFunction(localization, nested) {
return function localizeFunction(key) {
return nested ? byString(localization, key) : localization[key];
};
}
|
[
"function",
"makeLocalizeFunction",
"(",
"localization",
",",
"nested",
")",
"{",
"return",
"function",
"localizeFunction",
"(",
"key",
")",
"{",
"return",
"nested",
"?",
"byString",
"(",
"localization",
",",
"key",
")",
":",
"localization",
"[",
"key",
"]",
";",
"}",
";",
"}"
] |
Convert the localization object into a function in case we need to support nested keys.
@param {Object} localization the language object,
@param {Boolean} nested
@returns {Function}
|
[
"Convert",
"the",
"localization",
"object",
"into",
"a",
"function",
"in",
"case",
"we",
"need",
"to",
"support",
"nested",
"keys",
"."
] |
930100a93e1a7009d3f5e128287395c43e12f94d
|
https://github.com/webpack-contrib/i18n-webpack-plugin/blob/930100a93e1a7009d3f5e128287395c43e12f94d/src/MakeLocalizeFunction.js#L9-L13
|
14,949
|
webpack-contrib/i18n-webpack-plugin
|
src/MakeLocalizeFunction.js
|
byString
|
function byString(localization, nestedKey) {
// remove a leading dot and split by dot
const keys = nestedKey.replace(/^\./, '').split('.');
// loop through the keys to find the nested value
for (let i = 0, length = keys.length; i < length; ++i) {
const key = keys[i];
if (!(key in localization)) { return; }
localization = localization[key];
}
return localization;
}
|
javascript
|
function byString(localization, nestedKey) {
// remove a leading dot and split by dot
const keys = nestedKey.replace(/^\./, '').split('.');
// loop through the keys to find the nested value
for (let i = 0, length = keys.length; i < length; ++i) {
const key = keys[i];
if (!(key in localization)) { return; }
localization = localization[key];
}
return localization;
}
|
[
"function",
"byString",
"(",
"localization",
",",
"nestedKey",
")",
"{",
"// remove a leading dot and split by dot",
"const",
"keys",
"=",
"nestedKey",
".",
"replace",
"(",
"/",
"^\\.",
"/",
",",
"''",
")",
".",
"split",
"(",
"'.'",
")",
";",
"// loop through the keys to find the nested value",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"length",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"length",
";",
"++",
"i",
")",
"{",
"const",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"(",
"key",
"in",
"localization",
")",
")",
"{",
"return",
";",
"}",
"localization",
"=",
"localization",
"[",
"key",
"]",
";",
"}",
"return",
"localization",
";",
"}"
] |
Find the key if the key is a path expressed with dots
e.g.
Code: __("errors.connectionError")
Lang: {"errors": {"connectionError": "There was an error connecting."}}
New Code: "There was an error connecting."
@param {Object} localization
@param {String} nestedKey The original key
@returns {*}
|
[
"Find",
"the",
"key",
"if",
"the",
"key",
"is",
"a",
"path",
"expressed",
"with",
"dots"
] |
930100a93e1a7009d3f5e128287395c43e12f94d
|
https://github.com/webpack-contrib/i18n-webpack-plugin/blob/930100a93e1a7009d3f5e128287395c43e12f94d/src/MakeLocalizeFunction.js#L28-L42
|
14,950
|
tj/node-delegates
|
index.js
|
Delegator
|
function Delegator(proto, target) {
if (!(this instanceof Delegator)) return new Delegator(proto, target);
this.proto = proto;
this.target = target;
this.methods = [];
this.getters = [];
this.setters = [];
this.fluents = [];
}
|
javascript
|
function Delegator(proto, target) {
if (!(this instanceof Delegator)) return new Delegator(proto, target);
this.proto = proto;
this.target = target;
this.methods = [];
this.getters = [];
this.setters = [];
this.fluents = [];
}
|
[
"function",
"Delegator",
"(",
"proto",
",",
"target",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Delegator",
")",
")",
"return",
"new",
"Delegator",
"(",
"proto",
",",
"target",
")",
";",
"this",
".",
"proto",
"=",
"proto",
";",
"this",
".",
"target",
"=",
"target",
";",
"this",
".",
"methods",
"=",
"[",
"]",
";",
"this",
".",
"getters",
"=",
"[",
"]",
";",
"this",
".",
"setters",
"=",
"[",
"]",
";",
"this",
".",
"fluents",
"=",
"[",
"]",
";",
"}"
] |
Initialize a delegator.
@param {Object} proto
@param {String} target
@api public
|
[
"Initialize",
"a",
"delegator",
"."
] |
01086138281bad311bc162ce80f98be59bce18ce
|
https://github.com/tj/node-delegates/blob/01086138281bad311bc162ce80f98be59bce18ce/index.js#L16-L24
|
14,951
|
jaredhanson/passport-remember-me
|
lib/strategy.js
|
issued
|
function issued(err, val) {
if (err) { return self.error(err); }
res.cookie(self._key, val, self._opts);
return self.success(user, info);
}
|
javascript
|
function issued(err, val) {
if (err) { return self.error(err); }
res.cookie(self._key, val, self._opts);
return self.success(user, info);
}
|
[
"function",
"issued",
"(",
"err",
",",
"val",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"self",
".",
"error",
"(",
"err",
")",
";",
"}",
"res",
".",
"cookie",
"(",
"self",
".",
"_key",
",",
"val",
",",
"self",
".",
"_opts",
")",
";",
"return",
"self",
".",
"success",
"(",
"user",
",",
"info",
")",
";",
"}"
] |
The remember me cookie was valid and consumed. For security reasons, the just-used token should have been invalidated by the application. A new token will be issued and set as the value of the remember me cookie.
|
[
"The",
"remember",
"me",
"cookie",
"was",
"valid",
"and",
"consumed",
".",
"For",
"security",
"reasons",
"the",
"just",
"-",
"used",
"token",
"should",
"have",
"been",
"invalidated",
"by",
"the",
"application",
".",
"A",
"new",
"token",
"will",
"be",
"issued",
"and",
"set",
"as",
"the",
"value",
"of",
"the",
"remember",
"me",
"cookie",
"."
] |
255d5506a1fcef57b13de31e742c67a580899819
|
https://github.com/jaredhanson/passport-remember-me/blob/255d5506a1fcef57b13de31e742c67a580899819/lib/strategy.js#L91-L95
|
14,952
|
vanevery/p5.serialport
|
examples/readAndAnimate/sketch.js
|
gotData
|
function gotData() {
var currentString = serial.readLine(); // read the incoming data
trim(currentString); // trim off trailing whitespace
if (!currentString) return; // if the incoming string is empty, do no more
console.log(currentString);
if (!isNaN(currentString)) { // make sure the string is a number (i.e. NOT Not a Number (NaN))
textXpos = currentString; // save the currentString to use for the text position in draw()
}
}
|
javascript
|
function gotData() {
var currentString = serial.readLine(); // read the incoming data
trim(currentString); // trim off trailing whitespace
if (!currentString) return; // if the incoming string is empty, do no more
console.log(currentString);
if (!isNaN(currentString)) { // make sure the string is a number (i.e. NOT Not a Number (NaN))
textXpos = currentString; // save the currentString to use for the text position in draw()
}
}
|
[
"function",
"gotData",
"(",
")",
"{",
"var",
"currentString",
"=",
"serial",
".",
"readLine",
"(",
")",
";",
"// read the incoming data",
"trim",
"(",
"currentString",
")",
";",
"// trim off trailing whitespace",
"if",
"(",
"!",
"currentString",
")",
"return",
";",
"// if the incoming string is empty, do no more",
"console",
".",
"log",
"(",
"currentString",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"currentString",
")",
")",
"{",
"// make sure the string is a number (i.e. NOT Not a Number (NaN))",
"textXpos",
"=",
"currentString",
";",
"// save the currentString to use for the text position in draw()",
"}",
"}"
] |
Called when there is data available from the serial port
|
[
"Called",
"when",
"there",
"is",
"data",
"available",
"from",
"the",
"serial",
"port"
] |
0369e337297679ab96b07d67b1d600da9d1999eb
|
https://github.com/vanevery/p5.serialport/blob/0369e337297679ab96b07d67b1d600da9d1999eb/examples/readAndAnimate/sketch.js#L52-L60
|
14,953
|
vanevery/p5.serialport
|
examples/basics/sketch.js
|
setup
|
function setup() {
createCanvas(windowWidth, windowHeight);
// Instantiate our SerialPort object
serial = new p5.SerialPort();
// Get a list the ports available
// You should have a callback defined to see the results
serial.list();
// Assuming our Arduino is connected, let's open the connection to it
// Change this to the name of your arduino's serial port
serial.open("/dev/cu.usbmodem1411");
// Here are the callbacks that you can register
// When we connect to the underlying server
serial.on('connected', serverConnected);
// When we get a list of serial ports that are available
serial.on('list', gotList);
// OR
//serial.onList(gotList);
// When we some data from the serial port
serial.on('data', gotData);
// OR
//serial.onData(gotData);
// When or if we get an error
serial.on('error', gotError);
// OR
//serial.onError(gotError);
// When our serial port is opened and ready for read/write
serial.on('open', gotOpen);
// OR
//serial.onOpen(gotOpen);
// Callback to get the raw data, as it comes in for handling yourself
//serial.on('rawdata', gotRawData);
// OR
//serial.onRawData(gotRawData);
}
|
javascript
|
function setup() {
createCanvas(windowWidth, windowHeight);
// Instantiate our SerialPort object
serial = new p5.SerialPort();
// Get a list the ports available
// You should have a callback defined to see the results
serial.list();
// Assuming our Arduino is connected, let's open the connection to it
// Change this to the name of your arduino's serial port
serial.open("/dev/cu.usbmodem1411");
// Here are the callbacks that you can register
// When we connect to the underlying server
serial.on('connected', serverConnected);
// When we get a list of serial ports that are available
serial.on('list', gotList);
// OR
//serial.onList(gotList);
// When we some data from the serial port
serial.on('data', gotData);
// OR
//serial.onData(gotData);
// When or if we get an error
serial.on('error', gotError);
// OR
//serial.onError(gotError);
// When our serial port is opened and ready for read/write
serial.on('open', gotOpen);
// OR
//serial.onOpen(gotOpen);
// Callback to get the raw data, as it comes in for handling yourself
//serial.on('rawdata', gotRawData);
// OR
//serial.onRawData(gotRawData);
}
|
[
"function",
"setup",
"(",
")",
"{",
"createCanvas",
"(",
"windowWidth",
",",
"windowHeight",
")",
";",
"// Instantiate our SerialPort object",
"serial",
"=",
"new",
"p5",
".",
"SerialPort",
"(",
")",
";",
"// Get a list the ports available",
"// You should have a callback defined to see the results",
"serial",
".",
"list",
"(",
")",
";",
"// Assuming our Arduino is connected, let's open the connection to it",
"// Change this to the name of your arduino's serial port",
"serial",
".",
"open",
"(",
"\"/dev/cu.usbmodem1411\"",
")",
";",
"// Here are the callbacks that you can register",
"// When we connect to the underlying server",
"serial",
".",
"on",
"(",
"'connected'",
",",
"serverConnected",
")",
";",
"// When we get a list of serial ports that are available",
"serial",
".",
"on",
"(",
"'list'",
",",
"gotList",
")",
";",
"// OR",
"//serial.onList(gotList);",
"// When we some data from the serial port",
"serial",
".",
"on",
"(",
"'data'",
",",
"gotData",
")",
";",
"// OR",
"//serial.onData(gotData);",
"// When or if we get an error",
"serial",
".",
"on",
"(",
"'error'",
",",
"gotError",
")",
";",
"// OR",
"//serial.onError(gotError);",
"// When our serial port is opened and ready for read/write",
"serial",
".",
"on",
"(",
"'open'",
",",
"gotOpen",
")",
";",
"// OR",
"//serial.onOpen(gotOpen);",
"// Callback to get the raw data, as it comes in for handling yourself",
"//serial.on('rawdata', gotRawData);",
"// OR",
"//serial.onRawData(gotRawData);",
"}"
] |
you'll use this to write incoming data to the canvas
|
[
"you",
"ll",
"use",
"this",
"to",
"write",
"incoming",
"data",
"to",
"the",
"canvas"
] |
0369e337297679ab96b07d67b1d600da9d1999eb
|
https://github.com/vanevery/p5.serialport/blob/0369e337297679ab96b07d67b1d600da9d1999eb/examples/basics/sketch.js#L5-L48
|
14,954
|
vanevery/p5.serialport
|
examples/basics/sketch.js
|
gotData
|
function gotData() {
var currentString = serial.readLine(); // read the incoming string
trim(currentString); // remove any trailing whitespace
if (!currentString) return; // if the string is empty, do no more
console.log(currentString); // println the string
latestData = currentString; // save it for the draw method
}
|
javascript
|
function gotData() {
var currentString = serial.readLine(); // read the incoming string
trim(currentString); // remove any trailing whitespace
if (!currentString) return; // if the string is empty, do no more
console.log(currentString); // println the string
latestData = currentString; // save it for the draw method
}
|
[
"function",
"gotData",
"(",
")",
"{",
"var",
"currentString",
"=",
"serial",
".",
"readLine",
"(",
")",
";",
"// read the incoming string",
"trim",
"(",
"currentString",
")",
";",
"// remove any trailing whitespace",
"if",
"(",
"!",
"currentString",
")",
"return",
";",
"// if the string is empty, do no more",
"console",
".",
"log",
"(",
"currentString",
")",
";",
"// println the string",
"latestData",
"=",
"currentString",
";",
"// save it for the draw method",
"}"
] |
There is data available to work with from the serial port
|
[
"There",
"is",
"data",
"available",
"to",
"work",
"with",
"from",
"the",
"serial",
"port"
] |
0369e337297679ab96b07d67b1d600da9d1999eb
|
https://github.com/vanevery/p5.serialport/blob/0369e337297679ab96b07d67b1d600da9d1999eb/examples/basics/sketch.js#L76-L82
|
14,955
|
jonycheung/deadsimple-less-watch-compiler
|
src/lib/lessWatchCompilerUtils.js
|
function (f) {
var filename = path.basename(f);
var extension = path.extname(f),
allowedExtensions = lessWatchCompilerUtilsModule.config.allowedExtensions || defaultAllowedExtensions;
if (filename.substr(0, 1) == '_' ||
filename.substr(0, 1) == '.' ||
filename == '' ||
allowedExtensions.indexOf(extension) == -1
)
return true;
else {
return false;
}
}
|
javascript
|
function (f) {
var filename = path.basename(f);
var extension = path.extname(f),
allowedExtensions = lessWatchCompilerUtilsModule.config.allowedExtensions || defaultAllowedExtensions;
if (filename.substr(0, 1) == '_' ||
filename.substr(0, 1) == '.' ||
filename == '' ||
allowedExtensions.indexOf(extension) == -1
)
return true;
else {
return false;
}
}
|
[
"function",
"(",
"f",
")",
"{",
"var",
"filename",
"=",
"path",
".",
"basename",
"(",
"f",
")",
";",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"f",
")",
",",
"allowedExtensions",
"=",
"lessWatchCompilerUtilsModule",
".",
"config",
".",
"allowedExtensions",
"||",
"defaultAllowedExtensions",
";",
"if",
"(",
"filename",
".",
"substr",
"(",
"0",
",",
"1",
")",
"==",
"'_'",
"||",
"filename",
".",
"substr",
"(",
"0",
",",
"1",
")",
"==",
"'.'",
"||",
"filename",
"==",
"''",
"||",
"allowedExtensions",
".",
"indexOf",
"(",
"extension",
")",
"==",
"-",
"1",
")",
"return",
"true",
";",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
This is the function we use to filter the files to watch.
|
[
"This",
"is",
"the",
"function",
"we",
"use",
"to",
"filter",
"the",
"files",
"to",
"watch",
"."
] |
678867c733de91bb72ba8ce63d7bf5d31d9f966a
|
https://github.com/jonycheung/deadsimple-less-watch-compiler/blob/678867c733de91bb72ba8ce63d7bf5d31d9f966a/src/lib/lessWatchCompilerUtils.js#L153-L166
|
|
14,956
|
anselmh/object-fit
|
dist/polyfill.object-fit.js
|
function (list) {
var items = [];
var i = 0;
var listLength = list.length;
for (; i < listLength; i++) {
items.push(list[i]);
}
return items;
}
|
javascript
|
function (list) {
var items = [];
var i = 0;
var listLength = list.length;
for (; i < listLength; i++) {
items.push(list[i]);
}
return items;
}
|
[
"function",
"(",
"list",
")",
"{",
"var",
"items",
"=",
"[",
"]",
";",
"var",
"i",
"=",
"0",
";",
"var",
"listLength",
"=",
"list",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"listLength",
";",
"i",
"++",
")",
"{",
"items",
".",
"push",
"(",
"list",
"[",
"i",
"]",
")",
";",
"}",
"return",
"items",
";",
"}"
] |
convert an array-like object to array
|
[
"convert",
"an",
"array",
"-",
"like",
"object",
"to",
"array"
] |
c6e275b099caf59ca44bfc5cbbaf4c388ace9980
|
https://github.com/anselmh/object-fit/blob/c6e275b099caf59ca44bfc5cbbaf4c388ace9980/dist/polyfill.object-fit.js#L57-L67
|
|
14,957
|
anselmh/object-fit
|
dist/polyfill.object-fit.js
|
function (stylesheet) {
var sheetMedia = stylesheet.media && stylesheet.media.mediaText;
var sheetHost;
// if this sheet is cross-origin and option is set skip it
if (objectFit.disableCrossDomain == 'true') {
sheetHost = getCSSHost(stylesheet.href);
if ((sheetHost !== window.location.host)) {
return [];
}
}
// if this sheet is disabled skip it
if (stylesheet.disabled) {
return [];
}
if (!window.matchMedia) {
if (sheetMedia && sheetMedia.length) {
return [];
}
}
// if this sheet's media is specified and doesn't match the viewport then skip it
else if (sheetMedia && sheetMedia.length && ! window.matchMedia(sheetMedia).matches) {
return [];
}
// get the style rules of this sheet
return toArray(stylesheet.cssRules);
}
|
javascript
|
function (stylesheet) {
var sheetMedia = stylesheet.media && stylesheet.media.mediaText;
var sheetHost;
// if this sheet is cross-origin and option is set skip it
if (objectFit.disableCrossDomain == 'true') {
sheetHost = getCSSHost(stylesheet.href);
if ((sheetHost !== window.location.host)) {
return [];
}
}
// if this sheet is disabled skip it
if (stylesheet.disabled) {
return [];
}
if (!window.matchMedia) {
if (sheetMedia && sheetMedia.length) {
return [];
}
}
// if this sheet's media is specified and doesn't match the viewport then skip it
else if (sheetMedia && sheetMedia.length && ! window.matchMedia(sheetMedia).matches) {
return [];
}
// get the style rules of this sheet
return toArray(stylesheet.cssRules);
}
|
[
"function",
"(",
"stylesheet",
")",
"{",
"var",
"sheetMedia",
"=",
"stylesheet",
".",
"media",
"&&",
"stylesheet",
".",
"media",
".",
"mediaText",
";",
"var",
"sheetHost",
";",
"// if this sheet is cross-origin and option is set skip it",
"if",
"(",
"objectFit",
".",
"disableCrossDomain",
"==",
"'true'",
")",
"{",
"sheetHost",
"=",
"getCSSHost",
"(",
"stylesheet",
".",
"href",
")",
";",
"if",
"(",
"(",
"sheetHost",
"!==",
"window",
".",
"location",
".",
"host",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}",
"// if this sheet is disabled skip it",
"if",
"(",
"stylesheet",
".",
"disabled",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"window",
".",
"matchMedia",
")",
"{",
"if",
"(",
"sheetMedia",
"&&",
"sheetMedia",
".",
"length",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}",
"// if this sheet's media is specified and doesn't match the viewport then skip it",
"else",
"if",
"(",
"sheetMedia",
"&&",
"sheetMedia",
".",
"length",
"&&",
"!",
"window",
".",
"matchMedia",
"(",
"sheetMedia",
")",
".",
"matches",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// get the style rules of this sheet",
"return",
"toArray",
"(",
"stylesheet",
".",
"cssRules",
")",
";",
"}"
] |
handles extraction of `cssRules` as an `Array` from a stylesheet or something that behaves the same
|
[
"handles",
"extraction",
"of",
"cssRules",
"as",
"an",
"Array",
"from",
"a",
"stylesheet",
"or",
"something",
"that",
"behaves",
"the",
"same"
] |
c6e275b099caf59ca44bfc5cbbaf4c388ace9980
|
https://github.com/anselmh/object-fit/blob/c6e275b099caf59ca44bfc5cbbaf4c388ace9980/dist/polyfill.object-fit.js#L79-L110
|
|
14,958
|
anselmh/object-fit
|
dist/polyfill.object-fit.js
|
function (selector) {
var score = [0, 0, 0];
var parts = selector.split(' ');
var part;
var match;
//TODO: clean the ':not' part since the last ELEMENT_RE will pick it up
while (part = parts.shift(), typeof part === 'string') {
// find all pseudo-elements
match = _find(part, PSEUDO_ELEMENTS_RE);
score[2] = match;
// and remove them
match && (part = part.replace(PSEUDO_ELEMENTS_RE, ''));
// find all pseudo-classes
match = _find(part, PSEUDO_CLASSES_RE);
score[1] = match;
// and remove them
match && (part = part.replace(PSEUDO_CLASSES_RE, ''));
// find all attributes
match = _find(part, ATTR_RE);
score[1] += match;
// and remove them
match && (part = part.replace(ATTR_RE, ''));
// find all IDs
match = _find(part, ID_RE);
score[0] = match;
// and remove them
match && (part = part.replace(ID_RE, ''));
// find all classes
match = _find(part, CLASS_RE);
score[1] += match;
// and remove them
match && (part = part.replace(CLASS_RE, ''));
// find all elements
score[2] += _find(part, ELEMENT_RE);
}
return parseInt(score.join(''), 10);
}
|
javascript
|
function (selector) {
var score = [0, 0, 0];
var parts = selector.split(' ');
var part;
var match;
//TODO: clean the ':not' part since the last ELEMENT_RE will pick it up
while (part = parts.shift(), typeof part === 'string') {
// find all pseudo-elements
match = _find(part, PSEUDO_ELEMENTS_RE);
score[2] = match;
// and remove them
match && (part = part.replace(PSEUDO_ELEMENTS_RE, ''));
// find all pseudo-classes
match = _find(part, PSEUDO_CLASSES_RE);
score[1] = match;
// and remove them
match && (part = part.replace(PSEUDO_CLASSES_RE, ''));
// find all attributes
match = _find(part, ATTR_RE);
score[1] += match;
// and remove them
match && (part = part.replace(ATTR_RE, ''));
// find all IDs
match = _find(part, ID_RE);
score[0] = match;
// and remove them
match && (part = part.replace(ID_RE, ''));
// find all classes
match = _find(part, CLASS_RE);
score[1] += match;
// and remove them
match && (part = part.replace(CLASS_RE, ''));
// find all elements
score[2] += _find(part, ELEMENT_RE);
}
return parseInt(score.join(''), 10);
}
|
[
"function",
"(",
"selector",
")",
"{",
"var",
"score",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
";",
"var",
"parts",
"=",
"selector",
".",
"split",
"(",
"' '",
")",
";",
"var",
"part",
";",
"var",
"match",
";",
"//TODO: clean the ':not' part since the last ELEMENT_RE will pick it up",
"while",
"(",
"part",
"=",
"parts",
".",
"shift",
"(",
")",
",",
"typeof",
"part",
"===",
"'string'",
")",
"{",
"// find all pseudo-elements",
"match",
"=",
"_find",
"(",
"part",
",",
"PSEUDO_ELEMENTS_RE",
")",
";",
"score",
"[",
"2",
"]",
"=",
"match",
";",
"// and remove them",
"match",
"&&",
"(",
"part",
"=",
"part",
".",
"replace",
"(",
"PSEUDO_ELEMENTS_RE",
",",
"''",
")",
")",
";",
"// find all pseudo-classes",
"match",
"=",
"_find",
"(",
"part",
",",
"PSEUDO_CLASSES_RE",
")",
";",
"score",
"[",
"1",
"]",
"=",
"match",
";",
"// and remove them",
"match",
"&&",
"(",
"part",
"=",
"part",
".",
"replace",
"(",
"PSEUDO_CLASSES_RE",
",",
"''",
")",
")",
";",
"// find all attributes",
"match",
"=",
"_find",
"(",
"part",
",",
"ATTR_RE",
")",
";",
"score",
"[",
"1",
"]",
"+=",
"match",
";",
"// and remove them",
"match",
"&&",
"(",
"part",
"=",
"part",
".",
"replace",
"(",
"ATTR_RE",
",",
"''",
")",
")",
";",
"// find all IDs",
"match",
"=",
"_find",
"(",
"part",
",",
"ID_RE",
")",
";",
"score",
"[",
"0",
"]",
"=",
"match",
";",
"// and remove them",
"match",
"&&",
"(",
"part",
"=",
"part",
".",
"replace",
"(",
"ID_RE",
",",
"''",
")",
")",
";",
"// find all classes",
"match",
"=",
"_find",
"(",
"part",
",",
"CLASS_RE",
")",
";",
"score",
"[",
"1",
"]",
"+=",
"match",
";",
"// and remove them",
"match",
"&&",
"(",
"part",
"=",
"part",
".",
"replace",
"(",
"CLASS_RE",
",",
"''",
")",
")",
";",
"// find all elements",
"score",
"[",
"2",
"]",
"+=",
"_find",
"(",
"part",
",",
"ELEMENT_RE",
")",
";",
"}",
"return",
"parseInt",
"(",
"score",
".",
"join",
"(",
"''",
")",
",",
"10",
")",
";",
"}"
] |
calculates the specificity of a given `selector`
|
[
"calculates",
"the",
"specificity",
"of",
"a",
"given",
"selector"
] |
c6e275b099caf59ca44bfc5cbbaf4c388ace9980
|
https://github.com/anselmh/object-fit/blob/c6e275b099caf59ca44bfc5cbbaf4c388ace9980/dist/polyfill.object-fit.js#L119-L157
|
|
14,959
|
anselmh/object-fit
|
dist/polyfill.object-fit.js
|
function (a, b) {
return getSpecificityScore(element, b.selectorText) - getSpecificityScore(element, a.selectorText);
}
|
javascript
|
function (a, b) {
return getSpecificityScore(element, b.selectorText) - getSpecificityScore(element, a.selectorText);
}
|
[
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"getSpecificityScore",
"(",
"element",
",",
"b",
".",
"selectorText",
")",
"-",
"getSpecificityScore",
"(",
"element",
",",
"a",
".",
"selectorText",
")",
";",
"}"
] |
comparing function that sorts CSSStyleRules according to specificity of their `selectorText`
|
[
"comparing",
"function",
"that",
"sorts",
"CSSStyleRules",
"according",
"to",
"specificity",
"of",
"their",
"selectorText"
] |
c6e275b099caf59ca44bfc5cbbaf4c388ace9980
|
https://github.com/anselmh/object-fit/blob/c6e275b099caf59ca44bfc5cbbaf4c388ace9980/dist/polyfill.object-fit.js#L176-L178
|
|
14,960
|
mapbox/node-mbtiles
|
lib/mbtiles.js
|
tms2zxy
|
function tms2zxy(zxys) {
return zxys.split(',').map(function(tms) {
var zxy = tms.split('/').map(function(v) { return parseInt(v, 10); });
zxy[2] = (1 << zxy[0]) - 1 - zxy[2];
return zxy.join('/');
});
}
|
javascript
|
function tms2zxy(zxys) {
return zxys.split(',').map(function(tms) {
var zxy = tms.split('/').map(function(v) { return parseInt(v, 10); });
zxy[2] = (1 << zxy[0]) - 1 - zxy[2];
return zxy.join('/');
});
}
|
[
"function",
"tms2zxy",
"(",
"zxys",
")",
"{",
"return",
"zxys",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"function",
"(",
"tms",
")",
"{",
"var",
"zxy",
"=",
"tms",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"parseInt",
"(",
"v",
",",
"10",
")",
";",
"}",
")",
";",
"zxy",
"[",
"2",
"]",
"=",
"(",
"1",
"<<",
"zxy",
"[",
"0",
"]",
")",
"-",
"1",
"-",
"zxy",
"[",
"2",
"]",
";",
"return",
"zxy",
".",
"join",
"(",
"'/'",
")",
";",
"}",
")",
";",
"}"
] |
Converts MBTiles native TMS coords to ZXY.
|
[
"Converts",
"MBTiles",
"native",
"TMS",
"coords",
"to",
"ZXY",
"."
] |
681f4cca31c40aae8f6130056a180008cd13d002
|
https://github.com/mapbox/node-mbtiles/blob/681f4cca31c40aae8f6130056a180008cd13d002/lib/mbtiles.js#L769-L775
|
14,961
|
gheeres/node-activedirectory
|
lib/models/user.js
|
function(properties) {
if (this instanceof User) {
for (var property in (properties || {})) {
if (Array.prototype.hasOwnProperty.call(properties, property)) {
this[property] = properties[property];
}
}
}
else {
return(new User(properties));
}
}
|
javascript
|
function(properties) {
if (this instanceof User) {
for (var property in (properties || {})) {
if (Array.prototype.hasOwnProperty.call(properties, property)) {
this[property] = properties[property];
}
}
}
else {
return(new User(properties));
}
}
|
[
"function",
"(",
"properties",
")",
"{",
"if",
"(",
"this",
"instanceof",
"User",
")",
"{",
"for",
"(",
"var",
"property",
"in",
"(",
"properties",
"||",
"{",
"}",
")",
")",
"{",
"if",
"(",
"Array",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"properties",
",",
"property",
")",
")",
"{",
"this",
"[",
"property",
"]",
"=",
"properties",
"[",
"property",
"]",
";",
"}",
"}",
"}",
"else",
"{",
"return",
"(",
"new",
"User",
"(",
"properties",
")",
")",
";",
"}",
"}"
] |
Represents an ActiveDirectory user account.
@private
@param {Object} [properties] The properties to assign to the newly created item.
@returns {User}
|
[
"Represents",
"an",
"ActiveDirectory",
"user",
"account",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/models/user.js#L10-L21
|
|
14,962
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
function(url, baseDN, username, password, defaults) {
if (this instanceof ActiveDirectory) {
this.opts = {};
if (typeof(url) === 'string') {
this.opts.url = url;
this.baseDN = baseDN;
this.opts.bindDN = username;
this.opts.bindCredentials = password;
if (typeof((defaults || {}).entryParser) === 'function') {
this.opts.entryParser = defaults.entryParser;
}
}
else {
this.opts = _.defaults({}, url);
this.baseDN = this.opts.baseDN;
if (! this.opts.bindDN) this.opts.bindDN = this.opts.username;
if (! this.opts.bindCredentials) this.opts.bindCredentials = this.opts.password;
if (this.opts.logging) {
log = bunyan.createLogger(_.defaults({}, this.opts.logging));
delete(this.opts.logging);
}
}
defaultAttributes = _.extend({}, originalDefaultAttributes, (this.opts || {}).attributes || {}, (defaults || {}).attributes || {});
defaultReferrals = _.extend({}, originalDefaultReferrals, (this.opts || {}).referrals || {}, (defaults || {}).referrals || {});
log.info('Using username/password (%s/%s) to bind to ActiveDirectory (%s).', this.opts.bindDN,
isPasswordLoggingEnabled ? this.opts.bindCredentials : '********', this.opts.url);
log.info('Referrals are %s', defaultReferrals.enabled ? 'enabled. Exclusions: '+JSON.stringify(defaultReferrals.exclude): 'disabled');
log.info('Default user attributes: %j', defaultAttributes.user || []);
log.info('Default group attributes: %j', defaultAttributes.group || []);
// Enable connection pooling
// TODO: To be disabled / removed in future release of ldapjs > 0.7.1
if (typeof(this.opts.maxConnections) === 'undefined') {
this.opts.maxConnections = 20;
}
events.EventEmitter.call(this);
}
else {
return(new ActiveDirectory(url, baseDN, username, password, defaults));
}
}
|
javascript
|
function(url, baseDN, username, password, defaults) {
if (this instanceof ActiveDirectory) {
this.opts = {};
if (typeof(url) === 'string') {
this.opts.url = url;
this.baseDN = baseDN;
this.opts.bindDN = username;
this.opts.bindCredentials = password;
if (typeof((defaults || {}).entryParser) === 'function') {
this.opts.entryParser = defaults.entryParser;
}
}
else {
this.opts = _.defaults({}, url);
this.baseDN = this.opts.baseDN;
if (! this.opts.bindDN) this.opts.bindDN = this.opts.username;
if (! this.opts.bindCredentials) this.opts.bindCredentials = this.opts.password;
if (this.opts.logging) {
log = bunyan.createLogger(_.defaults({}, this.opts.logging));
delete(this.opts.logging);
}
}
defaultAttributes = _.extend({}, originalDefaultAttributes, (this.opts || {}).attributes || {}, (defaults || {}).attributes || {});
defaultReferrals = _.extend({}, originalDefaultReferrals, (this.opts || {}).referrals || {}, (defaults || {}).referrals || {});
log.info('Using username/password (%s/%s) to bind to ActiveDirectory (%s).', this.opts.bindDN,
isPasswordLoggingEnabled ? this.opts.bindCredentials : '********', this.opts.url);
log.info('Referrals are %s', defaultReferrals.enabled ? 'enabled. Exclusions: '+JSON.stringify(defaultReferrals.exclude): 'disabled');
log.info('Default user attributes: %j', defaultAttributes.user || []);
log.info('Default group attributes: %j', defaultAttributes.group || []);
// Enable connection pooling
// TODO: To be disabled / removed in future release of ldapjs > 0.7.1
if (typeof(this.opts.maxConnections) === 'undefined') {
this.opts.maxConnections = 20;
}
events.EventEmitter.call(this);
}
else {
return(new ActiveDirectory(url, baseDN, username, password, defaults));
}
}
|
[
"function",
"(",
"url",
",",
"baseDN",
",",
"username",
",",
"password",
",",
"defaults",
")",
"{",
"if",
"(",
"this",
"instanceof",
"ActiveDirectory",
")",
"{",
"this",
".",
"opts",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"(",
"url",
")",
"===",
"'string'",
")",
"{",
"this",
".",
"opts",
".",
"url",
"=",
"url",
";",
"this",
".",
"baseDN",
"=",
"baseDN",
";",
"this",
".",
"opts",
".",
"bindDN",
"=",
"username",
";",
"this",
".",
"opts",
".",
"bindCredentials",
"=",
"password",
";",
"if",
"(",
"typeof",
"(",
"(",
"defaults",
"||",
"{",
"}",
")",
".",
"entryParser",
")",
"===",
"'function'",
")",
"{",
"this",
".",
"opts",
".",
"entryParser",
"=",
"defaults",
".",
"entryParser",
";",
"}",
"}",
"else",
"{",
"this",
".",
"opts",
"=",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"url",
")",
";",
"this",
".",
"baseDN",
"=",
"this",
".",
"opts",
".",
"baseDN",
";",
"if",
"(",
"!",
"this",
".",
"opts",
".",
"bindDN",
")",
"this",
".",
"opts",
".",
"bindDN",
"=",
"this",
".",
"opts",
".",
"username",
";",
"if",
"(",
"!",
"this",
".",
"opts",
".",
"bindCredentials",
")",
"this",
".",
"opts",
".",
"bindCredentials",
"=",
"this",
".",
"opts",
".",
"password",
";",
"if",
"(",
"this",
".",
"opts",
".",
"logging",
")",
"{",
"log",
"=",
"bunyan",
".",
"createLogger",
"(",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"this",
".",
"opts",
".",
"logging",
")",
")",
";",
"delete",
"(",
"this",
".",
"opts",
".",
"logging",
")",
";",
"}",
"}",
"defaultAttributes",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"originalDefaultAttributes",
",",
"(",
"this",
".",
"opts",
"||",
"{",
"}",
")",
".",
"attributes",
"||",
"{",
"}",
",",
"(",
"defaults",
"||",
"{",
"}",
")",
".",
"attributes",
"||",
"{",
"}",
")",
";",
"defaultReferrals",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"originalDefaultReferrals",
",",
"(",
"this",
".",
"opts",
"||",
"{",
"}",
")",
".",
"referrals",
"||",
"{",
"}",
",",
"(",
"defaults",
"||",
"{",
"}",
")",
".",
"referrals",
"||",
"{",
"}",
")",
";",
"log",
".",
"info",
"(",
"'Using username/password (%s/%s) to bind to ActiveDirectory (%s).'",
",",
"this",
".",
"opts",
".",
"bindDN",
",",
"isPasswordLoggingEnabled",
"?",
"this",
".",
"opts",
".",
"bindCredentials",
":",
"'********'",
",",
"this",
".",
"opts",
".",
"url",
")",
";",
"log",
".",
"info",
"(",
"'Referrals are %s'",
",",
"defaultReferrals",
".",
"enabled",
"?",
"'enabled. Exclusions: '",
"+",
"JSON",
".",
"stringify",
"(",
"defaultReferrals",
".",
"exclude",
")",
":",
"'disabled'",
")",
";",
"log",
".",
"info",
"(",
"'Default user attributes: %j'",
",",
"defaultAttributes",
".",
"user",
"||",
"[",
"]",
")",
";",
"log",
".",
"info",
"(",
"'Default group attributes: %j'",
",",
"defaultAttributes",
".",
"group",
"||",
"[",
"]",
")",
";",
"// Enable connection pooling",
"// TODO: To be disabled / removed in future release of ldapjs > 0.7.1",
"if",
"(",
"typeof",
"(",
"this",
".",
"opts",
".",
"maxConnections",
")",
"===",
"'undefined'",
")",
"{",
"this",
".",
"opts",
".",
"maxConnections",
"=",
"20",
";",
"}",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}",
"else",
"{",
"return",
"(",
"new",
"ActiveDirectory",
"(",
"url",
",",
"baseDN",
",",
"username",
",",
"password",
",",
"defaults",
")",
")",
";",
"}",
"}"
] |
Agent for retrieving ActiveDirectory user & group information.
@public
@constructor
@param {Object|String} url The url of the ldap server (i.e. ldap://domain.com). Optionally, all of the parameters can be specified as an object. { url: 'ldap://domain.com', baseDN: 'dc=domain,dc=com', username: 'admin@domain.com', password: 'supersecret', { referrals: { enabled: true }, attributes: { user: [ 'attributes to include in response' ], group: [ 'attributes to include in response' ] } } }. 'attributes' & 'referrals' parameter is optional and only necesary if overriding functionality.
@param {String} baseDN The default base container where all LDAP queries originate from. (i.e. dc=domain,dc=com)
@param {String} username The administrative username or dn of the user for retrieving user & group information. (i.e. Must be a DN or a userPrincipalName (email))
@param {String} password The administrative password of the specified user.
@param {Object} defaults Allow for default options to be overridden. { attributes: { user: [ 'attributes to include in response' ], group: [ 'attributes to include in response' ] } }
@returns {ActiveDirectory}
|
[
"Agent",
"for",
"retrieving",
"ActiveDirectory",
"user",
"&",
"group",
"information",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L69-L114
|
|
14,963
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
truncateLogOutput
|
function truncateLogOutput(output, maxLength) {
if (typeof(maxLength) === 'undefined') maxLength = maxOutputLength;
if (! output) return(output);
if (typeof(output) !== 'string') output = output.toString();
var length = output.length;
if ((! length) || (length < (maxLength + 3))) return(output);
var prefix = Math.ceil((maxLength - 3)/2);
var suffix = Math.floor((maxLength - 3)/2);
return(output.slice(0, prefix)+ '...' +
output.slice(length-suffix));
}
|
javascript
|
function truncateLogOutput(output, maxLength) {
if (typeof(maxLength) === 'undefined') maxLength = maxOutputLength;
if (! output) return(output);
if (typeof(output) !== 'string') output = output.toString();
var length = output.length;
if ((! length) || (length < (maxLength + 3))) return(output);
var prefix = Math.ceil((maxLength - 3)/2);
var suffix = Math.floor((maxLength - 3)/2);
return(output.slice(0, prefix)+ '...' +
output.slice(length-suffix));
}
|
[
"function",
"truncateLogOutput",
"(",
"output",
",",
"maxLength",
")",
"{",
"if",
"(",
"typeof",
"(",
"maxLength",
")",
"===",
"'undefined'",
")",
"maxLength",
"=",
"maxOutputLength",
";",
"if",
"(",
"!",
"output",
")",
"return",
"(",
"output",
")",
";",
"if",
"(",
"typeof",
"(",
"output",
")",
"!==",
"'string'",
")",
"output",
"=",
"output",
".",
"toString",
"(",
")",
";",
"var",
"length",
"=",
"output",
".",
"length",
";",
"if",
"(",
"(",
"!",
"length",
")",
"||",
"(",
"length",
"<",
"(",
"maxLength",
"+",
"3",
")",
")",
")",
"return",
"(",
"output",
")",
";",
"var",
"prefix",
"=",
"Math",
".",
"ceil",
"(",
"(",
"maxLength",
"-",
"3",
")",
"/",
"2",
")",
";",
"var",
"suffix",
"=",
"Math",
".",
"floor",
"(",
"(",
"maxLength",
"-",
"3",
")",
"/",
"2",
")",
";",
"return",
"(",
"output",
".",
"slice",
"(",
"0",
",",
"prefix",
")",
"+",
"'...'",
"+",
"output",
".",
"slice",
"(",
"length",
"-",
"suffix",
")",
")",
";",
"}"
] |
Truncates the specified output to the specified length if exceeded.
@param {String} output The output to truncate if too long
@param {Number} [maxLength] The maximum length. If not specified, then the global value maxOutputLength is used.
|
[
"Truncates",
"the",
"specified",
"output",
"to",
"the",
"specified",
"length",
"if",
"exceeded",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L128-L140
|
14,964
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
isDistinguishedName
|
function isDistinguishedName(value) {
log.trace('isDistinguishedName(%s)', value);
if ((! value) || (value.length === 0)) return(false);
re.isDistinguishedName.lastIndex = 0; // Reset the regular expression
return(re.isDistinguishedName.test(value));
}
|
javascript
|
function isDistinguishedName(value) {
log.trace('isDistinguishedName(%s)', value);
if ((! value) || (value.length === 0)) return(false);
re.isDistinguishedName.lastIndex = 0; // Reset the regular expression
return(re.isDistinguishedName.test(value));
}
|
[
"function",
"isDistinguishedName",
"(",
"value",
")",
"{",
"log",
".",
"trace",
"(",
"'isDistinguishedName(%s)'",
",",
"value",
")",
";",
"if",
"(",
"(",
"!",
"value",
")",
"||",
"(",
"value",
".",
"length",
"===",
"0",
")",
")",
"return",
"(",
"false",
")",
";",
"re",
".",
"isDistinguishedName",
".",
"lastIndex",
"=",
"0",
";",
"// Reset the regular expression",
"return",
"(",
"re",
".",
"isDistinguishedName",
".",
"test",
"(",
"value",
")",
")",
";",
"}"
] |
Checks to see if the value is a distinguished name.
@private
@param {String} value The value to check to see if it's a distinguished name.
@returns {Boolean}
|
[
"Checks",
"to",
"see",
"if",
"the",
"value",
"is",
"a",
"distinguished",
"name",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L159-L164
|
14,965
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
getUserQueryFilter
|
function getUserQueryFilter(username) {
log.trace('getUserQueryFilter(%s)', username);
var self = this;
if (! username) return('(objectCategory=User)');
if (isDistinguishedName.call(self, username)) {
return('(&(objectCategory=User)(distinguishedName='+parseDistinguishedName(username)+'))');
}
return('(&(objectCategory=User)(|(sAMAccountName='+username+')(userPrincipalName='+username+')))');
}
|
javascript
|
function getUserQueryFilter(username) {
log.trace('getUserQueryFilter(%s)', username);
var self = this;
if (! username) return('(objectCategory=User)');
if (isDistinguishedName.call(self, username)) {
return('(&(objectCategory=User)(distinguishedName='+parseDistinguishedName(username)+'))');
}
return('(&(objectCategory=User)(|(sAMAccountName='+username+')(userPrincipalName='+username+')))');
}
|
[
"function",
"getUserQueryFilter",
"(",
"username",
")",
"{",
"log",
".",
"trace",
"(",
"'getUserQueryFilter(%s)'",
",",
"username",
")",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"username",
")",
"return",
"(",
"'(objectCategory=User)'",
")",
";",
"if",
"(",
"isDistinguishedName",
".",
"call",
"(",
"self",
",",
"username",
")",
")",
"{",
"return",
"(",
"'(&(objectCategory=User)(distinguishedName='",
"+",
"parseDistinguishedName",
"(",
"username",
")",
"+",
"'))'",
")",
";",
"}",
"return",
"(",
"'(&(objectCategory=User)(|(sAMAccountName='",
"+",
"username",
"+",
"')(userPrincipalName='",
"+",
"username",
"+",
"')))'",
")",
";",
"}"
] |
Gets the ActiveDirectory LDAP query string for a user search.
@private
@param {String} username The samAccountName or userPrincipalName (email) of the user.
@returns {String}
|
[
"Gets",
"the",
"ActiveDirectory",
"LDAP",
"query",
"string",
"for",
"a",
"user",
"search",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L189-L199
|
14,966
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
getGroupQueryFilter
|
function getGroupQueryFilter(groupName) {
log.trace('getGroupQueryFilter(%s)', groupName);
var self = this;
if (! groupName) return('(objectCategory=Group)');
if (isDistinguishedName.call(self, groupName)) {
return('(&(objectCategory=Group)(distinguishedName='+parseDistinguishedName(groupName)+'))');
}
return('(&(objectCategory=Group)(cn='+groupName+'))');
}
|
javascript
|
function getGroupQueryFilter(groupName) {
log.trace('getGroupQueryFilter(%s)', groupName);
var self = this;
if (! groupName) return('(objectCategory=Group)');
if (isDistinguishedName.call(self, groupName)) {
return('(&(objectCategory=Group)(distinguishedName='+parseDistinguishedName(groupName)+'))');
}
return('(&(objectCategory=Group)(cn='+groupName+'))');
}
|
[
"function",
"getGroupQueryFilter",
"(",
"groupName",
")",
"{",
"log",
".",
"trace",
"(",
"'getGroupQueryFilter(%s)'",
",",
"groupName",
")",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"groupName",
")",
"return",
"(",
"'(objectCategory=Group)'",
")",
";",
"if",
"(",
"isDistinguishedName",
".",
"call",
"(",
"self",
",",
"groupName",
")",
")",
"{",
"return",
"(",
"'(&(objectCategory=Group)(distinguishedName='",
"+",
"parseDistinguishedName",
"(",
"groupName",
")",
"+",
"'))'",
")",
";",
"}",
"return",
"(",
"'(&(objectCategory=Group)(cn='",
"+",
"groupName",
"+",
"'))'",
")",
";",
"}"
] |
Gets the ActiveDirectory LDAP query string for a group search.
@private
@param {String} groupName The name of the group
@returns {String}
|
[
"Gets",
"the",
"ActiveDirectory",
"LDAP",
"query",
"string",
"for",
"a",
"group",
"search",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L225-L234
|
14,967
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
isGroupResult
|
function isGroupResult(item) {
log.trace('isGroupResult(%j)', item);
if (! item) return(false);
if (item.groupType) return(true);
if (item.objectCategory) {
re.isGroupResult.lastIndex = 0; // Reset the regular expression
return(re.isGroupResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'group'); }));
}
return(false);
}
|
javascript
|
function isGroupResult(item) {
log.trace('isGroupResult(%j)', item);
if (! item) return(false);
if (item.groupType) return(true);
if (item.objectCategory) {
re.isGroupResult.lastIndex = 0; // Reset the regular expression
return(re.isGroupResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'group'); }));
}
return(false);
}
|
[
"function",
"isGroupResult",
"(",
"item",
")",
"{",
"log",
".",
"trace",
"(",
"'isGroupResult(%j)'",
",",
"item",
")",
";",
"if",
"(",
"!",
"item",
")",
"return",
"(",
"false",
")",
";",
"if",
"(",
"item",
".",
"groupType",
")",
"return",
"(",
"true",
")",
";",
"if",
"(",
"item",
".",
"objectCategory",
")",
"{",
"re",
".",
"isGroupResult",
".",
"lastIndex",
"=",
"0",
";",
"// Reset the regular expression",
"return",
"(",
"re",
".",
"isGroupResult",
".",
"test",
"(",
"item",
".",
"objectCategory",
")",
")",
";",
"}",
"if",
"(",
"(",
"item",
".",
"objectClass",
")",
"&&",
"(",
"item",
".",
"objectClass",
".",
"length",
">",
"0",
")",
")",
"{",
"return",
"(",
"_",
".",
"any",
"(",
"item",
".",
"objectClass",
",",
"function",
"(",
"c",
")",
"{",
"return",
"(",
"c",
".",
"toLowerCase",
"(",
")",
"===",
"'group'",
")",
";",
"}",
")",
")",
";",
"}",
"return",
"(",
"false",
")",
";",
"}"
] |
Checks to see if the LDAP result describes a group entry.
@param {Object} item The LDAP result to inspect.
@returns {Boolean}
|
[
"Checks",
"to",
"see",
"if",
"the",
"LDAP",
"result",
"describes",
"a",
"group",
"entry",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L241-L254
|
14,968
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
isUserResult
|
function isUserResult(item) {
log.trace('isUserResult(%j)', item);
if (! item) return(false);
if (item.userPrincipalName) return(true);
if (item.objectCategory) {
re.isUserResult.lastIndex = 0; // Reset the regular expression
return(re.isUserResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'user'); }));
}
return(false);
}
|
javascript
|
function isUserResult(item) {
log.trace('isUserResult(%j)', item);
if (! item) return(false);
if (item.userPrincipalName) return(true);
if (item.objectCategory) {
re.isUserResult.lastIndex = 0; // Reset the regular expression
return(re.isUserResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'user'); }));
}
return(false);
}
|
[
"function",
"isUserResult",
"(",
"item",
")",
"{",
"log",
".",
"trace",
"(",
"'isUserResult(%j)'",
",",
"item",
")",
";",
"if",
"(",
"!",
"item",
")",
"return",
"(",
"false",
")",
";",
"if",
"(",
"item",
".",
"userPrincipalName",
")",
"return",
"(",
"true",
")",
";",
"if",
"(",
"item",
".",
"objectCategory",
")",
"{",
"re",
".",
"isUserResult",
".",
"lastIndex",
"=",
"0",
";",
"// Reset the regular expression",
"return",
"(",
"re",
".",
"isUserResult",
".",
"test",
"(",
"item",
".",
"objectCategory",
")",
")",
";",
"}",
"if",
"(",
"(",
"item",
".",
"objectClass",
")",
"&&",
"(",
"item",
".",
"objectClass",
".",
"length",
">",
"0",
")",
")",
"{",
"return",
"(",
"_",
".",
"any",
"(",
"item",
".",
"objectClass",
",",
"function",
"(",
"c",
")",
"{",
"return",
"(",
"c",
".",
"toLowerCase",
"(",
")",
"===",
"'user'",
")",
";",
"}",
")",
")",
";",
"}",
"return",
"(",
"false",
")",
";",
"}"
] |
Checks to see if the LDAP result describes a user entry.
@param {Object} item The LDAP result to inspect.
@returns {Boolean}
|
[
"Checks",
"to",
"see",
"if",
"the",
"LDAP",
"result",
"describes",
"a",
"user",
"entry",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L261-L274
|
14,969
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
createClient
|
function createClient(url, opts) {
// Attempt to get Url from this instance.
url = url || this.url || (this.opts || {}).url || (opts || {}).url;
if (! url) {
throw 'No url specified for ActiveDirectory client.';
}
log.trace('createClient(%s)', url);
var opts = getLdapClientOpts(_.defaults({}, { url: url }, opts, this.opts));
log.debug('Creating ldapjs client for %s. Opts: %j', opts.url, _.omit(opts, 'url', 'bindDN', 'bindCredentials'));
var client = ldap.createClient(opts);
return(client);
}
|
javascript
|
function createClient(url, opts) {
// Attempt to get Url from this instance.
url = url || this.url || (this.opts || {}).url || (opts || {}).url;
if (! url) {
throw 'No url specified for ActiveDirectory client.';
}
log.trace('createClient(%s)', url);
var opts = getLdapClientOpts(_.defaults({}, { url: url }, opts, this.opts));
log.debug('Creating ldapjs client for %s. Opts: %j', opts.url, _.omit(opts, 'url', 'bindDN', 'bindCredentials'));
var client = ldap.createClient(opts);
return(client);
}
|
[
"function",
"createClient",
"(",
"url",
",",
"opts",
")",
"{",
"// Attempt to get Url from this instance.",
"url",
"=",
"url",
"||",
"this",
".",
"url",
"||",
"(",
"this",
".",
"opts",
"||",
"{",
"}",
")",
".",
"url",
"||",
"(",
"opts",
"||",
"{",
"}",
")",
".",
"url",
";",
"if",
"(",
"!",
"url",
")",
"{",
"throw",
"'No url specified for ActiveDirectory client.'",
";",
"}",
"log",
".",
"trace",
"(",
"'createClient(%s)'",
",",
"url",
")",
";",
"var",
"opts",
"=",
"getLdapClientOpts",
"(",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"{",
"url",
":",
"url",
"}",
",",
"opts",
",",
"this",
".",
"opts",
")",
")",
";",
"log",
".",
"debug",
"(",
"'Creating ldapjs client for %s. Opts: %j'",
",",
"opts",
".",
"url",
",",
"_",
".",
"omit",
"(",
"opts",
",",
"'url'",
",",
"'bindDN'",
",",
"'bindCredentials'",
")",
")",
";",
"var",
"client",
"=",
"ldap",
".",
"createClient",
"(",
"opts",
")",
";",
"return",
"(",
"client",
")",
";",
"}"
] |
Factory to create the LDAP client object.
@private
@param {String} url The url to use when creating the LDAP client.
@param {object} opts The optional LDAP client options.
|
[
"Factory",
"to",
"create",
"the",
"LDAP",
"client",
"object",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L283-L295
|
14,970
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
isAllowedReferral
|
function isAllowedReferral(referral) {
log.trace('isAllowedReferral(%j)', referral);
if (! defaultReferrals.enabled) return(false);
if (! referral) return(false);
return(! _.any(defaultReferrals.exclude, function(exclusion) {
var re = new RegExp(exclusion, "i");
return(re.test(referral));
}));
}
|
javascript
|
function isAllowedReferral(referral) {
log.trace('isAllowedReferral(%j)', referral);
if (! defaultReferrals.enabled) return(false);
if (! referral) return(false);
return(! _.any(defaultReferrals.exclude, function(exclusion) {
var re = new RegExp(exclusion, "i");
return(re.test(referral));
}));
}
|
[
"function",
"isAllowedReferral",
"(",
"referral",
")",
"{",
"log",
".",
"trace",
"(",
"'isAllowedReferral(%j)'",
",",
"referral",
")",
";",
"if",
"(",
"!",
"defaultReferrals",
".",
"enabled",
")",
"return",
"(",
"false",
")",
";",
"if",
"(",
"!",
"referral",
")",
"return",
"(",
"false",
")",
";",
"return",
"(",
"!",
"_",
".",
"any",
"(",
"defaultReferrals",
".",
"exclude",
",",
"function",
"(",
"exclusion",
")",
"{",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"exclusion",
",",
"\"i\"",
")",
";",
"return",
"(",
"re",
".",
"test",
"(",
"referral",
")",
")",
";",
"}",
")",
")",
";",
"}"
] |
Checks to see if the specified referral or "chase" is allowed.
@param {String} referral The referral to inspect.
@returns {Boolean} True if the referral should be followed, false if otherwise.
|
[
"Checks",
"to",
"see",
"if",
"the",
"specified",
"referral",
"or",
"chase",
"is",
"allowed",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L302-L311
|
14,971
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
removeReferral
|
function removeReferral(client) {
if (! client) return;
client.unbind();
var indexOf = pendingReferrals.indexOf(client);
if (indexOf >= 0) {
pendingReferrals.splice(indexOf, 1);
}
}
|
javascript
|
function removeReferral(client) {
if (! client) return;
client.unbind();
var indexOf = pendingReferrals.indexOf(client);
if (indexOf >= 0) {
pendingReferrals.splice(indexOf, 1);
}
}
|
[
"function",
"removeReferral",
"(",
"client",
")",
"{",
"if",
"(",
"!",
"client",
")",
"return",
";",
"client",
".",
"unbind",
"(",
")",
";",
"var",
"indexOf",
"=",
"pendingReferrals",
".",
"indexOf",
"(",
"client",
")",
";",
"if",
"(",
"indexOf",
">=",
"0",
")",
"{",
"pendingReferrals",
".",
"splice",
"(",
"indexOf",
",",
"1",
")",
";",
"}",
"}"
] |
Call to remove the specified referral client.
@param {Object} client The referral client to remove.
|
[
"Call",
"to",
"remove",
"the",
"specified",
"referral",
"client",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L390-L398
|
14,972
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
onSearchEntry
|
function onSearchEntry(entry) {
log.trace('onSearchEntry(%j)', entry);
var result = entry.object;
delete result.controls; // Remove the controls array returned as part of the SearchEntry
// Some attributes can have range attributes (paging). Execute the query
// again to get additional items.
pendingRangeRetrievals++;
parseRangeAttributes.call(self, result, opts, function(err, item) {
pendingRangeRetrievals--;
if (err) item = entry.object;
entryParser(item, entry.raw, function(item) {
if (item) results.push(item);
if ((! pendingRangeRetrievals) && (isDone)) {
onSearchEnd();
}
});
});
}
|
javascript
|
function onSearchEntry(entry) {
log.trace('onSearchEntry(%j)', entry);
var result = entry.object;
delete result.controls; // Remove the controls array returned as part of the SearchEntry
// Some attributes can have range attributes (paging). Execute the query
// again to get additional items.
pendingRangeRetrievals++;
parseRangeAttributes.call(self, result, opts, function(err, item) {
pendingRangeRetrievals--;
if (err) item = entry.object;
entryParser(item, entry.raw, function(item) {
if (item) results.push(item);
if ((! pendingRangeRetrievals) && (isDone)) {
onSearchEnd();
}
});
});
}
|
[
"function",
"onSearchEntry",
"(",
"entry",
")",
"{",
"log",
".",
"trace",
"(",
"'onSearchEntry(%j)'",
",",
"entry",
")",
";",
"var",
"result",
"=",
"entry",
".",
"object",
";",
"delete",
"result",
".",
"controls",
";",
"// Remove the controls array returned as part of the SearchEntry",
"// Some attributes can have range attributes (paging). Execute the query",
"// again to get additional items.",
"pendingRangeRetrievals",
"++",
";",
"parseRangeAttributes",
".",
"call",
"(",
"self",
",",
"result",
",",
"opts",
",",
"function",
"(",
"err",
",",
"item",
")",
"{",
"pendingRangeRetrievals",
"--",
";",
"if",
"(",
"err",
")",
"item",
"=",
"entry",
".",
"object",
";",
"entryParser",
"(",
"item",
",",
"entry",
".",
"raw",
",",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
")",
"results",
".",
"push",
"(",
"item",
")",
";",
"if",
"(",
"(",
"!",
"pendingRangeRetrievals",
")",
"&&",
"(",
"isDone",
")",
")",
"{",
"onSearchEnd",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Occurs when a search entry is received. Cleans up the search entry and pushes it to the result set.
@param {Object} entry The entry received.
|
[
"Occurs",
"when",
"a",
"search",
"entry",
"is",
"received",
".",
"Cleans",
"up",
"the",
"search",
"entry",
"and",
"pushes",
"it",
"to",
"the",
"result",
"set",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L413-L432
|
14,973
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
onReferralError
|
function onReferralError(err) {
log.error(err, '[%s] An error occurred chasing the LDAP referral on %s (%j)',
(err || {}).errno, referralBaseDn, opts);
removeReferral(referralClient);
}
|
javascript
|
function onReferralError(err) {
log.error(err, '[%s] An error occurred chasing the LDAP referral on %s (%j)',
(err || {}).errno, referralBaseDn, opts);
removeReferral(referralClient);
}
|
[
"function",
"onReferralError",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"err",
",",
"'[%s] An error occurred chasing the LDAP referral on %s (%j)'",
",",
"(",
"err",
"||",
"{",
"}",
")",
".",
"errno",
",",
"referralBaseDn",
",",
"opts",
")",
";",
"removeReferral",
"(",
"referralClient",
")",
";",
"}"
] |
Occurs when a error is encountered with the referral client.
@param {Object} err The error object or string.
|
[
"Occurs",
"when",
"a",
"error",
"is",
"encountered",
"with",
"the",
"referral",
"client",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L456-L460
|
14,974
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
onSearchEnd
|
function onSearchEnd(result) {
if ((! pendingRangeRetrievals) && (pendingReferrals.length <= 0)) {
client.unbind();
log.info('Active directory search (%s) for "%s" returned %d entries.',
baseDN, truncateLogOutput(opts.filter),
(results || []).length);
if (callback) callback(null, results);
}
}
|
javascript
|
function onSearchEnd(result) {
if ((! pendingRangeRetrievals) && (pendingReferrals.length <= 0)) {
client.unbind();
log.info('Active directory search (%s) for "%s" returned %d entries.',
baseDN, truncateLogOutput(opts.filter),
(results || []).length);
if (callback) callback(null, results);
}
}
|
[
"function",
"onSearchEnd",
"(",
"result",
")",
"{",
"if",
"(",
"(",
"!",
"pendingRangeRetrievals",
")",
"&&",
"(",
"pendingReferrals",
".",
"length",
"<=",
"0",
")",
")",
"{",
"client",
".",
"unbind",
"(",
")",
";",
"log",
".",
"info",
"(",
"'Active directory search (%s) for \"%s\" returned %d entries.'",
",",
"baseDN",
",",
"truncateLogOutput",
"(",
"opts",
".",
"filter",
")",
",",
"(",
"results",
"||",
"[",
"]",
")",
".",
"length",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
"}"
] |
Occurs when a search results have all been processed.
@param {Object} result
|
[
"Occurs",
"when",
"a",
"search",
"results",
"have",
"all",
"been",
"processed",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L500-L508
|
14,975
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
parseRangeAttributes
|
function parseRangeAttributes(result, opts, callback) {
log.trace('parseRangeAttributes(%j,%j)', result, opts);
var self = this;
// Check to see if any of the result attributes have range= attributes.
// If not, return immediately.
if (! RangeRetrievalSpecifierAttribute.prototype.hasRangeAttributes(result)) {
callback(null, result);
return;
}
// Parse the range attributes that were provided. If the range attributes are null
// or indicate that the range is complete, return the result.
var rangeAttributes = RangeRetrievalSpecifierAttribute.prototype.getRangeAttributes(result);
if ((! rangeAttributes) || (rangeAttributes.length <= 0)) {
callback(null, result);
return;
}
// Parse each of the range attributes. Merge the range attributes into
// the properly named property.
var queryAttributes = [];
_.each(rangeAttributes, function(rangeAttribute, index) {
// Merge existing range into the properly named property.
if (! result[rangeAttribute.attributeName]) result[rangeAttribute.attributeName] = [];
Array.prototype.push.apply(result[rangeAttribute.attributeName], result[rangeAttribute.toString()]);
delete(result[rangeAttribute.toString()]);
// Build our ldap query attributes with the proper attribute;range= tags to
// get the next sequence of data.
var queryAttribute = rangeAttribute.next();
if ((queryAttribute) && (! queryAttribute.isComplete())) {
queryAttributes.push(queryAttribute.toString());
}
});
// If we're at the end of the range (i.e. all items retrieved), return the result.
if (queryAttributes.length <= 0) {
log.debug('All attribute ranges %j retrieved for %s', rangeAttributes, result.dn);
callback(null, result);
return;
}
log.debug('Attribute range retrieval specifiers %j found for "%s". Next range: %j',
rangeAttributes, result.dn, queryAttributes);
// Execute the query again with the query attributes updated.
opts = _.defaults({ filter: '(distinguishedName='+parseDistinguishedName(result.dn)+')',
attributes: queryAttributes }, opts);
search.call(self, opts, function onSearch(err, results) {
if (err) {
callback(err);
return;
}
// Should be only one result
var item = (results || [])[0];
for(var property in item) {
if (item.hasOwnProperty(property)) {
if (! result[property]) result[property] = [];
if (_.isArray(result[property])) {
Array.prototype.push.apply(result[property], item[property]);
}
}
}
callback(null, result);
});
}
|
javascript
|
function parseRangeAttributes(result, opts, callback) {
log.trace('parseRangeAttributes(%j,%j)', result, opts);
var self = this;
// Check to see if any of the result attributes have range= attributes.
// If not, return immediately.
if (! RangeRetrievalSpecifierAttribute.prototype.hasRangeAttributes(result)) {
callback(null, result);
return;
}
// Parse the range attributes that were provided. If the range attributes are null
// or indicate that the range is complete, return the result.
var rangeAttributes = RangeRetrievalSpecifierAttribute.prototype.getRangeAttributes(result);
if ((! rangeAttributes) || (rangeAttributes.length <= 0)) {
callback(null, result);
return;
}
// Parse each of the range attributes. Merge the range attributes into
// the properly named property.
var queryAttributes = [];
_.each(rangeAttributes, function(rangeAttribute, index) {
// Merge existing range into the properly named property.
if (! result[rangeAttribute.attributeName]) result[rangeAttribute.attributeName] = [];
Array.prototype.push.apply(result[rangeAttribute.attributeName], result[rangeAttribute.toString()]);
delete(result[rangeAttribute.toString()]);
// Build our ldap query attributes with the proper attribute;range= tags to
// get the next sequence of data.
var queryAttribute = rangeAttribute.next();
if ((queryAttribute) && (! queryAttribute.isComplete())) {
queryAttributes.push(queryAttribute.toString());
}
});
// If we're at the end of the range (i.e. all items retrieved), return the result.
if (queryAttributes.length <= 0) {
log.debug('All attribute ranges %j retrieved for %s', rangeAttributes, result.dn);
callback(null, result);
return;
}
log.debug('Attribute range retrieval specifiers %j found for "%s". Next range: %j',
rangeAttributes, result.dn, queryAttributes);
// Execute the query again with the query attributes updated.
opts = _.defaults({ filter: '(distinguishedName='+parseDistinguishedName(result.dn)+')',
attributes: queryAttributes }, opts);
search.call(self, opts, function onSearch(err, results) {
if (err) {
callback(err);
return;
}
// Should be only one result
var item = (results || [])[0];
for(var property in item) {
if (item.hasOwnProperty(property)) {
if (! result[property]) result[property] = [];
if (_.isArray(result[property])) {
Array.prototype.push.apply(result[property], item[property]);
}
}
}
callback(null, result);
});
}
|
[
"function",
"parseRangeAttributes",
"(",
"result",
",",
"opts",
",",
"callback",
")",
"{",
"log",
".",
"trace",
"(",
"'parseRangeAttributes(%j,%j)'",
",",
"result",
",",
"opts",
")",
";",
"var",
"self",
"=",
"this",
";",
"// Check to see if any of the result attributes have range= attributes.",
"// If not, return immediately.",
"if",
"(",
"!",
"RangeRetrievalSpecifierAttribute",
".",
"prototype",
".",
"hasRangeAttributes",
"(",
"result",
")",
")",
"{",
"callback",
"(",
"null",
",",
"result",
")",
";",
"return",
";",
"}",
"// Parse the range attributes that were provided. If the range attributes are null",
"// or indicate that the range is complete, return the result.",
"var",
"rangeAttributes",
"=",
"RangeRetrievalSpecifierAttribute",
".",
"prototype",
".",
"getRangeAttributes",
"(",
"result",
")",
";",
"if",
"(",
"(",
"!",
"rangeAttributes",
")",
"||",
"(",
"rangeAttributes",
".",
"length",
"<=",
"0",
")",
")",
"{",
"callback",
"(",
"null",
",",
"result",
")",
";",
"return",
";",
"}",
"// Parse each of the range attributes. Merge the range attributes into",
"// the properly named property.",
"var",
"queryAttributes",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"rangeAttributes",
",",
"function",
"(",
"rangeAttribute",
",",
"index",
")",
"{",
"// Merge existing range into the properly named property.",
"if",
"(",
"!",
"result",
"[",
"rangeAttribute",
".",
"attributeName",
"]",
")",
"result",
"[",
"rangeAttribute",
".",
"attributeName",
"]",
"=",
"[",
"]",
";",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"result",
"[",
"rangeAttribute",
".",
"attributeName",
"]",
",",
"result",
"[",
"rangeAttribute",
".",
"toString",
"(",
")",
"]",
")",
";",
"delete",
"(",
"result",
"[",
"rangeAttribute",
".",
"toString",
"(",
")",
"]",
")",
";",
"// Build our ldap query attributes with the proper attribute;range= tags to",
"// get the next sequence of data.",
"var",
"queryAttribute",
"=",
"rangeAttribute",
".",
"next",
"(",
")",
";",
"if",
"(",
"(",
"queryAttribute",
")",
"&&",
"(",
"!",
"queryAttribute",
".",
"isComplete",
"(",
")",
")",
")",
"{",
"queryAttributes",
".",
"push",
"(",
"queryAttribute",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"// If we're at the end of the range (i.e. all items retrieved), return the result.",
"if",
"(",
"queryAttributes",
".",
"length",
"<=",
"0",
")",
"{",
"log",
".",
"debug",
"(",
"'All attribute ranges %j retrieved for %s'",
",",
"rangeAttributes",
",",
"result",
".",
"dn",
")",
";",
"callback",
"(",
"null",
",",
"result",
")",
";",
"return",
";",
"}",
"log",
".",
"debug",
"(",
"'Attribute range retrieval specifiers %j found for \"%s\". Next range: %j'",
",",
"rangeAttributes",
",",
"result",
".",
"dn",
",",
"queryAttributes",
")",
";",
"// Execute the query again with the query attributes updated.",
"opts",
"=",
"_",
".",
"defaults",
"(",
"{",
"filter",
":",
"'(distinguishedName='",
"+",
"parseDistinguishedName",
"(",
"result",
".",
"dn",
")",
"+",
"')'",
",",
"attributes",
":",
"queryAttributes",
"}",
",",
"opts",
")",
";",
"search",
".",
"call",
"(",
"self",
",",
"opts",
",",
"function",
"onSearch",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"// Should be only one result",
"var",
"item",
"=",
"(",
"results",
"||",
"[",
"]",
")",
"[",
"0",
"]",
";",
"for",
"(",
"var",
"property",
"in",
"item",
")",
"{",
"if",
"(",
"item",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"if",
"(",
"!",
"result",
"[",
"property",
"]",
")",
"result",
"[",
"property",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"result",
"[",
"property",
"]",
")",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"result",
"[",
"property",
"]",
",",
"item",
"[",
"property",
"]",
")",
";",
"}",
"}",
"}",
"callback",
"(",
"null",
",",
"result",
")",
";",
"}",
")",
";",
"}"
] |
Handles any attributes that might have been returned with a range= specifier.
@private
@param {Object} result The entry returned from the query.
@param {Object} opts The original LDAP query string parameters to execute. { scope: '', filter: '', attributes: [ '', '', ... ], sizeLimit: 0, timelimit: 0 }
@param {Function} callback The callback to execute when completed. callback(err: {Object}, result: {Object}})
|
[
"Handles",
"any",
"attributes",
"that",
"might",
"have",
"been",
"returned",
"with",
"a",
"range",
"=",
"specifier",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L553-L619
|
14,976
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
pickAttributes
|
function pickAttributes(result, attributes) {
if (shouldIncludeAllAttributes(attributes)) {
attributes = function() {
return(true);
};
}
return(_.pick(result, attributes));
}
|
javascript
|
function pickAttributes(result, attributes) {
if (shouldIncludeAllAttributes(attributes)) {
attributes = function() {
return(true);
};
}
return(_.pick(result, attributes));
}
|
[
"function",
"pickAttributes",
"(",
"result",
",",
"attributes",
")",
"{",
"if",
"(",
"shouldIncludeAllAttributes",
"(",
"attributes",
")",
")",
"{",
"attributes",
"=",
"function",
"(",
")",
"{",
"return",
"(",
"true",
")",
";",
"}",
";",
"}",
"return",
"(",
"_",
".",
"pick",
"(",
"result",
",",
"attributes",
")",
")",
";",
"}"
] |
Picks only the requested attributes from the ldap result. If a wildcard or
empty result is specified, then all attributes are returned.
@private
@params {Object} result The ldap result
@params {Array} attributes The desired or wanted attributes
@returns {Object} A copy of the object with only the requested attributes
|
[
"Picks",
"only",
"the",
"requested",
"attributes",
"from",
"the",
"ldap",
"result",
".",
"If",
"a",
"wildcard",
"or",
"empty",
"result",
"is",
"specified",
"then",
"all",
"attributes",
"are",
"returned",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L687-L694
|
14,977
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
chunk
|
function chunk(arr, chunkSize) {
var result = [];
for (var index = 0, length = arr.length; index < length; index += chunkSize) {
result.push(arr.slice(index,index + chunkSize));
}
return(result);
}
|
javascript
|
function chunk(arr, chunkSize) {
var result = [];
for (var index = 0, length = arr.length; index < length; index += chunkSize) {
result.push(arr.slice(index,index + chunkSize));
}
return(result);
}
|
[
"function",
"chunk",
"(",
"arr",
",",
"chunkSize",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"index",
"=",
"0",
",",
"length",
"=",
"arr",
".",
"length",
";",
"index",
"<",
"length",
";",
"index",
"+=",
"chunkSize",
")",
"{",
"result",
".",
"push",
"(",
"arr",
".",
"slice",
"(",
"index",
",",
"index",
"+",
"chunkSize",
")",
")",
";",
"}",
"return",
"(",
"result",
")",
";",
"}"
] |
Breaks the large array into chucks of the specified size.
@param {Array} arr The array to break into chunks
@param {Number} chunkSize The size of each chunk.
@returns {Array} The resulting array containing each chunk
|
[
"Breaks",
"the",
"large",
"array",
"into",
"chucks",
"of",
"the",
"specified",
"size",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L999-L1005
|
14,978
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
includeGroupMembershipFor
|
function includeGroupMembershipFor(opts, name) {
if (typeof(opts) === 'string') {
name = opts;
opts = this.opts;
}
var lowerCaseName = (name || '').toLowerCase();
return(_.any(((opts || this.opts || {}).includeMembership || []), function(i) {
i = i.toLowerCase();
return((i === 'all') || (i === lowerCaseName));
}));
}
|
javascript
|
function includeGroupMembershipFor(opts, name) {
if (typeof(opts) === 'string') {
name = opts;
opts = this.opts;
}
var lowerCaseName = (name || '').toLowerCase();
return(_.any(((opts || this.opts || {}).includeMembership || []), function(i) {
i = i.toLowerCase();
return((i === 'all') || (i === lowerCaseName));
}));
}
|
[
"function",
"includeGroupMembershipFor",
"(",
"opts",
",",
"name",
")",
"{",
"if",
"(",
"typeof",
"(",
"opts",
")",
"===",
"'string'",
")",
"{",
"name",
"=",
"opts",
";",
"opts",
"=",
"this",
".",
"opts",
";",
"}",
"var",
"lowerCaseName",
"=",
"(",
"name",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"return",
"(",
"_",
".",
"any",
"(",
"(",
"(",
"opts",
"||",
"this",
".",
"opts",
"||",
"{",
"}",
")",
".",
"includeMembership",
"||",
"[",
"]",
")",
",",
"function",
"(",
"i",
")",
"{",
"i",
"=",
"i",
".",
"toLowerCase",
"(",
")",
";",
"return",
"(",
"(",
"i",
"===",
"'all'",
")",
"||",
"(",
"i",
"===",
"lowerCaseName",
")",
")",
";",
"}",
")",
")",
";",
"}"
] |
Checks to see if group membership for the specified type is enabled.
@param {Object} [opts] The options to inspect. If not specified, uses this.opts.
@param {String} name The name of the membership value to inspect. Values: (all|user|group)
@returns {Boolean} True if the specified membership is enabled.
|
[
"Checks",
"to",
"see",
"if",
"group",
"membership",
"for",
"the",
"specified",
"type",
"is",
"enabled",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L1284-L1295
|
14,979
|
gheeres/node-activedirectory
|
lib/activedirectory.js
|
onClientError
|
function onClientError(err) {
// Ignore ECONNRESET errors
if ((err || {}).errno !== 'ECONNRESET') {
log.error('An unhandled error occured when searching for the root DSE at "%s". Error: %j', url, err);
if (hasEvents.call(self, 'error')) self.emit('error', err)
}
}
|
javascript
|
function onClientError(err) {
// Ignore ECONNRESET errors
if ((err || {}).errno !== 'ECONNRESET') {
log.error('An unhandled error occured when searching for the root DSE at "%s". Error: %j', url, err);
if (hasEvents.call(self, 'error')) self.emit('error', err)
}
}
|
[
"function",
"onClientError",
"(",
"err",
")",
"{",
"// Ignore ECONNRESET errors",
"if",
"(",
"(",
"err",
"||",
"{",
"}",
")",
".",
"errno",
"!==",
"'ECONNRESET'",
")",
"{",
"log",
".",
"error",
"(",
"'An unhandled error occured when searching for the root DSE at \"%s\". Error: %j'",
",",
"url",
",",
"err",
")",
";",
"if",
"(",
"hasEvents",
".",
"call",
"(",
"self",
",",
"'error'",
")",
")",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"}"
] |
Inline function handle connection and result errors.
@private
|
[
"Inline",
"function",
"handle",
"connection",
"and",
"result",
"errors",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/activedirectory.js#L1865-L1871
|
14,980
|
gheeres/node-activedirectory
|
lib/client/rangeretrievalspecifierattribute.js
|
parseRangeRetrievalSpecifierAttribute
|
function parseRangeRetrievalSpecifierAttribute(attribute) {
var re = new RegExp(pattern, 'i');
var match = re.exec(attribute);
return({
attributeName: match[1],
low: parseInt(match[2]),
high: parseInt(match[3]) || null
});
}
|
javascript
|
function parseRangeRetrievalSpecifierAttribute(attribute) {
var re = new RegExp(pattern, 'i');
var match = re.exec(attribute);
return({
attributeName: match[1],
low: parseInt(match[2]),
high: parseInt(match[3]) || null
});
}
|
[
"function",
"parseRangeRetrievalSpecifierAttribute",
"(",
"attribute",
")",
"{",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"pattern",
",",
"'i'",
")",
";",
"var",
"match",
"=",
"re",
".",
"exec",
"(",
"attribute",
")",
";",
"return",
"(",
"{",
"attributeName",
":",
"match",
"[",
"1",
"]",
",",
"low",
":",
"parseInt",
"(",
"match",
"[",
"2",
"]",
")",
",",
"high",
":",
"parseInt",
"(",
"match",
"[",
"3",
"]",
")",
"||",
"null",
"}",
")",
";",
"}"
] |
Parses the range retrieval specifier into an object.
@private
@param {String} range The range retrieval specifier to parse.
@returns {RangeRetrievalSpecifier}
|
[
"Parses",
"the",
"range",
"retrieval",
"specifier",
"into",
"an",
"object",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/client/rangeretrievalspecifierattribute.js#L14-L22
|
14,981
|
gheeres/node-activedirectory
|
lib/client/rangeretrievalspecifierattribute.js
|
function(attribute) {
if (this instanceof RangeRetrievalSpecifierAttribute) {
if (! attribute) throw new Error('No attribute provided to create a range retrieval specifier.');
if (typeof(attribute) === 'string') {
attribute = parseRangeRetrievalSpecifierAttribute(attribute);
}
for(var property in attribute) {
if (Array.prototype.hasOwnProperty.call(attribute, property)) {
this[property] = attribute[property];
}
}
}
else {
return(new RangeRetrievalSpecifierAttribute(attribute));
}
}
|
javascript
|
function(attribute) {
if (this instanceof RangeRetrievalSpecifierAttribute) {
if (! attribute) throw new Error('No attribute provided to create a range retrieval specifier.');
if (typeof(attribute) === 'string') {
attribute = parseRangeRetrievalSpecifierAttribute(attribute);
}
for(var property in attribute) {
if (Array.prototype.hasOwnProperty.call(attribute, property)) {
this[property] = attribute[property];
}
}
}
else {
return(new RangeRetrievalSpecifierAttribute(attribute));
}
}
|
[
"function",
"(",
"attribute",
")",
"{",
"if",
"(",
"this",
"instanceof",
"RangeRetrievalSpecifierAttribute",
")",
"{",
"if",
"(",
"!",
"attribute",
")",
"throw",
"new",
"Error",
"(",
"'No attribute provided to create a range retrieval specifier.'",
")",
";",
"if",
"(",
"typeof",
"(",
"attribute",
")",
"===",
"'string'",
")",
"{",
"attribute",
"=",
"parseRangeRetrievalSpecifierAttribute",
"(",
"attribute",
")",
";",
"}",
"for",
"(",
"var",
"property",
"in",
"attribute",
")",
"{",
"if",
"(",
"Array",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"attribute",
",",
"property",
")",
")",
"{",
"this",
"[",
"property",
"]",
"=",
"attribute",
"[",
"property",
"]",
";",
"}",
"}",
"}",
"else",
"{",
"return",
"(",
"new",
"RangeRetrievalSpecifierAttribute",
"(",
"attribute",
")",
")",
";",
"}",
"}"
] |
Multi-valued attribute range retreival specifier.
@private
@constructor
@param {String|Object} attribute The actual attribute name. May also contain a full range retrieval specifier for parsing. (i.e. [attribute];range=[low]-[high]). Optionally an object can be specified.
@returns {RangeRetrievalSpecifierAttribute}
|
[
"Multi",
"-",
"valued",
"attribute",
"range",
"retreival",
"specifier",
"."
] |
409aaa1ba8af4b36e40f7d717637a9380cbc260a
|
https://github.com/gheeres/node-activedirectory/blob/409aaa1ba8af4b36e40f7d717637a9380cbc260a/lib/client/rangeretrievalspecifierattribute.js#L32-L48
|
|
14,982
|
itemsapi/itemsjs
|
src/fulltext.js
|
function(items, config) {
config = config || {};
config.searchableFields = config.searchableFields || [];
this.items = items;
// creating index
this.idx = lunr(function () {
// currently schema hardcoded
this.field('name', { boost: 10 });
var self = this;
_.forEach(config.searchableFields, function(field) {
self.field(field);
});
this.ref('id');
})
//var items2 = _.clone(items)
var i = 1;
_.map(items, (doc) => {
if (!doc.id) {
doc.id = i;
++i;
}
this.idx.add(doc)
})
this.store = _.mapKeys(items, (doc) => {
return doc.id;
})
}
|
javascript
|
function(items, config) {
config = config || {};
config.searchableFields = config.searchableFields || [];
this.items = items;
// creating index
this.idx = lunr(function () {
// currently schema hardcoded
this.field('name', { boost: 10 });
var self = this;
_.forEach(config.searchableFields, function(field) {
self.field(field);
});
this.ref('id');
})
//var items2 = _.clone(items)
var i = 1;
_.map(items, (doc) => {
if (!doc.id) {
doc.id = i;
++i;
}
this.idx.add(doc)
})
this.store = _.mapKeys(items, (doc) => {
return doc.id;
})
}
|
[
"function",
"(",
"items",
",",
"config",
")",
"{",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"config",
".",
"searchableFields",
"=",
"config",
".",
"searchableFields",
"||",
"[",
"]",
";",
"this",
".",
"items",
"=",
"items",
";",
"// creating index",
"this",
".",
"idx",
"=",
"lunr",
"(",
"function",
"(",
")",
"{",
"// currently schema hardcoded",
"this",
".",
"field",
"(",
"'name'",
",",
"{",
"boost",
":",
"10",
"}",
")",
";",
"var",
"self",
"=",
"this",
";",
"_",
".",
"forEach",
"(",
"config",
".",
"searchableFields",
",",
"function",
"(",
"field",
")",
"{",
"self",
".",
"field",
"(",
"field",
")",
";",
"}",
")",
";",
"this",
".",
"ref",
"(",
"'id'",
")",
";",
"}",
")",
"//var items2 = _.clone(items)",
"var",
"i",
"=",
"1",
";",
"_",
".",
"map",
"(",
"items",
",",
"(",
"doc",
")",
"=>",
"{",
"if",
"(",
"!",
"doc",
".",
"id",
")",
"{",
"doc",
".",
"id",
"=",
"i",
";",
"++",
"i",
";",
"}",
"this",
".",
"idx",
".",
"add",
"(",
"doc",
")",
"}",
")",
"this",
".",
"store",
"=",
"_",
".",
"mapKeys",
"(",
"items",
",",
"(",
"doc",
")",
"=>",
"{",
"return",
"doc",
".",
"id",
";",
"}",
")",
"}"
] |
responsible for making full text searching on items
config provide only searchableFields
|
[
"responsible",
"for",
"making",
"full",
"text",
"searching",
"on",
"items",
"config",
"provide",
"only",
"searchableFields"
] |
a399aca050a906dcabed6f22eb369ad41f1c2b6c
|
https://github.com/itemsapi/itemsjs/blob/a399aca050a906dcabed6f22eb369ad41f1c2b6c/src/fulltext.js#L8-L38
|
|
14,983
|
itemsapi/itemsjs
|
src/index.js
|
function(input) {
input = input || {};
/**
* merge configuration aggregation with user input
*/
input.aggregations = helpers.mergeAggregations(configuration.aggregations, input);
return service.search(items, input, configuration, fulltext);
}
|
javascript
|
function(input) {
input = input || {};
/**
* merge configuration aggregation with user input
*/
input.aggregations = helpers.mergeAggregations(configuration.aggregations, input);
return service.search(items, input, configuration, fulltext);
}
|
[
"function",
"(",
"input",
")",
"{",
"input",
"=",
"input",
"||",
"{",
"}",
";",
"/**\n * merge configuration aggregation with user input\n */",
"input",
".",
"aggregations",
"=",
"helpers",
".",
"mergeAggregations",
"(",
"configuration",
".",
"aggregations",
",",
"input",
")",
";",
"return",
"service",
".",
"search",
"(",
"items",
",",
"input",
",",
"configuration",
",",
"fulltext",
")",
";",
"}"
] |
per_page
page
query
sort
filters
|
[
"per_page",
"page",
"query",
"sort",
"filters"
] |
a399aca050a906dcabed6f22eb369ad41f1c2b6c
|
https://github.com/itemsapi/itemsjs/blob/a399aca050a906dcabed6f22eb369ad41f1c2b6c/src/index.js#L22-L31
|
|
14,984
|
thgh/rollup-plugin-serve
|
src/index.js
|
serve
|
function serve (options = { contentBase: '' }) {
if (Array.isArray(options) || typeof options === 'string') {
options = { contentBase: options }
}
options.contentBase = Array.isArray(options.contentBase) ? options.contentBase : [options.contentBase]
options.host = options.host || 'localhost'
options.port = options.port || 10001
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
mime.default_type = 'text/plain'
const requestListener = (request, response) => {
// Remove querystring
const urlPath = decodeURI(request.url.split('?')[0])
Object.keys(options.headers).forEach((key) => {
response.setHeader(key, options.headers[key])
})
readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
}
if (error.code !== 'ENOENT') {
response.writeHead(500)
response.end('500 Internal Server Error' +
'\n\n' + filePath +
'\n\n' + Object.values(error).join('\n') +
'\n\n(rollup-plugin-serve)', 'utf-8')
return
}
if (options.historyApiFallback) {
var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
if (error) {
notFound(response, filePath)
} else {
found(response, filePath, content)
}
})
} else {
notFound(response, filePath)
}
})
}
// release previous server instance if rollup is reloading configuration in watch mode
if (server) {
server.close()
}
// If HTTPS options are available, create an HTTPS server
if (options.https) {
server = createHttpsServer(options.https, requestListener).listen(options.port, options.host)
} else {
server = createServer(requestListener).listen(options.port, options.host)
}
closeServerOnTermination(server)
var running = options.verbose === false
return {
name: 'serve',
generateBundle () {
if (!running) {
running = true
// Log which url to visit
const url = (options.https ? 'https' : 'http') + '://' + options.host + ':' + options.port
options.contentBase.forEach(base => {
console.log(green(url) + ' -> ' + resolve(base))
})
// Open browser
if (options.open) {
opener(url + options.openPage)
}
}
}
}
}
|
javascript
|
function serve (options = { contentBase: '' }) {
if (Array.isArray(options) || typeof options === 'string') {
options = { contentBase: options }
}
options.contentBase = Array.isArray(options.contentBase) ? options.contentBase : [options.contentBase]
options.host = options.host || 'localhost'
options.port = options.port || 10001
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
mime.default_type = 'text/plain'
const requestListener = (request, response) => {
// Remove querystring
const urlPath = decodeURI(request.url.split('?')[0])
Object.keys(options.headers).forEach((key) => {
response.setHeader(key, options.headers[key])
})
readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
}
if (error.code !== 'ENOENT') {
response.writeHead(500)
response.end('500 Internal Server Error' +
'\n\n' + filePath +
'\n\n' + Object.values(error).join('\n') +
'\n\n(rollup-plugin-serve)', 'utf-8')
return
}
if (options.historyApiFallback) {
var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
if (error) {
notFound(response, filePath)
} else {
found(response, filePath, content)
}
})
} else {
notFound(response, filePath)
}
})
}
// release previous server instance if rollup is reloading configuration in watch mode
if (server) {
server.close()
}
// If HTTPS options are available, create an HTTPS server
if (options.https) {
server = createHttpsServer(options.https, requestListener).listen(options.port, options.host)
} else {
server = createServer(requestListener).listen(options.port, options.host)
}
closeServerOnTermination(server)
var running = options.verbose === false
return {
name: 'serve',
generateBundle () {
if (!running) {
running = true
// Log which url to visit
const url = (options.https ? 'https' : 'http') + '://' + options.host + ':' + options.port
options.contentBase.forEach(base => {
console.log(green(url) + ' -> ' + resolve(base))
})
// Open browser
if (options.open) {
opener(url + options.openPage)
}
}
}
}
}
|
[
"function",
"serve",
"(",
"options",
"=",
"{",
"contentBase",
":",
"''",
"}",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
")",
"||",
"typeof",
"options",
"===",
"'string'",
")",
"{",
"options",
"=",
"{",
"contentBase",
":",
"options",
"}",
"}",
"options",
".",
"contentBase",
"=",
"Array",
".",
"isArray",
"(",
"options",
".",
"contentBase",
")",
"?",
"options",
".",
"contentBase",
":",
"[",
"options",
".",
"contentBase",
"]",
"options",
".",
"host",
"=",
"options",
".",
"host",
"||",
"'localhost'",
"options",
".",
"port",
"=",
"options",
".",
"port",
"||",
"10001",
"options",
".",
"headers",
"=",
"options",
".",
"headers",
"||",
"{",
"}",
"options",
".",
"https",
"=",
"options",
".",
"https",
"||",
"false",
"options",
".",
"openPage",
"=",
"options",
".",
"openPage",
"||",
"''",
"mime",
".",
"default_type",
"=",
"'text/plain'",
"const",
"requestListener",
"=",
"(",
"request",
",",
"response",
")",
"=>",
"{",
"// Remove querystring",
"const",
"urlPath",
"=",
"decodeURI",
"(",
"request",
".",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
")",
"Object",
".",
"keys",
"(",
"options",
".",
"headers",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"response",
".",
"setHeader",
"(",
"key",
",",
"options",
".",
"headers",
"[",
"key",
"]",
")",
"}",
")",
"readFileFromContentBase",
"(",
"options",
".",
"contentBase",
",",
"urlPath",
",",
"function",
"(",
"error",
",",
"content",
",",
"filePath",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"return",
"found",
"(",
"response",
",",
"filePath",
",",
"content",
")",
"}",
"if",
"(",
"error",
".",
"code",
"!==",
"'ENOENT'",
")",
"{",
"response",
".",
"writeHead",
"(",
"500",
")",
"response",
".",
"end",
"(",
"'500 Internal Server Error'",
"+",
"'\\n\\n'",
"+",
"filePath",
"+",
"'\\n\\n'",
"+",
"Object",
".",
"values",
"(",
"error",
")",
".",
"join",
"(",
"'\\n'",
")",
"+",
"'\\n\\n(rollup-plugin-serve)'",
",",
"'utf-8'",
")",
"return",
"}",
"if",
"(",
"options",
".",
"historyApiFallback",
")",
"{",
"var",
"fallbackPath",
"=",
"typeof",
"options",
".",
"historyApiFallback",
"===",
"'string'",
"?",
"options",
".",
"historyApiFallback",
":",
"'/index.html'",
"readFileFromContentBase",
"(",
"options",
".",
"contentBase",
",",
"fallbackPath",
",",
"function",
"(",
"error",
",",
"content",
",",
"filePath",
")",
"{",
"if",
"(",
"error",
")",
"{",
"notFound",
"(",
"response",
",",
"filePath",
")",
"}",
"else",
"{",
"found",
"(",
"response",
",",
"filePath",
",",
"content",
")",
"}",
"}",
")",
"}",
"else",
"{",
"notFound",
"(",
"response",
",",
"filePath",
")",
"}",
"}",
")",
"}",
"// release previous server instance if rollup is reloading configuration in watch mode",
"if",
"(",
"server",
")",
"{",
"server",
".",
"close",
"(",
")",
"}",
"// If HTTPS options are available, create an HTTPS server",
"if",
"(",
"options",
".",
"https",
")",
"{",
"server",
"=",
"createHttpsServer",
"(",
"options",
".",
"https",
",",
"requestListener",
")",
".",
"listen",
"(",
"options",
".",
"port",
",",
"options",
".",
"host",
")",
"}",
"else",
"{",
"server",
"=",
"createServer",
"(",
"requestListener",
")",
".",
"listen",
"(",
"options",
".",
"port",
",",
"options",
".",
"host",
")",
"}",
"closeServerOnTermination",
"(",
"server",
")",
"var",
"running",
"=",
"options",
".",
"verbose",
"===",
"false",
"return",
"{",
"name",
":",
"'serve'",
",",
"generateBundle",
"(",
")",
"{",
"if",
"(",
"!",
"running",
")",
"{",
"running",
"=",
"true",
"// Log which url to visit",
"const",
"url",
"=",
"(",
"options",
".",
"https",
"?",
"'https'",
":",
"'http'",
")",
"+",
"'://'",
"+",
"options",
".",
"host",
"+",
"':'",
"+",
"options",
".",
"port",
"options",
".",
"contentBase",
".",
"forEach",
"(",
"base",
"=>",
"{",
"console",
".",
"log",
"(",
"green",
"(",
"url",
")",
"+",
"' -> '",
"+",
"resolve",
"(",
"base",
")",
")",
"}",
")",
"// Open browser",
"if",
"(",
"options",
".",
"open",
")",
"{",
"opener",
"(",
"url",
"+",
"options",
".",
"openPage",
")",
"}",
"}",
"}",
"}",
"}"
] |
Serve your rolled up bundle like webpack-dev-server
@param {ServeOptions|string|string[]} options
|
[
"Serve",
"your",
"rolled",
"up",
"bundle",
"like",
"webpack",
"-",
"dev",
"-",
"server"
] |
c9c4f4ee2a28a80d8dd98917a54116660a2c6bb5
|
https://github.com/thgh/rollup-plugin-serve/blob/c9c4f4ee2a28a80d8dd98917a54116660a2c6bb5/src/index.js#L15-L97
|
14,985
|
chieffancypants/angular-hotkeys
|
src/hotkeys.js
|
Hotkey
|
function Hotkey (combo, description, callback, action, allowIn, persistent) {
// TODO: Check that the values are sane because we could
// be trying to instantiate a new Hotkey with outside dev's
// supplied values
this.combo = combo instanceof Array ? combo : [combo];
this.description = description;
this.callback = callback;
this.action = action;
this.allowIn = allowIn;
this.persistent = persistent;
this._formated = null;
}
|
javascript
|
function Hotkey (combo, description, callback, action, allowIn, persistent) {
// TODO: Check that the values are sane because we could
// be trying to instantiate a new Hotkey with outside dev's
// supplied values
this.combo = combo instanceof Array ? combo : [combo];
this.description = description;
this.callback = callback;
this.action = action;
this.allowIn = allowIn;
this.persistent = persistent;
this._formated = null;
}
|
[
"function",
"Hotkey",
"(",
"combo",
",",
"description",
",",
"callback",
",",
"action",
",",
"allowIn",
",",
"persistent",
")",
"{",
"// TODO: Check that the values are sane because we could",
"// be trying to instantiate a new Hotkey with outside dev's",
"// supplied values",
"this",
".",
"combo",
"=",
"combo",
"instanceof",
"Array",
"?",
"combo",
":",
"[",
"combo",
"]",
";",
"this",
".",
"description",
"=",
"description",
";",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"action",
"=",
"action",
";",
"this",
".",
"allowIn",
"=",
"allowIn",
";",
"this",
".",
"persistent",
"=",
"persistent",
";",
"this",
".",
"_formated",
"=",
"null",
";",
"}"
] |
Hotkey object used internally for consistency
@param {array} combo The keycombo. it's an array to support multiple combos
@param {String} description Description for the keycombo
@param {Function} callback function to execute when keycombo pressed
@param {string} action the type of event to listen for (for mousetrap)
@param {array} allowIn an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
@param {Boolean} persistent Whether the hotkey persists navigation events
|
[
"Hotkey",
"object",
"used",
"internally",
"for",
"consistency"
] |
07251370c2f772acff204387d4b7d74831f1d777
|
https://github.com/chieffancypants/angular-hotkeys/blob/07251370c2f772acff204387d4b7d74831f1d777/src/hotkeys.js#L146-L158
|
14,986
|
chieffancypants/angular-hotkeys
|
src/hotkeys.js
|
_add
|
function _add (combo, description, callback, action, allowIn, persistent) {
// used to save original callback for "allowIn" wrapping:
var _callback;
// these elements are prevented by the default Mousetrap.stopCallback():
var preventIn = ['INPUT', 'SELECT', 'TEXTAREA'];
// Determine if object format was given:
var objType = Object.prototype.toString.call(combo);
if (objType === '[object Object]') {
description = combo.description;
callback = combo.callback;
action = combo.action;
persistent = combo.persistent;
allowIn = combo.allowIn;
combo = combo.combo;
}
// no duplicates please
_del(combo);
// description is optional:
if (description instanceof Function) {
action = callback;
callback = description;
description = '$$undefined$$';
} else if (angular.isUndefined(description)) {
description = '$$undefined$$';
}
// any items added through the public API are for controllers
// that persist through navigation, and thus undefined should mean
// true in this case.
if (persistent === undefined) {
persistent = true;
}
// if callback is defined, then wrap it in a function
// that checks if the event originated from a form element.
// the function blocks the callback from executing unless the element is specified
// in allowIn (emulates Mousetrap.stopCallback() on a per-key level)
if (typeof callback === 'function') {
// save the original callback
_callback = callback;
// make sure allowIn is an array
if (!(allowIn instanceof Array)) {
allowIn = [];
}
// remove anything from preventIn that's present in allowIn
var index;
for (var i=0; i < allowIn.length; i++) {
allowIn[i] = allowIn[i].toUpperCase();
index = preventIn.indexOf(allowIn[i]);
if (index !== -1) {
preventIn.splice(index, 1);
}
}
// create the new wrapper callback
callback = function(event) {
var shouldExecute = true;
// if the callback is executed directly `hotkey.get('w').callback()`
// there will be no event, so just execute the callback.
if (event) {
var target = event.target || event.srcElement; // srcElement is IE only
var nodeName = target.nodeName.toUpperCase();
// check if the input has a mousetrap class, and skip checking preventIn if so
if ((' ' + target.className + ' ').indexOf(' mousetrap ') > -1) {
shouldExecute = true;
} else {
// don't execute callback if the event was fired from inside an element listed in preventIn
for (var i=0; i<preventIn.length; i++) {
if (preventIn[i] === nodeName) {
shouldExecute = false;
break;
}
}
}
}
if (shouldExecute) {
wrapApply(_callback.apply(this, arguments));
}
};
}
if (typeof(action) === 'string') {
Mousetrap.bind(combo, wrapApply(callback), action);
} else {
Mousetrap.bind(combo, wrapApply(callback));
}
var hotkey = new Hotkey(combo, description, callback, action, allowIn, persistent);
scope.hotkeys.push(hotkey);
return hotkey;
}
|
javascript
|
function _add (combo, description, callback, action, allowIn, persistent) {
// used to save original callback for "allowIn" wrapping:
var _callback;
// these elements are prevented by the default Mousetrap.stopCallback():
var preventIn = ['INPUT', 'SELECT', 'TEXTAREA'];
// Determine if object format was given:
var objType = Object.prototype.toString.call(combo);
if (objType === '[object Object]') {
description = combo.description;
callback = combo.callback;
action = combo.action;
persistent = combo.persistent;
allowIn = combo.allowIn;
combo = combo.combo;
}
// no duplicates please
_del(combo);
// description is optional:
if (description instanceof Function) {
action = callback;
callback = description;
description = '$$undefined$$';
} else if (angular.isUndefined(description)) {
description = '$$undefined$$';
}
// any items added through the public API are for controllers
// that persist through navigation, and thus undefined should mean
// true in this case.
if (persistent === undefined) {
persistent = true;
}
// if callback is defined, then wrap it in a function
// that checks if the event originated from a form element.
// the function blocks the callback from executing unless the element is specified
// in allowIn (emulates Mousetrap.stopCallback() on a per-key level)
if (typeof callback === 'function') {
// save the original callback
_callback = callback;
// make sure allowIn is an array
if (!(allowIn instanceof Array)) {
allowIn = [];
}
// remove anything from preventIn that's present in allowIn
var index;
for (var i=0; i < allowIn.length; i++) {
allowIn[i] = allowIn[i].toUpperCase();
index = preventIn.indexOf(allowIn[i]);
if (index !== -1) {
preventIn.splice(index, 1);
}
}
// create the new wrapper callback
callback = function(event) {
var shouldExecute = true;
// if the callback is executed directly `hotkey.get('w').callback()`
// there will be no event, so just execute the callback.
if (event) {
var target = event.target || event.srcElement; // srcElement is IE only
var nodeName = target.nodeName.toUpperCase();
// check if the input has a mousetrap class, and skip checking preventIn if so
if ((' ' + target.className + ' ').indexOf(' mousetrap ') > -1) {
shouldExecute = true;
} else {
// don't execute callback if the event was fired from inside an element listed in preventIn
for (var i=0; i<preventIn.length; i++) {
if (preventIn[i] === nodeName) {
shouldExecute = false;
break;
}
}
}
}
if (shouldExecute) {
wrapApply(_callback.apply(this, arguments));
}
};
}
if (typeof(action) === 'string') {
Mousetrap.bind(combo, wrapApply(callback), action);
} else {
Mousetrap.bind(combo, wrapApply(callback));
}
var hotkey = new Hotkey(combo, description, callback, action, allowIn, persistent);
scope.hotkeys.push(hotkey);
return hotkey;
}
|
[
"function",
"_add",
"(",
"combo",
",",
"description",
",",
"callback",
",",
"action",
",",
"allowIn",
",",
"persistent",
")",
"{",
"// used to save original callback for \"allowIn\" wrapping:",
"var",
"_callback",
";",
"// these elements are prevented by the default Mousetrap.stopCallback():",
"var",
"preventIn",
"=",
"[",
"'INPUT'",
",",
"'SELECT'",
",",
"'TEXTAREA'",
"]",
";",
"// Determine if object format was given:",
"var",
"objType",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"combo",
")",
";",
"if",
"(",
"objType",
"===",
"'[object Object]'",
")",
"{",
"description",
"=",
"combo",
".",
"description",
";",
"callback",
"=",
"combo",
".",
"callback",
";",
"action",
"=",
"combo",
".",
"action",
";",
"persistent",
"=",
"combo",
".",
"persistent",
";",
"allowIn",
"=",
"combo",
".",
"allowIn",
";",
"combo",
"=",
"combo",
".",
"combo",
";",
"}",
"// no duplicates please",
"_del",
"(",
"combo",
")",
";",
"// description is optional:",
"if",
"(",
"description",
"instanceof",
"Function",
")",
"{",
"action",
"=",
"callback",
";",
"callback",
"=",
"description",
";",
"description",
"=",
"'$$undefined$$'",
";",
"}",
"else",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"description",
")",
")",
"{",
"description",
"=",
"'$$undefined$$'",
";",
"}",
"// any items added through the public API are for controllers",
"// that persist through navigation, and thus undefined should mean",
"// true in this case.",
"if",
"(",
"persistent",
"===",
"undefined",
")",
"{",
"persistent",
"=",
"true",
";",
"}",
"// if callback is defined, then wrap it in a function",
"// that checks if the event originated from a form element.",
"// the function blocks the callback from executing unless the element is specified",
"// in allowIn (emulates Mousetrap.stopCallback() on a per-key level)",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"// save the original callback",
"_callback",
"=",
"callback",
";",
"// make sure allowIn is an array",
"if",
"(",
"!",
"(",
"allowIn",
"instanceof",
"Array",
")",
")",
"{",
"allowIn",
"=",
"[",
"]",
";",
"}",
"// remove anything from preventIn that's present in allowIn",
"var",
"index",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"allowIn",
".",
"length",
";",
"i",
"++",
")",
"{",
"allowIn",
"[",
"i",
"]",
"=",
"allowIn",
"[",
"i",
"]",
".",
"toUpperCase",
"(",
")",
";",
"index",
"=",
"preventIn",
".",
"indexOf",
"(",
"allowIn",
"[",
"i",
"]",
")",
";",
"if",
"(",
"index",
"!==",
"-",
"1",
")",
"{",
"preventIn",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}",
"// create the new wrapper callback",
"callback",
"=",
"function",
"(",
"event",
")",
"{",
"var",
"shouldExecute",
"=",
"true",
";",
"// if the callback is executed directly `hotkey.get('w').callback()`",
"// there will be no event, so just execute the callback.",
"if",
"(",
"event",
")",
"{",
"var",
"target",
"=",
"event",
".",
"target",
"||",
"event",
".",
"srcElement",
";",
"// srcElement is IE only",
"var",
"nodeName",
"=",
"target",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
";",
"// check if the input has a mousetrap class, and skip checking preventIn if so",
"if",
"(",
"(",
"' '",
"+",
"target",
".",
"className",
"+",
"' '",
")",
".",
"indexOf",
"(",
"' mousetrap '",
")",
">",
"-",
"1",
")",
"{",
"shouldExecute",
"=",
"true",
";",
"}",
"else",
"{",
"// don't execute callback if the event was fired from inside an element listed in preventIn",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"preventIn",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"preventIn",
"[",
"i",
"]",
"===",
"nodeName",
")",
"{",
"shouldExecute",
"=",
"false",
";",
"break",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"shouldExecute",
")",
"{",
"wrapApply",
"(",
"_callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"}",
";",
"}",
"if",
"(",
"typeof",
"(",
"action",
")",
"===",
"'string'",
")",
"{",
"Mousetrap",
".",
"bind",
"(",
"combo",
",",
"wrapApply",
"(",
"callback",
")",
",",
"action",
")",
";",
"}",
"else",
"{",
"Mousetrap",
".",
"bind",
"(",
"combo",
",",
"wrapApply",
"(",
"callback",
")",
")",
";",
"}",
"var",
"hotkey",
"=",
"new",
"Hotkey",
"(",
"combo",
",",
"description",
",",
"callback",
",",
"action",
",",
"allowIn",
",",
"persistent",
")",
";",
"scope",
".",
"hotkeys",
".",
"push",
"(",
"hotkey",
")",
";",
"return",
"hotkey",
";",
"}"
] |
Creates a new Hotkey and creates the Mousetrap binding
@param {string} combo mousetrap key binding
@param {string} description description for the help menu
@param {Function} callback method to call when key is pressed
@param {string} action the type of event to listen for (for mousetrap)
@param {array} allowIn an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
@param {boolean} persistent if true, the binding is preserved upon route changes
|
[
"Creates",
"a",
"new",
"Hotkey",
"and",
"creates",
"the",
"Mousetrap",
"binding"
] |
07251370c2f772acff204387d4b7d74831f1d777
|
https://github.com/chieffancypants/angular-hotkeys/blob/07251370c2f772acff204387d4b7d74831f1d777/src/hotkeys.js#L332-L433
|
14,987
|
chieffancypants/angular-hotkeys
|
src/hotkeys.js
|
_del
|
function _del (hotkey) {
var combo = (hotkey instanceof Hotkey) ? hotkey.combo : hotkey;
Mousetrap.unbind(combo);
if (angular.isArray(combo)) {
var retStatus = true;
var i = combo.length;
while (i--) {
retStatus = _del(combo[i]) && retStatus;
}
return retStatus;
} else {
var index = scope.hotkeys.indexOf(_get(combo));
if (index > -1) {
// if the combo has other combos bound, don't unbind the whole thing, just the one combo:
if (scope.hotkeys[index].combo.length > 1) {
scope.hotkeys[index].combo.splice(scope.hotkeys[index].combo.indexOf(combo), 1);
} else {
// remove hotkey from bound scopes
angular.forEach(boundScopes, function (boundScope) {
var scopeIndex = boundScope.indexOf(scope.hotkeys[index]);
if (scopeIndex !== -1) {
boundScope.splice(scopeIndex, 1);
}
});
scope.hotkeys.splice(index, 1);
}
return true;
}
}
return false;
}
|
javascript
|
function _del (hotkey) {
var combo = (hotkey instanceof Hotkey) ? hotkey.combo : hotkey;
Mousetrap.unbind(combo);
if (angular.isArray(combo)) {
var retStatus = true;
var i = combo.length;
while (i--) {
retStatus = _del(combo[i]) && retStatus;
}
return retStatus;
} else {
var index = scope.hotkeys.indexOf(_get(combo));
if (index > -1) {
// if the combo has other combos bound, don't unbind the whole thing, just the one combo:
if (scope.hotkeys[index].combo.length > 1) {
scope.hotkeys[index].combo.splice(scope.hotkeys[index].combo.indexOf(combo), 1);
} else {
// remove hotkey from bound scopes
angular.forEach(boundScopes, function (boundScope) {
var scopeIndex = boundScope.indexOf(scope.hotkeys[index]);
if (scopeIndex !== -1) {
boundScope.splice(scopeIndex, 1);
}
});
scope.hotkeys.splice(index, 1);
}
return true;
}
}
return false;
}
|
[
"function",
"_del",
"(",
"hotkey",
")",
"{",
"var",
"combo",
"=",
"(",
"hotkey",
"instanceof",
"Hotkey",
")",
"?",
"hotkey",
".",
"combo",
":",
"hotkey",
";",
"Mousetrap",
".",
"unbind",
"(",
"combo",
")",
";",
"if",
"(",
"angular",
".",
"isArray",
"(",
"combo",
")",
")",
"{",
"var",
"retStatus",
"=",
"true",
";",
"var",
"i",
"=",
"combo",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"retStatus",
"=",
"_del",
"(",
"combo",
"[",
"i",
"]",
")",
"&&",
"retStatus",
";",
"}",
"return",
"retStatus",
";",
"}",
"else",
"{",
"var",
"index",
"=",
"scope",
".",
"hotkeys",
".",
"indexOf",
"(",
"_get",
"(",
"combo",
")",
")",
";",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"// if the combo has other combos bound, don't unbind the whole thing, just the one combo:",
"if",
"(",
"scope",
".",
"hotkeys",
"[",
"index",
"]",
".",
"combo",
".",
"length",
">",
"1",
")",
"{",
"scope",
".",
"hotkeys",
"[",
"index",
"]",
".",
"combo",
".",
"splice",
"(",
"scope",
".",
"hotkeys",
"[",
"index",
"]",
".",
"combo",
".",
"indexOf",
"(",
"combo",
")",
",",
"1",
")",
";",
"}",
"else",
"{",
"// remove hotkey from bound scopes",
"angular",
".",
"forEach",
"(",
"boundScopes",
",",
"function",
"(",
"boundScope",
")",
"{",
"var",
"scopeIndex",
"=",
"boundScope",
".",
"indexOf",
"(",
"scope",
".",
"hotkeys",
"[",
"index",
"]",
")",
";",
"if",
"(",
"scopeIndex",
"!==",
"-",
"1",
")",
"{",
"boundScope",
".",
"splice",
"(",
"scopeIndex",
",",
"1",
")",
";",
"}",
"}",
")",
";",
"scope",
".",
"hotkeys",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
delete and unbind a Hotkey
@param {mixed} hotkey Either the bound key or an instance of Hotkey
@return {boolean} true if successful
|
[
"delete",
"and",
"unbind",
"a",
"Hotkey"
] |
07251370c2f772acff204387d4b7d74831f1d777
|
https://github.com/chieffancypants/angular-hotkeys/blob/07251370c2f772acff204387d4b7d74831f1d777/src/hotkeys.js#L441-L478
|
14,988
|
chieffancypants/angular-hotkeys
|
src/hotkeys.js
|
_get
|
function _get (combo) {
if (!combo) {
return scope.hotkeys;
}
var hotkey;
for (var i = 0; i < scope.hotkeys.length; i++) {
hotkey = scope.hotkeys[i];
if (hotkey.combo.indexOf(combo) > -1) {
return hotkey;
}
}
return false;
}
|
javascript
|
function _get (combo) {
if (!combo) {
return scope.hotkeys;
}
var hotkey;
for (var i = 0; i < scope.hotkeys.length; i++) {
hotkey = scope.hotkeys[i];
if (hotkey.combo.indexOf(combo) > -1) {
return hotkey;
}
}
return false;
}
|
[
"function",
"_get",
"(",
"combo",
")",
"{",
"if",
"(",
"!",
"combo",
")",
"{",
"return",
"scope",
".",
"hotkeys",
";",
"}",
"var",
"hotkey",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"scope",
".",
"hotkeys",
".",
"length",
";",
"i",
"++",
")",
"{",
"hotkey",
"=",
"scope",
".",
"hotkeys",
"[",
"i",
"]",
";",
"if",
"(",
"hotkey",
".",
"combo",
".",
"indexOf",
"(",
"combo",
")",
">",
"-",
"1",
")",
"{",
"return",
"hotkey",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Get a Hotkey object by key binding
@param {[string]} [combo] the key the Hotkey is bound to. Returns all key bindings if no key is passed
@return {Hotkey} The Hotkey object
|
[
"Get",
"a",
"Hotkey",
"object",
"by",
"key",
"binding"
] |
07251370c2f772acff204387d4b7d74831f1d777
|
https://github.com/chieffancypants/angular-hotkeys/blob/07251370c2f772acff204387d4b7d74831f1d777/src/hotkeys.js#L486-L503
|
14,989
|
chieffancypants/angular-hotkeys
|
src/hotkeys.js
|
bindTo
|
function bindTo (scope) {
// Only initialize once to allow multiple calls for same scope.
if (!(scope.$id in boundScopes)) {
// Add the scope to the list of bound scopes
boundScopes[scope.$id] = [];
scope.$on('$destroy', function () {
var i = boundScopes[scope.$id].length;
while (i--) {
_del(boundScopes[scope.$id].pop());
}
});
}
// return an object with an add function so we can keep track of the
// hotkeys and their scope that we added via this chaining method
return {
add: function (args) {
var hotkey;
if (arguments.length > 1) {
hotkey = _add.apply(this, arguments);
} else {
hotkey = _add(args);
}
boundScopes[scope.$id].push(hotkey);
return this;
}
};
}
|
javascript
|
function bindTo (scope) {
// Only initialize once to allow multiple calls for same scope.
if (!(scope.$id in boundScopes)) {
// Add the scope to the list of bound scopes
boundScopes[scope.$id] = [];
scope.$on('$destroy', function () {
var i = boundScopes[scope.$id].length;
while (i--) {
_del(boundScopes[scope.$id].pop());
}
});
}
// return an object with an add function so we can keep track of the
// hotkeys and their scope that we added via this chaining method
return {
add: function (args) {
var hotkey;
if (arguments.length > 1) {
hotkey = _add.apply(this, arguments);
} else {
hotkey = _add(args);
}
boundScopes[scope.$id].push(hotkey);
return this;
}
};
}
|
[
"function",
"bindTo",
"(",
"scope",
")",
"{",
"// Only initialize once to allow multiple calls for same scope.",
"if",
"(",
"!",
"(",
"scope",
".",
"$id",
"in",
"boundScopes",
")",
")",
"{",
"// Add the scope to the list of bound scopes",
"boundScopes",
"[",
"scope",
".",
"$id",
"]",
"=",
"[",
"]",
";",
"scope",
".",
"$on",
"(",
"'$destroy'",
",",
"function",
"(",
")",
"{",
"var",
"i",
"=",
"boundScopes",
"[",
"scope",
".",
"$id",
"]",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"_del",
"(",
"boundScopes",
"[",
"scope",
".",
"$id",
"]",
".",
"pop",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"// return an object with an add function so we can keep track of the",
"// hotkeys and their scope that we added via this chaining method",
"return",
"{",
"add",
":",
"function",
"(",
"args",
")",
"{",
"var",
"hotkey",
";",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
")",
"{",
"hotkey",
"=",
"_add",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"hotkey",
"=",
"_add",
"(",
"args",
")",
";",
"}",
"boundScopes",
"[",
"scope",
".",
"$id",
"]",
".",
"push",
"(",
"hotkey",
")",
";",
"return",
"this",
";",
"}",
"}",
";",
"}"
] |
Binds the hotkey to a particular scope. Useful if the scope is
destroyed, we can automatically destroy the hotkey binding.
@param {Object} scope The scope to bind to
|
[
"Binds",
"the",
"hotkey",
"to",
"a",
"particular",
"scope",
".",
"Useful",
"if",
"the",
"scope",
"is",
"destroyed",
"we",
"can",
"automatically",
"destroy",
"the",
"hotkey",
"binding",
"."
] |
07251370c2f772acff204387d4b7d74831f1d777
|
https://github.com/chieffancypants/angular-hotkeys/blob/07251370c2f772acff204387d4b7d74831f1d777/src/hotkeys.js#L511-L541
|
14,990
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/methodCache.js
|
create
|
function create(method, options = {}) {
options = Object.assign(exports.defaults, options);
exports.results.set(method, new lru_cache_1.default(options));
return exports.results.get(method);
}
|
javascript
|
function create(method, options = {}) {
options = Object.assign(exports.defaults, options);
exports.results.set(method, new lru_cache_1.default(options));
return exports.results.get(method);
}
|
[
"function",
"create",
"(",
"method",
",",
"options",
"=",
"{",
"}",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"exports",
".",
"defaults",
",",
"options",
")",
";",
"exports",
".",
"results",
".",
"set",
"(",
"method",
",",
"new",
"lru_cache_1",
".",
"default",
"(",
"options",
")",
")",
";",
"return",
"exports",
".",
"results",
".",
"get",
"(",
"method",
")",
";",
"}"
] |
Setup a cache for a method call.
@param method Method name, for index of cached results
@param options.max Maximum size of cache
@param options.maxAge Maximum age of cache
|
[
"Setup",
"a",
"cache",
"for",
"a",
"method",
"call",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/methodCache.js#L27-L31
|
14,991
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/methodCache.js
|
call
|
function call(method, key) {
if (!exports.results.has(method))
create(method); // create as needed
const methodCache = exports.results.get(method);
let callResults;
if (methodCache.has(key)) {
log_1.logger.debug(`[${method}] Calling (cached): ${key}`);
// return from cache if key has been used on method before
callResults = methodCache.get(key);
}
else {
// call and cache for next time, returning results
log_1.logger.debug(`[${method}] Calling (caching): ${key}`);
callResults = exports.instance.call(method, key).result;
methodCache.set(key, callResults);
}
return Promise.resolve(callResults);
}
|
javascript
|
function call(method, key) {
if (!exports.results.has(method))
create(method); // create as needed
const methodCache = exports.results.get(method);
let callResults;
if (methodCache.has(key)) {
log_1.logger.debug(`[${method}] Calling (cached): ${key}`);
// return from cache if key has been used on method before
callResults = methodCache.get(key);
}
else {
// call and cache for next time, returning results
log_1.logger.debug(`[${method}] Calling (caching): ${key}`);
callResults = exports.instance.call(method, key).result;
methodCache.set(key, callResults);
}
return Promise.resolve(callResults);
}
|
[
"function",
"call",
"(",
"method",
",",
"key",
")",
"{",
"if",
"(",
"!",
"exports",
".",
"results",
".",
"has",
"(",
"method",
")",
")",
"create",
"(",
"method",
")",
";",
"// create as needed",
"const",
"methodCache",
"=",
"exports",
".",
"results",
".",
"get",
"(",
"method",
")",
";",
"let",
"callResults",
";",
"if",
"(",
"methodCache",
".",
"has",
"(",
"key",
")",
")",
"{",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"${",
"key",
"}",
"`",
")",
";",
"// return from cache if key has been used on method before",
"callResults",
"=",
"methodCache",
".",
"get",
"(",
"key",
")",
";",
"}",
"else",
"{",
"// call and cache for next time, returning results",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"${",
"key",
"}",
"`",
")",
";",
"callResults",
"=",
"exports",
".",
"instance",
".",
"call",
"(",
"method",
",",
"key",
")",
".",
"result",
";",
"methodCache",
".",
"set",
"(",
"key",
",",
"callResults",
")",
";",
"}",
"return",
"Promise",
".",
"resolve",
"(",
"callResults",
")",
";",
"}"
] |
Get results of a prior method call or call and cache.
@param method Method name, to call on instance in use
@param key Key to pass to method call and save results against
|
[
"Get",
"results",
"of",
"a",
"prior",
"method",
"call",
"or",
"call",
"and",
"cache",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/methodCache.js#L38-L55
|
14,992
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/methodCache.js
|
get
|
function get(method, key) {
if (exports.results.has(method))
return exports.results.get(method).get(key);
}
|
javascript
|
function get(method, key) {
if (exports.results.has(method))
return exports.results.get(method).get(key);
}
|
[
"function",
"get",
"(",
"method",
",",
"key",
")",
"{",
"if",
"(",
"exports",
".",
"results",
".",
"has",
"(",
"method",
")",
")",
"return",
"exports",
".",
"results",
".",
"get",
"(",
"method",
")",
".",
"get",
"(",
"key",
")",
";",
"}"
] |
Get results of a prior method call.
@param method Method name for cache to get
@param key Key for method result set to return
|
[
"Get",
"results",
"of",
"a",
"prior",
"method",
"call",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/methodCache.js#L71-L74
|
14,993
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
getQueryString
|
function getQueryString(data) {
if (!data || typeof data !== 'object' || !Object.keys(data).length)
return '';
return '?' + Object.keys(data).map((k) => {
const value = (typeof data[k] === 'object')
? JSON.stringify(data[k])
: encodeURIComponent(data[k]);
return `${encodeURIComponent(k)}=${value}`;
}).join('&');
}
|
javascript
|
function getQueryString(data) {
if (!data || typeof data !== 'object' || !Object.keys(data).length)
return '';
return '?' + Object.keys(data).map((k) => {
const value = (typeof data[k] === 'object')
? JSON.stringify(data[k])
: encodeURIComponent(data[k]);
return `${encodeURIComponent(k)}=${value}`;
}).join('&');
}
|
[
"function",
"getQueryString",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"data",
"||",
"typeof",
"data",
"!==",
"'object'",
"||",
"!",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"length",
")",
"return",
"''",
";",
"return",
"'?'",
"+",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"map",
"(",
"(",
"k",
")",
"=>",
"{",
"const",
"value",
"=",
"(",
"typeof",
"data",
"[",
"k",
"]",
"===",
"'object'",
")",
"?",
"JSON",
".",
"stringify",
"(",
"data",
"[",
"k",
"]",
")",
":",
"encodeURIComponent",
"(",
"data",
"[",
"k",
"]",
")",
";",
"return",
"`",
"${",
"encodeURIComponent",
"(",
"k",
")",
"}",
"${",
"value",
"}",
"`",
";",
"}",
")",
".",
"join",
"(",
"'&'",
")",
";",
"}"
] |
Convert payload data to query string for GET requests
|
[
"Convert",
"payload",
"data",
"to",
"query",
"string",
"for",
"GET",
"requests"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L38-L47
|
14,994
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
getHeaders
|
function getHeaders(authRequired = false) {
if (!authRequired)
return exports.basicHeaders;
if ((!('X-Auth-Token' in exports.authHeaders) || !('X-User-Id' in exports.authHeaders)) ||
exports.authHeaders['X-Auth-Token'] === '' ||
exports.authHeaders['X-User-Id'] === '') {
throw new Error('Auth required endpoint cannot be called before login');
}
return Object.assign({}, exports.basicHeaders, exports.authHeaders);
}
|
javascript
|
function getHeaders(authRequired = false) {
if (!authRequired)
return exports.basicHeaders;
if ((!('X-Auth-Token' in exports.authHeaders) || !('X-User-Id' in exports.authHeaders)) ||
exports.authHeaders['X-Auth-Token'] === '' ||
exports.authHeaders['X-User-Id'] === '') {
throw new Error('Auth required endpoint cannot be called before login');
}
return Object.assign({}, exports.basicHeaders, exports.authHeaders);
}
|
[
"function",
"getHeaders",
"(",
"authRequired",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"authRequired",
")",
"return",
"exports",
".",
"basicHeaders",
";",
"if",
"(",
"(",
"!",
"(",
"'X-Auth-Token'",
"in",
"exports",
".",
"authHeaders",
")",
"||",
"!",
"(",
"'X-User-Id'",
"in",
"exports",
".",
"authHeaders",
")",
")",
"||",
"exports",
".",
"authHeaders",
"[",
"'X-Auth-Token'",
"]",
"===",
"''",
"||",
"exports",
".",
"authHeaders",
"[",
"'X-User-Id'",
"]",
"===",
"''",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Auth required endpoint cannot be called before login'",
")",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"exports",
".",
"basicHeaders",
",",
"exports",
".",
"authHeaders",
")",
";",
"}"
] |
Join basic headers with auth headers if required
|
[
"Join",
"basic",
"headers",
"with",
"auth",
"headers",
"if",
"required"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L59-L68
|
14,995
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
success
|
function success(result, ignore) {
return ((typeof result.error === 'undefined' &&
typeof result.status === 'undefined' &&
typeof result.success === 'undefined') ||
(result.status && result.status === 'success') ||
(result.success && result.success === true) ||
(ignore && result.error && !ignore.test(result.error))) ? true : false;
}
|
javascript
|
function success(result, ignore) {
return ((typeof result.error === 'undefined' &&
typeof result.status === 'undefined' &&
typeof result.success === 'undefined') ||
(result.status && result.status === 'success') ||
(result.success && result.success === true) ||
(ignore && result.error && !ignore.test(result.error))) ? true : false;
}
|
[
"function",
"success",
"(",
"result",
",",
"ignore",
")",
"{",
"return",
"(",
"(",
"typeof",
"result",
".",
"error",
"===",
"'undefined'",
"&&",
"typeof",
"result",
".",
"status",
"===",
"'undefined'",
"&&",
"typeof",
"result",
".",
"success",
"===",
"'undefined'",
")",
"||",
"(",
"result",
".",
"status",
"&&",
"result",
".",
"status",
"===",
"'success'",
")",
"||",
"(",
"result",
".",
"success",
"&&",
"result",
".",
"success",
"===",
"true",
")",
"||",
"(",
"ignore",
"&&",
"result",
".",
"error",
"&&",
"!",
"ignore",
".",
"test",
"(",
"result",
".",
"error",
")",
")",
")",
"?",
"true",
":",
"false",
";",
"}"
] |
Check result data for success, allowing override to ignore some errors
|
[
"Check",
"result",
"data",
"for",
"success",
"allowing",
"override",
"to",
"ignore",
"some",
"errors"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L77-L84
|
14,996
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
get
|
function get(endpoint, data, auth = true, ignore) {
return __awaiter(this, void 0, void 0, function* () {
try {
log_1.logger.debug(`[API] GET: ${endpoint}`, data);
if (auth && !loggedIn())
yield login();
let headers = getHeaders(auth);
const query = getQueryString(data);
const result = yield new Promise((resolve, reject) => {
exports.client.get(exports.url + endpoint + query, { headers }, (result) => {
if (Buffer.isBuffer(result))
reject('Result was buffer (HTML, not JSON)');
else if (!success(result, ignore))
reject(result);
else
resolve(result);
}).on('error', (err) => reject(err));
});
log_1.logger.debug('[API] GET result:', result);
return result;
}
catch (err) {
log_1.logger.error(`[API] GET error (${endpoint}):`, err);
}
});
}
|
javascript
|
function get(endpoint, data, auth = true, ignore) {
return __awaiter(this, void 0, void 0, function* () {
try {
log_1.logger.debug(`[API] GET: ${endpoint}`, data);
if (auth && !loggedIn())
yield login();
let headers = getHeaders(auth);
const query = getQueryString(data);
const result = yield new Promise((resolve, reject) => {
exports.client.get(exports.url + endpoint + query, { headers }, (result) => {
if (Buffer.isBuffer(result))
reject('Result was buffer (HTML, not JSON)');
else if (!success(result, ignore))
reject(result);
else
resolve(result);
}).on('error', (err) => reject(err));
});
log_1.logger.debug('[API] GET result:', result);
return result;
}
catch (err) {
log_1.logger.error(`[API] GET error (${endpoint}):`, err);
}
});
}
|
[
"function",
"get",
"(",
"endpoint",
",",
"data",
",",
"auth",
"=",
"true",
",",
"ignore",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"try",
"{",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"endpoint",
"}",
"`",
",",
"data",
")",
";",
"if",
"(",
"auth",
"&&",
"!",
"loggedIn",
"(",
")",
")",
"yield",
"login",
"(",
")",
";",
"let",
"headers",
"=",
"getHeaders",
"(",
"auth",
")",
";",
"const",
"query",
"=",
"getQueryString",
"(",
"data",
")",
";",
"const",
"result",
"=",
"yield",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"exports",
".",
"client",
".",
"get",
"(",
"exports",
".",
"url",
"+",
"endpoint",
"+",
"query",
",",
"{",
"headers",
"}",
",",
"(",
"result",
")",
"=>",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"result",
")",
")",
"reject",
"(",
"'Result was buffer (HTML, not JSON)'",
")",
";",
"else",
"if",
"(",
"!",
"success",
"(",
"result",
",",
"ignore",
")",
")",
"reject",
"(",
"result",
")",
";",
"else",
"resolve",
"(",
"result",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"reject",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"log_1",
".",
"logger",
".",
"debug",
"(",
"'[API] GET result:'",
",",
"result",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"endpoint",
"}",
"`",
",",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Do a GET request to an API endpoint
@param endpoint The API endpoint (including version) e.g. `users.info`
@param data Object to serialise for GET request query string
@param auth Require auth headers for endpoint, default true
@param ignore Allows certain matching error messages to not count as errors
|
[
"Do",
"a",
"GET",
"request",
"to",
"an",
"API",
"endpoint"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L129-L154
|
14,997
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
login
|
function login(user = {
username: settings.username,
password: settings.password
}) {
return __awaiter(this, void 0, void 0, function* () {
log_1.logger.info(`[API] Logging in ${user.username}`);
if (exports.currentLogin !== null) {
log_1.logger.debug(`[API] Already logged in`);
if (exports.currentLogin.username === user.username) {
return exports.currentLogin.result;
}
else {
yield logout();
}
}
const result = yield post('login', user, false);
if (result && result.data && result.data.authToken) {
exports.currentLogin = {
result: result,
username: user.username,
authToken: result.data.authToken,
userId: result.data.userId
};
setAuth(exports.currentLogin);
log_1.logger.info(`[API] Logged in ID ${exports.currentLogin.userId}`);
return result;
}
else {
throw new Error(`[API] Login failed for ${user.username}`);
}
});
}
|
javascript
|
function login(user = {
username: settings.username,
password: settings.password
}) {
return __awaiter(this, void 0, void 0, function* () {
log_1.logger.info(`[API] Logging in ${user.username}`);
if (exports.currentLogin !== null) {
log_1.logger.debug(`[API] Already logged in`);
if (exports.currentLogin.username === user.username) {
return exports.currentLogin.result;
}
else {
yield logout();
}
}
const result = yield post('login', user, false);
if (result && result.data && result.data.authToken) {
exports.currentLogin = {
result: result,
username: user.username,
authToken: result.data.authToken,
userId: result.data.userId
};
setAuth(exports.currentLogin);
log_1.logger.info(`[API] Logged in ID ${exports.currentLogin.userId}`);
return result;
}
else {
throw new Error(`[API] Login failed for ${user.username}`);
}
});
}
|
[
"function",
"login",
"(",
"user",
"=",
"{",
"username",
":",
"settings",
".",
"username",
",",
"password",
":",
"settings",
".",
"password",
"}",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"user",
".",
"username",
"}",
"`",
")",
";",
"if",
"(",
"exports",
".",
"currentLogin",
"!==",
"null",
")",
"{",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"`",
")",
";",
"if",
"(",
"exports",
".",
"currentLogin",
".",
"username",
"===",
"user",
".",
"username",
")",
"{",
"return",
"exports",
".",
"currentLogin",
".",
"result",
";",
"}",
"else",
"{",
"yield",
"logout",
"(",
")",
";",
"}",
"}",
"const",
"result",
"=",
"yield",
"post",
"(",
"'login'",
",",
"user",
",",
"false",
")",
";",
"if",
"(",
"result",
"&&",
"result",
".",
"data",
"&&",
"result",
".",
"data",
".",
"authToken",
")",
"{",
"exports",
".",
"currentLogin",
"=",
"{",
"result",
":",
"result",
",",
"username",
":",
"user",
".",
"username",
",",
"authToken",
":",
"result",
".",
"data",
".",
"authToken",
",",
"userId",
":",
"result",
".",
"data",
".",
"userId",
"}",
";",
"setAuth",
"(",
"exports",
".",
"currentLogin",
")",
";",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"exports",
".",
"currentLogin",
".",
"userId",
"}",
"`",
")",
";",
"return",
"result",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"user",
".",
"username",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Login a user for further API calls
Result should come back with a token, to authorise following requests.
Use env default credentials, unless overridden by login arguments.
|
[
"Login",
"a",
"user",
"for",
"further",
"API",
"calls",
"Result",
"should",
"come",
"back",
"with",
"a",
"token",
"to",
"authorise",
"following",
"requests",
".",
"Use",
"env",
"default",
"credentials",
"unless",
"overridden",
"by",
"login",
"arguments",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L161-L192
|
14,998
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/api.js
|
logout
|
function logout() {
if (exports.currentLogin === null) {
log_1.logger.debug(`[API] Already logged out`);
return Promise.resolve();
}
log_1.logger.info(`[API] Logging out ${exports.currentLogin.username}`);
return get('logout', null, true).then(() => {
clearHeaders();
exports.currentLogin = null;
});
}
|
javascript
|
function logout() {
if (exports.currentLogin === null) {
log_1.logger.debug(`[API] Already logged out`);
return Promise.resolve();
}
log_1.logger.info(`[API] Logging out ${exports.currentLogin.username}`);
return get('logout', null, true).then(() => {
clearHeaders();
exports.currentLogin = null;
});
}
|
[
"function",
"logout",
"(",
")",
"{",
"if",
"(",
"exports",
".",
"currentLogin",
"===",
"null",
")",
"{",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"exports",
".",
"currentLogin",
".",
"username",
"}",
"`",
")",
";",
"return",
"get",
"(",
"'logout'",
",",
"null",
",",
"true",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"clearHeaders",
"(",
")",
";",
"exports",
".",
"currentLogin",
"=",
"null",
";",
"}",
")",
";",
"}"
] |
Logout a user at end of API calls
|
[
"Logout",
"a",
"user",
"at",
"end",
"of",
"API",
"calls"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/api.js#L195-L205
|
14,999
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
asyncCall
|
function asyncCall(method, params) {
if (!Array.isArray(params))
params = [params]; // cast to array for apply
log_1.logger.info(`[${method}] Calling (async): ${JSON.stringify(params)}`);
return Promise.resolve(exports.asteroid.apply(method, params).result)
.catch((err) => {
log_1.logger.error(`[${method}] Error:`, err);
throw err; // throw after log to stop async chain
})
.then((result) => {
(result)
? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`)
: log_1.logger.debug(`[${method}] Success`);
return result;
});
}
|
javascript
|
function asyncCall(method, params) {
if (!Array.isArray(params))
params = [params]; // cast to array for apply
log_1.logger.info(`[${method}] Calling (async): ${JSON.stringify(params)}`);
return Promise.resolve(exports.asteroid.apply(method, params).result)
.catch((err) => {
log_1.logger.error(`[${method}] Error:`, err);
throw err; // throw after log to stop async chain
})
.then((result) => {
(result)
? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`)
: log_1.logger.debug(`[${method}] Success`);
return result;
});
}
|
[
"function",
"asyncCall",
"(",
"method",
",",
"params",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"params",
")",
")",
"params",
"=",
"[",
"params",
"]",
";",
"// cast to array for apply",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"method",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"params",
")",
"}",
"`",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"exports",
".",
"asteroid",
".",
"apply",
"(",
"method",
",",
"params",
")",
".",
"result",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"method",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"// throw after log to stop async chain",
"}",
")",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"{",
"(",
"result",
")",
"?",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
":",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"`",
")",
";",
"return",
"result",
";",
"}",
")",
";",
"}"
] |
Wraps method calls to ensure they return a Promise with caught exceptions.
@param method The Rocket.Chat server method, to call through Asteroid
@param params Single or array of parameters of the method to call
|
[
"Wraps",
"method",
"calls",
"to",
"ensure",
"they",
"return",
"a",
"Promise",
"with",
"caught",
"exceptions",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L148-L163
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.