repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
winjs/react-winjs | react-winjs.js | function (propType) {
return {
propType: propType,
preCtorInit: function focusProperty_preCtorInit(element, options, data, displayName, propName, value) {
options[propName] = value;
},
update: function focusProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
asyncToken = setImmediate(function () {
winjsComponent.data[propName] = null;
winjsComponent.winControl[propName] = newValue;
});
}
},
dispose: function focusProperty_dispose(winjsComponent, propName) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
}
};
} | javascript | function (propType) {
return {
propType: propType,
preCtorInit: function focusProperty_preCtorInit(element, options, data, displayName, propName, value) {
options[propName] = value;
},
update: function focusProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
asyncToken = setImmediate(function () {
winjsComponent.data[propName] = null;
winjsComponent.winControl[propName] = newValue;
});
}
},
dispose: function focusProperty_dispose(winjsComponent, propName) {
var asyncToken = winjsComponent.data[propName];
asyncToken && clearImmediate(asyncToken);
}
};
} | [
"function",
"(",
"propType",
")",
"{",
"return",
"{",
"propType",
":",
"propType",
",",
"preCtorInit",
":",
"function",
"focusProperty_preCtorInit",
"(",
"element",
",",
"options",
",",
"data",
",",
"displayName",
",",
"propName",
",",
"value",
")",
"{",
"options",
"[",
"propName",
"]",
"=",
"value",
";",
"}",
",",
"update",
":",
"function",
"focusProperty_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"if",
"(",
"oldValue",
"!==",
"newValue",
")",
"{",
"var",
"asyncToken",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
";",
"asyncToken",
"&&",
"clearImmediate",
"(",
"asyncToken",
")",
";",
"asyncToken",
"=",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"=",
"null",
";",
"winjsComponent",
".",
"winControl",
"[",
"propName",
"]",
"=",
"newValue",
";",
"}",
")",
";",
"}",
"}",
",",
"dispose",
":",
"function",
"focusProperty_dispose",
"(",
"winjsComponent",
",",
"propName",
")",
"{",
"var",
"asyncToken",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
";",
"asyncToken",
"&&",
"clearImmediate",
"(",
"asyncToken",
")",
";",
"}",
"}",
";",
"}"
]
| Maps to a property on the winControl which involves setting focus. Such properties are set outside of componentWillReceiveProps to prevent React from undoing the focus move. | [
"Maps",
"to",
"a",
"property",
"on",
"the",
"winControl",
"which",
"involves",
"setting",
"focus",
".",
"Such",
"properties",
"are",
"set",
"outside",
"of",
"componentWillReceiveProps",
"to",
"prevent",
"React",
"from",
"undoing",
"the",
"focus",
"move",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L1955-L1976 | train |
|
winjs/react-winjs | react-winjs.js | function (propType) {
return {
propType: propType,
preCtorInit: function domProperty_preCtorInit(element, options, data, displayName, propName, value) {
element[propName] = value;
},
update: function domProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.element[propName] = newValue;
}
}
};
} | javascript | function (propType) {
return {
propType: propType,
preCtorInit: function domProperty_preCtorInit(element, options, data, displayName, propName, value) {
element[propName] = value;
},
update: function domProperty_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.element[propName] = newValue;
}
}
};
} | [
"function",
"(",
"propType",
")",
"{",
"return",
"{",
"propType",
":",
"propType",
",",
"preCtorInit",
":",
"function",
"domProperty_preCtorInit",
"(",
"element",
",",
"options",
",",
"data",
",",
"displayName",
",",
"propName",
",",
"value",
")",
"{",
"element",
"[",
"propName",
"]",
"=",
"value",
";",
"}",
",",
"update",
":",
"function",
"domProperty_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"if",
"(",
"oldValue",
"!==",
"newValue",
")",
"{",
"winjsComponent",
".",
"element",
"[",
"propName",
"]",
"=",
"newValue",
";",
"}",
"}",
"}",
";",
"}"
]
| Maps to a property on the winControl's element. | [
"Maps",
"to",
"a",
"property",
"on",
"the",
"winControl",
"s",
"element",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L1979-L1991 | train |
|
winjs/react-winjs | react-winjs.js | function (propType) {
return {
propType: propType,
update: function domAttribute_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
if (newValue !== null && newValue !== undefined) {
winjsComponent.element.setAttribute(propName, "" + newValue);
} else {
winjsComponent.element.removeAttribute(propName);
}
}
}
};
} | javascript | function (propType) {
return {
propType: propType,
update: function domAttribute_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
if (newValue !== null && newValue !== undefined) {
winjsComponent.element.setAttribute(propName, "" + newValue);
} else {
winjsComponent.element.removeAttribute(propName);
}
}
}
};
} | [
"function",
"(",
"propType",
")",
"{",
"return",
"{",
"propType",
":",
"propType",
",",
"update",
":",
"function",
"domAttribute_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"if",
"(",
"oldValue",
"!==",
"newValue",
")",
"{",
"if",
"(",
"newValue",
"!==",
"null",
"&&",
"newValue",
"!==",
"undefined",
")",
"{",
"winjsComponent",
".",
"element",
".",
"setAttribute",
"(",
"propName",
",",
"\"\"",
"+",
"newValue",
")",
";",
"}",
"else",
"{",
"winjsComponent",
".",
"element",
".",
"removeAttribute",
"(",
"propName",
")",
";",
"}",
"}",
"}",
"}",
";",
"}"
]
| Maps to an attribute on the winControl's element. | [
"Maps",
"to",
"an",
"attribute",
"on",
"the",
"winControl",
"s",
"element",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L1994-L2007 | train |
|
winjs/react-winjs | react-winjs.js | event_update | function event_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.winControl[propName.toLowerCase()] = newValue;
}
} | javascript | function event_update(winjsComponent, propName, oldValue, newValue) {
if (oldValue !== newValue) {
winjsComponent.winControl[propName.toLowerCase()] = newValue;
}
} | [
"function",
"event_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"if",
"(",
"oldValue",
"!==",
"newValue",
")",
"{",
"winjsComponent",
".",
"winControl",
"[",
"propName",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"newValue",
";",
"}",
"}"
]
| Can't set options in preCtorInit for events. The problem is WinJS control options use a different code path to hook up events than the event property setters. Consequently, setting an event property will not automatically unhook the event listener that was specified in the options during initialization. To avoid this problem, always go thru the event property setters. | [
"Can",
"t",
"set",
"options",
"in",
"preCtorInit",
"for",
"events",
".",
"The",
"problem",
"is",
"WinJS",
"control",
"options",
"use",
"a",
"different",
"code",
"path",
"to",
"hook",
"up",
"events",
"than",
"the",
"event",
"property",
"setters",
".",
"Consequently",
"setting",
"an",
"event",
"property",
"will",
"not",
"automatically",
"unhook",
"the",
"event",
"listener",
"that",
"was",
"specified",
"in",
"the",
"options",
"during",
"initialization",
".",
"To",
"avoid",
"this",
"problem",
"always",
"go",
"thru",
"the",
"event",
"property",
"setters",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2017-L2021 | train |
winjs/react-winjs | react-winjs.js | PropHandlers_warn | function PropHandlers_warn(warnMessage) {
return {
// Don't need preCtorInit because this prop handler doesn't have any side
// effects on the WinJS control. update also runs during initialization so
// update is just as good as preCtorInit for our use case.
update: function warn_update(winjsComponent, propName, oldValue, newValue) {
console.warn(winjsComponent.displayName + ": " + warnMessage);
}
};
} | javascript | function PropHandlers_warn(warnMessage) {
return {
// Don't need preCtorInit because this prop handler doesn't have any side
// effects on the WinJS control. update also runs during initialization so
// update is just as good as preCtorInit for our use case.
update: function warn_update(winjsComponent, propName, oldValue, newValue) {
console.warn(winjsComponent.displayName + ": " + warnMessage);
}
};
} | [
"function",
"PropHandlers_warn",
"(",
"warnMessage",
")",
"{",
"return",
"{",
"update",
":",
"function",
"warn_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"console",
".",
"warn",
"(",
"winjsComponent",
".",
"displayName",
"+",
"\": \"",
"+",
"warnMessage",
")",
";",
"}",
"}",
";",
"}"
]
| Emits a warning to the console whenever prop gets used. | [
"Emits",
"a",
"warning",
"to",
"the",
"console",
"whenever",
"prop",
"gets",
"used",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2101-L2110 | train |
winjs/react-winjs | react-winjs.js | PropHandlers_mountTo | function PropHandlers_mountTo(getMountPoint) {
return {
propType: React.PropTypes.element,
// Can't use preCtorInit because the mount point may not exist until the
// constructor has run.
update: function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
},
dispose: function mountTo_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var element = data.element;
element && ReactDOM.unmountComponentAtNode(element);
}
};
} | javascript | function PropHandlers_mountTo(getMountPoint) {
return {
propType: React.PropTypes.element,
// Can't use preCtorInit because the mount point may not exist until the
// constructor has run.
update: function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
},
dispose: function mountTo_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var element = data.element;
element && ReactDOM.unmountComponentAtNode(element);
}
};
} | [
"function",
"PropHandlers_mountTo",
"(",
"getMountPoint",
")",
"{",
"return",
"{",
"propType",
":",
"React",
".",
"PropTypes",
".",
"element",
",",
"update",
":",
"function",
"mountTo_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"var",
"data",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"||",
"{",
"}",
";",
"var",
"version",
"=",
"(",
"data",
".",
"version",
"||",
"0",
")",
"+",
"1",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"=",
"{",
"version",
":",
"version",
",",
"element",
":",
"data",
".",
"element",
"}",
";",
"var",
"mountComponent",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"version",
"===",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"version",
")",
"{",
"var",
"oldElement",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
";",
"if",
"(",
"newValue",
")",
"{",
"var",
"newElement",
"=",
"getMountPoint",
"(",
"winjsComponent",
")",
";",
"if",
"(",
"oldElement",
"&&",
"oldElement",
"!==",
"newElement",
")",
"{",
"ReactDOM",
".",
"unmountComponentAtNode",
"(",
"oldElement",
")",
";",
"}",
"ReactDOM",
".",
"render",
"(",
"newValue",
",",
"newElement",
")",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
"=",
"newElement",
";",
"}",
"else",
"if",
"(",
"oldValue",
")",
"{",
"oldElement",
"&&",
"ReactDOM",
".",
"unmountComponentAtNode",
"(",
"oldElement",
")",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
"=",
"null",
";",
"}",
"}",
"}",
";",
"var",
"winControl",
"=",
"winjsComponent",
".",
"winControl",
";",
"var",
"queueProcessing",
"=",
"winControl",
".",
"constructor",
".",
"isDeclarativeControlContainer",
";",
"if",
"(",
"queueProcessing",
"&&",
"typeof",
"queueProcessing",
"===",
"\"function\"",
")",
"{",
"queueProcessing",
"(",
"winControl",
",",
"mountComponent",
")",
";",
"}",
"else",
"{",
"mountComponent",
"(",
")",
";",
"}",
"}",
",",
"dispose",
":",
"function",
"mountTo_dispose",
"(",
"winjsComponent",
",",
"propName",
")",
"{",
"var",
"data",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"||",
"{",
"}",
";",
"var",
"element",
"=",
"data",
".",
"element",
";",
"element",
"&&",
"ReactDOM",
".",
"unmountComponentAtNode",
"(",
"element",
")",
";",
"}",
"}",
";",
"}"
]
| Mounts a React component on whatever element gets returned by getMountPoint. | [
"Mounts",
"a",
"React",
"component",
"on",
"whatever",
"element",
"gets",
"returned",
"by",
"getMountPoint",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2150-L2206 | train |
winjs/react-winjs | react-winjs.js | mountTo_update | function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
} | javascript | function mountTo_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var version = (data.version || 0) + 1;
winjsComponent.data[propName] = {
// *mountComponent* may run asynchronously and we may queue it multiple
// times before it runs. *version* allows us to ensure only the latest
// version runs and the others are no ops.
version: version,
// *element* is the element to which we last mounted the component.
element: data.element
};
var mountComponent = function () {
if (version === winjsComponent.data[propName].version) {
var oldElement = winjsComponent.data[propName].element;
if (newValue) {
var newElement = getMountPoint(winjsComponent);
if (oldElement && oldElement !== newElement) {
ReactDOM.unmountComponentAtNode(oldElement);
}
ReactDOM.render(newValue, newElement);
winjsComponent.data[propName].element = newElement;
} else if (oldValue) {
oldElement && ReactDOM.unmountComponentAtNode(oldElement);
winjsComponent.data[propName].element = null;
}
}
};
// *isDeclarativeControlContainer* is a hook some WinJS controls provide
// (e.g. HubSection, PivotItem) to ensure that processing runs on the
// control only when the control is ready for it. This enables lazy loading
// of HubSections/PivotItems (e.g. load off screen items asynchronously in
// batches). Additionally, doing processing thru this hook guarantees that
// the processing won't run until the control is in the DOM.
var winControl = winjsComponent.winControl;
var queueProcessing = winControl.constructor.isDeclarativeControlContainer;
if (queueProcessing && typeof queueProcessing === "function") {
queueProcessing(winControl, mountComponent);
} else {
mountComponent();
}
} | [
"function",
"mountTo_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"var",
"data",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"||",
"{",
"}",
";",
"var",
"version",
"=",
"(",
"data",
".",
"version",
"||",
"0",
")",
"+",
"1",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"=",
"{",
"version",
":",
"version",
",",
"element",
":",
"data",
".",
"element",
"}",
";",
"var",
"mountComponent",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"version",
"===",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"version",
")",
"{",
"var",
"oldElement",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
";",
"if",
"(",
"newValue",
")",
"{",
"var",
"newElement",
"=",
"getMountPoint",
"(",
"winjsComponent",
")",
";",
"if",
"(",
"oldElement",
"&&",
"oldElement",
"!==",
"newElement",
")",
"{",
"ReactDOM",
".",
"unmountComponentAtNode",
"(",
"oldElement",
")",
";",
"}",
"ReactDOM",
".",
"render",
"(",
"newValue",
",",
"newElement",
")",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
"=",
"newElement",
";",
"}",
"else",
"if",
"(",
"oldValue",
")",
"{",
"oldElement",
"&&",
"ReactDOM",
".",
"unmountComponentAtNode",
"(",
"oldElement",
")",
";",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
".",
"element",
"=",
"null",
";",
"}",
"}",
"}",
";",
"var",
"winControl",
"=",
"winjsComponent",
".",
"winControl",
";",
"var",
"queueProcessing",
"=",
"winControl",
".",
"constructor",
".",
"isDeclarativeControlContainer",
";",
"if",
"(",
"queueProcessing",
"&&",
"typeof",
"queueProcessing",
"===",
"\"function\"",
")",
"{",
"queueProcessing",
"(",
"winControl",
",",
"mountComponent",
")",
";",
"}",
"else",
"{",
"mountComponent",
"(",
")",
";",
"}",
"}"
]
| Can't use preCtorInit because the mount point may not exist until the constructor has run. | [
"Can",
"t",
"use",
"preCtorInit",
"because",
"the",
"mount",
"point",
"may",
"not",
"exist",
"until",
"the",
"constructor",
"has",
"run",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2155-L2199 | train |
winjs/react-winjs | react-winjs.js | PropHandlers_syncChildrenWithBindingList | function PropHandlers_syncChildrenWithBindingList(bindingListName) {
return {
preCtorInit: function syncChildrenWithBindingList_preCtorInit(element, options, data, displayName, propName, value) {
var latest = processChildren(displayName, value, {});
data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
options[bindingListName] = new WinJS.Binding.List(
latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
})
);
},
update: function syncChildrenWithBindingList_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var oldChildComponents = data.winjsChildComponents || [];
var oldChildComponentsMap = data.winjsChildComponentsMap || {};
var latest = processChildren(winjsComponent.displayName, newValue, oldChildComponentsMap);
var bindingList = winjsComponent.winControl[bindingListName];
if (bindingList) {
applyEditsToBindingList(
bindingList,
diffArraysByKey(oldChildComponents, latest.childComponents)
);
} else {
winjsComponent.winControl[bindingListName] = new WinJS.Binding.List(latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
}));
}
winjsComponent.data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
},
dispose: function syncChildrenWithBindingList_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var childComponents = data.winjsChildComponents || [];
childComponents.forEach(function (winjsChildComponent) {
winjsChildComponent.dispose();
});
}
}
} | javascript | function PropHandlers_syncChildrenWithBindingList(bindingListName) {
return {
preCtorInit: function syncChildrenWithBindingList_preCtorInit(element, options, data, displayName, propName, value) {
var latest = processChildren(displayName, value, {});
data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
options[bindingListName] = new WinJS.Binding.List(
latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
})
);
},
update: function syncChildrenWithBindingList_update(winjsComponent, propName, oldValue, newValue) {
var data = winjsComponent.data[propName] || {};
var oldChildComponents = data.winjsChildComponents || [];
var oldChildComponentsMap = data.winjsChildComponentsMap || {};
var latest = processChildren(winjsComponent.displayName, newValue, oldChildComponentsMap);
var bindingList = winjsComponent.winControl[bindingListName];
if (bindingList) {
applyEditsToBindingList(
bindingList,
diffArraysByKey(oldChildComponents, latest.childComponents)
);
} else {
winjsComponent.winControl[bindingListName] = new WinJS.Binding.List(latest.childComponents.map(function (winjsChildComponent) {
return winjsChildComponent.winControl;
}));
}
winjsComponent.data[propName] = {
winjsChildComponents: latest.childComponents,
winjsChildComponentsMap: latest.childComponentsMap
};
},
dispose: function syncChildrenWithBindingList_dispose(winjsComponent, propName) {
var data = winjsComponent.data[propName] || {};
var childComponents = data.winjsChildComponents || [];
childComponents.forEach(function (winjsChildComponent) {
winjsChildComponent.dispose();
});
}
}
} | [
"function",
"PropHandlers_syncChildrenWithBindingList",
"(",
"bindingListName",
")",
"{",
"return",
"{",
"preCtorInit",
":",
"function",
"syncChildrenWithBindingList_preCtorInit",
"(",
"element",
",",
"options",
",",
"data",
",",
"displayName",
",",
"propName",
",",
"value",
")",
"{",
"var",
"latest",
"=",
"processChildren",
"(",
"displayName",
",",
"value",
",",
"{",
"}",
")",
";",
"data",
"[",
"propName",
"]",
"=",
"{",
"winjsChildComponents",
":",
"latest",
".",
"childComponents",
",",
"winjsChildComponentsMap",
":",
"latest",
".",
"childComponentsMap",
"}",
";",
"options",
"[",
"bindingListName",
"]",
"=",
"new",
"WinJS",
".",
"Binding",
".",
"List",
"(",
"latest",
".",
"childComponents",
".",
"map",
"(",
"function",
"(",
"winjsChildComponent",
")",
"{",
"return",
"winjsChildComponent",
".",
"winControl",
";",
"}",
")",
")",
";",
"}",
",",
"update",
":",
"function",
"syncChildrenWithBindingList_update",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"var",
"data",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"||",
"{",
"}",
";",
"var",
"oldChildComponents",
"=",
"data",
".",
"winjsChildComponents",
"||",
"[",
"]",
";",
"var",
"oldChildComponentsMap",
"=",
"data",
".",
"winjsChildComponentsMap",
"||",
"{",
"}",
";",
"var",
"latest",
"=",
"processChildren",
"(",
"winjsComponent",
".",
"displayName",
",",
"newValue",
",",
"oldChildComponentsMap",
")",
";",
"var",
"bindingList",
"=",
"winjsComponent",
".",
"winControl",
"[",
"bindingListName",
"]",
";",
"if",
"(",
"bindingList",
")",
"{",
"applyEditsToBindingList",
"(",
"bindingList",
",",
"diffArraysByKey",
"(",
"oldChildComponents",
",",
"latest",
".",
"childComponents",
")",
")",
";",
"}",
"else",
"{",
"winjsComponent",
".",
"winControl",
"[",
"bindingListName",
"]",
"=",
"new",
"WinJS",
".",
"Binding",
".",
"List",
"(",
"latest",
".",
"childComponents",
".",
"map",
"(",
"function",
"(",
"winjsChildComponent",
")",
"{",
"return",
"winjsChildComponent",
".",
"winControl",
";",
"}",
")",
")",
";",
"}",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"=",
"{",
"winjsChildComponents",
":",
"latest",
".",
"childComponents",
",",
"winjsChildComponentsMap",
":",
"latest",
".",
"childComponentsMap",
"}",
";",
"}",
",",
"dispose",
":",
"function",
"syncChildrenWithBindingList_dispose",
"(",
"winjsComponent",
",",
"propName",
")",
"{",
"var",
"data",
"=",
"winjsComponent",
".",
"data",
"[",
"propName",
"]",
"||",
"{",
"}",
";",
"var",
"childComponents",
"=",
"data",
".",
"winjsChildComponents",
"||",
"[",
"]",
";",
"childComponents",
".",
"forEach",
"(",
"function",
"(",
"winjsChildComponent",
")",
"{",
"winjsChildComponent",
".",
"dispose",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
]
| Uses the Binding.List's editing APIs to make it match the children prop. Does this to the Binding.List stored in the winControl's property called bindingListName. | [
"Uses",
"the",
"Binding",
".",
"List",
"s",
"editing",
"APIs",
"to",
"make",
"it",
"match",
"the",
"children",
"prop",
".",
"Does",
"this",
"to",
"the",
"Binding",
".",
"List",
"stored",
"in",
"the",
"winControl",
"s",
"property",
"called",
"bindingListName",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2210-L2256 | train |
winjs/react-winjs | react-winjs.js | function (winjsComponent, propName, oldValue, newValue) {
// TODO: dispose
ReactDOM.render(React.DOM.div(null, newValue), winjsComponent.winControl.element);
} | javascript | function (winjsComponent, propName, oldValue, newValue) {
// TODO: dispose
ReactDOM.render(React.DOM.div(null, newValue), winjsComponent.winControl.element);
} | [
"function",
"(",
"winjsComponent",
",",
"propName",
",",
"oldValue",
",",
"newValue",
")",
"{",
"ReactDOM",
".",
"render",
"(",
"React",
".",
"DOM",
".",
"div",
"(",
"null",
",",
"newValue",
")",
",",
"winjsComponent",
".",
"winControl",
".",
"element",
")",
";",
"}"
]
| children propHandler looks like this rather than using mountTo on winControl.element because this enables props.children to have multiple components whereas the other technique restricts it to one. | [
"children",
"propHandler",
"looks",
"like",
"this",
"rather",
"than",
"using",
"mountTo",
"on",
"winControl",
".",
"element",
"because",
"this",
"enables",
"props",
".",
"children",
"to",
"have",
"multiple",
"components",
"whereas",
"the",
"other",
"technique",
"restricts",
"it",
"to",
"one",
"."
]
| 1a117744f24cbeb1729f38debde43550e34affeb | https://github.com/winjs/react-winjs/blob/1a117744f24cbeb1729f38debde43550e34affeb/react-winjs.js#L2626-L2629 | train |
|
ciena-frost/ember-frost-bunsen | addon/components/detail.js | addMetaProperty | function addMetaProperty (object, propName, value) {
defineProperty(object, propName, {
enumerable: false,
value
})
} | javascript | function addMetaProperty (object, propName, value) {
defineProperty(object, propName, {
enumerable: false,
value
})
} | [
"function",
"addMetaProperty",
"(",
"object",
",",
"propName",
",",
"value",
")",
"{",
"defineProperty",
"(",
"object",
",",
"propName",
",",
"{",
"enumerable",
":",
"false",
",",
"value",
"}",
")",
"}"
]
| Adds an unenumerable property to an object
@param {Object} object - object to add property to
@param {String} propName - property name
@param {Object|Number|String} value - property value | [
"Adds",
"an",
"unenumerable",
"property",
"to",
"an",
"object"
]
| 0a4d323484e49aca86404204e4139a64d43829ad | https://github.com/ciena-frost/ember-frost-bunsen/blob/0a4d323484e49aca86404204e4139a64d43829ad/addon/components/detail.js#L69-L74 | train |
virtkick/http-master | src/di.js | functionParameters | function functionParameters(f) {
assert(typeof f === 'function');
var matches = functionRegex.exec(f.toString());
if(!matches || !matches[2].length) {
return [];
}
return matches[2].split(/[,\s]+/).filter(function(str) {
return str.length;
});
} | javascript | function functionParameters(f) {
assert(typeof f === 'function');
var matches = functionRegex.exec(f.toString());
if(!matches || !matches[2].length) {
return [];
}
return matches[2].split(/[,\s]+/).filter(function(str) {
return str.length;
});
} | [
"function",
"functionParameters",
"(",
"f",
")",
"{",
"assert",
"(",
"typeof",
"f",
"===",
"'function'",
")",
";",
"var",
"matches",
"=",
"functionRegex",
".",
"exec",
"(",
"f",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"!",
"matches",
"||",
"!",
"matches",
"[",
"2",
"]",
".",
"length",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"matches",
"[",
"2",
"]",
".",
"split",
"(",
"/",
"[,\\s]+",
"/",
")",
".",
"filter",
"(",
"function",
"(",
"str",
")",
"{",
"return",
"str",
".",
"length",
";",
"}",
")",
";",
"}"
]
| get function arguments as array | [
"get",
"function",
"arguments",
"as",
"array"
]
| 0bc7bededda0679590789642fff010d1df5d2395 | https://github.com/virtkick/http-master/blob/0bc7bededda0679590789642fff010d1df5d2395/src/di.js#L7-L16 | train |
virtkick/http-master | src/di.js | function(overrides) {
var result = this.cache;
if(!result) {
result = construct(type, functionParameters(type).map(function(paramName) {
return self.resolve(paramName, overrides);
}));
}
if(doCache) {
this.cache = result;
}
return result;
} | javascript | function(overrides) {
var result = this.cache;
if(!result) {
result = construct(type, functionParameters(type).map(function(paramName) {
return self.resolve(paramName, overrides);
}));
}
if(doCache) {
this.cache = result;
}
return result;
} | [
"function",
"(",
"overrides",
")",
"{",
"var",
"result",
"=",
"this",
".",
"cache",
";",
"if",
"(",
"!",
"result",
")",
"{",
"result",
"=",
"construct",
"(",
"type",
",",
"functionParameters",
"(",
"type",
")",
".",
"map",
"(",
"function",
"(",
"paramName",
")",
"{",
"return",
"self",
".",
"resolve",
"(",
"paramName",
",",
"overrides",
")",
";",
"}",
")",
")",
";",
"}",
"if",
"(",
"doCache",
")",
"{",
"this",
".",
"cache",
"=",
"result",
";",
"}",
"return",
"result",
";",
"}"
]
| this.cache is saved in mapping 'this' is mapping | [
"this",
".",
"cache",
"is",
"saved",
"in",
"mapping",
"this",
"is",
"mapping"
]
| 0bc7bededda0679590789642fff010d1df5d2395 | https://github.com/virtkick/http-master/blob/0bc7bededda0679590789642fff010d1df5d2395/src/di.js#L77-L88 | train |
|
ciena-frost/ember-frost-bunsen | addon/components/inputs/geolocation.js | deserializeProperty | function deserializeProperty (bunsenId, value, bunsenModel) {
const subModel = getSubModel(bunsenModel, bunsenId)
switch (subModel.type) {
case 'integer':
return parseInt(value)
case 'number':
return parseFloat(value)
default:
return value
}
} | javascript | function deserializeProperty (bunsenId, value, bunsenModel) {
const subModel = getSubModel(bunsenModel, bunsenId)
switch (subModel.type) {
case 'integer':
return parseInt(value)
case 'number':
return parseFloat(value)
default:
return value
}
} | [
"function",
"deserializeProperty",
"(",
"bunsenId",
",",
"value",
",",
"bunsenModel",
")",
"{",
"const",
"subModel",
"=",
"getSubModel",
"(",
"bunsenModel",
",",
"bunsenId",
")",
"switch",
"(",
"subModel",
".",
"type",
")",
"{",
"case",
"'integer'",
":",
"return",
"parseInt",
"(",
"value",
")",
"case",
"'number'",
":",
"return",
"parseFloat",
"(",
"value",
")",
"default",
":",
"return",
"value",
"}",
"}"
]
| Deserialize property value to format consumer expects
@param {String} bunsenId - property key
@param {String} value - property value
@param {Object} bunsenModel - bunsen model
@returns {String|Number} deserialized value | [
"Deserialize",
"property",
"value",
"to",
"format",
"consumer",
"expects"
]
| 0a4d323484e49aca86404204e4139a64d43829ad | https://github.com/ciena-frost/ember-frost-bunsen/blob/0a4d323484e49aca86404204e4139a64d43829ad/addon/components/inputs/geolocation.js#L84-L97 | train |
ciena-frost/ember-frost-bunsen | addon/components/inputs/geolocation.js | serializeFormValue | function serializeFormValue (formValue) {
if (formValue.country) {
formValue.country = countryCodeToName(formValue.country)
}
if (typeOf(formValue.latitude) === 'number') {
formValue.latitude = `${formValue.latitude}`
}
if (typeOf(formValue.longitude) === 'number') {
formValue.longitude = `${formValue.longitude}`
}
} | javascript | function serializeFormValue (formValue) {
if (formValue.country) {
formValue.country = countryCodeToName(formValue.country)
}
if (typeOf(formValue.latitude) === 'number') {
formValue.latitude = `${formValue.latitude}`
}
if (typeOf(formValue.longitude) === 'number') {
formValue.longitude = `${formValue.longitude}`
}
} | [
"function",
"serializeFormValue",
"(",
"formValue",
")",
"{",
"if",
"(",
"formValue",
".",
"country",
")",
"{",
"formValue",
".",
"country",
"=",
"countryCodeToName",
"(",
"formValue",
".",
"country",
")",
"}",
"if",
"(",
"typeOf",
"(",
"formValue",
".",
"latitude",
")",
"===",
"'number'",
")",
"{",
"formValue",
".",
"latitude",
"=",
"`",
"${",
"formValue",
".",
"latitude",
"}",
"`",
"}",
"if",
"(",
"typeOf",
"(",
"formValue",
".",
"longitude",
")",
"===",
"'number'",
")",
"{",
"formValue",
".",
"longitude",
"=",
"`",
"${",
"formValue",
".",
"longitude",
"}",
"`",
"}",
"}"
]
| Serialize form value to be in correct format for sub-forms
@param {Object} formValue - unserialized form value | [
"Serialize",
"form",
"value",
"to",
"be",
"in",
"correct",
"format",
"for",
"sub",
"-",
"forms"
]
| 0a4d323484e49aca86404204e4139a64d43829ad | https://github.com/ciena-frost/ember-frost-bunsen/blob/0a4d323484e49aca86404204e4139a64d43829ad/addon/components/inputs/geolocation.js#L103-L115 | train |
ciena-frost/ember-frost-bunsen | addon/list-utils.js | normalizeItems | function normalizeItems ({data, labelAttribute, records, valueAttribute}) {
const labelAttr = labelAttribute || 'label'
const valueAttr = valueAttribute || 'id'
return data.concat(
records.map((record) => {
if (typeof record !== 'object') {
return {
label: `${record}`, // make sure label is a string
value: record
}
}
let label, value
if (labelAttr.indexOf('${') !== -1) {
label = utils.parseVariables(record, labelAttr)
} else {
label = get(record, labelAttr) || get(record, 'title')
}
if (valueAttr.indexOf('${') !== -1) {
value = utils.parseVariables(record, valueAttr)
} else {
value = get(record, valueAttr)
}
return {
label,
value
}
})
)
} | javascript | function normalizeItems ({data, labelAttribute, records, valueAttribute}) {
const labelAttr = labelAttribute || 'label'
const valueAttr = valueAttribute || 'id'
return data.concat(
records.map((record) => {
if (typeof record !== 'object') {
return {
label: `${record}`, // make sure label is a string
value: record
}
}
let label, value
if (labelAttr.indexOf('${') !== -1) {
label = utils.parseVariables(record, labelAttr)
} else {
label = get(record, labelAttr) || get(record, 'title')
}
if (valueAttr.indexOf('${') !== -1) {
value = utils.parseVariables(record, valueAttr)
} else {
value = get(record, valueAttr)
}
return {
label,
value
}
})
)
} | [
"function",
"normalizeItems",
"(",
"{",
"data",
",",
"labelAttribute",
",",
"records",
",",
"valueAttribute",
"}",
")",
"{",
"const",
"labelAttr",
"=",
"labelAttribute",
"||",
"'label'",
"const",
"valueAttr",
"=",
"valueAttribute",
"||",
"'id'",
"return",
"data",
".",
"concat",
"(",
"records",
".",
"map",
"(",
"(",
"record",
")",
"=>",
"{",
"if",
"(",
"typeof",
"record",
"!==",
"'object'",
")",
"{",
"return",
"{",
"label",
":",
"`",
"${",
"record",
"}",
"`",
",",
"value",
":",
"record",
"}",
"}",
"let",
"label",
",",
"value",
"if",
"(",
"labelAttr",
".",
"indexOf",
"(",
"'${'",
")",
"!==",
"-",
"1",
")",
"{",
"label",
"=",
"utils",
".",
"parseVariables",
"(",
"record",
",",
"labelAttr",
")",
"}",
"else",
"{",
"label",
"=",
"get",
"(",
"record",
",",
"labelAttr",
")",
"||",
"get",
"(",
"record",
",",
"'title'",
")",
"}",
"if",
"(",
"valueAttr",
".",
"indexOf",
"(",
"'${'",
")",
"!==",
"-",
"1",
")",
"{",
"value",
"=",
"utils",
".",
"parseVariables",
"(",
"record",
",",
"valueAttr",
")",
"}",
"else",
"{",
"value",
"=",
"get",
"(",
"record",
",",
"valueAttr",
")",
"}",
"return",
"{",
"label",
",",
"value",
"}",
"}",
")",
")",
"}"
]
| Converts records from an API response into a standard format with "label"
and "value" properties so renderers can predictably process the data.
@param {Object[]} data - initializes the list with this
@param {String} labelAttribute - dot notated path to label attribute in record
@param {Array<Object>} records - records to normalize
@param {String} valueAttribute - dot notated path to value attribute in record
@returns {Array<Object>} normalized items | [
"Converts",
"records",
"from",
"an",
"API",
"response",
"into",
"a",
"standard",
"format",
"with",
"label",
"and",
"value",
"properties",
"so",
"renderers",
"can",
"predictably",
"process",
"the",
"data",
"."
]
| 0a4d323484e49aca86404204e4139a64d43829ad | https://github.com/ciena-frost/ember-frost-bunsen/blob/0a4d323484e49aca86404204e4139a64d43829ad/addon/list-utils.js#L256-L289 | train |
ciena-frost/ember-frost-bunsen | addon/list-utils.js | shouldAddCurrentValue | function shouldAddCurrentValue ({items, valueRecord, labelAttribute, valueAttribute, filter}) {
const filterRegex = new RegExp(filter, 'i')
const valueRecordMatchesFilter = filterRegex.test(valueRecord.get(labelAttribute))
const itemsContainsValueRecord = items.find(item => item.value === valueRecord.get(valueAttribute))
return valueRecordMatchesFilter && !itemsContainsValueRecord
} | javascript | function shouldAddCurrentValue ({items, valueRecord, labelAttribute, valueAttribute, filter}) {
const filterRegex = new RegExp(filter, 'i')
const valueRecordMatchesFilter = filterRegex.test(valueRecord.get(labelAttribute))
const itemsContainsValueRecord = items.find(item => item.value === valueRecord.get(valueAttribute))
return valueRecordMatchesFilter && !itemsContainsValueRecord
} | [
"function",
"shouldAddCurrentValue",
"(",
"{",
"items",
",",
"valueRecord",
",",
"labelAttribute",
",",
"valueAttribute",
",",
"filter",
"}",
")",
"{",
"const",
"filterRegex",
"=",
"new",
"RegExp",
"(",
"filter",
",",
"'i'",
")",
"const",
"valueRecordMatchesFilter",
"=",
"filterRegex",
".",
"test",
"(",
"valueRecord",
".",
"get",
"(",
"labelAttribute",
")",
")",
"const",
"itemsContainsValueRecord",
"=",
"items",
".",
"find",
"(",
"item",
"=>",
"item",
".",
"value",
"===",
"valueRecord",
".",
"get",
"(",
"valueAttribute",
")",
")",
"return",
"valueRecordMatchesFilter",
"&&",
"!",
"itemsContainsValueRecord",
"}"
]
| Determine whether or not valueRecord should be appended to data
@param {Object[]} items - the larger set of data
@param {EmberObject} valueRecord - the record to add or not
@param {String} labelAttribute - dot notated path to label attribute in record
@param {String} valueAttribute - dot notated path to value attribute in record
@param {String} filter - the partial match query filter to populate
@returns {boolean} true if valueRecord should be added to items | [
"Determine",
"whether",
"or",
"not",
"valueRecord",
"should",
"be",
"appended",
"to",
"data"
]
| 0a4d323484e49aca86404204e4139a64d43829ad | https://github.com/ciena-frost/ember-frost-bunsen/blob/0a4d323484e49aca86404204e4139a64d43829ad/addon/list-utils.js#L300-L305 | train |
ryanwilliams/cocos2d-javascript | src/nodes/RenderTexture.js | function (rect) {
if (rect) {
this.context.clearRect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
} else {
this.canvas.width = this.canvas.width
if (cc.FLIP_Y_AXIS) {
this.context.scale(1, -1)
this.context.translate(0, -this.canvas.height)
}
}
} | javascript | function (rect) {
if (rect) {
this.context.clearRect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
} else {
this.canvas.width = this.canvas.width
if (cc.FLIP_Y_AXIS) {
this.context.scale(1, -1)
this.context.translate(0, -this.canvas.height)
}
}
} | [
"function",
"(",
"rect",
")",
"{",
"if",
"(",
"rect",
")",
"{",
"this",
".",
"context",
".",
"clearRect",
"(",
"rect",
".",
"origin",
".",
"x",
",",
"rect",
".",
"origin",
".",
"y",
",",
"rect",
".",
"size",
".",
"width",
",",
"rect",
".",
"size",
".",
"height",
")",
"}",
"else",
"{",
"this",
".",
"canvas",
".",
"width",
"=",
"this",
".",
"canvas",
".",
"width",
"if",
"(",
"cc",
".",
"FLIP_Y_AXIS",
")",
"{",
"this",
".",
"context",
".",
"scale",
"(",
"1",
",",
"-",
"1",
")",
"this",
".",
"context",
".",
"translate",
"(",
"0",
",",
"-",
"this",
".",
"canvas",
".",
"height",
")",
"}",
"}",
"}"
]
| Clear the canvas | [
"Clear",
"the",
"canvas"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/nodes/RenderTexture.js#L70-L80 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function (opts) {
var target = opts.target,
priority = opts.priority,
paused = opts.paused
var i, len
var entry = {target: target, priority: priority, paused: paused}
var added = false
if (priority === 0) {
this.updates0.push(entry)
} else if (priority < 0) {
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
if (priority < this.updatesNeg[i].priority) {
this.updatesNeg.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesNeg.push(entry)
}
} else /* priority > 0 */{
for (i = 0, len = this.updatesPos.length; i < len; i++) {
if (priority < this.updatesPos[i].priority) {
this.updatesPos.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesPos.push(entry)
}
}
this.hashForUpdates[target.id] = entry
} | javascript | function (opts) {
var target = opts.target,
priority = opts.priority,
paused = opts.paused
var i, len
var entry = {target: target, priority: priority, paused: paused}
var added = false
if (priority === 0) {
this.updates0.push(entry)
} else if (priority < 0) {
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
if (priority < this.updatesNeg[i].priority) {
this.updatesNeg.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesNeg.push(entry)
}
} else /* priority > 0 */{
for (i = 0, len = this.updatesPos.length; i < len; i++) {
if (priority < this.updatesPos[i].priority) {
this.updatesPos.splice(i, 0, entry)
added = true
break
}
}
if (!added) {
this.updatesPos.push(entry)
}
}
this.hashForUpdates[target.id] = entry
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"target",
"=",
"opts",
".",
"target",
",",
"priority",
"=",
"opts",
".",
"priority",
",",
"paused",
"=",
"opts",
".",
"paused",
"var",
"i",
",",
"len",
"var",
"entry",
"=",
"{",
"target",
":",
"target",
",",
"priority",
":",
"priority",
",",
"paused",
":",
"paused",
"}",
"var",
"added",
"=",
"false",
"if",
"(",
"priority",
"===",
"0",
")",
"{",
"this",
".",
"updates0",
".",
"push",
"(",
"entry",
")",
"}",
"else",
"if",
"(",
"priority",
"<",
"0",
")",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesNeg",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"priority",
"<",
"this",
".",
"updatesNeg",
"[",
"i",
"]",
".",
"priority",
")",
"{",
"this",
".",
"updatesNeg",
".",
"splice",
"(",
"i",
",",
"0",
",",
"entry",
")",
"added",
"=",
"true",
"break",
"}",
"}",
"if",
"(",
"!",
"added",
")",
"{",
"this",
".",
"updatesNeg",
".",
"push",
"(",
"entry",
")",
"}",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesPos",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"priority",
"<",
"this",
".",
"updatesPos",
"[",
"i",
"]",
".",
"priority",
")",
"{",
"this",
".",
"updatesPos",
".",
"splice",
"(",
"i",
",",
"0",
",",
"entry",
")",
"added",
"=",
"true",
"break",
"}",
"}",
"if",
"(",
"!",
"added",
")",
"{",
"this",
".",
"updatesPos",
".",
"push",
"(",
"entry",
")",
"}",
"}",
"this",
".",
"hashForUpdates",
"[",
"target",
".",
"id",
"]",
"=",
"entry",
"}"
]
| Schedules the 'update' selector for a given target with a given priority.
The 'update' selector will be called every frame.
The lower the priority, the earlier it is called. | [
"Schedules",
"the",
"update",
"selector",
"for",
"a",
"given",
"target",
"with",
"a",
"given",
"priority",
".",
"The",
"update",
"selector",
"will",
"be",
"called",
"every",
"frame",
".",
"The",
"lower",
"the",
"priority",
"the",
"earlier",
"it",
"is",
"called",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L115-L153 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function (dt) {
var i, len, x
if (this.timeScale != 1.0) {
dt *= this.timeScale
}
var entry
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
if (entry) {
for (i = 0, len = entry.timers.length; i < len; i++) {
var timer = entry.timers[i]
if (timer) {
timer.update(dt)
}
}
}
}
}
} | javascript | function (dt) {
var i, len, x
if (this.timeScale != 1.0) {
dt *= this.timeScale
}
var entry
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry && !entry.paused) {
entry.target.update(dt)
}
}
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
if (entry) {
for (i = 0, len = entry.timers.length; i < len; i++) {
var timer = entry.timers[i]
if (timer) {
timer.update(dt)
}
}
}
}
}
} | [
"function",
"(",
"dt",
")",
"{",
"var",
"i",
",",
"len",
",",
"x",
"if",
"(",
"this",
".",
"timeScale",
"!=",
"1.0",
")",
"{",
"dt",
"*=",
"this",
".",
"timeScale",
"}",
"var",
"entry",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesNeg",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updatesNeg",
"[",
"i",
"]",
"if",
"(",
"entry",
"&&",
"!",
"entry",
".",
"paused",
")",
"{",
"entry",
".",
"target",
".",
"update",
"(",
"dt",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updates0",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updates0",
"[",
"i",
"]",
"if",
"(",
"entry",
"&&",
"!",
"entry",
".",
"paused",
")",
"{",
"entry",
".",
"target",
".",
"update",
"(",
"dt",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesPos",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updatesPos",
"[",
"i",
"]",
"if",
"(",
"entry",
"&&",
"!",
"entry",
".",
"paused",
")",
"{",
"entry",
".",
"target",
".",
"update",
"(",
"dt",
")",
"}",
"}",
"for",
"(",
"x",
"in",
"this",
".",
"hashForMethods",
")",
"{",
"if",
"(",
"this",
".",
"hashForMethods",
".",
"hasOwnProperty",
"(",
"x",
")",
")",
"{",
"entry",
"=",
"this",
".",
"hashForMethods",
"[",
"x",
"]",
"if",
"(",
"entry",
")",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"entry",
".",
"timers",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"timer",
"=",
"entry",
".",
"timers",
"[",
"i",
"]",
"if",
"(",
"timer",
")",
"{",
"timer",
".",
"update",
"(",
"dt",
")",
"}",
"}",
"}",
"}",
"}",
"}"
]
| 'tick' the scheduler.
You should NEVER call this method, unless you know what you are doing. | [
"tick",
"the",
"scheduler",
".",
"You",
"should",
"NEVER",
"call",
"this",
"method",
"unless",
"you",
"know",
"what",
"you",
"are",
"doing",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L159-L203 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function (opts) {
if (!opts.target || !opts.method) {
return
}
var target = opts.target,
method = (typeof opts.method == 'function') ? opts.method : target[opts.method]
var element = this.hashForMethods[opts.target.id]
if (element) {
for (var i=0; i<element.timers.length; i++) {
// Compare callback function
if (element.timers[i].callback == method.bind(target)) {
var timer = element.timers.splice(i, 1)
timer = null
}
}
}
} | javascript | function (opts) {
if (!opts.target || !opts.method) {
return
}
var target = opts.target,
method = (typeof opts.method == 'function') ? opts.method : target[opts.method]
var element = this.hashForMethods[opts.target.id]
if (element) {
for (var i=0; i<element.timers.length; i++) {
// Compare callback function
if (element.timers[i].callback == method.bind(target)) {
var timer = element.timers.splice(i, 1)
timer = null
}
}
}
} | [
"function",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"target",
"||",
"!",
"opts",
".",
"method",
")",
"{",
"return",
"}",
"var",
"target",
"=",
"opts",
".",
"target",
",",
"method",
"=",
"(",
"typeof",
"opts",
".",
"method",
"==",
"'function'",
")",
"?",
"opts",
".",
"method",
":",
"target",
"[",
"opts",
".",
"method",
"]",
"var",
"element",
"=",
"this",
".",
"hashForMethods",
"[",
"opts",
".",
"target",
".",
"id",
"]",
"if",
"(",
"element",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"element",
".",
"timers",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"element",
".",
"timers",
"[",
"i",
"]",
".",
"callback",
"==",
"method",
".",
"bind",
"(",
"target",
")",
")",
"{",
"var",
"timer",
"=",
"element",
".",
"timers",
".",
"splice",
"(",
"i",
",",
"1",
")",
"timer",
"=",
"null",
"}",
"}",
"}",
"}"
]
| Unshedules a selector for a given target.
If you want to unschedule the "update", use unscheduleUpdateForTarget. | [
"Unshedules",
"a",
"selector",
"for",
"a",
"given",
"target",
".",
"If",
"you",
"want",
"to",
"unschedule",
"the",
"update",
"use",
"unscheduleUpdateForTarget",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L209-L227 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function (target) {
if (!target) {
return
}
var id = target.id,
elementUpdate = this.hashForUpdates[id]
if (elementUpdate) {
// Remove from updates list
if (elementUpdate.priority === 0) {
this.updates0.splice(this.updates0.indexOf(elementUpdate), 1)
} else if (elementUpdate.priority < 0) {
this.updatesNeg.splice(this.updatesNeg.indexOf(elementUpdate), 1)
} else /* priority > 0 */{
this.updatesPos.splice(this.updatesPos.indexOf(elementUpdate), 1)
}
}
// Release HashMethodEntry object
this.hashForUpdates[id] = null
} | javascript | function (target) {
if (!target) {
return
}
var id = target.id,
elementUpdate = this.hashForUpdates[id]
if (elementUpdate) {
// Remove from updates list
if (elementUpdate.priority === 0) {
this.updates0.splice(this.updates0.indexOf(elementUpdate), 1)
} else if (elementUpdate.priority < 0) {
this.updatesNeg.splice(this.updatesNeg.indexOf(elementUpdate), 1)
} else /* priority > 0 */{
this.updatesPos.splice(this.updatesPos.indexOf(elementUpdate), 1)
}
}
// Release HashMethodEntry object
this.hashForUpdates[id] = null
} | [
"function",
"(",
"target",
")",
"{",
"if",
"(",
"!",
"target",
")",
"{",
"return",
"}",
"var",
"id",
"=",
"target",
".",
"id",
",",
"elementUpdate",
"=",
"this",
".",
"hashForUpdates",
"[",
"id",
"]",
"if",
"(",
"elementUpdate",
")",
"{",
"if",
"(",
"elementUpdate",
".",
"priority",
"===",
"0",
")",
"{",
"this",
".",
"updates0",
".",
"splice",
"(",
"this",
".",
"updates0",
".",
"indexOf",
"(",
"elementUpdate",
")",
",",
"1",
")",
"}",
"else",
"if",
"(",
"elementUpdate",
".",
"priority",
"<",
"0",
")",
"{",
"this",
".",
"updatesNeg",
".",
"splice",
"(",
"this",
".",
"updatesNeg",
".",
"indexOf",
"(",
"elementUpdate",
")",
",",
"1",
")",
"}",
"else",
"{",
"this",
".",
"updatesPos",
".",
"splice",
"(",
"this",
".",
"updatesPos",
".",
"indexOf",
"(",
"elementUpdate",
")",
",",
"1",
")",
"}",
"}",
"this",
".",
"hashForUpdates",
"[",
"id",
"]",
"=",
"null",
"}"
]
| Unschedules the update selector for a given target | [
"Unschedules",
"the",
"update",
"selector",
"for",
"a",
"given",
"target"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L232-L250 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function () {
var i, x, entry
// Custom selectors
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
this.unscheduleAllSelectorsForTarget(entry.target)
}
}
// Updates selectors
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
} | javascript | function () {
var i, x, entry
// Custom selectors
for (x in this.hashForMethods) {
if (this.hashForMethods.hasOwnProperty(x)) {
entry = this.hashForMethods[x]
this.unscheduleAllSelectorsForTarget(entry.target)
}
}
// Updates selectors
for (i = 0, len = this.updatesNeg.length; i < len; i++) {
entry = this.updatesNeg[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updates0.length; i < len; i++) {
entry = this.updates0[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
for (i = 0, len = this.updatesPos.length; i < len; i++) {
entry = this.updatesPos[i]
if (entry) {
this.unscheduleUpdateForTarget(entry.target)
}
}
} | [
"function",
"(",
")",
"{",
"var",
"i",
",",
"x",
",",
"entry",
"for",
"(",
"x",
"in",
"this",
".",
"hashForMethods",
")",
"{",
"if",
"(",
"this",
".",
"hashForMethods",
".",
"hasOwnProperty",
"(",
"x",
")",
")",
"{",
"entry",
"=",
"this",
".",
"hashForMethods",
"[",
"x",
"]",
"this",
".",
"unscheduleAllSelectorsForTarget",
"(",
"entry",
".",
"target",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesNeg",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updatesNeg",
"[",
"i",
"]",
"if",
"(",
"entry",
")",
"{",
"this",
".",
"unscheduleUpdateForTarget",
"(",
"entry",
".",
"target",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updates0",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updates0",
"[",
"i",
"]",
"if",
"(",
"entry",
")",
"{",
"this",
".",
"unscheduleUpdateForTarget",
"(",
"entry",
".",
"target",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"updatesPos",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"entry",
"=",
"this",
".",
"updatesPos",
"[",
"i",
"]",
"if",
"(",
"entry",
")",
"{",
"this",
".",
"unscheduleUpdateForTarget",
"(",
"entry",
".",
"target",
")",
"}",
"}",
"}"
]
| Unschedules all selectors from all targets.
You should NEVER call this method, unless you know what you are doing. | [
"Unschedules",
"all",
"selectors",
"from",
"all",
"targets",
".",
"You",
"should",
"NEVER",
"call",
"this",
"method",
"unless",
"you",
"know",
"what",
"you",
"are",
"doing",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L256-L287 | train |
|
ryanwilliams/cocos2d-javascript | src/Scheduler.js | function (target) {
if (!target) {
return
}
// Custom selector
var element = this.hashForMethods[target.id]
if (element) {
element.paused = true
element.timers = []; // Clear all timers
}
// Release HashMethodEntry object
this.hashForMethods[target.id] = null
// Update selector
this.unscheduleUpdateForTarget(target)
} | javascript | function (target) {
if (!target) {
return
}
// Custom selector
var element = this.hashForMethods[target.id]
if (element) {
element.paused = true
element.timers = []; // Clear all timers
}
// Release HashMethodEntry object
this.hashForMethods[target.id] = null
// Update selector
this.unscheduleUpdateForTarget(target)
} | [
"function",
"(",
"target",
")",
"{",
"if",
"(",
"!",
"target",
")",
"{",
"return",
"}",
"var",
"element",
"=",
"this",
".",
"hashForMethods",
"[",
"target",
".",
"id",
"]",
"if",
"(",
"element",
")",
"{",
"element",
".",
"paused",
"=",
"true",
"element",
".",
"timers",
"=",
"[",
"]",
";",
"}",
"this",
".",
"hashForMethods",
"[",
"target",
".",
"id",
"]",
"=",
"null",
"this",
".",
"unscheduleUpdateForTarget",
"(",
"target",
")",
"}"
]
| Unschedules all selectors for a given target.
This also includes the "update" selector. | [
"Unschedules",
"all",
"selectors",
"for",
"a",
"given",
"target",
".",
"This",
"also",
"includes",
"the",
"update",
"selector",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Scheduler.js#L293-L308 | train |
|
ryanwilliams/cocos2d-javascript | src/ActionManager.js | function (opts) {
var targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
element = this.targets[targetID] = {
paused: false,
target: opts.target,
actions: []
}
}
element.actions.push(opts.action)
opts.action.startWithTarget(opts.target)
} | javascript | function (opts) {
var targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
element = this.targets[targetID] = {
paused: false,
target: opts.target,
actions: []
}
}
element.actions.push(opts.action)
opts.action.startWithTarget(opts.target)
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"targetID",
"=",
"opts",
".",
"target",
".",
"id",
"var",
"element",
"=",
"this",
".",
"targets",
"[",
"targetID",
"]",
"if",
"(",
"!",
"element",
")",
"{",
"element",
"=",
"this",
".",
"targets",
"[",
"targetID",
"]",
"=",
"{",
"paused",
":",
"false",
",",
"target",
":",
"opts",
".",
"target",
",",
"actions",
":",
"[",
"]",
"}",
"}",
"element",
".",
"actions",
".",
"push",
"(",
"opts",
".",
"action",
")",
"opts",
".",
"action",
".",
"startWithTarget",
"(",
"opts",
".",
"target",
")",
"}"
]
| Adds an action with a target. If the target is already present, then the
action will be added to the existing target. If the target is not
present, a new instance of this target will be created either paused or
paused, and the action will be added to the newly created target. When
the target is paused, the queued actions won't be 'ticked'.
@opt {cocos.nodes.Node} target Node to run the action on | [
"Adds",
"an",
"action",
"with",
"a",
"target",
".",
"If",
"the",
"target",
"is",
"already",
"present",
"then",
"the",
"action",
"will",
"be",
"added",
"to",
"the",
"existing",
"target",
".",
"If",
"the",
"target",
"is",
"not",
"present",
"a",
"new",
"instance",
"of",
"this",
"target",
"will",
"be",
"created",
"either",
"paused",
"or",
"paused",
"and",
"the",
"action",
"will",
"be",
"added",
"to",
"the",
"newly",
"created",
"target",
".",
"When",
"the",
"target",
"is",
"paused",
"the",
"queued",
"actions",
"won",
"t",
"be",
"ticked",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/ActionManager.js#L42-L58 | train |
|
ryanwilliams/cocos2d-javascript | src/ActionManager.js | function (action) {
var targetID = action.originalTarget.id,
element = this.targets[targetID]
if (!element) {
return
}
var actionIndex = element.actions.indexOf(action)
if (actionIndex == -1) {
return
}
if (this.currentTarget == element) {
element.currentActionSalvaged = true
}
element.actions[actionIndex] = null
element.actions.splice(actionIndex, 1); // Delete array item
if (element.actions.length === 0) {
if (this.currentTarget == element) {
this.currentTargetSalvaged = true
}
}
} | javascript | function (action) {
var targetID = action.originalTarget.id,
element = this.targets[targetID]
if (!element) {
return
}
var actionIndex = element.actions.indexOf(action)
if (actionIndex == -1) {
return
}
if (this.currentTarget == element) {
element.currentActionSalvaged = true
}
element.actions[actionIndex] = null
element.actions.splice(actionIndex, 1); // Delete array item
if (element.actions.length === 0) {
if (this.currentTarget == element) {
this.currentTargetSalvaged = true
}
}
} | [
"function",
"(",
"action",
")",
"{",
"var",
"targetID",
"=",
"action",
".",
"originalTarget",
".",
"id",
",",
"element",
"=",
"this",
".",
"targets",
"[",
"targetID",
"]",
"if",
"(",
"!",
"element",
")",
"{",
"return",
"}",
"var",
"actionIndex",
"=",
"element",
".",
"actions",
".",
"indexOf",
"(",
"action",
")",
"if",
"(",
"actionIndex",
"==",
"-",
"1",
")",
"{",
"return",
"}",
"if",
"(",
"this",
".",
"currentTarget",
"==",
"element",
")",
"{",
"element",
".",
"currentActionSalvaged",
"=",
"true",
"}",
"element",
".",
"actions",
"[",
"actionIndex",
"]",
"=",
"null",
"element",
".",
"actions",
".",
"splice",
"(",
"actionIndex",
",",
"1",
")",
";",
"if",
"(",
"element",
".",
"actions",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"this",
".",
"currentTarget",
"==",
"element",
")",
"{",
"this",
".",
"currentTargetSalvaged",
"=",
"true",
"}",
"}",
"}"
]
| Remove an action
@param {cocos.actions.Action} action Action to remove | [
"Remove",
"an",
"action"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/ActionManager.js#L65-L92 | train |
|
ryanwilliams/cocos2d-javascript | src/ActionManager.js | function(opts) {
var tag = opts.tag,
targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
return null
}
for (var i = 0; i < element.actions.length; i++ ) {
if (element.actions[i] &&
(element.actions[i].tag === tag)) {
return element.actions[i]
}
}
// Not found
return null
} | javascript | function(opts) {
var tag = opts.tag,
targetID = opts.target.id
var element = this.targets[targetID]
if (!element) {
return null
}
for (var i = 0; i < element.actions.length; i++ ) {
if (element.actions[i] &&
(element.actions[i].tag === tag)) {
return element.actions[i]
}
}
// Not found
return null
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"tag",
"=",
"opts",
".",
"tag",
",",
"targetID",
"=",
"opts",
".",
"target",
".",
"id",
"var",
"element",
"=",
"this",
".",
"targets",
"[",
"targetID",
"]",
"if",
"(",
"!",
"element",
")",
"{",
"return",
"null",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"element",
".",
"actions",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"element",
".",
"actions",
"[",
"i",
"]",
"&&",
"(",
"element",
".",
"actions",
"[",
"i",
"]",
".",
"tag",
"===",
"tag",
")",
")",
"{",
"return",
"element",
".",
"actions",
"[",
"i",
"]",
"}",
"}",
"return",
"null",
"}"
]
| Fetch an action belonging to a cocos.nodes.Node
@returns {cocos.actions.Action}
@opts {cocos.nodes.Node} target Target of the action
@opts {String} tag Tag of the action | [
"Fetch",
"an",
"action",
"belonging",
"to",
"a",
"cocos",
".",
"nodes",
".",
"Node"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/ActionManager.js#L102-L118 | train |
|
ryanwilliams/cocos2d-javascript | src/ActionManager.js | function (target) {
var targetID = target.id
var element = this.targets[targetID]
if (!element) {
return
}
delete this.targets[targetID]
// Delete everything in array but don't replace it incase something else has a reference
element.actions.splice(0, element.actions.length)
} | javascript | function (target) {
var targetID = target.id
var element = this.targets[targetID]
if (!element) {
return
}
delete this.targets[targetID]
// Delete everything in array but don't replace it incase something else has a reference
element.actions.splice(0, element.actions.length)
} | [
"function",
"(",
"target",
")",
"{",
"var",
"targetID",
"=",
"target",
".",
"id",
"var",
"element",
"=",
"this",
".",
"targets",
"[",
"targetID",
"]",
"if",
"(",
"!",
"element",
")",
"{",
"return",
"}",
"delete",
"this",
".",
"targets",
"[",
"targetID",
"]",
"element",
".",
"actions",
".",
"splice",
"(",
"0",
",",
"element",
".",
"actions",
".",
"length",
")",
"}"
]
| Remove all actions for a cocos.nodes.Node
@param {cocos.nodes.Node} target Node to remove all actions for | [
"Remove",
"all",
"actions",
"for",
"a",
"cocos",
".",
"nodes",
".",
"Node"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/ActionManager.js#L125-L136 | train |
|
ryanwilliams/cocos2d-javascript | lib/cocos2d/opts.js | function () {
var str = 'Usage: ' + path.basename(process.argv[1]) + ' ' + process.argv[2];
if (descriptors.opts.length) str += ' [options]';
if (descriptors.args.length) {
for (var i=0; i<descriptors.args.length; i++) {
if (descriptors.args[i].required) {
str += ' ' + descriptors.args[i].name;
} else {
str += ' [' + descriptors.args[i].name + ']';
}
}
}
str += '\n';
for (var i=0; i<descriptors.opts.length; i++) {
var opt = descriptors.opts[i];
if (opt.description) str += (opt.description) + '\n';
var line = '';
if (opt.short && !opt.long) line += '-' + opt.short;
else if (opt.long && !opt.short) line += '--' + opt.long;
else line += '-' + opt.short + ', --' + opt.long;
if (opt.value) line += ' <value>';
if (opt.required) line += ' (required)';
str += ' ' + line + '\n';
}
return str;
} | javascript | function () {
var str = 'Usage: ' + path.basename(process.argv[1]) + ' ' + process.argv[2];
if (descriptors.opts.length) str += ' [options]';
if (descriptors.args.length) {
for (var i=0; i<descriptors.args.length; i++) {
if (descriptors.args[i].required) {
str += ' ' + descriptors.args[i].name;
} else {
str += ' [' + descriptors.args[i].name + ']';
}
}
}
str += '\n';
for (var i=0; i<descriptors.opts.length; i++) {
var opt = descriptors.opts[i];
if (opt.description) str += (opt.description) + '\n';
var line = '';
if (opt.short && !opt.long) line += '-' + opt.short;
else if (opt.long && !opt.short) line += '--' + opt.long;
else line += '-' + opt.short + ', --' + opt.long;
if (opt.value) line += ' <value>';
if (opt.required) line += ' (required)';
str += ' ' + line + '\n';
}
return str;
} | [
"function",
"(",
")",
"{",
"var",
"str",
"=",
"'Usage: '",
"+",
"path",
".",
"basename",
"(",
"process",
".",
"argv",
"[",
"1",
"]",
")",
"+",
"' '",
"+",
"process",
".",
"argv",
"[",
"2",
"]",
";",
"if",
"(",
"descriptors",
".",
"opts",
".",
"length",
")",
"str",
"+=",
"' [options]'",
";",
"if",
"(",
"descriptors",
".",
"args",
".",
"length",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"descriptors",
".",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"descriptors",
".",
"args",
"[",
"i",
"]",
".",
"required",
")",
"{",
"str",
"+=",
"' '",
"+",
"descriptors",
".",
"args",
"[",
"i",
"]",
".",
"name",
";",
"}",
"else",
"{",
"str",
"+=",
"' ['",
"+",
"descriptors",
".",
"args",
"[",
"i",
"]",
".",
"name",
"+",
"']'",
";",
"}",
"}",
"}",
"str",
"+=",
"'\\n'",
";",
"\\n",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"descriptors",
".",
"opts",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"opt",
"=",
"descriptors",
".",
"opts",
"[",
"i",
"]",
";",
"if",
"(",
"opt",
".",
"description",
")",
"str",
"+=",
"(",
"opt",
".",
"description",
")",
"+",
"'\\n'",
";",
"\\n",
"var",
"line",
"=",
"''",
";",
"if",
"(",
"opt",
".",
"short",
"&&",
"!",
"opt",
".",
"long",
")",
"line",
"+=",
"'-'",
"+",
"opt",
".",
"short",
";",
"else",
"if",
"(",
"opt",
".",
"long",
"&&",
"!",
"opt",
".",
"short",
")",
"line",
"+=",
"'--'",
"+",
"opt",
".",
"long",
";",
"else",
"line",
"+=",
"'-'",
"+",
"opt",
".",
"short",
"+",
"', --'",
"+",
"opt",
".",
"long",
";",
"if",
"(",
"opt",
".",
"value",
")",
"line",
"+=",
"' <value>'",
";",
"if",
"(",
"opt",
".",
"required",
")",
"line",
"+=",
"' (required)'",
";",
"}",
"}"
]
| Create the help string | [
"Create",
"the",
"help",
"string"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/lib/cocos2d/opts.js#L251-L276 | train |
|
ryanwilliams/cocos2d-javascript | src/SpriteFrameCache.js | function (opts) {
var name = opts.name || opts
var frame = this.spriteFrames[name]
if (!frame) {
// No frame, look for an alias
var key = this.spriteFrameAliases[name]
if (key) {
frame = this.spriteFrames[key]
}
if (!frame) {
throw "Unable to find frame: " + name
}
}
return frame
} | javascript | function (opts) {
var name = opts.name || opts
var frame = this.spriteFrames[name]
if (!frame) {
// No frame, look for an alias
var key = this.spriteFrameAliases[name]
if (key) {
frame = this.spriteFrames[key]
}
if (!frame) {
throw "Unable to find frame: " + name
}
}
return frame
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"name",
"=",
"opts",
".",
"name",
"||",
"opts",
"var",
"frame",
"=",
"this",
".",
"spriteFrames",
"[",
"name",
"]",
"if",
"(",
"!",
"frame",
")",
"{",
"var",
"key",
"=",
"this",
".",
"spriteFrameAliases",
"[",
"name",
"]",
"if",
"(",
"key",
")",
"{",
"frame",
"=",
"this",
".",
"spriteFrames",
"[",
"key",
"]",
"}",
"if",
"(",
"!",
"frame",
")",
"{",
"throw",
"\"Unable to find frame: \"",
"+",
"name",
"}",
"}",
"return",
"frame",
"}"
]
| Get a single SpriteFrame
@param {String} opts.name The name of the sprite frame
@returns {cocos.SpriteFrame} The sprite frame | [
"Get",
"a",
"single",
"SpriteFrame"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/SpriteFrameCache.js#L167-L186 | train |
|
ryanwilliams/cocos2d-javascript | src/nodes/TMXLayer.js | function (pos) {
var layerSize = this.layerSize,
tiles = this.tiles
if (pos.x < 0 || pos.y < 0 || pos.x >= layerSize.width || pos.y >= layerSize.height) {
throw "TMX Layer: Invalid position"
}
var tile,
gid = this.tileGIDAt(pos)
// if GID is 0 then no tile exists at that point
if (gid) {
var z = pos.x + pos.y * layerSize.width
tile = this.getChild({tag: z})
}
return tile
} | javascript | function (pos) {
var layerSize = this.layerSize,
tiles = this.tiles
if (pos.x < 0 || pos.y < 0 || pos.x >= layerSize.width || pos.y >= layerSize.height) {
throw "TMX Layer: Invalid position"
}
var tile,
gid = this.tileGIDAt(pos)
// if GID is 0 then no tile exists at that point
if (gid) {
var z = pos.x + pos.y * layerSize.width
tile = this.getChild({tag: z})
}
return tile
} | [
"function",
"(",
"pos",
")",
"{",
"var",
"layerSize",
"=",
"this",
".",
"layerSize",
",",
"tiles",
"=",
"this",
".",
"tiles",
"if",
"(",
"pos",
".",
"x",
"<",
"0",
"||",
"pos",
".",
"y",
"<",
"0",
"||",
"pos",
".",
"x",
">=",
"layerSize",
".",
"width",
"||",
"pos",
".",
"y",
">=",
"layerSize",
".",
"height",
")",
"{",
"throw",
"\"TMX Layer: Invalid position\"",
"}",
"var",
"tile",
",",
"gid",
"=",
"this",
".",
"tileGIDAt",
"(",
"pos",
")",
"if",
"(",
"gid",
")",
"{",
"var",
"z",
"=",
"pos",
".",
"x",
"+",
"pos",
".",
"y",
"*",
"layerSize",
".",
"width",
"tile",
"=",
"this",
".",
"getChild",
"(",
"{",
"tag",
":",
"z",
"}",
")",
"}",
"return",
"tile",
"}"
]
| Get the tile at a specifix tile coordinate
@param {geometry.Point} pos Position of tile to get in tile coordinates (not pixels)
@returns {cocos.nodes.Sprite} The tile | [
"Get",
"the",
"tile",
"at",
"a",
"specifix",
"tile",
"coordinate"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/nodes/TMXLayer.js#L257-L275 | train |
|
ryanwilliams/cocos2d-javascript | lib/cocos2d/mimetypes.js | read | function read(file) {
var data = fs.readFileSync(file, 'ascii');
// Strip comments
data = data.replace(/#.*/g, '');
var lines = data.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i].trim();
if (!line) {
continue;
}
var words = line.split(/\s/),
type = words.shift(),
suffixes = words;
for (var j = 0, jen = suffixes.length; j < jen; j++) {
var suff = suffixes[j].trim();
if (!suff) {
continue;
}
addType(type, '.' + suff);
}
}
} | javascript | function read(file) {
var data = fs.readFileSync(file, 'ascii');
// Strip comments
data = data.replace(/#.*/g, '');
var lines = data.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i].trim();
if (!line) {
continue;
}
var words = line.split(/\s/),
type = words.shift(),
suffixes = words;
for (var j = 0, jen = suffixes.length; j < jen; j++) {
var suff = suffixes[j].trim();
if (!suff) {
continue;
}
addType(type, '.' + suff);
}
}
} | [
"function",
"read",
"(",
"file",
")",
"{",
"var",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"'ascii'",
")",
";",
"data",
"=",
"data",
".",
"replace",
"(",
"/",
"g",
"/",
"''",
",",
"var",
"lines",
"=",
"data",
".",
"split",
"(",
"'\\n'",
")",
";",
")",
";",
"\\n",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"lines",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"line",
"=",
"lines",
"[",
"i",
"]",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"line",
")",
"{",
"continue",
";",
"}",
"var",
"words",
"=",
"line",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
",",
"type",
"=",
"words",
".",
"shift",
"(",
")",
",",
"suffixes",
"=",
"words",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"jen",
"=",
"suffixes",
".",
"length",
";",
"j",
"<",
"jen",
";",
"j",
"++",
")",
"{",
"var",
"suff",
"=",
"suffixes",
"[",
"j",
"]",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"suff",
")",
"{",
"continue",
";",
"}",
"addType",
"(",
"type",
",",
"'.'",
"+",
"suff",
")",
";",
"}",
"}",
"}"
]
| Read a single mime.types-format file | [
"Read",
"a",
"single",
"mime",
".",
"types",
"-",
"format",
"file"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/lib/cocos2d/mimetypes.js#L38-L62 | train |
ryanwilliams/cocos2d-javascript | src/AnimationCache.js | function (opts) {
var name = opts.name,
animation = opts.animation
this.animations[name] = animation
} | javascript | function (opts) {
var name = opts.name,
animation = opts.animation
this.animations[name] = animation
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"name",
"=",
"opts",
".",
"name",
",",
"animation",
"=",
"opts",
".",
"animation",
"this",
".",
"animations",
"[",
"name",
"]",
"=",
"animation",
"}"
]
| Add an animation to the cache
@opt {String} name Unique name of the animation
@opt {cocos.Animcation} animation Animation to cache | [
"Add",
"an",
"animation",
"to",
"the",
"cache"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/AnimationCache.js#L31-L36 | train |
|
ryanwilliams/cocos2d-javascript | src/TMXXMLParser.js | function (opts) {
var objectName = opts.name
var object = null
this.objects.forEach(function (item) {
if (item.name == objectName) {
object = item
}
})
if (object !== null) {
return object
}
} | javascript | function (opts) {
var objectName = opts.name
var object = null
this.objects.forEach(function (item) {
if (item.name == objectName) {
object = item
}
})
if (object !== null) {
return object
}
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"objectName",
"=",
"opts",
".",
"name",
"var",
"object",
"=",
"null",
"this",
".",
"objects",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
".",
"name",
"==",
"objectName",
")",
"{",
"object",
"=",
"item",
"}",
"}",
")",
"if",
"(",
"object",
"!==",
"null",
")",
"{",
"return",
"object",
"}",
"}"
]
| Get the object for the specific object name. It will return the 1st
object found on the array for the given name.
@opt {String} name Object name
@returns {Object} Object | [
"Get",
"the",
"object",
"for",
"the",
"specific",
"object",
"name",
".",
"It",
"will",
"return",
"the",
"1st",
"object",
"found",
"on",
"the",
"array",
"for",
"the",
"given",
"name",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/TMXXMLParser.js#L111-L123 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (key) {
var next = false
if (~key.indexOf('.')) {
var tokens = key.split('.');
key = tokens.shift();
next = tokens.join('.');
}
var accessor = getAccessors(this)[key],
val;
if (accessor) {
val = accessor.target.get(accessor.key);
} else {
// Call getting function
if (this['get_' + key]) {
val = this['get_' + key]();
} else {
val = this[key];
}
}
if (next) {
return val.get(next);
} else {
return val;
}
} | javascript | function (key) {
var next = false
if (~key.indexOf('.')) {
var tokens = key.split('.');
key = tokens.shift();
next = tokens.join('.');
}
var accessor = getAccessors(this)[key],
val;
if (accessor) {
val = accessor.target.get(accessor.key);
} else {
// Call getting function
if (this['get_' + key]) {
val = this['get_' + key]();
} else {
val = this[key];
}
}
if (next) {
return val.get(next);
} else {
return val;
}
} | [
"function",
"(",
"key",
")",
"{",
"var",
"next",
"=",
"false",
"if",
"(",
"~",
"key",
".",
"indexOf",
"(",
"'.'",
")",
")",
"{",
"var",
"tokens",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
";",
"key",
"=",
"tokens",
".",
"shift",
"(",
")",
";",
"next",
"=",
"tokens",
".",
"join",
"(",
"'.'",
")",
";",
"}",
"var",
"accessor",
"=",
"getAccessors",
"(",
"this",
")",
"[",
"key",
"]",
",",
"val",
";",
"if",
"(",
"accessor",
")",
"{",
"val",
"=",
"accessor",
".",
"target",
".",
"get",
"(",
"accessor",
".",
"key",
")",
";",
"}",
"else",
"{",
"if",
"(",
"this",
"[",
"'get_'",
"+",
"key",
"]",
")",
"{",
"val",
"=",
"this",
"[",
"'get_'",
"+",
"key",
"]",
"(",
")",
";",
"}",
"else",
"{",
"val",
"=",
"this",
"[",
"key",
"]",
";",
"}",
"}",
"if",
"(",
"next",
")",
"{",
"return",
"val",
".",
"get",
"(",
"next",
")",
";",
"}",
"else",
"{",
"return",
"val",
";",
"}",
"}"
]
| Get a property from the object. Always use this instead of trying to
access the property directly. This will ensure all bindings, setters and
getters work correctly.
@param {String} key Name of property to get or dot (.) separated path to a property
@returns {*} Value of the property | [
"Get",
"a",
"property",
"from",
"the",
"object",
".",
"Always",
"use",
"this",
"instead",
"of",
"trying",
"to",
"access",
"the",
"property",
"directly",
".",
"This",
"will",
"ensure",
"all",
"bindings",
"setters",
"and",
"getters",
"work",
"correctly",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L76-L103 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (key, value) {
var accessor = getAccessors(this)[key],
oldVal = this.get(key);
this.triggerBeforeChanged(key, oldVal);
if (accessor) {
accessor.target.set(accessor.key, value);
} else {
if (this['set_' + key]) {
this['set_' + key](value);
} else {
this[key] = value;
}
}
this.triggerChanged(key, oldVal);
} | javascript | function (key, value) {
var accessor = getAccessors(this)[key],
oldVal = this.get(key);
this.triggerBeforeChanged(key, oldVal);
if (accessor) {
accessor.target.set(accessor.key, value);
} else {
if (this['set_' + key]) {
this['set_' + key](value);
} else {
this[key] = value;
}
}
this.triggerChanged(key, oldVal);
} | [
"function",
"(",
"key",
",",
"value",
")",
"{",
"var",
"accessor",
"=",
"getAccessors",
"(",
"this",
")",
"[",
"key",
"]",
",",
"oldVal",
"=",
"this",
".",
"get",
"(",
"key",
")",
";",
"this",
".",
"triggerBeforeChanged",
"(",
"key",
",",
"oldVal",
")",
";",
"if",
"(",
"accessor",
")",
"{",
"accessor",
".",
"target",
".",
"set",
"(",
"accessor",
".",
"key",
",",
"value",
")",
";",
"}",
"else",
"{",
"if",
"(",
"this",
"[",
"'set_'",
"+",
"key",
"]",
")",
"{",
"this",
"[",
"'set_'",
"+",
"key",
"]",
"(",
"value",
")",
";",
"}",
"else",
"{",
"this",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
"this",
".",
"triggerChanged",
"(",
"key",
",",
"oldVal",
")",
";",
"}"
]
| Set a property on the object. Always use this instead of trying to
access the property directly. This will ensure all bindings, setters and
getters work correctly.
@param {String} key Name of property to get
@param {*} value New value for the property | [
"Set",
"a",
"property",
"on",
"the",
"object",
".",
"Always",
"use",
"this",
"instead",
"of",
"trying",
"to",
"access",
"the",
"property",
"directly",
".",
"This",
"will",
"ensure",
"all",
"bindings",
"setters",
"and",
"getters",
"work",
"correctly",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L114-L132 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (kvp) {
for (var x in kvp) {
if (kvp.hasOwnProperty(x)) {
this.set(x, kvp[x]);
}
}
} | javascript | function (kvp) {
for (var x in kvp) {
if (kvp.hasOwnProperty(x)) {
this.set(x, kvp[x]);
}
}
} | [
"function",
"(",
"kvp",
")",
"{",
"for",
"(",
"var",
"x",
"in",
"kvp",
")",
"{",
"if",
"(",
"kvp",
".",
"hasOwnProperty",
"(",
"x",
")",
")",
"{",
"this",
".",
"set",
"(",
"x",
",",
"kvp",
"[",
"x",
"]",
")",
";",
"}",
"}",
"}"
]
| Set multiple propertys in one go
@param {Object} kvp An Object where the key is a property name and the value is the value to assign to the property
@example
var props = {
monkey: 'ook',
cat: 'meow',
dog: 'woof'
};
foo.setValues(props);
console.log(foo.get('cat')); // Logs 'meow' | [
"Set",
"multiple",
"propertys",
"in",
"one",
"go"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L148-L154 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (key, target, targetKey, noNotify) {
targetKey = targetKey || key;
var self = this;
this.unbind(key);
var oldVal = this.get(key);
// When bound property changes, trigger a 'changed' event on this one too
getBindings(this)[key] = events.addListener(target, targetKey.toLowerCase() + '_changed', function (oldVal) {
self.triggerChanged(key, oldVal);
});
addAccessor(this, key, target, targetKey, noNotify);
} | javascript | function (key, target, targetKey, noNotify) {
targetKey = targetKey || key;
var self = this;
this.unbind(key);
var oldVal = this.get(key);
// When bound property changes, trigger a 'changed' event on this one too
getBindings(this)[key] = events.addListener(target, targetKey.toLowerCase() + '_changed', function (oldVal) {
self.triggerChanged(key, oldVal);
});
addAccessor(this, key, target, targetKey, noNotify);
} | [
"function",
"(",
"key",
",",
"target",
",",
"targetKey",
",",
"noNotify",
")",
"{",
"targetKey",
"=",
"targetKey",
"||",
"key",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"unbind",
"(",
"key",
")",
";",
"var",
"oldVal",
"=",
"this",
".",
"get",
"(",
"key",
")",
";",
"getBindings",
"(",
"this",
")",
"[",
"key",
"]",
"=",
"events",
".",
"addListener",
"(",
"target",
",",
"targetKey",
".",
"toLowerCase",
"(",
")",
"+",
"'_changed'",
",",
"function",
"(",
"oldVal",
")",
"{",
"self",
".",
"triggerChanged",
"(",
"key",
",",
"oldVal",
")",
";",
"}",
")",
";",
"addAccessor",
"(",
"this",
",",
"key",
",",
"target",
",",
"targetKey",
",",
"noNotify",
")",
";",
"}"
]
| Bind the value of a property on this object to that of another object so
they always have the same value. Setting the value on either object will update
the other too.
@param {String} key Name of the property on this object that should be bound
@param {BOject} target Object to bind to
@param {String} [targetKey=key] Key on the target object to bind to
@param {Boolean} [noNotify=false] Set to true to prevent this object's property triggering a 'changed' event when adding the binding | [
"Bind",
"the",
"value",
"of",
"a",
"property",
"on",
"this",
"object",
"to",
"that",
"of",
"another",
"object",
"so",
"they",
"always",
"have",
"the",
"same",
"value",
".",
"Setting",
"the",
"value",
"on",
"either",
"object",
"will",
"update",
"the",
"other",
"too",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L193-L206 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function () {
var keys = [],
bindings = getBindings(this);
for (var k in bindings) {
if (bindings.hasOwnProperty(k)) {
this.unbind(k);
}
}
} | javascript | function () {
var keys = [],
bindings = getBindings(this);
for (var k in bindings) {
if (bindings.hasOwnProperty(k)) {
this.unbind(k);
}
}
} | [
"function",
"(",
")",
"{",
"var",
"keys",
"=",
"[",
"]",
",",
"bindings",
"=",
"getBindings",
"(",
"this",
")",
";",
"for",
"(",
"var",
"k",
"in",
"bindings",
")",
"{",
"if",
"(",
"bindings",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"{",
"this",
".",
"unbind",
"(",
"k",
")",
";",
"}",
"}",
"}"
]
| Remove all bindings on this object | [
"Remove",
"all",
"bindings",
"on",
"this",
"object"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L231-L239 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (i, value) {
this.array.splice(i, 0, value);
this.set('length', this.array.length);
events.trigger(this, 'insert_at', i);
} | javascript | function (i, value) {
this.array.splice(i, 0, value);
this.set('length', this.array.length);
events.trigger(this, 'insert_at', i);
} | [
"function",
"(",
"i",
",",
"value",
")",
"{",
"this",
".",
"array",
".",
"splice",
"(",
"i",
",",
"0",
",",
"value",
")",
";",
"this",
".",
"set",
"(",
"'length'",
",",
"this",
".",
"array",
".",
"length",
")",
";",
"events",
".",
"trigger",
"(",
"this",
",",
"'insert_at'",
",",
"i",
")",
";",
"}"
]
| Insert a new item into the array without overwriting anything
@param {Integer} i Index to insert item at
@param {*} value Value to insert | [
"Insert",
"a",
"new",
"item",
"into",
"the",
"array",
"without",
"overwriting",
"anything"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L356-L360 | train |
|
ryanwilliams/cocos2d-javascript | src/libs/bobject.js | function (i) {
var oldVal = this.array[i];
this.array.splice(i, 1);
this.set('length', this.array.length);
events.trigger(this, 'remove_at', i, oldVal);
return oldVal;
} | javascript | function (i) {
var oldVal = this.array[i];
this.array.splice(i, 1);
this.set('length', this.array.length);
events.trigger(this, 'remove_at', i, oldVal);
return oldVal;
} | [
"function",
"(",
"i",
")",
"{",
"var",
"oldVal",
"=",
"this",
".",
"array",
"[",
"i",
"]",
";",
"this",
".",
"array",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"this",
".",
"set",
"(",
"'length'",
",",
"this",
".",
"array",
".",
"length",
")",
";",
"events",
".",
"trigger",
"(",
"this",
",",
"'remove_at'",
",",
"i",
",",
"oldVal",
")",
";",
"return",
"oldVal",
";",
"}"
]
| Remove item from the array and return it
@param {Integer} i Index to remove
@returns {*} Value that was removed | [
"Remove",
"item",
"from",
"the",
"array",
"and",
"return",
"it"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/libs/bobject.js#L368-L375 | train |
|
vixis/angularplasmid | src/js/services.js | round10 | function round10(value, exp) {
var type = 'round';
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
} | javascript | function round10(value, exp) {
var type = 'round';
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
} | [
"function",
"round10",
"(",
"value",
",",
"exp",
")",
"{",
"var",
"type",
"=",
"'round'",
";",
"if",
"(",
"typeof",
"exp",
"===",
"'undefined'",
"||",
"+",
"exp",
"===",
"0",
")",
"{",
"return",
"Math",
"[",
"type",
"]",
"(",
"value",
")",
";",
"}",
"value",
"=",
"+",
"value",
";",
"exp",
"=",
"+",
"exp",
";",
"if",
"(",
"isNaN",
"(",
"value",
")",
"||",
"!",
"(",
"typeof",
"exp",
"===",
"'number'",
"&&",
"exp",
"%",
"1",
"===",
"0",
")",
")",
"{",
"return",
"NaN",
";",
"}",
"value",
"=",
"value",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'e'",
")",
";",
"value",
"=",
"Math",
"[",
"type",
"]",
"(",
"+",
"(",
"value",
"[",
"0",
"]",
"+",
"'e'",
"+",
"(",
"value",
"[",
"1",
"]",
"?",
"(",
"+",
"value",
"[",
"1",
"]",
"-",
"exp",
")",
":",
"-",
"exp",
")",
")",
")",
";",
"value",
"=",
"value",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'e'",
")",
";",
"return",
"+",
"(",
"value",
"[",
"0",
"]",
"+",
"'e'",
"+",
"(",
"value",
"[",
"1",
"]",
"?",
"(",
"+",
"value",
"[",
"1",
"]",
"+",
"exp",
")",
":",
"exp",
")",
")",
";",
"}"
]
| Decimal round with precision | [
"Decimal",
"round",
"with",
"precision"
]
| fe43921e48357fd5bd4a1de70139148506ec9213 | https://github.com/vixis/angularplasmid/blob/fe43921e48357fd5bd4a1de70139148506ec9213/src/js/services.js#L20-L38 | train |
ryanwilliams/cocos2d-javascript | src/Director.js | Director | function Director () {
if (Director._instance) {
throw new Error('Director instance already exists')
}
this.sceneStack = []
this.window = parent.window
this.document = this.window.document
// Prevent writing to some properties
util.makeReadonly(this, 'canvas context sceneStack winSize isReady document window container isTouchScreen isMobile'.w)
} | javascript | function Director () {
if (Director._instance) {
throw new Error('Director instance already exists')
}
this.sceneStack = []
this.window = parent.window
this.document = this.window.document
// Prevent writing to some properties
util.makeReadonly(this, 'canvas context sceneStack winSize isReady document window container isTouchScreen isMobile'.w)
} | [
"function",
"Director",
"(",
")",
"{",
"if",
"(",
"Director",
".",
"_instance",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Director instance already exists'",
")",
"}",
"this",
".",
"sceneStack",
"=",
"[",
"]",
"this",
".",
"window",
"=",
"parent",
".",
"window",
"this",
".",
"document",
"=",
"this",
".",
"window",
".",
"document",
"util",
".",
"makeReadonly",
"(",
"this",
",",
"'canvas context sceneStack winSize isReady document window container isTouchScreen isMobile'",
".",
"w",
")",
"}"
]
| Create a new instance of Director. This is a singleton so you shouldn't use
the constructor directly. Instead grab the shared instance using the
cocos.Director.sharedDirector property.
@class
Creates and handles the main view and manages how and when to execute the
Scenes.
This class is a singleton so don't instantiate it yourself, instead use
cocos.Director.sharedDirector to return the instance.
@memberOf cocos
@singleton | [
"Create",
"a",
"new",
"instance",
"of",
"Director",
".",
"This",
"is",
"a",
"singleton",
"so",
"you",
"shouldn",
"t",
"use",
"the",
"constructor",
"directly",
".",
"Instead",
"grab",
"the",
"shared",
"instance",
"using",
"the",
"cocos",
".",
"Director",
".",
"sharedDirector",
"property",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Director.js#L27-L38 | train |
ryanwilliams/cocos2d-javascript | src/Director.js | function () {
if (!Director._instance) {
if (window.navigator.userAgent.match(/(iPhone|iPod|iPad|Android)/)) {
Director._instance = new DirectorTouchScreen()
} else {
Director._instance = new this()
}
}
return Director._instance
} | javascript | function () {
if (!Director._instance) {
if (window.navigator.userAgent.match(/(iPhone|iPod|iPad|Android)/)) {
Director._instance = new DirectorTouchScreen()
} else {
Director._instance = new this()
}
}
return Director._instance
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"Director",
".",
"_instance",
")",
"{",
"if",
"(",
"window",
".",
"navigator",
".",
"userAgent",
".",
"match",
"(",
"/",
"(iPhone|iPod|iPad|Android)",
"/",
")",
")",
"{",
"Director",
".",
"_instance",
"=",
"new",
"DirectorTouchScreen",
"(",
")",
"}",
"else",
"{",
"Director",
".",
"_instance",
"=",
"new",
"this",
"(",
")",
"}",
"}",
"return",
"Director",
".",
"_instance",
"}"
]
| A shared singleton instance of cocos.Director
@memberOf cocos.Director
@getter {cocos.Director} sharedDirector | [
"A",
"shared",
"singleton",
"instance",
"of",
"cocos",
".",
"Director"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/Director.js#L612-L622 | train |
|
ryanwilliams/cocos2d-javascript | src/nodes/Transition.js | function () {
var is = this.inScene,
os = this.outScene
/* clean up */
is.visible = true
is.position = geo.PointZero()
is.scale = 1.0
is.rotation = 0
os.visible = false
os.position = geo.PointZero()
os.scale = 1.0
os.rotation = 0
Scheduler.sharedScheduler.schedule({
target: this,
method: this.setNewScene,
interval: 0
})
} | javascript | function () {
var is = this.inScene,
os = this.outScene
/* clean up */
is.visible = true
is.position = geo.PointZero()
is.scale = 1.0
is.rotation = 0
os.visible = false
os.position = geo.PointZero()
os.scale = 1.0
os.rotation = 0
Scheduler.sharedScheduler.schedule({
target: this,
method: this.setNewScene,
interval: 0
})
} | [
"function",
"(",
")",
"{",
"var",
"is",
"=",
"this",
".",
"inScene",
",",
"os",
"=",
"this",
".",
"outScene",
"is",
".",
"visible",
"=",
"true",
"is",
".",
"position",
"=",
"geo",
".",
"PointZero",
"(",
")",
"is",
".",
"scale",
"=",
"1.0",
"is",
".",
"rotation",
"=",
"0",
"os",
".",
"visible",
"=",
"false",
"os",
".",
"position",
"=",
"geo",
".",
"PointZero",
"(",
")",
"os",
".",
"scale",
"=",
"1.0",
"os",
".",
"rotation",
"=",
"0",
"Scheduler",
".",
"sharedScheduler",
".",
"schedule",
"(",
"{",
"target",
":",
"this",
",",
"method",
":",
"this",
".",
"setNewScene",
",",
"interval",
":",
"0",
"}",
")",
"}"
]
| Called after the transition finishes | [
"Called",
"after",
"the",
"transition",
"finishes"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/nodes/Transition.js#L74-L94 | train |
|
infinum/webpack-asset-pipeline | index.js | function(manifest, compilation, props) {
const outputFolder = compilation.options.output.path;
const outputFile = path.join(outputFolder, props.fileName);
fse.outputFileSync(outputFile, manifest);
} | javascript | function(manifest, compilation, props) {
const outputFolder = compilation.options.output.path;
const outputFile = path.join(outputFolder, props.fileName);
fse.outputFileSync(outputFile, manifest);
} | [
"function",
"(",
"manifest",
",",
"compilation",
",",
"props",
")",
"{",
"const",
"outputFolder",
"=",
"compilation",
".",
"options",
".",
"output",
".",
"path",
";",
"const",
"outputFile",
"=",
"path",
".",
"join",
"(",
"outputFolder",
",",
"props",
".",
"fileName",
")",
";",
"fse",
".",
"outputFileSync",
"(",
"outputFile",
",",
"manifest",
")",
";",
"}"
]
| Writes a JSON to Webpack output path. If the output directory doesn't
exists it will create it.
@param {JSON} manifest - The manifest containing files
@param {object} compilation - Object containing Webpack context
@param {object} props - Props passed to the plugin
@return {undefined} | [
"Writes",
"a",
"JSON",
"to",
"Webpack",
"output",
"path",
".",
"If",
"the",
"output",
"directory",
"doesn",
"t",
"exists",
"it",
"will",
"create",
"it",
"."
]
| b01ca6ddd60b3f7a2809079aa08523e256889691 | https://github.com/infinum/webpack-asset-pipeline/blob/b01ca6ddd60b3f7a2809079aa08523e256889691/index.js#L27-L32 | train |
|
infinum/webpack-asset-pipeline | index.js | function(compilation, assetName) {
if (!compilation || !compilation.cache || typeof compilation.cache !== 'object') {
return null;
}
const cacheKeys = Object.keys(compilation.cache);
for (let keyIndex = 0; keyIndex < cacheKeys.length; keyIndex++) {
const cache = compilation.cache[cacheKeys[keyIndex]];
if (cache.assets && assetName in cache.assets) {
return cache.rawRequest;
}
}
return null;
} | javascript | function(compilation, assetName) {
if (!compilation || !compilation.cache || typeof compilation.cache !== 'object') {
return null;
}
const cacheKeys = Object.keys(compilation.cache);
for (let keyIndex = 0; keyIndex < cacheKeys.length; keyIndex++) {
const cache = compilation.cache[cacheKeys[keyIndex]];
if (cache.assets && assetName in cache.assets) {
return cache.rawRequest;
}
}
return null;
} | [
"function",
"(",
"compilation",
",",
"assetName",
")",
"{",
"if",
"(",
"!",
"compilation",
"||",
"!",
"compilation",
".",
"cache",
"||",
"typeof",
"compilation",
".",
"cache",
"!==",
"'object'",
")",
"{",
"return",
"null",
";",
"}",
"const",
"cacheKeys",
"=",
"Object",
".",
"keys",
"(",
"compilation",
".",
"cache",
")",
";",
"for",
"(",
"let",
"keyIndex",
"=",
"0",
";",
"keyIndex",
"<",
"cacheKeys",
".",
"length",
";",
"keyIndex",
"++",
")",
"{",
"const",
"cache",
"=",
"compilation",
".",
"cache",
"[",
"cacheKeys",
"[",
"keyIndex",
"]",
"]",
";",
"if",
"(",
"cache",
".",
"assets",
"&&",
"assetName",
"in",
"cache",
".",
"assets",
")",
"{",
"return",
"cache",
".",
"rawRequest",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Tries to find the user reuqired file in cace. If it does it returns the
file path user used in the `require` statement. Otherwise it returns null.
@param {object} compilation - Object containing Webpack context
@param {string} assetName - Emitted file name
@return {string} path that user used in require/import | [
"Tries",
"to",
"find",
"the",
"user",
"reuqired",
"file",
"in",
"cace",
".",
"If",
"it",
"does",
"it",
"returns",
"the",
"file",
"path",
"user",
"used",
"in",
"the",
"require",
"statement",
".",
"Otherwise",
"it",
"returns",
"null",
"."
]
| b01ca6ddd60b3f7a2809079aa08523e256889691 | https://github.com/infinum/webpack-asset-pipeline/blob/b01ca6ddd60b3f7a2809079aa08523e256889691/index.js#L42-L57 | train |
|
ryanwilliams/cocos2d-javascript | src/RemoteFont.js | hasFontLoaded | function hasFontLoaded (window, fontName) {
var testSize = 16
if (!fontTestElement) {
fontTestElement = window.document.createElement('canvas')
fontTestElement.width = testSize
fontTestElement.height = testSize
fontTestElement.style.display = 'none'
ctx = fontTestElement.getContext('2d')
window.document.body.appendChild(fontTestElement)
}
fontTestElement.width = testSize
ctx.fillStyle = 'rgba(0, 0, 0, 0)'
ctx.fillRect(0, 0, testSize, testSize)
ctx.font = testSize + "px __cc2d_" + fontName
ctx.fillStyle = 'rgba(255, 255, 255, 1)'
ctx.fillText("M", 0, testSize);
var pixels = ctx.getImageData(0, 0, testSize, testSize).data
for (var i = 0; i < testSize * testSize; i++) {
if (pixels[i * 4] != 0) {
fontTestElement.parentNode.removeChild(fontTestElement)
fontTestElement = null
return true
}
}
return false
} | javascript | function hasFontLoaded (window, fontName) {
var testSize = 16
if (!fontTestElement) {
fontTestElement = window.document.createElement('canvas')
fontTestElement.width = testSize
fontTestElement.height = testSize
fontTestElement.style.display = 'none'
ctx = fontTestElement.getContext('2d')
window.document.body.appendChild(fontTestElement)
}
fontTestElement.width = testSize
ctx.fillStyle = 'rgba(0, 0, 0, 0)'
ctx.fillRect(0, 0, testSize, testSize)
ctx.font = testSize + "px __cc2d_" + fontName
ctx.fillStyle = 'rgba(255, 255, 255, 1)'
ctx.fillText("M", 0, testSize);
var pixels = ctx.getImageData(0, 0, testSize, testSize).data
for (var i = 0; i < testSize * testSize; i++) {
if (pixels[i * 4] != 0) {
fontTestElement.parentNode.removeChild(fontTestElement)
fontTestElement = null
return true
}
}
return false
} | [
"function",
"hasFontLoaded",
"(",
"window",
",",
"fontName",
")",
"{",
"var",
"testSize",
"=",
"16",
"if",
"(",
"!",
"fontTestElement",
")",
"{",
"fontTestElement",
"=",
"window",
".",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
"fontTestElement",
".",
"width",
"=",
"testSize",
"fontTestElement",
".",
"height",
"=",
"testSize",
"fontTestElement",
".",
"style",
".",
"display",
"=",
"'none'",
"ctx",
"=",
"fontTestElement",
".",
"getContext",
"(",
"'2d'",
")",
"window",
".",
"document",
".",
"body",
".",
"appendChild",
"(",
"fontTestElement",
")",
"}",
"fontTestElement",
".",
"width",
"=",
"testSize",
"ctx",
".",
"fillStyle",
"=",
"'rgba(0, 0, 0, 0)'",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"testSize",
",",
"testSize",
")",
"ctx",
".",
"font",
"=",
"testSize",
"+",
"\"px __cc2d_\"",
"+",
"fontName",
"ctx",
".",
"fillStyle",
"=",
"'rgba(255, 255, 255, 1)'",
"ctx",
".",
"fillText",
"(",
"\"M\"",
",",
"0",
",",
"testSize",
")",
";",
"var",
"pixels",
"=",
"ctx",
".",
"getImageData",
"(",
"0",
",",
"0",
",",
"testSize",
",",
"testSize",
")",
".",
"data",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"testSize",
"*",
"testSize",
";",
"i",
"++",
")",
"{",
"if",
"(",
"pixels",
"[",
"i",
"*",
"4",
"]",
"!=",
"0",
")",
"{",
"fontTestElement",
".",
"parentNode",
".",
"removeChild",
"(",
"fontTestElement",
")",
"fontTestElement",
"=",
"null",
"return",
"true",
"}",
"}",
"return",
"false",
"}"
]
| Very crude way to test for when a font has loaded
While a font is loading they will be drawn as blank onto a canvas.
This function creates a small canvas and tests the pixels to see if the
given font draws. If it does then we can assume the font loaded. | [
"Very",
"crude",
"way",
"to",
"test",
"for",
"when",
"a",
"font",
"has",
"loaded"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/RemoteFont.js#L13-L43 | train |
ryanwilliams/cocos2d-javascript | src/nodes/TMXTiledMap.js | function (opts) {
var layerName = opts.name,
layer = null
this.children.forEach(function (item) {
if (item instanceof TMXLayer && item.layerName == layerName) {
layer = item
}
})
if (layer !== null) {
return layer
}
} | javascript | function (opts) {
var layerName = opts.name,
layer = null
this.children.forEach(function (item) {
if (item instanceof TMXLayer && item.layerName == layerName) {
layer = item
}
})
if (layer !== null) {
return layer
}
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"layerName",
"=",
"opts",
".",
"name",
",",
"layer",
"=",
"null",
"this",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
"instanceof",
"TMXLayer",
"&&",
"item",
".",
"layerName",
"==",
"layerName",
")",
"{",
"layer",
"=",
"item",
"}",
"}",
")",
"if",
"(",
"layer",
"!==",
"null",
")",
"{",
"return",
"layer",
"}",
"}"
]
| Get a layer
@opt {String} name The name of the layer to get
@returns {cocos.nodes.TMXLayer} The layer requested | [
"Get",
"a",
"layer"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/nodes/TMXTiledMap.js#L141-L153 | train |
|
ryanwilliams/cocos2d-javascript | src/nodes/TMXTiledMap.js | function (opts) {
var objectGroupName = opts.name,
objectGroup = null
this.objectGroups.forEach(function (item) {
if (item.name == objectGroupName) {
objectGroup = item
}
})
if (objectGroup !== null) {
return objectGroup
}
} | javascript | function (opts) {
var objectGroupName = opts.name,
objectGroup = null
this.objectGroups.forEach(function (item) {
if (item.name == objectGroupName) {
objectGroup = item
}
})
if (objectGroup !== null) {
return objectGroup
}
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"objectGroupName",
"=",
"opts",
".",
"name",
",",
"objectGroup",
"=",
"null",
"this",
".",
"objectGroups",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
".",
"name",
"==",
"objectGroupName",
")",
"{",
"objectGroup",
"=",
"item",
"}",
"}",
")",
"if",
"(",
"objectGroup",
"!==",
"null",
")",
"{",
"return",
"objectGroup",
"}",
"}"
]
| Return the ObjectGroup for the secific group
@opt {String} name The object group name
@returns {cocos.TMXObjectGroup} The object group | [
"Return",
"the",
"ObjectGroup",
"for",
"the",
"secific",
"group"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/nodes/TMXTiledMap.js#L161-L173 | train |
|
ryanwilliams/cocos2d-javascript | support/distribution/package.js | generateNSISScript | function generateNSISScript(files, callback) {
sys.puts('Generating NSIS script');
var installFileList = ' SetOverwrite try\n',
removeFileList = '',
removeDirList = '';
files = files.filter(function(file) {
// Ignore node-builds for other platforms
if (~file.indexOf('node-builds') && !~file.indexOf('cyg') && !~file.indexOf('tmp') && !~file.indexOf('etc')) {
return;
}
return file;
});
// Generate the install and remove lists
var prevDirname, i, len;
for (i = 0, len = files.length; i < len; i++) {
var file = files[i];
var dirname = path.dirname(file);
if (dirname != prevDirname) {
prevDirname = dirname;
installFileList += ' SetOutPath "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
removeDirList += ' RMDir "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
}
var m;
if ((m = file.match(/\/?(README|LICENSE)(.md)?$/))) {
// Rename README and LICENSE so they end in .txt
installFileList += ' File /oname=' + m[1] + '.txt "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
} else {
installFileList += ' File "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
}
removeFileList += ' Delete "$INSTDIR\\' + file.replace(/\//g, '\\') + '"\n';
}
var tmp = new Template(fs.readFileSync(path.join(__dirname, 'installer_nsi.template'), 'utf8'));
var data = tmp.substitute({
root_path: path.join(__dirname, '../..'),
output_path: OUTPUT_PATH,
version: 'v' + VERSION,
install_file_list: installFileList,
remove_file_list: removeFileList,
remove_dir_list: removeDirList
});
callback(data);
} | javascript | function generateNSISScript(files, callback) {
sys.puts('Generating NSIS script');
var installFileList = ' SetOverwrite try\n',
removeFileList = '',
removeDirList = '';
files = files.filter(function(file) {
// Ignore node-builds for other platforms
if (~file.indexOf('node-builds') && !~file.indexOf('cyg') && !~file.indexOf('tmp') && !~file.indexOf('etc')) {
return;
}
return file;
});
// Generate the install and remove lists
var prevDirname, i, len;
for (i = 0, len = files.length; i < len; i++) {
var file = files[i];
var dirname = path.dirname(file);
if (dirname != prevDirname) {
prevDirname = dirname;
installFileList += ' SetOutPath "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
removeDirList += ' RMDir "$INSTDIR\\' + dirname.replace(/\//g, '\\') + '"\n';
}
var m;
if ((m = file.match(/\/?(README|LICENSE)(.md)?$/))) {
// Rename README and LICENSE so they end in .txt
installFileList += ' File /oname=' + m[1] + '.txt "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
} else {
installFileList += ' File "${ROOT_PATH}\\' + file.replace(/\//g, '\\') + '"\n';
}
removeFileList += ' Delete "$INSTDIR\\' + file.replace(/\//g, '\\') + '"\n';
}
var tmp = new Template(fs.readFileSync(path.join(__dirname, 'installer_nsi.template'), 'utf8'));
var data = tmp.substitute({
root_path: path.join(__dirname, '../..'),
output_path: OUTPUT_PATH,
version: 'v' + VERSION,
install_file_list: installFileList,
remove_file_list: removeFileList,
remove_dir_list: removeDirList
});
callback(data);
} | [
"function",
"generateNSISScript",
"(",
"files",
",",
"callback",
")",
"{",
"sys",
".",
"puts",
"(",
"'Generating NSIS script'",
")",
";",
"var",
"installFileList",
"=",
"' SetOverwrite try\\n'",
",",
"\\n",
",",
"removeFileList",
"=",
"''",
";",
"removeDirList",
"=",
"''",
"files",
"=",
"files",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"~",
"file",
".",
"indexOf",
"(",
"'node-builds'",
")",
"&&",
"!",
"~",
"file",
".",
"indexOf",
"(",
"'cyg'",
")",
"&&",
"!",
"~",
"file",
".",
"indexOf",
"(",
"'tmp'",
")",
"&&",
"!",
"~",
"file",
".",
"indexOf",
"(",
"'etc'",
")",
")",
"{",
"return",
";",
"}",
"return",
"file",
";",
"}",
")",
";",
"var",
"prevDirname",
",",
"i",
",",
"len",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"files",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"var",
"dirname",
"=",
"path",
".",
"dirname",
"(",
"file",
")",
";",
"if",
"(",
"dirname",
"!=",
"prevDirname",
")",
"{",
"prevDirname",
"=",
"dirname",
";",
"installFileList",
"+=",
"' SetOutPath \"$INSTDIR\\\\'",
"+",
"\\\\",
"+",
"dirname",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\\\\'",
")",
";",
"\\\\",
"}",
"'\"\\n'",
"\\n",
"removeDirList",
"+=",
"' RMDir \"$INSTDIR\\\\'",
"+",
"\\\\",
"+",
"dirname",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\\\\'",
")",
";",
"}",
"\\\\",
"'\"\\n'",
"}"
]
| Generates an NSIS installer script to install the contents of a given
directory and returns it as a string.
@param {String} dir The directory that will be installed
@returns String The contents of the NSIS script | [
"Generates",
"an",
"NSIS",
"installer",
"script",
"to",
"install",
"the",
"contents",
"of",
"a",
"given",
"directory",
"and",
"returns",
"it",
"as",
"a",
"string",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/support/distribution/package.js#L37-L87 | train |
ryanwilliams/cocos2d-javascript | support/distribution/package.js | findFilesToPackage | function findFilesToPackage(dir, callback) {
var cwd = process.cwd();
process.chdir(dir);
var gitls = spawn('git', ['ls-files']),
// This gets the full path to each file in each submodule
subls = spawn('git', ['submodule', 'foreach', 'for file in `git ls-files`; do echo "$path/$file"; done']);
// List all node_modules
modls = spawn('find', ['node_modules']);
var mainFileList = '';
gitls.stdout.on('data', function (data) {
mainFileList += data;
});
gitls.on('exit', returnFileList);
var subFileList = '';
subls.stdout.on('data', function (data) {
subFileList += data;
});
subls.on('exit', returnFileList);
var modFileList = '';
modls.stdout.on('data', function (data) {
modFileList += data;
});
modls.on('exit', returnFileList);
var lsCount = 0;
function returnFileList(code) {
lsCount++;
if (lsCount < 3) {
return;
}
process.chdir(cwd);
// Convert \n separated list of filenames into a sorted array
var fileList = (mainFileList.trim() + '\n' + subFileList.trim() + '\n' + modFileList.trim()).split('\n').filter(function(file) {
// Ignore entering submodule messages
if (file.indexOf('Entering ') === 0) {
return;
}
// Ignore hidden and backup files
if (file.split('/').pop()[0] == '.' || file[file.length - 1] == '~') {
return;
}
// Submodules appear in ls-files but aren't files. Skip them
if (fs.statSync(path.join(dir, file)).isDirectory()) {
return;
}
return file;
}).sort();
callback(fileList);
}
} | javascript | function findFilesToPackage(dir, callback) {
var cwd = process.cwd();
process.chdir(dir);
var gitls = spawn('git', ['ls-files']),
// This gets the full path to each file in each submodule
subls = spawn('git', ['submodule', 'foreach', 'for file in `git ls-files`; do echo "$path/$file"; done']);
// List all node_modules
modls = spawn('find', ['node_modules']);
var mainFileList = '';
gitls.stdout.on('data', function (data) {
mainFileList += data;
});
gitls.on('exit', returnFileList);
var subFileList = '';
subls.stdout.on('data', function (data) {
subFileList += data;
});
subls.on('exit', returnFileList);
var modFileList = '';
modls.stdout.on('data', function (data) {
modFileList += data;
});
modls.on('exit', returnFileList);
var lsCount = 0;
function returnFileList(code) {
lsCount++;
if (lsCount < 3) {
return;
}
process.chdir(cwd);
// Convert \n separated list of filenames into a sorted array
var fileList = (mainFileList.trim() + '\n' + subFileList.trim() + '\n' + modFileList.trim()).split('\n').filter(function(file) {
// Ignore entering submodule messages
if (file.indexOf('Entering ') === 0) {
return;
}
// Ignore hidden and backup files
if (file.split('/').pop()[0] == '.' || file[file.length - 1] == '~') {
return;
}
// Submodules appear in ls-files but aren't files. Skip them
if (fs.statSync(path.join(dir, file)).isDirectory()) {
return;
}
return file;
}).sort();
callback(fileList);
}
} | [
"function",
"findFilesToPackage",
"(",
"dir",
",",
"callback",
")",
"{",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"process",
".",
"chdir",
"(",
"dir",
")",
";",
"var",
"gitls",
"=",
"spawn",
"(",
"'git'",
",",
"[",
"'ls-files'",
"]",
")",
",",
"subls",
"=",
"spawn",
"(",
"'git'",
",",
"[",
"'submodule'",
",",
"'foreach'",
",",
"'for file in `git ls-files`; do echo \"$path/$file\"; done'",
"]",
")",
";",
"modls",
"=",
"spawn",
"(",
"'find'",
",",
"[",
"'node_modules'",
"]",
")",
";",
"var",
"mainFileList",
"=",
"''",
";",
"gitls",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"mainFileList",
"+=",
"data",
";",
"}",
")",
";",
"gitls",
".",
"on",
"(",
"'exit'",
",",
"returnFileList",
")",
";",
"var",
"subFileList",
"=",
"''",
";",
"subls",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"subFileList",
"+=",
"data",
";",
"}",
")",
";",
"subls",
".",
"on",
"(",
"'exit'",
",",
"returnFileList",
")",
";",
"var",
"modFileList",
"=",
"''",
";",
"modls",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"modFileList",
"+=",
"data",
";",
"}",
")",
";",
"modls",
".",
"on",
"(",
"'exit'",
",",
"returnFileList",
")",
";",
"var",
"lsCount",
"=",
"0",
";",
"function",
"returnFileList",
"(",
"code",
")",
"{",
"lsCount",
"++",
";",
"if",
"(",
"lsCount",
"<",
"3",
")",
"{",
"return",
";",
"}",
"process",
".",
"chdir",
"(",
"cwd",
")",
";",
"var",
"fileList",
"=",
"(",
"mainFileList",
".",
"trim",
"(",
")",
"+",
"'\\n'",
"+",
"\\n",
"+",
"subFileList",
".",
"trim",
"(",
")",
"+",
"'\\n'",
")",
".",
"\\n",
"modFileList",
".",
"trim",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"filter",
";",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"file",
".",
"indexOf",
"(",
"'Entering '",
")",
"===",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"file",
".",
"split",
"(",
"'/'",
")",
".",
"pop",
"(",
")",
"[",
"0",
"]",
"==",
"'.'",
"||",
"file",
"[",
"file",
".",
"length",
"-",
"1",
"]",
"==",
"'~'",
")",
"{",
"return",
";",
"}",
"if",
"(",
"fs",
".",
"statSync",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
";",
"}",
"return",
"file",
";",
"}",
")",
"}",
"}"
]
| Uses git to find the files we want to install. If a file isn't commited,
then it won't be installed.
@param {String} dir The directory that will be installed
@returns String[] Array of file paths | [
"Uses",
"git",
"to",
"find",
"the",
"files",
"we",
"want",
"to",
"install",
".",
"If",
"a",
"file",
"isn",
"t",
"commited",
"then",
"it",
"won",
"t",
"be",
"installed",
"."
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/support/distribution/package.js#L96-L157 | train |
ryanwilliams/cocos2d-javascript | src/SpriteFrame.js | function () {
return new SpriteFrame({rect: this.rect, rotated: this.rotated, offset: this.offset, originalSize: this.originalSize, texture: this.texture})
} | javascript | function () {
return new SpriteFrame({rect: this.rect, rotated: this.rotated, offset: this.offset, originalSize: this.originalSize, texture: this.texture})
} | [
"function",
"(",
")",
"{",
"return",
"new",
"SpriteFrame",
"(",
"{",
"rect",
":",
"this",
".",
"rect",
",",
"rotated",
":",
"this",
".",
"rotated",
",",
"offset",
":",
"this",
".",
"offset",
",",
"originalSize",
":",
"this",
".",
"originalSize",
",",
"texture",
":",
"this",
".",
"texture",
"}",
")",
"}"
]
| Make a copy of this frame
@returns {cocos.SpriteFrame} Exact copy of this object | [
"Make",
"a",
"copy",
"of",
"this",
"frame"
]
| 6c156006333cb55a61555d4a755a43c5f12d1049 | https://github.com/ryanwilliams/cocos2d-javascript/blob/6c156006333cb55a61555d4a755a43c5f12d1049/src/SpriteFrame.js#L53-L55 | train |
|
stadt-bielefeld/wms-downloader | src/helper/handleResolution.js | handleResolution | function handleResolution(options, ws, resIdx, config, progress, callback) {
// Resolution object
let res = options.tiles.resolutions[resIdx];
// Workspace of this resolutions
let resWs;
if (options.tiles.resolutions.length == 1) {
resWs = ws;
} else {
resWs = ws + '/' + res.id;
}
// Create directory of resolution workspace
fs.ensureDir(resWs, (err) => {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Handle all wms
handleWMS(options, resWs, res, 0, config, progress, (err) => {
// Error
if (err) {
// It could not be handled all wms.
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise resolution index
resIdx++;
// New resolution index exists
if (resIdx < options.tiles.resolutions.length) {
handleResolution(options, ws, resIdx, config, progress, callback);
} else {
// New resolution index does not exists
// Call callback function without errors. All resolution
// were
// handled.
callback(null);
}
}
});
}
});
} | javascript | function handleResolution(options, ws, resIdx, config, progress, callback) {
// Resolution object
let res = options.tiles.resolutions[resIdx];
// Workspace of this resolutions
let resWs;
if (options.tiles.resolutions.length == 1) {
resWs = ws;
} else {
resWs = ws + '/' + res.id;
}
// Create directory of resolution workspace
fs.ensureDir(resWs, (err) => {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Handle all wms
handleWMS(options, resWs, res, 0, config, progress, (err) => {
// Error
if (err) {
// It could not be handled all wms.
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise resolution index
resIdx++;
// New resolution index exists
if (resIdx < options.tiles.resolutions.length) {
handleResolution(options, ws, resIdx, config, progress, callback);
} else {
// New resolution index does not exists
// Call callback function without errors. All resolution
// were
// handled.
callback(null);
}
}
});
}
});
} | [
"function",
"handleResolution",
"(",
"options",
",",
"ws",
",",
"resIdx",
",",
"config",
",",
"progress",
",",
"callback",
")",
"{",
"let",
"res",
"=",
"options",
".",
"tiles",
".",
"resolutions",
"[",
"resIdx",
"]",
";",
"let",
"resWs",
";",
"if",
"(",
"options",
".",
"tiles",
".",
"resolutions",
".",
"length",
"==",
"1",
")",
"{",
"resWs",
"=",
"ws",
";",
"}",
"else",
"{",
"resWs",
"=",
"ws",
"+",
"'/'",
"+",
"res",
".",
"id",
";",
"}",
"fs",
".",
"ensureDir",
"(",
"resWs",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"handleWMS",
"(",
"options",
",",
"resWs",
",",
"res",
",",
"0",
",",
"config",
",",
"progress",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resIdx",
"++",
";",
"if",
"(",
"resIdx",
"<",
"options",
".",
"tiles",
".",
"resolutions",
".",
"length",
")",
"{",
"handleResolution",
"(",
"options",
",",
"ws",
",",
"resIdx",
",",
"config",
",",
"progress",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| It handles recursive all resolutions of a task.
@param {Object} options
@param {String} ws Task workspace
@param {Number} resIdx Index of resolution
@param {Object} config See options of the {@link WMSDownloader|WMSDownloader constructor}
@param {Array} progress Array of the progress of all WMSDownloader tasks.
@param {Function} callback function(err){} | [
"It",
"handles",
"recursive",
"all",
"resolutions",
"of",
"a",
"task",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/handleResolution.js#L16-L74 | train |
stadt-bielefeld/wms-downloader | src/helper/writeTile.js | writeTile | function writeTile(file, url, request, callback) {
// Result of request
let res = null;
// FileWriteStream
let fileStream = fs.createWriteStream(file);
// Register finish callback of FileWriteStream
fileStream.on('finish', () => {
callback(null, res);
});
// Register error callback of FileWriteStream
fileStream.on('error', (err) => {
callback(err, res);
});
// Request object
let req = request.get(url);
// Register error callback of request
req.on('error', (err) => {
callback(err, res);
});
// Register response callback of request
req.on('response', (response) => {
res = response;
});
// Start download
req.pipe(fileStream);
} | javascript | function writeTile(file, url, request, callback) {
// Result of request
let res = null;
// FileWriteStream
let fileStream = fs.createWriteStream(file);
// Register finish callback of FileWriteStream
fileStream.on('finish', () => {
callback(null, res);
});
// Register error callback of FileWriteStream
fileStream.on('error', (err) => {
callback(err, res);
});
// Request object
let req = request.get(url);
// Register error callback of request
req.on('error', (err) => {
callback(err, res);
});
// Register response callback of request
req.on('response', (response) => {
res = response;
});
// Start download
req.pipe(fileStream);
} | [
"function",
"writeTile",
"(",
"file",
",",
"url",
",",
"request",
",",
"callback",
")",
"{",
"let",
"res",
"=",
"null",
";",
"let",
"fileStream",
"=",
"fs",
".",
"createWriteStream",
"(",
"file",
")",
";",
"fileStream",
".",
"on",
"(",
"'finish'",
",",
"(",
")",
"=>",
"{",
"callback",
"(",
"null",
",",
"res",
")",
";",
"}",
")",
";",
"fileStream",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
";",
"let",
"req",
"=",
"request",
".",
"get",
"(",
"url",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'response'",
",",
"(",
"response",
")",
"=>",
"{",
"res",
"=",
"response",
";",
"}",
")",
";",
"req",
".",
"pipe",
"(",
"fileStream",
")",
";",
"}"
]
| Downloads and writes a tile.
@param {String} file Path where the tile is to be stored.
@param {String} url URL of tile
@param {Object} request Object from request module (let request = require('request');)
@param {Function} callback function(err, res){} | [
"Downloads",
"and",
"writes",
"a",
"tile",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/writeTile.js#L13-L45 | train |
RackHD/on-tasks | spec/lib/jobs/poweron-node-spec.js | function() {
//var logger = Logger.initialize(mockChildProcessFactory);
function MockChildProcess() {}
MockChildProcess.prototype.run = function run (command, args) {
// logger.debug("CHILD PROCESS MOCK!");
// logger.debug("command: "+command);
// logger.debug("args: "+args);
// logger.debug("env: "+env);
// logger.debug("code: "+code);
if ((command === 'ipmitool') && _.contains(args, 'status')) {
// power status call, return a "success"
return Promise.resolve({
stdout: 'Chassis Power is on'
});
}
};
return MockChildProcess;
} | javascript | function() {
//var logger = Logger.initialize(mockChildProcessFactory);
function MockChildProcess() {}
MockChildProcess.prototype.run = function run (command, args) {
// logger.debug("CHILD PROCESS MOCK!");
// logger.debug("command: "+command);
// logger.debug("args: "+args);
// logger.debug("env: "+env);
// logger.debug("code: "+code);
if ((command === 'ipmitool') && _.contains(args, 'status')) {
// power status call, return a "success"
return Promise.resolve({
stdout: 'Chassis Power is on'
});
}
};
return MockChildProcess;
} | [
"function",
"(",
")",
"{",
"function",
"MockChildProcess",
"(",
")",
"{",
"}",
"MockChildProcess",
".",
"prototype",
".",
"run",
"=",
"function",
"run",
"(",
"command",
",",
"args",
")",
"{",
"if",
"(",
"(",
"command",
"===",
"'ipmitool'",
")",
"&&",
"_",
".",
"contains",
"(",
"args",
",",
"'status'",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"{",
"stdout",
":",
"'Chassis Power is on'",
"}",
")",
";",
"}",
"}",
";",
"return",
"MockChildProcess",
";",
"}"
]
| mock up the ChildProcess injectable to capture calls before they go to a local shell | [
"mock",
"up",
"the",
"ChildProcess",
"injectable",
"to",
"capture",
"calls",
"before",
"they",
"go",
"to",
"a",
"local",
"shell"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/lib/jobs/poweron-node-spec.js#L10-L27 | train |
|
RackHD/on-tasks | spec/lib/jobs/poweron-node-spec.js | function() {
function MockWaterline() {}
MockWaterline.prototype.nodes = {};
MockWaterline.prototype.nodes.findByIdentifier = function (nodeId) {
//return instance of a node with settings in it...
return Promise.resolve({
obmSettings: [
{
service: 'ipmi-obm-service',
config: {
'user': 'ADMIN',
'password': 'ADMIN',
'host': '192.192.192.192'
}
}
],
id: nodeId
});
};
return new MockWaterline();
} | javascript | function() {
function MockWaterline() {}
MockWaterline.prototype.nodes = {};
MockWaterline.prototype.nodes.findByIdentifier = function (nodeId) {
//return instance of a node with settings in it...
return Promise.resolve({
obmSettings: [
{
service: 'ipmi-obm-service',
config: {
'user': 'ADMIN',
'password': 'ADMIN',
'host': '192.192.192.192'
}
}
],
id: nodeId
});
};
return new MockWaterline();
} | [
"function",
"(",
")",
"{",
"function",
"MockWaterline",
"(",
")",
"{",
"}",
"MockWaterline",
".",
"prototype",
".",
"nodes",
"=",
"{",
"}",
";",
"MockWaterline",
".",
"prototype",
".",
"nodes",
".",
"findByIdentifier",
"=",
"function",
"(",
"nodeId",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"{",
"obmSettings",
":",
"[",
"{",
"service",
":",
"'ipmi-obm-service'",
",",
"config",
":",
"{",
"'user'",
":",
"'ADMIN'",
",",
"'password'",
":",
"'ADMIN'",
",",
"'host'",
":",
"'192.192.192.192'",
"}",
"}",
"]",
",",
"id",
":",
"nodeId",
"}",
")",
";",
"}",
";",
"return",
"new",
"MockWaterline",
"(",
")",
";",
"}"
]
| mock up the Services.Waterline injectable to subvert model lookups for our tests | [
"mock",
"up",
"the",
"Services",
".",
"Waterline",
"injectable",
"to",
"subvert",
"model",
"lookups",
"for",
"our",
"tests"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/lib/jobs/poweron-node-spec.js#L30-L50 | train |
|
RackHD/on-tasks | lib/jobs/pdu-node-relations.js | _adjustIpStrFormat | function _adjustIpStrFormat(ipString) {
var ip = ipString.split('.');
ipString = '';
for (var i = 0; i < ip.length; i += 1) {
switch (ip[i].length) {
case 1:
ip[i] = '00' + ip[i];
break;
case 2:
ip[i] = '0' + ip[i];
break;
default:
break;
}
ipString += ip[i];
}
return ipString.trim();
} | javascript | function _adjustIpStrFormat(ipString) {
var ip = ipString.split('.');
ipString = '';
for (var i = 0; i < ip.length; i += 1) {
switch (ip[i].length) {
case 1:
ip[i] = '00' + ip[i];
break;
case 2:
ip[i] = '0' + ip[i];
break;
default:
break;
}
ipString += ip[i];
}
return ipString.trim();
} | [
"function",
"_adjustIpStrFormat",
"(",
"ipString",
")",
"{",
"var",
"ip",
"=",
"ipString",
".",
"split",
"(",
"'.'",
")",
";",
"ipString",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ip",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"switch",
"(",
"ip",
"[",
"i",
"]",
".",
"length",
")",
"{",
"case",
"1",
":",
"ip",
"[",
"i",
"]",
"=",
"'00'",
"+",
"ip",
"[",
"i",
"]",
";",
"break",
";",
"case",
"2",
":",
"ip",
"[",
"i",
"]",
"=",
"'0'",
"+",
"ip",
"[",
"i",
"]",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"ipString",
"+=",
"ip",
"[",
"i",
"]",
";",
"}",
"return",
"ipString",
".",
"trim",
"(",
")",
";",
"}"
]
| Adjust ip Address format to 3 digits
return ip address string | [
"Adjust",
"ip",
"Address",
"format",
"to",
"3",
"digits",
"return",
"ip",
"address",
"string"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/pdu-node-relations.js#L171-L188 | train |
stadt-bielefeld/wms-downloader | src/helper/getRequestObject.js | getRequestObject | function getRequestObject(config, url) {
if (!request) {
// Init request object
request = require('request').defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout
});
}
if (!requestProxy) {
// If internet proxy is set
if (config.request.proxy) {
// String of username and password
let userPass = '';
if (config.request.proxy.http.user) {
if (config.request.proxy.http.password) {
userPass = encodeURIComponent(config.request.proxy.http.user) + ':' + encodeURIComponent(config.request.proxy.http.password) + '@';
}
}
// Init request object with internet proxy
requestProxy = request.defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout,
'proxy': 'http://' + userPass + config.request.proxy.http.host + ':' + config.request.proxy.http.port
});
}
}
let ret = request;
if (config.request.proxy) {
ret = requestProxy;
for (let int = 0; int < config.request.proxy.http.exclude.length; int++) {
if (url.includes(config.request.proxy.http.exclude[int])) {
ret = request;
break;
}
}
}
return ret;
} | javascript | function getRequestObject(config, url) {
if (!request) {
// Init request object
request = require('request').defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout
});
}
if (!requestProxy) {
// If internet proxy is set
if (config.request.proxy) {
// String of username and password
let userPass = '';
if (config.request.proxy.http.user) {
if (config.request.proxy.http.password) {
userPass = encodeURIComponent(config.request.proxy.http.user) + ':' + encodeURIComponent(config.request.proxy.http.password) + '@';
}
}
// Init request object with internet proxy
requestProxy = request.defaults({
'headers': {
'User-Agent': config.request.userAgent
},
strictSSL: false,
timeout: config.request.timeout,
'proxy': 'http://' + userPass + config.request.proxy.http.host + ':' + config.request.proxy.http.port
});
}
}
let ret = request;
if (config.request.proxy) {
ret = requestProxy;
for (let int = 0; int < config.request.proxy.http.exclude.length; int++) {
if (url.includes(config.request.proxy.http.exclude[int])) {
ret = request;
break;
}
}
}
return ret;
} | [
"function",
"getRequestObject",
"(",
"config",
",",
"url",
")",
"{",
"if",
"(",
"!",
"request",
")",
"{",
"request",
"=",
"require",
"(",
"'request'",
")",
".",
"defaults",
"(",
"{",
"'headers'",
":",
"{",
"'User-Agent'",
":",
"config",
".",
"request",
".",
"userAgent",
"}",
",",
"strictSSL",
":",
"false",
",",
"timeout",
":",
"config",
".",
"request",
".",
"timeout",
"}",
")",
";",
"}",
"if",
"(",
"!",
"requestProxy",
")",
"{",
"if",
"(",
"config",
".",
"request",
".",
"proxy",
")",
"{",
"let",
"userPass",
"=",
"''",
";",
"if",
"(",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"user",
")",
"{",
"if",
"(",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"password",
")",
"{",
"userPass",
"=",
"encodeURIComponent",
"(",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"user",
")",
"+",
"':'",
"+",
"encodeURIComponent",
"(",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"password",
")",
"+",
"'@'",
";",
"}",
"}",
"requestProxy",
"=",
"request",
".",
"defaults",
"(",
"{",
"'headers'",
":",
"{",
"'User-Agent'",
":",
"config",
".",
"request",
".",
"userAgent",
"}",
",",
"strictSSL",
":",
"false",
",",
"timeout",
":",
"config",
".",
"request",
".",
"timeout",
",",
"'proxy'",
":",
"'http://'",
"+",
"userPass",
"+",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"host",
"+",
"':'",
"+",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"port",
"}",
")",
";",
"}",
"}",
"let",
"ret",
"=",
"request",
";",
"if",
"(",
"config",
".",
"request",
".",
"proxy",
")",
"{",
"ret",
"=",
"requestProxy",
";",
"for",
"(",
"let",
"int",
"=",
"0",
";",
"int",
"<",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"exclude",
".",
"length",
";",
"int",
"++",
")",
"{",
"if",
"(",
"url",
".",
"includes",
"(",
"config",
".",
"request",
".",
"proxy",
".",
"http",
".",
"exclude",
"[",
"int",
"]",
")",
")",
"{",
"ret",
"=",
"request",
";",
"break",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
]
| Request object with internet proxy
Returns the correct request object with the right proxy settings.
@param {String} url URL of tile
@returns {Object} Object from request module (let request = require('request');) | [
"Request",
"object",
"with",
"internet",
"proxy",
"Returns",
"the",
"correct",
"request",
"object",
"with",
"the",
"right",
"proxy",
"settings",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/getRequestObject.js#L15-L66 | train |
RackHD/on-tasks | spec/mocks/logger.js | Logger | function Logger (module) {
// Set the intiial module to the provided string value if present.
this.module = module !== undefined ? module.toString() : 'No Module';
// If the module is a function then we'll look for di.js annotations to get the
// provide string.
if (_.isFunction(module)) {
if (module.annotations && module.annotations.length) {
// Detect DI provides
var provides = _.detect(module.annotations, function (annotation) {
return _.has(annotation, 'token');
});
// If provides is present use that.
if (provides) {
this.module = provides.token;
return;
}
}
// If no provides then use the function.
if (module.name) {
this.module = module.name;
}
}
} | javascript | function Logger (module) {
// Set the intiial module to the provided string value if present.
this.module = module !== undefined ? module.toString() : 'No Module';
// If the module is a function then we'll look for di.js annotations to get the
// provide string.
if (_.isFunction(module)) {
if (module.annotations && module.annotations.length) {
// Detect DI provides
var provides = _.detect(module.annotations, function (annotation) {
return _.has(annotation, 'token');
});
// If provides is present use that.
if (provides) {
this.module = provides.token;
return;
}
}
// If no provides then use the function.
if (module.name) {
this.module = module.name;
}
}
} | [
"function",
"Logger",
"(",
"module",
")",
"{",
"this",
".",
"module",
"=",
"module",
"!==",
"undefined",
"?",
"module",
".",
"toString",
"(",
")",
":",
"'No Module'",
";",
"if",
"(",
"_",
".",
"isFunction",
"(",
"module",
")",
")",
"{",
"if",
"(",
"module",
".",
"annotations",
"&&",
"module",
".",
"annotations",
".",
"length",
")",
"{",
"var",
"provides",
"=",
"_",
".",
"detect",
"(",
"module",
".",
"annotations",
",",
"function",
"(",
"annotation",
")",
"{",
"return",
"_",
".",
"has",
"(",
"annotation",
",",
"'token'",
")",
";",
"}",
")",
";",
"if",
"(",
"provides",
")",
"{",
"this",
".",
"module",
"=",
"provides",
".",
"token",
";",
"return",
";",
"}",
"}",
"if",
"(",
"module",
".",
"name",
")",
"{",
"this",
".",
"module",
"=",
"module",
".",
"name",
";",
"}",
"}",
"}"
]
| Logger is a logger class which provides methods for logging based
on log levels with mesages & metadata provisions. This logger is a stub for the real
logger used that doesn't persist or publish logs over AMQP.
Usage:
var logger=Logger.initialize(yourFunctionOrInjectable)
logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'});
@constructor | [
"Logger",
"is",
"a",
"logger",
"class",
"which",
"provides",
"methods",
"for",
"logging",
"based",
"on",
"log",
"levels",
"with",
"mesages",
"&",
"metadata",
"provisions",
".",
"This",
"logger",
"is",
"a",
"stub",
"for",
"the",
"real",
"logger",
"used",
"that",
"doesn",
"t",
"persist",
"or",
"publish",
"logs",
"over",
"AMQP",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/mocks/logger.js#L32-L57 | train |
imcuttle/babel-plugin-danger-remove-unused-import | src/utils/getSpecImport.js | getSpecifierIdentifiers | function getSpecifierIdentifiers(specifiers = [], withPath = false) {
const collection = [];
function loop(path, index) {
const node = path.node
const item = !withPath ? node.local.name : { path, name: node.local.name }
switch (node.type) {
case 'ImportDefaultSpecifier':
case 'ImportSpecifier':
case 'ImportNamespaceSpecifier':
collection.push(item);
break;
}
}
specifiers.forEach(loop);
return collection;
} | javascript | function getSpecifierIdentifiers(specifiers = [], withPath = false) {
const collection = [];
function loop(path, index) {
const node = path.node
const item = !withPath ? node.local.name : { path, name: node.local.name }
switch (node.type) {
case 'ImportDefaultSpecifier':
case 'ImportSpecifier':
case 'ImportNamespaceSpecifier':
collection.push(item);
break;
}
}
specifiers.forEach(loop);
return collection;
} | [
"function",
"getSpecifierIdentifiers",
"(",
"specifiers",
"=",
"[",
"]",
",",
"withPath",
"=",
"false",
")",
"{",
"const",
"collection",
"=",
"[",
"]",
";",
"function",
"loop",
"(",
"path",
",",
"index",
")",
"{",
"const",
"node",
"=",
"path",
".",
"node",
"const",
"item",
"=",
"!",
"withPath",
"?",
"node",
".",
"local",
".",
"name",
":",
"{",
"path",
",",
"name",
":",
"node",
".",
"local",
".",
"name",
"}",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"'ImportDefaultSpecifier'",
":",
"case",
"'ImportSpecifier'",
":",
"case",
"'ImportNamespaceSpecifier'",
":",
"collection",
".",
"push",
"(",
"item",
")",
";",
"break",
";",
"}",
"}",
"specifiers",
".",
"forEach",
"(",
"loop",
")",
";",
"return",
"collection",
";",
"}"
]
| get identifiers from the code, as follows
input: `import { b, c } from 'a'`
output: ['b', 'c']
input: `import a from 'a'`
output: ['a'] | [
"get",
"identifiers",
"from",
"the",
"code",
"as",
"follows"
]
| 25ea4078a83524b786ad762e60cbf8c3b613e64b | https://github.com/imcuttle/babel-plugin-danger-remove-unused-import/blob/25ea4078a83524b786ad762e60cbf8c3b613e64b/src/utils/getSpecImport.js#L22-L38 | train |
pierrec/js-cuint | build/uint32.js | UINT32 | function UINT32 (l, h) {
if ( !(this instanceof UINT32) )
return new UINT32(l, h)
this._low = 0
this._high = 0
this.remainder = null
if (typeof h == 'undefined')
return fromNumber.call(this, l)
if (typeof l == 'string')
return fromString.call(this, l, h)
fromBits.call(this, l, h)
} | javascript | function UINT32 (l, h) {
if ( !(this instanceof UINT32) )
return new UINT32(l, h)
this._low = 0
this._high = 0
this.remainder = null
if (typeof h == 'undefined')
return fromNumber.call(this, l)
if (typeof l == 'string')
return fromString.call(this, l, h)
fromBits.call(this, l, h)
} | [
"function",
"UINT32",
"(",
"l",
",",
"h",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"UINT32",
")",
")",
"return",
"new",
"UINT32",
"(",
"l",
",",
"h",
")",
"this",
".",
"_low",
"=",
"0",
"this",
".",
"_high",
"=",
"0",
"this",
".",
"remainder",
"=",
"null",
"if",
"(",
"typeof",
"h",
"==",
"'undefined'",
")",
"return",
"fromNumber",
".",
"call",
"(",
"this",
",",
"l",
")",
"if",
"(",
"typeof",
"l",
"==",
"'string'",
")",
"return",
"fromString",
".",
"call",
"(",
"this",
",",
"l",
",",
"h",
")",
"fromBits",
".",
"call",
"(",
"this",
",",
"l",
",",
"h",
")",
"}"
]
| Represents an unsigned 32 bits integer
@constructor
@param {Number|String|Number} low bits | integer as a string | integer as a number
@param {Number|Number|Undefined} high bits | radix (optional, default=10)
@return | [
"Represents",
"an",
"unsigned",
"32",
"bits",
"integer"
]
| b93425a8f1b98bab8e357cede34ed491125c0d8b | https://github.com/pierrec/js-cuint/blob/b93425a8f1b98bab8e357cede34ed491125c0d8b/build/uint32.js#L29-L43 | train |
pierrec/js-cuint | build/uint32.js | fromString | function fromString (s, radix) {
var value = parseInt(s, radix || 10)
this._low = value & 0xFFFF
this._high = value >>> 16
return this
} | javascript | function fromString (s, radix) {
var value = parseInt(s, radix || 10)
this._low = value & 0xFFFF
this._high = value >>> 16
return this
} | [
"function",
"fromString",
"(",
"s",
",",
"radix",
")",
"{",
"var",
"value",
"=",
"parseInt",
"(",
"s",
",",
"radix",
"||",
"10",
")",
"this",
".",
"_low",
"=",
"value",
"&",
"0xFFFF",
"this",
".",
"_high",
"=",
"value",
">>>",
"16",
"return",
"this",
"}"
]
| Set the current _UINT32_ object from a string
@method fromString
@param {String} integer as a string
@param {Number} radix (optional, default=10)
@return ThisExpression | [
"Set",
"the",
"current",
"_UINT32_",
"object",
"from",
"a",
"string"
]
| b93425a8f1b98bab8e357cede34ed491125c0d8b | https://github.com/pierrec/js-cuint/blob/b93425a8f1b98bab8e357cede34ed491125c0d8b/build/uint32.js#L81-L88 | train |
RackHD/on-tasks | lib/jobs/get-catalog-values-job.js | GetCatalogValuesJob | function GetCatalogValuesJob(options, context, taskId){
GetCatalogValuesJob.super_.call(this, logger, options, context, taskId);
this.nodeId = context.target;
this.options = options;
this.logger = logger;
} | javascript | function GetCatalogValuesJob(options, context, taskId){
GetCatalogValuesJob.super_.call(this, logger, options, context, taskId);
this.nodeId = context.target;
this.options = options;
this.logger = logger;
} | [
"function",
"GetCatalogValuesJob",
"(",
"options",
",",
"context",
",",
"taskId",
")",
"{",
"GetCatalogValuesJob",
".",
"super_",
".",
"call",
"(",
"this",
",",
"logger",
",",
"options",
",",
"context",
",",
"taskId",
")",
";",
"this",
".",
"nodeId",
"=",
"context",
".",
"target",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"logger",
"=",
"logger",
";",
"}"
]
| This job finds one or more requested values from one or more specified catalogs.
The catalog values are made available in the shared context in an object that
maps the catalog values to requester provided keys.
Example requestedData array:
[{
"source": "ohai",
"keys": {
"myIPAddrKeyName": "data.ipaddress"
}
}]
Adds to context.data:
{
"myIPAddrKeyName": <catalog value>
}
@param options
@param context
@param taskId
@constructor | [
"This",
"job",
"finds",
"one",
"or",
"more",
"requested",
"values",
"from",
"one",
"or",
"more",
"specified",
"catalogs",
".",
"The",
"catalog",
"values",
"are",
"made",
"available",
"in",
"the",
"shared",
"context",
"in",
"an",
"object",
"that",
"maps",
"the",
"catalog",
"values",
"to",
"requester",
"provided",
"keys",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/get-catalog-values-job.js#L50-L55 | train |
stadt-bielefeld/wms-downloader | src/helper/createGetMap.js | createGetMap | function createGetMap(wms, bbox, width, height) {
let getmap = wms.getmap.url;
for (let key in wms.getmap.kvp) {
getmap += encodeURIComponent(key) + '=' + encodeURIComponent(wms.getmap.kvp[key]) + '&';
}
getmap += 'BBOX=' + encodeURIComponent(bbox) + '&';
getmap += 'WIDTH=' + encodeURIComponent(width) + '&';
getmap += 'HEIGHT=' + encodeURIComponent(height) + '&';
return getmap;
} | javascript | function createGetMap(wms, bbox, width, height) {
let getmap = wms.getmap.url;
for (let key in wms.getmap.kvp) {
getmap += encodeURIComponent(key) + '=' + encodeURIComponent(wms.getmap.kvp[key]) + '&';
}
getmap += 'BBOX=' + encodeURIComponent(bbox) + '&';
getmap += 'WIDTH=' + encodeURIComponent(width) + '&';
getmap += 'HEIGHT=' + encodeURIComponent(height) + '&';
return getmap;
} | [
"function",
"createGetMap",
"(",
"wms",
",",
"bbox",
",",
"width",
",",
"height",
")",
"{",
"let",
"getmap",
"=",
"wms",
".",
"getmap",
".",
"url",
";",
"for",
"(",
"let",
"key",
"in",
"wms",
".",
"getmap",
".",
"kvp",
")",
"{",
"getmap",
"+=",
"encodeURIComponent",
"(",
"key",
")",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"wms",
".",
"getmap",
".",
"kvp",
"[",
"key",
"]",
")",
"+",
"'&'",
";",
"}",
"getmap",
"+=",
"'BBOX='",
"+",
"encodeURIComponent",
"(",
"bbox",
")",
"+",
"'&'",
";",
"getmap",
"+=",
"'WIDTH='",
"+",
"encodeURIComponent",
"(",
"width",
")",
"+",
"'&'",
";",
"getmap",
"+=",
"'HEIGHT='",
"+",
"encodeURIComponent",
"(",
"height",
")",
"+",
"'&'",
";",
"return",
"getmap",
";",
"}"
]
| Creates a full GetMap request from the following parameters.
@param {Object} wms Object with the GetMap base url and necessary key value pairs (kvp) like `{ 'getmap': { 'url':'http://', kvp: {'key': 'value' } } }`
@param {String} bbox BBOX of the GetMap request
@param {Number|String} width Width of the GetMap request
@param {Number|String} height Height of the GetMap request
@returns {String} Complete GetMap request
@example
const wms = {
'getmap': {
'url': 'http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=gebietsgliederung_wms_stadtbezirke_641&',
'kvp': {
'SERVICE': 'WMS',
'VERSION': '1.3.0',
'REQUEST': 'GetMap',
'FORMAT': 'image/png',
'TRANSPARENT': 'true',
'LAYERS': 'stadtbezirke_wms',
'CRS': 'EPSG:25832',
'STYLES': ''
}
}
};
const width = 1048;
const height = 953;
const bbox = '458163.5475413472,5754265.480964899,478190.04895206343,5772476.602953842';
let getMapUrl = createGetMap(wms, bbox, width, height);
console.log(getMapUrl);
//http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=gebietsgliederung_wms_stadtbezirke_641&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=true&LAYERS=stadtbezirke_wms&CRS=EPSG:25832&STYLES=&BBOX=458163.5475413472,5754265.480964899,478190.04895206343,5772476.602953842&WIDTH=1048&HEIGHT=953& | [
"Creates",
"a",
"full",
"GetMap",
"request",
"from",
"the",
"following",
"parameters",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/createGetMap.js#L36-L48 | train |
stadt-bielefeld/wms-downloader | src/helper/handleWMS.js | handleWMS | function handleWMS(options, ws, res, wmsIdx, config, progress, callback) {
// WMS object
let wms = options.wms[wmsIdx];
// Workspace of this WMS
let wmsWs = ws;
if (options.wms.length > 1) {
wmsWs += '/' + wms.id;
}
// Create directory of WMS workspace
fs.ensureDir(wmsWs, function (err) {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Calculate parameters of bbox
let bbox = {};
bbox.widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin;
bbox.heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin;
bbox.widthPx = bbox.widthM / res.groundResolution;
bbox.heightPx = bbox.heightM / res.groundResolution;
// Calculate parameters of tiles
let tiles = {};
tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx;
tiles.sizeM = tiles.sizePx * res.groundResolution;
tiles.xCount = Math.ceil(bbox.widthPx / tiles.sizePx);
tiles.yCount = Math.ceil(bbox.heightPx / tiles.sizePx);
tiles.xSizeOverAllPx = tiles.xCount * tiles.sizePx;
tiles.ySizeOverAllPx = tiles.yCount * tiles.sizePx;
tiles.gutterM = options.tiles.gutterPx * res.groundResolution;
tiles.x0 = options.task.area.bbox.xmin - (((tiles.xSizeOverAllPx - bbox.widthPx) / 2.0) * res.groundResolution);
tiles.y0 = options.task.area.bbox.ymax + (((tiles.ySizeOverAllPx - bbox.heightPx) / 2.0) * res.groundResolution);
// Handle all tiles
handleTiles(options, wms, wmsWs, tiles, 0, 0, res.groundResolution, config, progress, function (err) {
// Error
if (err) {
// Could not handle tiles
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise wms index
wmsIdx++;
// Handle next WMS
if (wmsIdx < options.wms.length) {
handleWMS(options, ws, res, wmsIdx, config, progress, callback);
} else {
// All WMS were handled
// Call callback function without errors
callback(null);
}
}
});
}
});
} | javascript | function handleWMS(options, ws, res, wmsIdx, config, progress, callback) {
// WMS object
let wms = options.wms[wmsIdx];
// Workspace of this WMS
let wmsWs = ws;
if (options.wms.length > 1) {
wmsWs += '/' + wms.id;
}
// Create directory of WMS workspace
fs.ensureDir(wmsWs, function (err) {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Calculate parameters of bbox
let bbox = {};
bbox.widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin;
bbox.heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin;
bbox.widthPx = bbox.widthM / res.groundResolution;
bbox.heightPx = bbox.heightM / res.groundResolution;
// Calculate parameters of tiles
let tiles = {};
tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx;
tiles.sizeM = tiles.sizePx * res.groundResolution;
tiles.xCount = Math.ceil(bbox.widthPx / tiles.sizePx);
tiles.yCount = Math.ceil(bbox.heightPx / tiles.sizePx);
tiles.xSizeOverAllPx = tiles.xCount * tiles.sizePx;
tiles.ySizeOverAllPx = tiles.yCount * tiles.sizePx;
tiles.gutterM = options.tiles.gutterPx * res.groundResolution;
tiles.x0 = options.task.area.bbox.xmin - (((tiles.xSizeOverAllPx - bbox.widthPx) / 2.0) * res.groundResolution);
tiles.y0 = options.task.area.bbox.ymax + (((tiles.ySizeOverAllPx - bbox.heightPx) / 2.0) * res.groundResolution);
// Handle all tiles
handleTiles(options, wms, wmsWs, tiles, 0, 0, res.groundResolution, config, progress, function (err) {
// Error
if (err) {
// Could not handle tiles
// Call callback function with error.
callback(err);
} else {
// No errors
// Raise wms index
wmsIdx++;
// Handle next WMS
if (wmsIdx < options.wms.length) {
handleWMS(options, ws, res, wmsIdx, config, progress, callback);
} else {
// All WMS were handled
// Call callback function without errors
callback(null);
}
}
});
}
});
} | [
"function",
"handleWMS",
"(",
"options",
",",
"ws",
",",
"res",
",",
"wmsIdx",
",",
"config",
",",
"progress",
",",
"callback",
")",
"{",
"let",
"wms",
"=",
"options",
".",
"wms",
"[",
"wmsIdx",
"]",
";",
"let",
"wmsWs",
"=",
"ws",
";",
"if",
"(",
"options",
".",
"wms",
".",
"length",
">",
"1",
")",
"{",
"wmsWs",
"+=",
"'/'",
"+",
"wms",
".",
"id",
";",
"}",
"fs",
".",
"ensureDir",
"(",
"wmsWs",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"let",
"bbox",
"=",
"{",
"}",
";",
"bbox",
".",
"widthM",
"=",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"xmax",
"-",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"xmin",
";",
"bbox",
".",
"heightM",
"=",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"ymax",
"-",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"ymin",
";",
"bbox",
".",
"widthPx",
"=",
"bbox",
".",
"widthM",
"/",
"res",
".",
"groundResolution",
";",
"bbox",
".",
"heightPx",
"=",
"bbox",
".",
"heightM",
"/",
"res",
".",
"groundResolution",
";",
"let",
"tiles",
"=",
"{",
"}",
";",
"tiles",
".",
"sizePx",
"=",
"options",
".",
"tiles",
".",
"maxSizePx",
"-",
"2",
"*",
"options",
".",
"tiles",
".",
"gutterPx",
";",
"tiles",
".",
"sizeM",
"=",
"tiles",
".",
"sizePx",
"*",
"res",
".",
"groundResolution",
";",
"tiles",
".",
"xCount",
"=",
"Math",
".",
"ceil",
"(",
"bbox",
".",
"widthPx",
"/",
"tiles",
".",
"sizePx",
")",
";",
"tiles",
".",
"yCount",
"=",
"Math",
".",
"ceil",
"(",
"bbox",
".",
"heightPx",
"/",
"tiles",
".",
"sizePx",
")",
";",
"tiles",
".",
"xSizeOverAllPx",
"=",
"tiles",
".",
"xCount",
"*",
"tiles",
".",
"sizePx",
";",
"tiles",
".",
"ySizeOverAllPx",
"=",
"tiles",
".",
"yCount",
"*",
"tiles",
".",
"sizePx",
";",
"tiles",
".",
"gutterM",
"=",
"options",
".",
"tiles",
".",
"gutterPx",
"*",
"res",
".",
"groundResolution",
";",
"tiles",
".",
"x0",
"=",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"xmin",
"-",
"(",
"(",
"(",
"tiles",
".",
"xSizeOverAllPx",
"-",
"bbox",
".",
"widthPx",
")",
"/",
"2.0",
")",
"*",
"res",
".",
"groundResolution",
")",
";",
"tiles",
".",
"y0",
"=",
"options",
".",
"task",
".",
"area",
".",
"bbox",
".",
"ymax",
"+",
"(",
"(",
"(",
"tiles",
".",
"ySizeOverAllPx",
"-",
"bbox",
".",
"heightPx",
")",
"/",
"2.0",
")",
"*",
"res",
".",
"groundResolution",
")",
";",
"handleTiles",
"(",
"options",
",",
"wms",
",",
"wmsWs",
",",
"tiles",
",",
"0",
",",
"0",
",",
"res",
".",
"groundResolution",
",",
"config",
",",
"progress",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"wmsIdx",
"++",
";",
"if",
"(",
"wmsIdx",
"<",
"options",
".",
"wms",
".",
"length",
")",
"{",
"handleWMS",
"(",
"options",
",",
"ws",
",",
"res",
",",
"wmsIdx",
",",
"config",
",",
"progress",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| It handles recursive all Web Map Services of a resolution.
@param {Object} options
@param {String} ws Resolution workspace
@param {Object} res Resolution object
@param {Number} wmsIdx Index of WMS
@param {Object} config See options of the {@link WMSDownloader|WMSDownloader constructor}
@param {Array} progress Array of the progress of all WMSDownloader tasks.
@param {Function} callback function(err){} | [
"It",
"handles",
"recursive",
"all",
"Web",
"Map",
"Services",
"of",
"a",
"resolution",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/handleWMS.js#L17-L90 | train |
stadt-bielefeld/wms-downloader | src/helper/determineGroundResolution.js | determineGroundResolution | function determineGroundResolution(res) {
//iterate over all resolutions
for (let int = 0; int < res.length; int++) {
let r = res[int];
//calculate the resolution if not available
if (!r.groundResolution) {
r.groundResolution = (0.0254 * r.scale) / r.dpi;
}
}
} | javascript | function determineGroundResolution(res) {
//iterate over all resolutions
for (let int = 0; int < res.length; int++) {
let r = res[int];
//calculate the resolution if not available
if (!r.groundResolution) {
r.groundResolution = (0.0254 * r.scale) / r.dpi;
}
}
} | [
"function",
"determineGroundResolution",
"(",
"res",
")",
"{",
"for",
"(",
"let",
"int",
"=",
"0",
";",
"int",
"<",
"res",
".",
"length",
";",
"int",
"++",
")",
"{",
"let",
"r",
"=",
"res",
"[",
"int",
"]",
";",
"if",
"(",
"!",
"r",
".",
"groundResolution",
")",
"{",
"r",
".",
"groundResolution",
"=",
"(",
"0.0254",
"*",
"r",
".",
"scale",
")",
"/",
"r",
".",
"dpi",
";",
"}",
"}",
"}"
]
| Calculates the ground resolution from scale and dpi.
If `groundResolution` is not set, it will be calculated and set into the array.
@param {Array<Object>} res Resolutions defined with scales like `[ {'dpi': 72, 'scale': 5000 }, {'dpi': 72, 'scale': 10000 } ]`
@example
const res = [ {'dpi': 72, 'scale': 5000 }, {'dpi': 72, 'scale': 10000 } ];
determineGroundResolution(res);
console.log(res);
// [ { dpi: 72, scale: 5000, groundResolution: 1.7638888888888888 },
// { dpi: 72, scale: 10000, groundResolution: 3.5277777777777777 } ] | [
"Calculates",
"the",
"ground",
"resolution",
"from",
"scale",
"and",
"dpi",
".",
"If",
"groundResolution",
"is",
"not",
"set",
"it",
"will",
"be",
"calculated",
"and",
"set",
"into",
"the",
"array",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/determineGroundResolution.js#L16-L28 | train |
RackHD/on-tasks | lib/utils/job-utils/net-snmp-parser.js | parseSnmpLine | function parseSnmpLine(line) {
if (typeof line !== 'string') {
throw new Error("Data is not in string format");
}
var data = line.trim();
var errString = 'No Such Object available on this agent at this OID';
if (data.indexOf(errString) >= 0) {
throw new Error(data);
}
// Messages that occur as a result of doing MIB translation on output
// We exclude "Cannot find module" and "Did not find *" messages because
// in some cases we walk the whole tree and there are may be vendor-specific
// mibs that we don't have installed.
if (data.indexOf('MIB search path') >= 0 ||
data.indexOf('Cannot find module') >= 0 ||
data.indexOf('Did not find') >= 0) {
return;
}
var parsed = data.split(' ');
return {
oid: parsed.shift(),
value: parsed.join(' ').replace(/["']/g, '') //remove "" in '"name"'
};
} | javascript | function parseSnmpLine(line) {
if (typeof line !== 'string') {
throw new Error("Data is not in string format");
}
var data = line.trim();
var errString = 'No Such Object available on this agent at this OID';
if (data.indexOf(errString) >= 0) {
throw new Error(data);
}
// Messages that occur as a result of doing MIB translation on output
// We exclude "Cannot find module" and "Did not find *" messages because
// in some cases we walk the whole tree and there are may be vendor-specific
// mibs that we don't have installed.
if (data.indexOf('MIB search path') >= 0 ||
data.indexOf('Cannot find module') >= 0 ||
data.indexOf('Did not find') >= 0) {
return;
}
var parsed = data.split(' ');
return {
oid: parsed.shift(),
value: parsed.join(' ').replace(/["']/g, '') //remove "" in '"name"'
};
} | [
"function",
"parseSnmpLine",
"(",
"line",
")",
"{",
"if",
"(",
"typeof",
"line",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Data is not in string format\"",
")",
";",
"}",
"var",
"data",
"=",
"line",
".",
"trim",
"(",
")",
";",
"var",
"errString",
"=",
"'No Such Object available on this agent at this OID'",
";",
"if",
"(",
"data",
".",
"indexOf",
"(",
"errString",
")",
">=",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"data",
")",
";",
"}",
"if",
"(",
"data",
".",
"indexOf",
"(",
"'MIB search path'",
")",
">=",
"0",
"||",
"data",
".",
"indexOf",
"(",
"'Cannot find module'",
")",
">=",
"0",
"||",
"data",
".",
"indexOf",
"(",
"'Did not find'",
")",
">=",
"0",
")",
"{",
"return",
";",
"}",
"var",
"parsed",
"=",
"data",
".",
"split",
"(",
"' '",
")",
";",
"return",
"{",
"oid",
":",
"parsed",
".",
"shift",
"(",
")",
",",
"value",
":",
"parsed",
".",
"join",
"(",
"' '",
")",
".",
"replace",
"(",
"/",
"[\"']",
"/",
"g",
",",
"''",
")",
"}",
";",
"}"
]
| Parse a line of output from SNMP data
@param line
@returns {{value: *, oid: *}} | [
"Parse",
"a",
"line",
"of",
"output",
"from",
"SNMP",
"data"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/net-snmp-parser.js#L18-L47 | train |
RackHD/on-tasks | lib/utils/job-utils/net-snmp-parser.js | parseSnmpData | function parseSnmpData(snmpData) {
var lines = snmpData.trim().split('\n');
return _.compact(_.map(lines, function(line) {
return parseSnmpLine(line);
}));
} | javascript | function parseSnmpData(snmpData) {
var lines = snmpData.trim().split('\n');
return _.compact(_.map(lines, function(line) {
return parseSnmpLine(line);
}));
} | [
"function",
"parseSnmpData",
"(",
"snmpData",
")",
"{",
"var",
"lines",
"=",
"snmpData",
".",
"trim",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"}"
]
| Parse the SNMP data.
@param snmpData
@returns [*] | [
"Parse",
"the",
"SNMP",
"data",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/net-snmp-parser.js#L54-L59 | train |
RackHD/on-tasks | lib/jobs/download-file.js | DownloadFileJob | function DownloadFileJob(options, context, taskId) {
var self = this;
DownloadFileJob.super_.call(self, logger, options, context, taskId);
self.nodeId = self.context.target;
if (self.options.filePath) {
self.options.filePath = self.options.filePath.trim();
if (_.last(self.options.filePath) === '/') {
self.options.filePath = self.options.filePath.substring(0, self.options.filePath.length - 1);
}
}
} | javascript | function DownloadFileJob(options, context, taskId) {
var self = this;
DownloadFileJob.super_.call(self, logger, options, context, taskId);
self.nodeId = self.context.target;
if (self.options.filePath) {
self.options.filePath = self.options.filePath.trim();
if (_.last(self.options.filePath) === '/') {
self.options.filePath = self.options.filePath.substring(0, self.options.filePath.length - 1);
}
}
} | [
"function",
"DownloadFileJob",
"(",
"options",
",",
"context",
",",
"taskId",
")",
"{",
"var",
"self",
"=",
"this",
";",
"DownloadFileJob",
".",
"super_",
".",
"call",
"(",
"self",
",",
"logger",
",",
"options",
",",
"context",
",",
"taskId",
")",
";",
"self",
".",
"nodeId",
"=",
"self",
".",
"context",
".",
"target",
";",
"if",
"(",
"self",
".",
"options",
".",
"filePath",
")",
"{",
"self",
".",
"options",
".",
"filePath",
"=",
"self",
".",
"options",
".",
"filePath",
".",
"trim",
"(",
")",
";",
"if",
"(",
"_",
".",
"last",
"(",
"self",
".",
"options",
".",
"filePath",
")",
"===",
"'/'",
")",
"{",
"self",
".",
"options",
".",
"filePath",
"=",
"self",
".",
"options",
".",
"filePath",
".",
"substring",
"(",
"0",
",",
"self",
".",
"options",
".",
"filePath",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"}"
]
| This job will fetch a file from some repository
@param {Object} options
@param {Object} context
@param {String} taskId
@constructor | [
"This",
"job",
"will",
"fetch",
"a",
"file",
"from",
"some",
"repository"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/download-file.js#L38-L49 | train |
DenisCarriere/sqlite3-offline | scripts/update-binaries.js | getVersion | function getVersion () {
const url = 'https://raw.githubusercontent.com/mapbox/node-sqlite3/master/package.json'
return new Promise((resolve, reject) => {
https.get(url, res => {
let data = ''
res.setEncoding('utf8')
if (res.statusCode !== 200) return reject(res.statusMessage)
res.on('data', chunk => { data += chunk })
res.on('end', () => resolve(JSON.parse(data).version))
})
})
} | javascript | function getVersion () {
const url = 'https://raw.githubusercontent.com/mapbox/node-sqlite3/master/package.json'
return new Promise((resolve, reject) => {
https.get(url, res => {
let data = ''
res.setEncoding('utf8')
if (res.statusCode !== 200) return reject(res.statusMessage)
res.on('data', chunk => { data += chunk })
res.on('end', () => resolve(JSON.parse(data).version))
})
})
} | [
"function",
"getVersion",
"(",
")",
"{",
"const",
"url",
"=",
"'https://raw.githubusercontent.com/mapbox/node-sqlite3/master/package.json'",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"https",
".",
"get",
"(",
"url",
",",
"res",
"=>",
"{",
"let",
"data",
"=",
"''",
"res",
".",
"setEncoding",
"(",
"'utf8'",
")",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"return",
"reject",
"(",
"res",
".",
"statusMessage",
")",
"res",
".",
"on",
"(",
"'data'",
",",
"chunk",
"=>",
"{",
"data",
"+=",
"chunk",
"}",
")",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"data",
")",
".",
"version",
")",
")",
"}",
")",
"}",
")",
"}"
]
| getVersion directly from GitHub repo package.json
@returns {Promise<string>} version
@example
const version = await getVersion()
//= '3.1.8' | [
"getVersion",
"directly",
"from",
"GitHub",
"repo",
"package",
".",
"json"
]
| c4fe3eda2d51b71af44105ce016b324838feea4b | https://github.com/DenisCarriere/sqlite3-offline/blob/c4fe3eda2d51b71af44105ce016b324838feea4b/scripts/update-binaries.js#L21-L32 | train |
DenisCarriere/sqlite3-offline | scripts/update-binaries.js | main | async function main () {
const version = await getVersion()
for (const MODULE of ELECTRON_MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getElectronName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
for (const MODULE of MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
} | javascript | async function main () {
const version = await getVersion()
for (const MODULE of ELECTRON_MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getElectronName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
for (const MODULE of MODULES) {
for (const PLATFORM of PLATFORMS) {
for (const ARCH of ARCHS) {
const name = getName(MODULE, PLATFORM, ARCH)
const filename = name + '.tar.gz'
const url = getUrl(version, name)
const binary = await download(url).catch(error => console.error(error, url))
if (binary) {
console.info(`Success ${url}`)
fs.writeFileSync(filename, binary)
await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
fs.removeSync(filename)
}
}
}
}
} | [
"async",
"function",
"main",
"(",
")",
"{",
"const",
"version",
"=",
"await",
"getVersion",
"(",
")",
"for",
"(",
"const",
"MODULE",
"of",
"ELECTRON_MODULES",
")",
"{",
"for",
"(",
"const",
"PLATFORM",
"of",
"PLATFORMS",
")",
"{",
"for",
"(",
"const",
"ARCH",
"of",
"ARCHS",
")",
"{",
"const",
"name",
"=",
"getElectronName",
"(",
"MODULE",
",",
"PLATFORM",
",",
"ARCH",
")",
"const",
"filename",
"=",
"name",
"+",
"'.tar.gz'",
"const",
"url",
"=",
"getUrl",
"(",
"version",
",",
"name",
")",
"const",
"binary",
"=",
"await",
"download",
"(",
"url",
")",
".",
"catch",
"(",
"error",
"=>",
"console",
".",
"error",
"(",
"error",
",",
"url",
")",
")",
"if",
"(",
"binary",
")",
"{",
"console",
".",
"info",
"(",
"`",
"${",
"url",
"}",
"`",
")",
"fs",
".",
"writeFileSync",
"(",
"filename",
",",
"binary",
")",
"await",
"decompress",
"(",
"filename",
",",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
",",
"'binaries'",
",",
"`",
"${",
"PLATFORM",
"}",
"`",
")",
")",
"fs",
".",
"removeSync",
"(",
"filename",
")",
"}",
"}",
"}",
"}",
"for",
"(",
"const",
"MODULE",
"of",
"MODULES",
")",
"{",
"for",
"(",
"const",
"PLATFORM",
"of",
"PLATFORMS",
")",
"{",
"for",
"(",
"const",
"ARCH",
"of",
"ARCHS",
")",
"{",
"const",
"name",
"=",
"getName",
"(",
"MODULE",
",",
"PLATFORM",
",",
"ARCH",
")",
"const",
"filename",
"=",
"name",
"+",
"'.tar.gz'",
"const",
"url",
"=",
"getUrl",
"(",
"version",
",",
"name",
")",
"const",
"binary",
"=",
"await",
"download",
"(",
"url",
")",
".",
"catch",
"(",
"error",
"=>",
"console",
".",
"error",
"(",
"error",
",",
"url",
")",
")",
"if",
"(",
"binary",
")",
"{",
"console",
".",
"info",
"(",
"`",
"${",
"url",
"}",
"`",
")",
"fs",
".",
"writeFileSync",
"(",
"filename",
",",
"binary",
")",
"await",
"decompress",
"(",
"filename",
",",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
",",
"'binaries'",
",",
"`",
"${",
"PLATFORM",
"}",
"`",
")",
")",
"fs",
".",
"removeSync",
"(",
"filename",
")",
"}",
"}",
"}",
"}",
"}"
]
| Update Binaries Scripts | [
"Update",
"Binaries",
"Scripts"
]
| c4fe3eda2d51b71af44105ce016b324838feea4b | https://github.com/DenisCarriere/sqlite3-offline/blob/c4fe3eda2d51b71af44105ce016b324838feea4b/scripts/update-binaries.js#L109-L146 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseControllerInfoOneDriveData | function _parseControllerInfoOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\n/); //Divided by line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
// Ignore empty line
if (data.length === 0) {
return;
}
//Split key and value by "="
var fields = data.split("="); //Divided by "="
drvObj[fields[0]] = fields[1].trim();
});
return drvObj;
} | javascript | function _parseControllerInfoOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\n/); //Divided by line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
// Ignore empty line
if (data.length === 0) {
return;
}
//Split key and value by "="
var fields = data.split("="); //Divided by "="
drvObj[fields[0]] = fields[1].trim();
});
return drvObj;
} | [
"function",
"_parseControllerInfoOneDriveData",
"(",
"dataBlock",
")",
"{",
"var",
"dataSegments",
"=",
"dataBlock",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
";",
"var",
"drvObj",
"=",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"dataSegments",
",",
"function",
"(",
"data",
")",
"{",
"data",
"=",
"data",
".",
"trim",
"(",
")",
";",
"if",
"(",
"data",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"var",
"fields",
"=",
"data",
".",
"split",
"(",
"\"=\"",
")",
";",
"drvObj",
"[",
"fields",
"[",
"0",
"]",
"]",
"=",
"fields",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"}",
")",
";",
"return",
"drvObj",
";",
"}"
]
| Parse the whole controller info of one drive.
@param {String} dataBlock - The controller info output data for one drive.
@returns {Object} The object with well classfied controller information. | [
"Parse",
"the",
"whole",
"controller",
"info",
"of",
"one",
"drive",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1255-L1273 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartOneDriveData | function _parseSmartOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\r?\n\s*\r?\n/); //Divided by empty line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
//remove the empty data segment and the segment with smartctl version
if (data.length === 0 || data.match(/^smartctl\s([\d\.]+)\s/)) {
return;
}
var lines = data.split(/\r?\n/); //Divided by line
if (data.startsWith('=== START OF INFORMATION SECTION ===')) {
drvObj.Identity = _parseSmartInfoSection(lines);
}
else if (data.startsWith('=== START OF READ SMART DATA SECTION ===')) {
drvObj['Self-Assessment'] = _parseSmartSelfAssessment(lines);
}
else if (data.startsWith('General SMART Values')) {
drvObj.Capabilities = _parseSmartCapabilities(lines);
}
else if (data.startsWith('SMART Attributes Data Structure revision number:')) {
drvObj.Attributes = _parseSmartAttributes(lines);
}
else if (data.startsWith('SMART Error Log Version:')) {
drvObj['Error Log'] = _parseSmartErrorLog(lines);
}
else if (data.startsWith('SMART Self-test log structure revision number')) {
drvObj['Self-test Log'] = _parseSmartSelfTestLog(lines);
}
else if (data.startsWith(
'SMART Selective self-test log data structure revision number')) {
drvObj['Selective Self-test Log'] = _parseSmartSelectiveSelfTestLog(lines);
}
else {
//I don't find the regular pattern for some data segment, or I don't know how to
//well classify some data, so just put them in the 'Un-parsed Raw Data'.
if (_.isArray(drvObj['Un-parsed Raw Data'])) {
drvObj['Un-parsed Raw Data'].push(data);
}
else {
drvObj['Un-parsed Raw Data'] = [data];
}
}
});
return drvObj;
} | javascript | function _parseSmartOneDriveData(dataBlock) {
//split output by empty line
var dataSegments = dataBlock.split(/\r?\n\s*\r?\n/); //Divided by empty line
var drvObj = {};
_.forEach(dataSegments, function(data) {
data = data.trim();
//remove the empty data segment and the segment with smartctl version
if (data.length === 0 || data.match(/^smartctl\s([\d\.]+)\s/)) {
return;
}
var lines = data.split(/\r?\n/); //Divided by line
if (data.startsWith('=== START OF INFORMATION SECTION ===')) {
drvObj.Identity = _parseSmartInfoSection(lines);
}
else if (data.startsWith('=== START OF READ SMART DATA SECTION ===')) {
drvObj['Self-Assessment'] = _parseSmartSelfAssessment(lines);
}
else if (data.startsWith('General SMART Values')) {
drvObj.Capabilities = _parseSmartCapabilities(lines);
}
else if (data.startsWith('SMART Attributes Data Structure revision number:')) {
drvObj.Attributes = _parseSmartAttributes(lines);
}
else if (data.startsWith('SMART Error Log Version:')) {
drvObj['Error Log'] = _parseSmartErrorLog(lines);
}
else if (data.startsWith('SMART Self-test log structure revision number')) {
drvObj['Self-test Log'] = _parseSmartSelfTestLog(lines);
}
else if (data.startsWith(
'SMART Selective self-test log data structure revision number')) {
drvObj['Selective Self-test Log'] = _parseSmartSelectiveSelfTestLog(lines);
}
else {
//I don't find the regular pattern for some data segment, or I don't know how to
//well classify some data, so just put them in the 'Un-parsed Raw Data'.
if (_.isArray(drvObj['Un-parsed Raw Data'])) {
drvObj['Un-parsed Raw Data'].push(data);
}
else {
drvObj['Un-parsed Raw Data'] = [data];
}
}
});
return drvObj;
} | [
"function",
"_parseSmartOneDriveData",
"(",
"dataBlock",
")",
"{",
"var",
"dataSegments",
"=",
"dataBlock",
".",
"split",
"(",
"/",
"\\r?\\n\\s*\\r?\\n",
"/",
")",
";",
"var",
"drvObj",
"=",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"dataSegments",
",",
"function",
"(",
"data",
")",
"{",
"data",
"=",
"data",
".",
"trim",
"(",
")",
";",
"if",
"(",
"data",
".",
"length",
"===",
"0",
"||",
"data",
".",
"match",
"(",
"/",
"^smartctl\\s([\\d\\.]+)\\s",
"/",
")",
")",
"{",
"return",
";",
"}",
"var",
"lines",
"=",
"data",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'=== START OF INFORMATION SECTION ==='",
")",
")",
"{",
"drvObj",
".",
"Identity",
"=",
"_parseSmartInfoSection",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'=== START OF READ SMART DATA SECTION ==='",
")",
")",
"{",
"drvObj",
"[",
"'Self-Assessment'",
"]",
"=",
"_parseSmartSelfAssessment",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'General SMART Values'",
")",
")",
"{",
"drvObj",
".",
"Capabilities",
"=",
"_parseSmartCapabilities",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'SMART Attributes Data Structure revision number:'",
")",
")",
"{",
"drvObj",
".",
"Attributes",
"=",
"_parseSmartAttributes",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'SMART Error Log Version:'",
")",
")",
"{",
"drvObj",
"[",
"'Error Log'",
"]",
"=",
"_parseSmartErrorLog",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'SMART Self-test log structure revision number'",
")",
")",
"{",
"drvObj",
"[",
"'Self-test Log'",
"]",
"=",
"_parseSmartSelfTestLog",
"(",
"lines",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"startsWith",
"(",
"'SMART Selective self-test log data structure revision number'",
")",
")",
"{",
"drvObj",
"[",
"'Selective Self-test Log'",
"]",
"=",
"_parseSmartSelectiveSelfTestLog",
"(",
"lines",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"drvObj",
"[",
"'Un-parsed Raw Data'",
"]",
")",
")",
"{",
"drvObj",
"[",
"'Un-parsed Raw Data'",
"]",
".",
"push",
"(",
"data",
")",
";",
"}",
"else",
"{",
"drvObj",
"[",
"'Un-parsed Raw Data'",
"]",
"=",
"[",
"data",
"]",
";",
"}",
"}",
"}",
")",
";",
"return",
"drvObj",
";",
"}"
]
| Parse the whole SMART data of one drive.
The data catalog is refer to the smartctl GUI.
@param {String} dataBlock - The whole smartctl output data for one drive.
@returns {Object} The object with well classfied SMART information. | [
"Parse",
"the",
"whole",
"SMART",
"data",
"of",
"one",
"drive",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1282-L1332 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartInfoSection | function _parseSmartInfoSection(lines) {
/*
*Example data:
=== START OF INFORMATION SECTION ===
Device Model: Micron_P400e-MTFDDAK200MAR
Serial Number: 1144031E6FB3
LU WWN Device Id: 5 00a075 1031e6fb3
Firmware Version: 0135
User Capacity: 200,049,647,616 bytes [200 GB]
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
} | javascript | function _parseSmartInfoSection(lines) {
/*
*Example data:
=== START OF INFORMATION SECTION ===
Device Model: Micron_P400e-MTFDDAK200MAR
Serial Number: 1144031E6FB3
LU WWN Device Id: 5 00a075 1031e6fb3
Firmware Version: 0135
User Capacity: 200,049,647,616 bytes [200 GB]
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
} | [
"function",
"_parseSmartInfoSection",
"(",
"lines",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"_parseSmartColonLine",
"(",
"lines",
"[",
"i",
"]",
",",
"result",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Parse the SMART information section
@param {Array} The data to parse, it has been splitted by lines
@return {Object} | [
"Parse",
"the",
"SMART",
"information",
"section"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1380-L1397 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartSelfAssessment | function _parseSmartSelfAssessment(lines) {
/*
Example 1:
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED
Example 2:
=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
} | javascript | function _parseSmartSelfAssessment(lines) {
/*
Example 1:
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED
Example 2:
=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK
*/
var result = {};
//ignore the first line
for (var i = 1; i < lines.length; i+=1) {
_parseSmartColonLine(lines[i], result);
}
return result;
} | [
"function",
"_parseSmartSelfAssessment",
"(",
"lines",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"_parseSmartColonLine",
"(",
"lines",
"[",
"i",
"]",
",",
"result",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Parse the SMART self-assessment result
@param {Array} The data to parse, it has been splitted by lines
@return {Object} | [
"Parse",
"the",
"SMART",
"self",
"-",
"assessment",
"result"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1405-L1423 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartCapabilities | function _parseSmartCapabilities(lines) {
var combineLines = [];
var strBuf = '';
/*
The first line is 'General SMART Values:', it should be discarded.
Some of the entry information is divided into multiline,
so first we try to combine these lines to achieve a regular patter.
Below is the example data:
Offline data collection status: (0x84) Offline data collection activity
was suspended by an interrupting command from host.
Auto Offline Data Collection: Enabled.
*/
for (var i = 1; i < lines.length; i+=1) {
var firstChar = lines[i][0];
if (firstChar >= 'A' && firstChar <= 'Z') {
if (strBuf !== '') {
combineLines.push(strBuf);
}
strBuf = lines[i];
}
else {
if (strBuf[strBuf.length-1] !== '.') {
strBuf += ' ';
}
strBuf += lines[i].trim();
}
}
if (strBuf !== '') { // if this is ignored, the last capabilities entry will be missed.
combineLines.push(strBuf);
}
//After combination, each line will become something like this:
//name: (0x84) annotation1.annotation2.annotation3
var result = [];
_.forEach(combineLines, function(line) {
var arr = line.split(/:\s*\(\s*(\w+)\)\s*/);
var annotation = (arr[2] ? arr[2].split('.') : []);
if (annotation.length > 0 && annotation[annotation.length-1].length === 0) {
annotation.pop();
}
result.push({
'Name' : arr[0],
'Value' : arr[1] || '',
'Annotation' : annotation
});
});
return result;
} | javascript | function _parseSmartCapabilities(lines) {
var combineLines = [];
var strBuf = '';
/*
The first line is 'General SMART Values:', it should be discarded.
Some of the entry information is divided into multiline,
so first we try to combine these lines to achieve a regular patter.
Below is the example data:
Offline data collection status: (0x84) Offline data collection activity
was suspended by an interrupting command from host.
Auto Offline Data Collection: Enabled.
*/
for (var i = 1; i < lines.length; i+=1) {
var firstChar = lines[i][0];
if (firstChar >= 'A' && firstChar <= 'Z') {
if (strBuf !== '') {
combineLines.push(strBuf);
}
strBuf = lines[i];
}
else {
if (strBuf[strBuf.length-1] !== '.') {
strBuf += ' ';
}
strBuf += lines[i].trim();
}
}
if (strBuf !== '') { // if this is ignored, the last capabilities entry will be missed.
combineLines.push(strBuf);
}
//After combination, each line will become something like this:
//name: (0x84) annotation1.annotation2.annotation3
var result = [];
_.forEach(combineLines, function(line) {
var arr = line.split(/:\s*\(\s*(\w+)\)\s*/);
var annotation = (arr[2] ? arr[2].split('.') : []);
if (annotation.length > 0 && annotation[annotation.length-1].length === 0) {
annotation.pop();
}
result.push({
'Name' : arr[0],
'Value' : arr[1] || '',
'Annotation' : annotation
});
});
return result;
} | [
"function",
"_parseSmartCapabilities",
"(",
"lines",
")",
"{",
"var",
"combineLines",
"=",
"[",
"]",
";",
"var",
"strBuf",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"firstChar",
"=",
"lines",
"[",
"i",
"]",
"[",
"0",
"]",
";",
"if",
"(",
"firstChar",
">=",
"'A'",
"&&",
"firstChar",
"<=",
"'Z'",
")",
"{",
"if",
"(",
"strBuf",
"!==",
"''",
")",
"{",
"combineLines",
".",
"push",
"(",
"strBuf",
")",
";",
"}",
"strBuf",
"=",
"lines",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"strBuf",
"[",
"strBuf",
".",
"length",
"-",
"1",
"]",
"!==",
"'.'",
")",
"{",
"strBuf",
"+=",
"' '",
";",
"}",
"strBuf",
"+=",
"lines",
"[",
"i",
"]",
".",
"trim",
"(",
")",
";",
"}",
"}",
"if",
"(",
"strBuf",
"!==",
"''",
")",
"{",
"combineLines",
".",
"push",
"(",
"strBuf",
")",
";",
"}",
"var",
"result",
"=",
"[",
"]",
";",
"_",
".",
"forEach",
"(",
"combineLines",
",",
"function",
"(",
"line",
")",
"{",
"var",
"arr",
"=",
"line",
".",
"split",
"(",
"/",
":\\s*\\(\\s*(\\w+)\\)\\s*",
"/",
")",
";",
"var",
"annotation",
"=",
"(",
"arr",
"[",
"2",
"]",
"?",
"arr",
"[",
"2",
"]",
".",
"split",
"(",
"'.'",
")",
":",
"[",
"]",
")",
";",
"if",
"(",
"annotation",
".",
"length",
">",
"0",
"&&",
"annotation",
"[",
"annotation",
".",
"length",
"-",
"1",
"]",
".",
"length",
"===",
"0",
")",
"{",
"annotation",
".",
"pop",
"(",
")",
";",
"}",
"result",
".",
"push",
"(",
"{",
"'Name'",
":",
"arr",
"[",
"0",
"]",
",",
"'Value'",
":",
"arr",
"[",
"1",
"]",
"||",
"''",
",",
"'Annotation'",
":",
"annotation",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
]
| Parse SMART capabilities information from smartctl output
@param {Array} The data to parse, it has been splitted by lines
@return {Array} All parsed capabilities entries,
each entry contains properties 'Name', 'Value' and 'Annotation'. | [
"Parse",
"SMART",
"capabilities",
"information",
"from",
"smartctl",
"output"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1432-L1482 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartAttributes | function _parseSmartAttributes(lines) {
var attrObj = {};
/* Example data:
SMART Attributes Data Structure revision number: 1
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
*/
//Parse first line to get revision number
//Example data: "SMART Attributes Data Structure revision number: 16"
if (lines.length > 0) {
attrObj.Revision = (lines[0].substring(lines[0].lastIndexOf(' ') + 1)).trim();
}
attrObj['Attributes Table'] = _parseSmartTable(lines, 2, /\s+/);
return attrObj;
} | javascript | function _parseSmartAttributes(lines) {
var attrObj = {};
/* Example data:
SMART Attributes Data Structure revision number: 1
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
*/
//Parse first line to get revision number
//Example data: "SMART Attributes Data Structure revision number: 16"
if (lines.length > 0) {
attrObj.Revision = (lines[0].substring(lines[0].lastIndexOf(' ') + 1)).trim();
}
attrObj['Attributes Table'] = _parseSmartTable(lines, 2, /\s+/);
return attrObj;
} | [
"function",
"_parseSmartAttributes",
"(",
"lines",
")",
"{",
"var",
"attrObj",
"=",
"{",
"}",
";",
"if",
"(",
"lines",
".",
"length",
">",
"0",
")",
"{",
"attrObj",
".",
"Revision",
"=",
"(",
"lines",
"[",
"0",
"]",
".",
"substring",
"(",
"lines",
"[",
"0",
"]",
".",
"lastIndexOf",
"(",
"' '",
")",
"+",
"1",
")",
")",
".",
"trim",
"(",
")",
";",
"}",
"attrObj",
"[",
"'Attributes Table'",
"]",
"=",
"_parseSmartTable",
"(",
"lines",
",",
"2",
",",
"/",
"\\s+",
"/",
")",
";",
"return",
"attrObj",
";",
"}"
]
| Parse the SMART attribute table
@param {Array} The input data that has been splitted by line.
@param {Object} The object with SMART attribute revision and table. | [
"Parse",
"the",
"SMART",
"attribute",
"table"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1490-L1507 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartErrorLog | function _parseSmartErrorLog(lines) {
var resultObj = {};
//Parse first line to get revision number
//Example data:
//SMART Error Log Version: 1
if (lines.length > 0) {
resultObj.Revision = (lines[0].substring(
lines[0].lastIndexOf(' ') + 1)).trim();
}
//TODO: need to implement the error log parser
resultObj['Error Log Table'] = [];
if (lines.length > 1 && lines[1].startsWith('No ')) {
return resultObj;
}
//resultObj['Error Log Table'] = _parseSmartTable(lines, 1);
return resultObj;
} | javascript | function _parseSmartErrorLog(lines) {
var resultObj = {};
//Parse first line to get revision number
//Example data:
//SMART Error Log Version: 1
if (lines.length > 0) {
resultObj.Revision = (lines[0].substring(
lines[0].lastIndexOf(' ') + 1)).trim();
}
//TODO: need to implement the error log parser
resultObj['Error Log Table'] = [];
if (lines.length > 1 && lines[1].startsWith('No ')) {
return resultObj;
}
//resultObj['Error Log Table'] = _parseSmartTable(lines, 1);
return resultObj;
} | [
"function",
"_parseSmartErrorLog",
"(",
"lines",
")",
"{",
"var",
"resultObj",
"=",
"{",
"}",
";",
"if",
"(",
"lines",
".",
"length",
">",
"0",
")",
"{",
"resultObj",
".",
"Revision",
"=",
"(",
"lines",
"[",
"0",
"]",
".",
"substring",
"(",
"lines",
"[",
"0",
"]",
".",
"lastIndexOf",
"(",
"' '",
")",
"+",
"1",
")",
")",
".",
"trim",
"(",
")",
";",
"}",
"resultObj",
"[",
"'Error Log Table'",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"lines",
".",
"length",
">",
"1",
"&&",
"lines",
"[",
"1",
"]",
".",
"startsWith",
"(",
"'No '",
")",
")",
"{",
"return",
"resultObj",
";",
"}",
"return",
"resultObj",
";",
"}"
]
| Parse SMART error log
@param {Array} The data to parse, it has been splitted by line.
@return {Object} The object with error log revision and table. | [
"Parse",
"SMART",
"error",
"log"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1515-L1535 | train |
RackHD/on-tasks | lib/utils/job-utils/command-parser.js | _parseSmartTable | function _parseSmartTable(lines,
ignoreLinesCount,
regSplitRow,
funcCheckTableEnd)
{
/* Example 1:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
5 Reallocated_Sector_Ct 0x0003 100 100 036 Pre-fail Always
9 Power_On_Hours 0x0003 100 100 000 Pre-fail Always
12 Power_Cycle_Count 0x0003 100 100 000 Pre-fail Always
190 Airflow_Temperature_Cel 0x0003 069 069 050 Pre-fail Always
Example 2:
Num Test_Description Status Remaining LifeTime
# 1 Vendor (0xff) Completed 00% 463
# 2 Vendor (0xff) Completed 00% 288
# 3 Extended offline Completed 00% 263
# 4 Short offline Completed 00% 263
*/
var resultObj = [];
var colHeaders;
regSplitRow = regSplitRow || /\s{2,}/; //default to split with more than 2 spaces
if (lines.length <= ignoreLinesCount + 1) { //should contains at least the column header row
return resultObj;
}
//The first line should be the column header
colHeaders = lines[ignoreLinesCount].split(/\s+/);
if (colHeaders[0].trim().length === 0) {
colHeaders.shift();
}
for (var i = ignoreLinesCount + 1; i < lines.length; i+=1) {
if (funcCheckTableEnd && funcCheckTableEnd(lines[i])) {
break; //skip early if reach the end of table
}
var arr = lines[i].split(regSplitRow);
if (arr[0].trim().length === 0) {
arr.shift();
}
var entry = {};
var j;
for (j = 0; j < colHeaders.length - 1; j += 1) {
entry[colHeaders[j]] = arr[j]; //Fill each column data
}
//There maybe more cells than the header, we append these cells to the last column.
//For example, the 'RAW_VALUE' in the attributes table may be like '31 (Min/Max 31/31)'
entry[colHeaders[j]] = arr.slice(j, arr.length).join(' ');
resultObj.push(entry);
}
return resultObj;
} | javascript | function _parseSmartTable(lines,
ignoreLinesCount,
regSplitRow,
funcCheckTableEnd)
{
/* Example 1:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED
1 Raw_Read_Error_Rate 0x0003 100 100 006 Pre-fail Always
3 Spin_Up_Time 0x0003 100 100 000 Pre-fail Always
4 Start_Stop_Count 0x0002 100 100 020 Old_age Always
5 Reallocated_Sector_Ct 0x0003 100 100 036 Pre-fail Always
9 Power_On_Hours 0x0003 100 100 000 Pre-fail Always
12 Power_Cycle_Count 0x0003 100 100 000 Pre-fail Always
190 Airflow_Temperature_Cel 0x0003 069 069 050 Pre-fail Always
Example 2:
Num Test_Description Status Remaining LifeTime
# 1 Vendor (0xff) Completed 00% 463
# 2 Vendor (0xff) Completed 00% 288
# 3 Extended offline Completed 00% 263
# 4 Short offline Completed 00% 263
*/
var resultObj = [];
var colHeaders;
regSplitRow = regSplitRow || /\s{2,}/; //default to split with more than 2 spaces
if (lines.length <= ignoreLinesCount + 1) { //should contains at least the column header row
return resultObj;
}
//The first line should be the column header
colHeaders = lines[ignoreLinesCount].split(/\s+/);
if (colHeaders[0].trim().length === 0) {
colHeaders.shift();
}
for (var i = ignoreLinesCount + 1; i < lines.length; i+=1) {
if (funcCheckTableEnd && funcCheckTableEnd(lines[i])) {
break; //skip early if reach the end of table
}
var arr = lines[i].split(regSplitRow);
if (arr[0].trim().length === 0) {
arr.shift();
}
var entry = {};
var j;
for (j = 0; j < colHeaders.length - 1; j += 1) {
entry[colHeaders[j]] = arr[j]; //Fill each column data
}
//There maybe more cells than the header, we append these cells to the last column.
//For example, the 'RAW_VALUE' in the attributes table may be like '31 (Min/Max 31/31)'
entry[colHeaders[j]] = arr.slice(j, arr.length).join(' ');
resultObj.push(entry);
}
return resultObj;
} | [
"function",
"_parseSmartTable",
"(",
"lines",
",",
"ignoreLinesCount",
",",
"regSplitRow",
",",
"funcCheckTableEnd",
")",
"{",
"var",
"resultObj",
"=",
"[",
"]",
";",
"var",
"colHeaders",
";",
"regSplitRow",
"=",
"regSplitRow",
"||",
"/",
"\\s{2,}",
"/",
";",
"if",
"(",
"lines",
".",
"length",
"<=",
"ignoreLinesCount",
"+",
"1",
")",
"{",
"return",
"resultObj",
";",
"}",
"colHeaders",
"=",
"lines",
"[",
"ignoreLinesCount",
"]",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
";",
"if",
"(",
"colHeaders",
"[",
"0",
"]",
".",
"trim",
"(",
")",
".",
"length",
"===",
"0",
")",
"{",
"colHeaders",
".",
"shift",
"(",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"ignoreLinesCount",
"+",
"1",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"funcCheckTableEnd",
"&&",
"funcCheckTableEnd",
"(",
"lines",
"[",
"i",
"]",
")",
")",
"{",
"break",
";",
"}",
"var",
"arr",
"=",
"lines",
"[",
"i",
"]",
".",
"split",
"(",
"regSplitRow",
")",
";",
"if",
"(",
"arr",
"[",
"0",
"]",
".",
"trim",
"(",
")",
".",
"length",
"===",
"0",
")",
"{",
"arr",
".",
"shift",
"(",
")",
";",
"}",
"var",
"entry",
"=",
"{",
"}",
";",
"var",
"j",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"colHeaders",
".",
"length",
"-",
"1",
";",
"j",
"+=",
"1",
")",
"{",
"entry",
"[",
"colHeaders",
"[",
"j",
"]",
"]",
"=",
"arr",
"[",
"j",
"]",
";",
"}",
"entry",
"[",
"colHeaders",
"[",
"j",
"]",
"]",
"=",
"arr",
".",
"slice",
"(",
"j",
",",
"arr",
".",
"length",
")",
".",
"join",
"(",
"' '",
")",
";",
"resultObj",
".",
"push",
"(",
"entry",
")",
";",
"}",
"return",
"resultObj",
";",
"}"
]
| Parse the table data to an array of object
The object properties (column header) is extracted from the first
valid line (line index = ignoreLinesCount)
@param {Array} The data to parse, it has been splitted by lines
@param {Number} The number of lines that needed be discarded before parsing.
@param {RegExp} The regular expression that tells how to split a row
(not including the column header)
@param {Function (String)} The function that tells whether the line has been the end of table
@return {Array}
@api private | [
"Parse",
"the",
"table",
"data",
"to",
"an",
"array",
"of",
"object"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/command-parser.js#L1638-L1699 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | findDriveWwidByIndex | function findDriveWwidByIndex(catalog, isEsx, driveIndex) {
var wwid = null;
_.forEach(catalog, function(entry) {
if (entry.identifier === driveIndex) {
wwid = isEsx ? entry.esxiWwid : entry.linuxWwid;
return false; //have found the result, so we can exit iteration early.
}
});
return wwid;
} | javascript | function findDriveWwidByIndex(catalog, isEsx, driveIndex) {
var wwid = null;
_.forEach(catalog, function(entry) {
if (entry.identifier === driveIndex) {
wwid = isEsx ? entry.esxiWwid : entry.linuxWwid;
return false; //have found the result, so we can exit iteration early.
}
});
return wwid;
} | [
"function",
"findDriveWwidByIndex",
"(",
"catalog",
",",
"isEsx",
",",
"driveIndex",
")",
"{",
"var",
"wwid",
"=",
"null",
";",
"_",
".",
"forEach",
"(",
"catalog",
",",
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"entry",
".",
"identifier",
"===",
"driveIndex",
")",
"{",
"wwid",
"=",
"isEsx",
"?",
"entry",
".",
"esxiWwid",
":",
"entry",
".",
"linuxWwid",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"return",
"wwid",
";",
"}"
]
| Search the driveid catalog and lookup the corresponding drive WWID by the input
drive index.
@param {Object} catalog - the catalog data of drive id
@param {Boolean} isEsx - True to return the ESXi formated wwid,
otherwise linux format wwid.
@param {Number} driveIndex - The drive index
@return {String} The WWID for the target drive. If failed, return null | [
"Search",
"the",
"driveid",
"catalog",
"and",
"lookup",
"the",
"corresponding",
"drive",
"WWID",
"by",
"the",
"input",
"drive",
"index",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L46-L55 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | getDriveIdCatalog | function getDriveIdCatalog(nodeId, filter) {
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'driveId'
}).then(function (catalog) {
if (!catalog || !_.has(catalog, 'data[0]')) {
return Promise.reject(
new Error('Could not find driveId catalog data.'));
}
return catalog.data;
}).filter(function (driveId) {
if (_.isEmpty(filter)) {
return true;
}
return _.indexOf(filter, driveId.identifier) > -1 ||
_.indexOf(filter, driveId.devName) > -1;
});
} | javascript | function getDriveIdCatalog(nodeId, filter) {
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'driveId'
}).then(function (catalog) {
if (!catalog || !_.has(catalog, 'data[0]')) {
return Promise.reject(
new Error('Could not find driveId catalog data.'));
}
return catalog.data;
}).filter(function (driveId) {
if (_.isEmpty(filter)) {
return true;
}
return _.indexOf(filter, driveId.identifier) > -1 ||
_.indexOf(filter, driveId.devName) > -1;
});
} | [
"function",
"getDriveIdCatalog",
"(",
"nodeId",
",",
"filter",
")",
"{",
"return",
"waterline",
".",
"catalogs",
".",
"findMostRecent",
"(",
"{",
"node",
":",
"nodeId",
",",
"source",
":",
"'driveId'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"catalog",
")",
"{",
"if",
"(",
"!",
"catalog",
"||",
"!",
"_",
".",
"has",
"(",
"catalog",
",",
"'data[0]'",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Could not find driveId catalog data.'",
")",
")",
";",
"}",
"return",
"catalog",
".",
"data",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"driveId",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"filter",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"_",
".",
"indexOf",
"(",
"filter",
",",
"driveId",
".",
"identifier",
")",
">",
"-",
"1",
"||",
"_",
".",
"indexOf",
"(",
"filter",
",",
"driveId",
".",
"devName",
")",
">",
"-",
"1",
";",
"}",
")",
";",
"}"
]
| Get driveId catalog data
@param {String} nodeId - node identifier
@param {Object} filter - [optional] The filter which contains the driveId catalogs identifier
Or devName. For example: ['sda', 'sdb', '1'].
driveId catalogs in filter will return, otherwise skip.
@return {Promise} driveId catalogs | [
"Get",
"driveId",
"catalog",
"data"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L65-L82 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | getVirtualDiskCatalog | function getVirtualDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-virtual-disks'
})
.then(function (virtualDiskCatalog) {
if (!_.has(virtualDiskCatalog, 'data.Controllers[0]')) {
return Promise.reject(
new Error('Could not find megaraid-virtual-disks catalog data.'));
}
return virtualDiskCatalog.data;
});
} | javascript | function getVirtualDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-virtual-disks'
})
.then(function (virtualDiskCatalog) {
if (!_.has(virtualDiskCatalog, 'data.Controllers[0]')) {
return Promise.reject(
new Error('Could not find megaraid-virtual-disks catalog data.'));
}
return virtualDiskCatalog.data;
});
} | [
"function",
"getVirtualDiskCatalog",
"(",
"nodeId",
")",
"{",
"return",
"waterline",
".",
"catalogs",
".",
"findMostRecent",
"(",
"{",
"node",
":",
"nodeId",
",",
"source",
":",
"'megaraid-virtual-disks'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"virtualDiskCatalog",
")",
"{",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"virtualDiskCatalog",
",",
"'data.Controllers[0]'",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Could not find megaraid-virtual-disks catalog data.'",
")",
")",
";",
"}",
"return",
"virtualDiskCatalog",
".",
"data",
";",
"}",
")",
";",
"}"
]
| Get virtual disk catalog data
@param {String} nodeId - node identifier
@return {Promise} drive virtual disk catalogs | [
"Get",
"virtual",
"disk",
"catalog",
"data"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L89-L101 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | getPhysicalDiskCatalog | function getPhysicalDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-physical-drives'
})
.then(function(physicalDiskCatalog){
if (!_.has(physicalDiskCatalog, 'data')) {
return Promise.reject(
new Error('Could not find megaraid-physical-drives catalog data.'));
}
return physicalDiskCatalog.data;
});
} | javascript | function getPhysicalDiskCatalog(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-physical-drives'
})
.then(function(physicalDiskCatalog){
if (!_.has(physicalDiskCatalog, 'data')) {
return Promise.reject(
new Error('Could not find megaraid-physical-drives catalog data.'));
}
return physicalDiskCatalog.data;
});
} | [
"function",
"getPhysicalDiskCatalog",
"(",
"nodeId",
")",
"{",
"return",
"waterline",
".",
"catalogs",
".",
"findMostRecent",
"(",
"{",
"node",
":",
"nodeId",
",",
"source",
":",
"'megaraid-physical-drives'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"physicalDiskCatalog",
")",
"{",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"physicalDiskCatalog",
",",
"'data'",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Could not find megaraid-physical-drives catalog data.'",
")",
")",
";",
"}",
"return",
"physicalDiskCatalog",
".",
"data",
";",
"}",
")",
";",
"}"
]
| Get physical disk catalog data
@param {String} nodeId - node identifier
@return {Promise} drive physical disk catalogs | [
"Get",
"physical",
"disk",
"catalog",
"data"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L108-L120 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | getRaidControllerVendor | function getRaidControllerVendor(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-controllers'
})
.then(function (controllerCatalog) {
if (!_.has(controllerCatalog, 'data.Controllers')) {
return Promise.reject(
new Error('Could not find megaraid-controllers catalog data.'));
}
var vendor,
controllerId,
controllerVendors = [];
var controllerDataList = _.get(controllerCatalog, 'data.Controllers');
_.forEach(controllerDataList, function(data){
vendor = _.get(data, '[Response Data][Scheduled Tasks].OEMID');
controllerId = _.get(data, '[Command Status][Controller]');
controllerVendors[controllerId] = vendor.toLowerCase();
});
return controllerVendors;
});
} | javascript | function getRaidControllerVendor(nodeId){
return waterline.catalogs.findMostRecent({
node: nodeId,
source: 'megaraid-controllers'
})
.then(function (controllerCatalog) {
if (!_.has(controllerCatalog, 'data.Controllers')) {
return Promise.reject(
new Error('Could not find megaraid-controllers catalog data.'));
}
var vendor,
controllerId,
controllerVendors = [];
var controllerDataList = _.get(controllerCatalog, 'data.Controllers');
_.forEach(controllerDataList, function(data){
vendor = _.get(data, '[Response Data][Scheduled Tasks].OEMID');
controllerId = _.get(data, '[Command Status][Controller]');
controllerVendors[controllerId] = vendor.toLowerCase();
});
return controllerVendors;
});
} | [
"function",
"getRaidControllerVendor",
"(",
"nodeId",
")",
"{",
"return",
"waterline",
".",
"catalogs",
".",
"findMostRecent",
"(",
"{",
"node",
":",
"nodeId",
",",
"source",
":",
"'megaraid-controllers'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"controllerCatalog",
")",
"{",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"controllerCatalog",
",",
"'data.Controllers'",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Could not find megaraid-controllers catalog data.'",
")",
")",
";",
"}",
"var",
"vendor",
",",
"controllerId",
",",
"controllerVendors",
"=",
"[",
"]",
";",
"var",
"controllerDataList",
"=",
"_",
".",
"get",
"(",
"controllerCatalog",
",",
"'data.Controllers'",
")",
";",
"_",
".",
"forEach",
"(",
"controllerDataList",
",",
"function",
"(",
"data",
")",
"{",
"vendor",
"=",
"_",
".",
"get",
"(",
"data",
",",
"'[Response Data][Scheduled Tasks].OEMID'",
")",
";",
"controllerId",
"=",
"_",
".",
"get",
"(",
"data",
",",
"'[Command Status][Controller]'",
")",
";",
"controllerVendors",
"[",
"controllerId",
"]",
"=",
"vendor",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"return",
"controllerVendors",
";",
"}",
")",
";",
"}"
]
| Get drive RAID controller vendor from catalog
@param {String} nodeId - node identifier
@return {Promise} drive RAID controller vendors | [
"Get",
"drive",
"RAID",
"controller",
"vendor",
"from",
"catalog"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L127-L148 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | getDriveIdCatalogExt | function getDriveIdCatalogExt(nodeId, filter, extendJbod) {
return getDriveIdCatalog(nodeId, filter)
.then(function (driveIds) {
// get virtualDisk data from megaraid-virtual-disks catalog
var foundVdHasValue = _.find(driveIds, function (driveId) {
return !_.isEmpty(driveId.virtualDisk);
});
if (!foundVdHasValue && !extendJbod) {
// If none of drives are VDs, and extend JBOD is not required,
// it is not necessary to extend Megaraid information.
return Promise.resolve(driveIds);
}
return Promise.all([
foundVdHasValue ? getVirtualDiskCatalog(nodeId) : Promise.resolve(),
extendJbod ? getPhysicalDiskCatalog(nodeId) : Promise.resolve(),
getRaidControllerVendor(nodeId)
])
.spread(function(virtualDiskData, physicalDiskData, controllerVendors){
return Promise.map(driveIds, function(driveId){
if (!_.isEmpty(driveId.virtualDisk)) {
return _getVdExtDriveIdCatalog(
nodeId,
driveId,
virtualDiskData,
controllerVendors
);
}
if (extendJbod){
return _getJbodExtDriveIdCatalog(
nodeId,
driveId,
physicalDiskData,
controllerVendors
);
}
return driveId;
});
});
});
} | javascript | function getDriveIdCatalogExt(nodeId, filter, extendJbod) {
return getDriveIdCatalog(nodeId, filter)
.then(function (driveIds) {
// get virtualDisk data from megaraid-virtual-disks catalog
var foundVdHasValue = _.find(driveIds, function (driveId) {
return !_.isEmpty(driveId.virtualDisk);
});
if (!foundVdHasValue && !extendJbod) {
// If none of drives are VDs, and extend JBOD is not required,
// it is not necessary to extend Megaraid information.
return Promise.resolve(driveIds);
}
return Promise.all([
foundVdHasValue ? getVirtualDiskCatalog(nodeId) : Promise.resolve(),
extendJbod ? getPhysicalDiskCatalog(nodeId) : Promise.resolve(),
getRaidControllerVendor(nodeId)
])
.spread(function(virtualDiskData, physicalDiskData, controllerVendors){
return Promise.map(driveIds, function(driveId){
if (!_.isEmpty(driveId.virtualDisk)) {
return _getVdExtDriveIdCatalog(
nodeId,
driveId,
virtualDiskData,
controllerVendors
);
}
if (extendJbod){
return _getJbodExtDriveIdCatalog(
nodeId,
driveId,
physicalDiskData,
controllerVendors
);
}
return driveId;
});
});
});
} | [
"function",
"getDriveIdCatalogExt",
"(",
"nodeId",
",",
"filter",
",",
"extendJbod",
")",
"{",
"return",
"getDriveIdCatalog",
"(",
"nodeId",
",",
"filter",
")",
".",
"then",
"(",
"function",
"(",
"driveIds",
")",
"{",
"var",
"foundVdHasValue",
"=",
"_",
".",
"find",
"(",
"driveIds",
",",
"function",
"(",
"driveId",
")",
"{",
"return",
"!",
"_",
".",
"isEmpty",
"(",
"driveId",
".",
"virtualDisk",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"foundVdHasValue",
"&&",
"!",
"extendJbod",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"driveIds",
")",
";",
"}",
"return",
"Promise",
".",
"all",
"(",
"[",
"foundVdHasValue",
"?",
"getVirtualDiskCatalog",
"(",
"nodeId",
")",
":",
"Promise",
".",
"resolve",
"(",
")",
",",
"extendJbod",
"?",
"getPhysicalDiskCatalog",
"(",
"nodeId",
")",
":",
"Promise",
".",
"resolve",
"(",
")",
",",
"getRaidControllerVendor",
"(",
"nodeId",
")",
"]",
")",
".",
"spread",
"(",
"function",
"(",
"virtualDiskData",
",",
"physicalDiskData",
",",
"controllerVendors",
")",
"{",
"return",
"Promise",
".",
"map",
"(",
"driveIds",
",",
"function",
"(",
"driveId",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"driveId",
".",
"virtualDisk",
")",
")",
"{",
"return",
"_getVdExtDriveIdCatalog",
"(",
"nodeId",
",",
"driveId",
",",
"virtualDiskData",
",",
"controllerVendors",
")",
";",
"}",
"if",
"(",
"extendJbod",
")",
"{",
"return",
"_getJbodExtDriveIdCatalog",
"(",
"nodeId",
",",
"driveId",
",",
"physicalDiskData",
",",
"controllerVendors",
")",
";",
"}",
"return",
"driveId",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Get extended driveId catalog
@param {String} nodeId - node identifier
@param {Object} driveIds - driveId list retrieved from driveId catalogs
@param {Boolean} extendJbod - flag for if we should extend JBOD physical information
@return {Promise} Drive catalogs extended with Megaraid information | [
"Get",
"extended",
"driveId",
"catalog"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L157-L198 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | _getVdExtDriveIdCatalog | function _getVdExtDriveIdCatalog(nodeId, driveId, virtualDiskData, vendors){
var match = driveId.virtualDisk.match(/^\/c(\d+)\/v(\d+)/);
if (!match) {
return driveId;
}
var vid = match[2];
var cid = match[1];
var vdInfo;
_.forEach(virtualDiskData.Controllers, function(controller) {
var vd = _.get(controller,
'Response Data[%s]'.format(driveId.virtualDisk));
if (vd) {
vdInfo = vd[0];
vdInfo.oemId = controller.oemId;
vdInfo.pdList = _.get(controller,
'Response Data[PDs for VD %d]'.format(vid)
);
return false; // break forEach
}
});
if(!vdInfo) {
// clear virtualDisk if no matched info found in catalog
driveId.virtualDisk = '';
return driveId;
}
// set extended info to driveId catalog
driveId.size = vdInfo.Size;
driveId.type = vdInfo.TYPE;
driveId.controllerId = cid;
driveId.physicalDisks = _.map(vdInfo.pdList, function (pd) {
// for more physical disk info, search megaraid-physical-drives
var eidslt = pd['EID:Slt'].split(':');
return {
deviceId : pd.DID,
enclosureId : eidslt[0],
slotId : eidslt[1],
size: pd.Size,
protocol: pd.Intf,
type: pd.Med,
model: pd.Model
};
});
driveId.deviceIds = _.map(driveId.physicalDisks, function (disk) {
return disk.deviceId;
});
driveId.slotIds = _.map(driveId.physicalDisks, function (disk) {
// slotId : /c0/e252/s10
return '/c%d/e%d/s%d'.format(cid, disk.enclosureId, disk.slotId);
});
// OEM id is Dell or LSI
driveId.controllerVendor = vendors[_.parseInt(cid)];
return driveId;
} | javascript | function _getVdExtDriveIdCatalog(nodeId, driveId, virtualDiskData, vendors){
var match = driveId.virtualDisk.match(/^\/c(\d+)\/v(\d+)/);
if (!match) {
return driveId;
}
var vid = match[2];
var cid = match[1];
var vdInfo;
_.forEach(virtualDiskData.Controllers, function(controller) {
var vd = _.get(controller,
'Response Data[%s]'.format(driveId.virtualDisk));
if (vd) {
vdInfo = vd[0];
vdInfo.oemId = controller.oemId;
vdInfo.pdList = _.get(controller,
'Response Data[PDs for VD %d]'.format(vid)
);
return false; // break forEach
}
});
if(!vdInfo) {
// clear virtualDisk if no matched info found in catalog
driveId.virtualDisk = '';
return driveId;
}
// set extended info to driveId catalog
driveId.size = vdInfo.Size;
driveId.type = vdInfo.TYPE;
driveId.controllerId = cid;
driveId.physicalDisks = _.map(vdInfo.pdList, function (pd) {
// for more physical disk info, search megaraid-physical-drives
var eidslt = pd['EID:Slt'].split(':');
return {
deviceId : pd.DID,
enclosureId : eidslt[0],
slotId : eidslt[1],
size: pd.Size,
protocol: pd.Intf,
type: pd.Med,
model: pd.Model
};
});
driveId.deviceIds = _.map(driveId.physicalDisks, function (disk) {
return disk.deviceId;
});
driveId.slotIds = _.map(driveId.physicalDisks, function (disk) {
// slotId : /c0/e252/s10
return '/c%d/e%d/s%d'.format(cid, disk.enclosureId, disk.slotId);
});
// OEM id is Dell or LSI
driveId.controllerVendor = vendors[_.parseInt(cid)];
return driveId;
} | [
"function",
"_getVdExtDriveIdCatalog",
"(",
"nodeId",
",",
"driveId",
",",
"virtualDiskData",
",",
"vendors",
")",
"{",
"var",
"match",
"=",
"driveId",
".",
"virtualDisk",
".",
"match",
"(",
"/",
"^\\/c(\\d+)\\/v(\\d+)",
"/",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"driveId",
";",
"}",
"var",
"vid",
"=",
"match",
"[",
"2",
"]",
";",
"var",
"cid",
"=",
"match",
"[",
"1",
"]",
";",
"var",
"vdInfo",
";",
"_",
".",
"forEach",
"(",
"virtualDiskData",
".",
"Controllers",
",",
"function",
"(",
"controller",
")",
"{",
"var",
"vd",
"=",
"_",
".",
"get",
"(",
"controller",
",",
"'Response Data[%s]'",
".",
"format",
"(",
"driveId",
".",
"virtualDisk",
")",
")",
";",
"if",
"(",
"vd",
")",
"{",
"vdInfo",
"=",
"vd",
"[",
"0",
"]",
";",
"vdInfo",
".",
"oemId",
"=",
"controller",
".",
"oemId",
";",
"vdInfo",
".",
"pdList",
"=",
"_",
".",
"get",
"(",
"controller",
",",
"'Response Data[PDs for VD %d]'",
".",
"format",
"(",
"vid",
")",
")",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"vdInfo",
")",
"{",
"driveId",
".",
"virtualDisk",
"=",
"''",
";",
"return",
"driveId",
";",
"}",
"driveId",
".",
"size",
"=",
"vdInfo",
".",
"Size",
";",
"driveId",
".",
"type",
"=",
"vdInfo",
".",
"TYPE",
";",
"driveId",
".",
"controllerId",
"=",
"cid",
";",
"driveId",
".",
"physicalDisks",
"=",
"_",
".",
"map",
"(",
"vdInfo",
".",
"pdList",
",",
"function",
"(",
"pd",
")",
"{",
"var",
"eidslt",
"=",
"pd",
"[",
"'EID:Slt'",
"]",
".",
"split",
"(",
"':'",
")",
";",
"return",
"{",
"deviceId",
":",
"pd",
".",
"DID",
",",
"enclosureId",
":",
"eidslt",
"[",
"0",
"]",
",",
"slotId",
":",
"eidslt",
"[",
"1",
"]",
",",
"size",
":",
"pd",
".",
"Size",
",",
"protocol",
":",
"pd",
".",
"Intf",
",",
"type",
":",
"pd",
".",
"Med",
",",
"model",
":",
"pd",
".",
"Model",
"}",
";",
"}",
")",
";",
"driveId",
".",
"deviceIds",
"=",
"_",
".",
"map",
"(",
"driveId",
".",
"physicalDisks",
",",
"function",
"(",
"disk",
")",
"{",
"return",
"disk",
".",
"deviceId",
";",
"}",
")",
";",
"driveId",
".",
"slotIds",
"=",
"_",
".",
"map",
"(",
"driveId",
".",
"physicalDisks",
",",
"function",
"(",
"disk",
")",
"{",
"return",
"'/c%d/e%d/s%d'",
".",
"format",
"(",
"cid",
",",
"disk",
".",
"enclosureId",
",",
"disk",
".",
"slotId",
")",
";",
"}",
")",
";",
"driveId",
".",
"controllerVendor",
"=",
"vendors",
"[",
"_",
".",
"parseInt",
"(",
"cid",
")",
"]",
";",
"return",
"driveId",
";",
"}"
]
| Get extended driveId catalog data for disk from virtualDiskData
@param {String} nodeId - node identifier
@param {Object} driveId - driveId catalog
@param {Object} virtualDiskData - Megaraid virtual disk catalogs
@param {Array} vendors - Drive vendor controller list
@return {Promise} driveId catalogs extended | [
"Get",
"extended",
"driveId",
"catalog",
"data",
"for",
"disk",
"from",
"virtualDiskData"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L208-L263 | train |
RackHD/on-tasks | lib/utils/job-utils/catalog-searcher.js | _getJbodExtDriveIdCatalog | function _getJbodExtDriveIdCatalog(nodeId, driveId, physicalDiskData, vendors){
//Devide ID in SCSI ID is used to match megaraid DID
//This feature is only qualified on servers with one RAID card
//An alternative method is to use logic wwid
//to find "OS Device Name" in smart catalog and get megaraid DID
var scsiIds = driveId.scsiId.split(':');
var deviceId = scsiIds[2];
var controllerId = scsiIds[0];
/**
*physicalDiskCatalog.data example, not fully displayed:
* "Controllers": [
* {
* "Command Status": {
* "Controller": 0,
* "Description": "Show Drive Information Succeeded.",
* "Status": "Success"
* },
* "Response Data": {
* "Drive /c0/e252/s0": [
* {
* "DG": 0,
* "DID": 0,
* "EID:Slt": "252:0",
* "Intf": "SAS",
* "Med": "HDD",
* "Model": "ST1200MM0088 ",
* "PI": "N",
* "SED": "N",
* "SeSz": "512B",
* "Size": "1.091 TB",
* "Sp": "U",
* "State": "Onln"
* }
*/
var driveDataList,
driveBaseInfoList = {},
matchedBaseInfo,
matchedBaseInfoKey;
_.forEach(physicalDiskData.Controllers, function(controller){
if (controller['Command Status'].Controller.toString() === controllerId) {
driveDataList = controller['Response Data'];
return false;
}
});
//Filter Drive Basic information from Response Data
//Drive Basic information is the only one has array as element
_.forEach(driveDataList, function(driveInfo, key){
if(_.isArray(driveInfo)) {
driveBaseInfoList[key] = driveInfo[0];
}
});
_.forEach(driveBaseInfoList, function(info, key){
if(info.DID.toString() === deviceId){
matchedBaseInfoKey = key;
return false;
}
});
if (matchedBaseInfoKey ) {
// Base info key example:
// "Drive /c0/e252/s0"
var match = matchedBaseInfoKey.match(/.*\/c(\d+)\/e(\d+)\/s(\d+)/);
matchedBaseInfo = driveBaseInfoList[matchedBaseInfoKey];
driveId.controllerId = controllerId;
driveId.deviceIds = [matchedBaseInfo.DID];
driveId.slotIds = matchedBaseInfoKey.split(' ').slice(-1);
driveId.size = matchedBaseInfo.Size;
driveId.type = matchedBaseInfo.State;
driveId.controllerVendor = vendors[_.parseInt(controllerId)];
driveId.physicalDisks = [{
protocol: matchedBaseInfo.Intf,
model: matchedBaseInfo.Model,
deviceId: matchedBaseInfo.DID,
slotId: match[3],
size: matchedBaseInfo.Size,
type: matchedBaseInfo.Med,
enclosureId: match[2]
}];
}
return driveId;
} | javascript | function _getJbodExtDriveIdCatalog(nodeId, driveId, physicalDiskData, vendors){
//Devide ID in SCSI ID is used to match megaraid DID
//This feature is only qualified on servers with one RAID card
//An alternative method is to use logic wwid
//to find "OS Device Name" in smart catalog and get megaraid DID
var scsiIds = driveId.scsiId.split(':');
var deviceId = scsiIds[2];
var controllerId = scsiIds[0];
/**
*physicalDiskCatalog.data example, not fully displayed:
* "Controllers": [
* {
* "Command Status": {
* "Controller": 0,
* "Description": "Show Drive Information Succeeded.",
* "Status": "Success"
* },
* "Response Data": {
* "Drive /c0/e252/s0": [
* {
* "DG": 0,
* "DID": 0,
* "EID:Slt": "252:0",
* "Intf": "SAS",
* "Med": "HDD",
* "Model": "ST1200MM0088 ",
* "PI": "N",
* "SED": "N",
* "SeSz": "512B",
* "Size": "1.091 TB",
* "Sp": "U",
* "State": "Onln"
* }
*/
var driveDataList,
driveBaseInfoList = {},
matchedBaseInfo,
matchedBaseInfoKey;
_.forEach(physicalDiskData.Controllers, function(controller){
if (controller['Command Status'].Controller.toString() === controllerId) {
driveDataList = controller['Response Data'];
return false;
}
});
//Filter Drive Basic information from Response Data
//Drive Basic information is the only one has array as element
_.forEach(driveDataList, function(driveInfo, key){
if(_.isArray(driveInfo)) {
driveBaseInfoList[key] = driveInfo[0];
}
});
_.forEach(driveBaseInfoList, function(info, key){
if(info.DID.toString() === deviceId){
matchedBaseInfoKey = key;
return false;
}
});
if (matchedBaseInfoKey ) {
// Base info key example:
// "Drive /c0/e252/s0"
var match = matchedBaseInfoKey.match(/.*\/c(\d+)\/e(\d+)\/s(\d+)/);
matchedBaseInfo = driveBaseInfoList[matchedBaseInfoKey];
driveId.controllerId = controllerId;
driveId.deviceIds = [matchedBaseInfo.DID];
driveId.slotIds = matchedBaseInfoKey.split(' ').slice(-1);
driveId.size = matchedBaseInfo.Size;
driveId.type = matchedBaseInfo.State;
driveId.controllerVendor = vendors[_.parseInt(controllerId)];
driveId.physicalDisks = [{
protocol: matchedBaseInfo.Intf,
model: matchedBaseInfo.Model,
deviceId: matchedBaseInfo.DID,
slotId: match[3],
size: matchedBaseInfo.Size,
type: matchedBaseInfo.Med,
enclosureId: match[2]
}];
}
return driveId;
} | [
"function",
"_getJbodExtDriveIdCatalog",
"(",
"nodeId",
",",
"driveId",
",",
"physicalDiskData",
",",
"vendors",
")",
"{",
"var",
"scsiIds",
"=",
"driveId",
".",
"scsiId",
".",
"split",
"(",
"':'",
")",
";",
"var",
"deviceId",
"=",
"scsiIds",
"[",
"2",
"]",
";",
"var",
"controllerId",
"=",
"scsiIds",
"[",
"0",
"]",
";",
"var",
"driveDataList",
",",
"driveBaseInfoList",
"=",
"{",
"}",
",",
"matchedBaseInfo",
",",
"matchedBaseInfoKey",
";",
"_",
".",
"forEach",
"(",
"physicalDiskData",
".",
"Controllers",
",",
"function",
"(",
"controller",
")",
"{",
"if",
"(",
"controller",
"[",
"'Command Status'",
"]",
".",
"Controller",
".",
"toString",
"(",
")",
"===",
"controllerId",
")",
"{",
"driveDataList",
"=",
"controller",
"[",
"'Response Data'",
"]",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"_",
".",
"forEach",
"(",
"driveDataList",
",",
"function",
"(",
"driveInfo",
",",
"key",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"driveInfo",
")",
")",
"{",
"driveBaseInfoList",
"[",
"key",
"]",
"=",
"driveInfo",
"[",
"0",
"]",
";",
"}",
"}",
")",
";",
"_",
".",
"forEach",
"(",
"driveBaseInfoList",
",",
"function",
"(",
"info",
",",
"key",
")",
"{",
"if",
"(",
"info",
".",
"DID",
".",
"toString",
"(",
")",
"===",
"deviceId",
")",
"{",
"matchedBaseInfoKey",
"=",
"key",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"if",
"(",
"matchedBaseInfoKey",
")",
"{",
"var",
"match",
"=",
"matchedBaseInfoKey",
".",
"match",
"(",
"/",
".*\\/c(\\d+)\\/e(\\d+)\\/s(\\d+)",
"/",
")",
";",
"matchedBaseInfo",
"=",
"driveBaseInfoList",
"[",
"matchedBaseInfoKey",
"]",
";",
"driveId",
".",
"controllerId",
"=",
"controllerId",
";",
"driveId",
".",
"deviceIds",
"=",
"[",
"matchedBaseInfo",
".",
"DID",
"]",
";",
"driveId",
".",
"slotIds",
"=",
"matchedBaseInfoKey",
".",
"split",
"(",
"' '",
")",
".",
"slice",
"(",
"-",
"1",
")",
";",
"driveId",
".",
"size",
"=",
"matchedBaseInfo",
".",
"Size",
";",
"driveId",
".",
"type",
"=",
"matchedBaseInfo",
".",
"State",
";",
"driveId",
".",
"controllerVendor",
"=",
"vendors",
"[",
"_",
".",
"parseInt",
"(",
"controllerId",
")",
"]",
";",
"driveId",
".",
"physicalDisks",
"=",
"[",
"{",
"protocol",
":",
"matchedBaseInfo",
".",
"Intf",
",",
"model",
":",
"matchedBaseInfo",
".",
"Model",
",",
"deviceId",
":",
"matchedBaseInfo",
".",
"DID",
",",
"slotId",
":",
"match",
"[",
"3",
"]",
",",
"size",
":",
"matchedBaseInfo",
".",
"Size",
",",
"type",
":",
"matchedBaseInfo",
".",
"Med",
",",
"enclosureId",
":",
"match",
"[",
"2",
"]",
"}",
"]",
";",
"}",
"return",
"driveId",
";",
"}"
]
| Get extended driveId catalog data for JBOD disk from megaraid-physical-drives
@param {String} nodeId - node identifier
@param {Object} driveId - driveId catalog
@param {Object} physicalDiskData - Megaraid physical disk catalogs
@param {Array} vendors - Drive vendor controller list
@return {Promise} driveId catalogs extended | [
"Get",
"extended",
"driveId",
"catalog",
"data",
"for",
"JBOD",
"disk",
"from",
"megaraid",
"-",
"physical",
"-",
"drives"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/catalog-searcher.js#L273-L356 | train |
RackHD/on-tasks | lib/task.js | handleCommonOptions | function handleCommonOptions(options) {
// check the task timeout, if not specified, then set a default one.
if (!options.hasOwnProperty('_taskTimeout') && options.schedulerOverrides &&
options.schedulerOverrides.hasOwnProperty('timeout')) {
options._taskTimeout = options.schedulerOverrides.timeout;
}
if (typeof options._taskTimeout !== 'number') {
options._taskTimeout = 24 * 60 * 60 * 1000; //default to 24 hour timeout
}
return options;
} | javascript | function handleCommonOptions(options) {
// check the task timeout, if not specified, then set a default one.
if (!options.hasOwnProperty('_taskTimeout') && options.schedulerOverrides &&
options.schedulerOverrides.hasOwnProperty('timeout')) {
options._taskTimeout = options.schedulerOverrides.timeout;
}
if (typeof options._taskTimeout !== 'number') {
options._taskTimeout = 24 * 60 * 60 * 1000; //default to 24 hour timeout
}
return options;
} | [
"function",
"handleCommonOptions",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
".",
"hasOwnProperty",
"(",
"'_taskTimeout'",
")",
"&&",
"options",
".",
"schedulerOverrides",
"&&",
"options",
".",
"schedulerOverrides",
".",
"hasOwnProperty",
"(",
"'timeout'",
")",
")",
"{",
"options",
".",
"_taskTimeout",
"=",
"options",
".",
"schedulerOverrides",
".",
"timeout",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"_taskTimeout",
"!==",
"'number'",
")",
"{",
"options",
".",
"_taskTimeout",
"=",
"24",
"*",
"60",
"*",
"60",
"*",
"1000",
";",
"}",
"return",
"options",
";",
"}"
]
| handle task common options
This handling will operate on the input options itself. Currently this function only checks
the task timout setting, if in future there is additional common setting, put it here as
well.
@param {Object} options - The input task options.
@return {Object} the result options object. | [
"handle",
"task",
"common",
"options"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/task.js#L482-L493 | train |
stadt-bielefeld/wms-downloader | src/helper/createWorldFile.js | createWorldFile | function createWorldFile(x0, y0, res) {
let halfPxInM = res / 2.0;
let ret = res + '\n';
ret += '0.0' + '\n';
ret += '0.0' + '\n';
ret += '-' + res + '\n';
ret += x0 + halfPxInM + '\n';
ret += y0 - halfPxInM;
return ret;
} | javascript | function createWorldFile(x0, y0, res) {
let halfPxInM = res / 2.0;
let ret = res + '\n';
ret += '0.0' + '\n';
ret += '0.0' + '\n';
ret += '-' + res + '\n';
ret += x0 + halfPxInM + '\n';
ret += y0 - halfPxInM;
return ret;
} | [
"function",
"createWorldFile",
"(",
"x0",
",",
"y0",
",",
"res",
")",
"{",
"let",
"halfPxInM",
"=",
"res",
"/",
"2.0",
";",
"let",
"ret",
"=",
"res",
"+",
"'\\n'",
";",
"\\n",
"ret",
"+=",
"'0.0'",
"+",
"'\\n'",
";",
"\\n",
"ret",
"+=",
"'0.0'",
"+",
"'\\n'",
";",
"\\n",
"ret",
"+=",
"'-'",
"+",
"res",
"+",
"'\\n'",
";",
"}"
]
| Creates world file content.
@param {Number} x0 X value of start point (top-left)
@param {Number} y0 Y value of start point (top-left)
@param {Number} res Ground resolution
@returns {string} Content of world file
@example
const x0 = 458000;
const y0 = 5754000;
const res = 1;
let wordlFileContent = createWorldFile(x0, y0, res);
console.log(wordlFileContent);
// 1
// 0.0
// 0.0
// -1
// 458000.5
// 5753999.5 | [
"Creates",
"world",
"file",
"content",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/createWorldFile.js#L24-L33 | train |
RackHD/on-tasks | lib/services/obm-service.js | ObmService | function ObmService(nodeId, obmServiceFactory, obmSettings, options) {
assert.object(obmSettings);
assert.object(obmSettings.config);
assert.string(obmSettings.service);
assert.func(obmServiceFactory);
assert.isMongoId(nodeId);
this.params = options || {};
this.retries = this.params.retries;
this.delay = this.params.delay;
if (this.params.delay !== 0) {
this.delay = this.params.delay || config.get('obmInitialDelay') || 500;
}
if (this.params.retries !== 0) {
this.retries = this.params.retries || config.get('obmRetries') || 6;
}
this.serviceFactory = obmServiceFactory;
this.obmConfig = obmSettings.config;
this.serviceType = obmSettings.service;
this.nodeId = nodeId;
} | javascript | function ObmService(nodeId, obmServiceFactory, obmSettings, options) {
assert.object(obmSettings);
assert.object(obmSettings.config);
assert.string(obmSettings.service);
assert.func(obmServiceFactory);
assert.isMongoId(nodeId);
this.params = options || {};
this.retries = this.params.retries;
this.delay = this.params.delay;
if (this.params.delay !== 0) {
this.delay = this.params.delay || config.get('obmInitialDelay') || 500;
}
if (this.params.retries !== 0) {
this.retries = this.params.retries || config.get('obmRetries') || 6;
}
this.serviceFactory = obmServiceFactory;
this.obmConfig = obmSettings.config;
this.serviceType = obmSettings.service;
this.nodeId = nodeId;
} | [
"function",
"ObmService",
"(",
"nodeId",
",",
"obmServiceFactory",
",",
"obmSettings",
",",
"options",
")",
"{",
"assert",
".",
"object",
"(",
"obmSettings",
")",
";",
"assert",
".",
"object",
"(",
"obmSettings",
".",
"config",
")",
";",
"assert",
".",
"string",
"(",
"obmSettings",
".",
"service",
")",
";",
"assert",
".",
"func",
"(",
"obmServiceFactory",
")",
";",
"assert",
".",
"isMongoId",
"(",
"nodeId",
")",
";",
"this",
".",
"params",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"retries",
"=",
"this",
".",
"params",
".",
"retries",
";",
"this",
".",
"delay",
"=",
"this",
".",
"params",
".",
"delay",
";",
"if",
"(",
"this",
".",
"params",
".",
"delay",
"!==",
"0",
")",
"{",
"this",
".",
"delay",
"=",
"this",
".",
"params",
".",
"delay",
"||",
"config",
".",
"get",
"(",
"'obmInitialDelay'",
")",
"||",
"500",
";",
"}",
"if",
"(",
"this",
".",
"params",
".",
"retries",
"!==",
"0",
")",
"{",
"this",
".",
"retries",
"=",
"this",
".",
"params",
".",
"retries",
"||",
"config",
".",
"get",
"(",
"'obmRetries'",
")",
"||",
"6",
";",
"}",
"this",
".",
"serviceFactory",
"=",
"obmServiceFactory",
";",
"this",
".",
"obmConfig",
"=",
"obmSettings",
".",
"config",
";",
"this",
".",
"serviceType",
"=",
"obmSettings",
".",
"service",
";",
"this",
".",
"nodeId",
"=",
"nodeId",
";",
"}"
]
| An OBM command interface that runs raw OBM commands from
various OBM services with failure and retry logic.
@constructor | [
"An",
"OBM",
"command",
"interface",
"that",
"runs",
"raw",
"OBM",
"commands",
"from",
"various",
"OBM",
"services",
"with",
"failure",
"and",
"retry",
"logic",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/services/obm-service.js#L56-L77 | train |
RackHD/on-tasks | lib/services/obm-service.js | _getValidSku | function _getValidSku (node) {
if (node.sku) {
return waterline.skus.findOne({ id: node.sku }).then(function (sku) {
if (sku && sku.name) {
node.sku = sku.name;
}
else {
return Promise.reject();
}
});
}
else {
return Promise.reject();
}
} | javascript | function _getValidSku (node) {
if (node.sku) {
return waterline.skus.findOne({ id: node.sku }).then(function (sku) {
if (sku && sku.name) {
node.sku = sku.name;
}
else {
return Promise.reject();
}
});
}
else {
return Promise.reject();
}
} | [
"function",
"_getValidSku",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"sku",
")",
"{",
"return",
"waterline",
".",
"skus",
".",
"findOne",
"(",
"{",
"id",
":",
"node",
".",
"sku",
"}",
")",
".",
"then",
"(",
"function",
"(",
"sku",
")",
"{",
"if",
"(",
"sku",
"&&",
"sku",
".",
"name",
")",
"{",
"node",
".",
"sku",
"=",
"sku",
".",
"name",
";",
"}",
"else",
"{",
"return",
"Promise",
".",
"reject",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"return",
"Promise",
".",
"reject",
"(",
")",
";",
"}",
"}"
]
| Get valid sku info from database | [
"Get",
"valid",
"sku",
"info",
"from",
"database"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/services/obm-service.js#L657-L671 | train |
pierrec/js-cuint | build/uint64.js | UINT64 | function UINT64 (a00, a16, a32, a48) {
if ( !(this instanceof UINT64) )
return new UINT64(a00, a16, a32, a48)
this.remainder = null
if (typeof a00 == 'string')
return fromString.call(this, a00, a16)
if (typeof a16 == 'undefined')
return fromNumber.call(this, a00)
fromBits.apply(this, arguments)
} | javascript | function UINT64 (a00, a16, a32, a48) {
if ( !(this instanceof UINT64) )
return new UINT64(a00, a16, a32, a48)
this.remainder = null
if (typeof a00 == 'string')
return fromString.call(this, a00, a16)
if (typeof a16 == 'undefined')
return fromNumber.call(this, a00)
fromBits.apply(this, arguments)
} | [
"function",
"UINT64",
"(",
"a00",
",",
"a16",
",",
"a32",
",",
"a48",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"UINT64",
")",
")",
"return",
"new",
"UINT64",
"(",
"a00",
",",
"a16",
",",
"a32",
",",
"a48",
")",
"this",
".",
"remainder",
"=",
"null",
"if",
"(",
"typeof",
"a00",
"==",
"'string'",
")",
"return",
"fromString",
".",
"call",
"(",
"this",
",",
"a00",
",",
"a16",
")",
"if",
"(",
"typeof",
"a16",
"==",
"'undefined'",
")",
"return",
"fromNumber",
".",
"call",
"(",
"this",
",",
"a00",
")",
"fromBits",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}"
]
| Represents an unsigned 64 bits integer
@constructor
@param {Number} first low bits (8)
@param {Number} second low bits (8)
@param {Number} first high bits (8)
@param {Number} second high bits (8)
or
@param {Number} low bits (32)
@param {Number} high bits (32)
or
@param {String|Number} integer as a string | integer as a number
@param {Number|Undefined} radix (optional, default=10)
@return | [
"Represents",
"an",
"unsigned",
"64",
"bits",
"integer"
]
| b93425a8f1b98bab8e357cede34ed491125c0d8b | https://github.com/pierrec/js-cuint/blob/b93425a8f1b98bab8e357cede34ed491125c0d8b/build/uint64.js#L35-L47 | train |
pierrec/js-cuint | build/uint64.js | fromBits | function fromBits (a00, a16, a32, a48) {
if (typeof a32 == 'undefined') {
this._a00 = a00 & 0xFFFF
this._a16 = a00 >>> 16
this._a32 = a16 & 0xFFFF
this._a48 = a16 >>> 16
return this
}
this._a00 = a00 | 0
this._a16 = a16 | 0
this._a32 = a32 | 0
this._a48 = a48 | 0
return this
} | javascript | function fromBits (a00, a16, a32, a48) {
if (typeof a32 == 'undefined') {
this._a00 = a00 & 0xFFFF
this._a16 = a00 >>> 16
this._a32 = a16 & 0xFFFF
this._a48 = a16 >>> 16
return this
}
this._a00 = a00 | 0
this._a16 = a16 | 0
this._a32 = a32 | 0
this._a48 = a48 | 0
return this
} | [
"function",
"fromBits",
"(",
"a00",
",",
"a16",
",",
"a32",
",",
"a48",
")",
"{",
"if",
"(",
"typeof",
"a32",
"==",
"'undefined'",
")",
"{",
"this",
".",
"_a00",
"=",
"a00",
"&",
"0xFFFF",
"this",
".",
"_a16",
"=",
"a00",
">>>",
"16",
"this",
".",
"_a32",
"=",
"a16",
"&",
"0xFFFF",
"this",
".",
"_a48",
"=",
"a16",
">>>",
"16",
"return",
"this",
"}",
"this",
".",
"_a00",
"=",
"a00",
"|",
"0",
"this",
".",
"_a16",
"=",
"a16",
"|",
"0",
"this",
".",
"_a32",
"=",
"a32",
"|",
"0",
"this",
".",
"_a48",
"=",
"a48",
"|",
"0",
"return",
"this",
"}"
]
| Set the current _UINT64_ object with its low and high bits
@method fromBits
@param {Number} first low bits (8)
@param {Number} second low bits (8)
@param {Number} first high bits (8)
@param {Number} second high bits (8)
or
@param {Number} low bits (32)
@param {Number} high bits (32)
@return ThisExpression | [
"Set",
"the",
"current",
"_UINT64_",
"object",
"with",
"its",
"low",
"and",
"high",
"bits"
]
| b93425a8f1b98bab8e357cede34ed491125c0d8b | https://github.com/pierrec/js-cuint/blob/b93425a8f1b98bab8e357cede34ed491125c0d8b/build/uint64.js#L61-L76 | train |
pierrec/js-cuint | build/uint64.js | fromString | function fromString (s, radix) {
radix = radix || 10
this._a00 = 0
this._a16 = 0
this._a32 = 0
this._a48 = 0
/*
In Javascript, bitwise operators only operate on the first 32 bits
of a number, even though parseInt() encodes numbers with a 53 bits
mantissa.
Therefore UINT64(<Number>) can only work on 32 bits.
The radix maximum value is 36 (as per ECMA specs) (26 letters + 10 digits)
maximum input value is m = 32bits as 1 = 2^32 - 1
So the maximum substring length n is:
36^(n+1) - 1 = 2^32 - 1
36^(n+1) = 2^32
(n+1)ln(36) = 32ln(2)
n = 32ln(2)/ln(36) - 1
n = 5.189644915687692
n = 5
*/
var radixUint = radixPowerCache[radix] || new UINT64( Math.pow(radix, 5) )
for (var i = 0, len = s.length; i < len; i += 5) {
var size = Math.min(5, len - i)
var value = parseInt( s.slice(i, i + size), radix )
this.multiply(
size < 5
? new UINT64( Math.pow(radix, size) )
: radixUint
)
.add( new UINT64(value) )
}
return this
} | javascript | function fromString (s, radix) {
radix = radix || 10
this._a00 = 0
this._a16 = 0
this._a32 = 0
this._a48 = 0
/*
In Javascript, bitwise operators only operate on the first 32 bits
of a number, even though parseInt() encodes numbers with a 53 bits
mantissa.
Therefore UINT64(<Number>) can only work on 32 bits.
The radix maximum value is 36 (as per ECMA specs) (26 letters + 10 digits)
maximum input value is m = 32bits as 1 = 2^32 - 1
So the maximum substring length n is:
36^(n+1) - 1 = 2^32 - 1
36^(n+1) = 2^32
(n+1)ln(36) = 32ln(2)
n = 32ln(2)/ln(36) - 1
n = 5.189644915687692
n = 5
*/
var radixUint = radixPowerCache[radix] || new UINT64( Math.pow(radix, 5) )
for (var i = 0, len = s.length; i < len; i += 5) {
var size = Math.min(5, len - i)
var value = parseInt( s.slice(i, i + size), radix )
this.multiply(
size < 5
? new UINT64( Math.pow(radix, size) )
: radixUint
)
.add( new UINT64(value) )
}
return this
} | [
"function",
"fromString",
"(",
"s",
",",
"radix",
")",
"{",
"radix",
"=",
"radix",
"||",
"10",
"this",
".",
"_a00",
"=",
"0",
"this",
".",
"_a16",
"=",
"0",
"this",
".",
"_a32",
"=",
"0",
"this",
".",
"_a48",
"=",
"0",
"var",
"radixUint",
"=",
"radixPowerCache",
"[",
"radix",
"]",
"||",
"new",
"UINT64",
"(",
"Math",
".",
"pow",
"(",
"radix",
",",
"5",
")",
")",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"s",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"5",
")",
"{",
"var",
"size",
"=",
"Math",
".",
"min",
"(",
"5",
",",
"len",
"-",
"i",
")",
"var",
"value",
"=",
"parseInt",
"(",
"s",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"size",
")",
",",
"radix",
")",
"this",
".",
"multiply",
"(",
"size",
"<",
"5",
"?",
"new",
"UINT64",
"(",
"Math",
".",
"pow",
"(",
"radix",
",",
"size",
")",
")",
":",
"radixUint",
")",
".",
"add",
"(",
"new",
"UINT64",
"(",
"value",
")",
")",
"}",
"return",
"this",
"}"
]
| Set the current _UINT64_ object from a string
@method fromString
@param {String} integer as a string
@param {Number} radix (optional, default=10)
@return ThisExpression | [
"Set",
"the",
"current",
"_UINT64_",
"object",
"from",
"a",
"string"
]
| b93425a8f1b98bab8e357cede34ed491125c0d8b | https://github.com/pierrec/js-cuint/blob/b93425a8f1b98bab8e357cede34ed491125c0d8b/build/uint64.js#L102-L139 | train |
RackHD/on-tasks | lib/jobs/switch-node-relations.js | _findMatchingMac | function _findMatchingMac(nodeLldpData, lldpMacList) {
var relationsList = {};
return Promise.all(
_.forEach(_.keys(nodeLldpData.data), function (ethPort) {
//validate mac first
var lldpMac = catalogSearch.getPath(nodeLldpData.data[ethPort], 'chassis.mac');
if (!lldpMac) {
throw new Error('cant find mac address in lldp data for node ' +
nodeLldpData.node + ' port ' + ethPort);
}
if (_validateMacStrFormat(lldpMac)) {
lldpMac = _adjustMacStrFormat(lldpMac);
if (lldpMacList.indexOf(lldpMac) >= 0) {
var singleEntry = {
destMac: nodeLldpData.data[ethPort].chassis.mac,
destPort: nodeLldpData.data[ethPort].port.ifname
};
relationsList[ethPort] = singleEntry;
}
} else {
throw new Error('mac: ' + lldpMac + ' bad format',
+nodeLldpData.node + ' port ' + ethPort);
}
}))
.then(function () {
return Promise.resolve(relationsList);
});
} | javascript | function _findMatchingMac(nodeLldpData, lldpMacList) {
var relationsList = {};
return Promise.all(
_.forEach(_.keys(nodeLldpData.data), function (ethPort) {
//validate mac first
var lldpMac = catalogSearch.getPath(nodeLldpData.data[ethPort], 'chassis.mac');
if (!lldpMac) {
throw new Error('cant find mac address in lldp data for node ' +
nodeLldpData.node + ' port ' + ethPort);
}
if (_validateMacStrFormat(lldpMac)) {
lldpMac = _adjustMacStrFormat(lldpMac);
if (lldpMacList.indexOf(lldpMac) >= 0) {
var singleEntry = {
destMac: nodeLldpData.data[ethPort].chassis.mac,
destPort: nodeLldpData.data[ethPort].port.ifname
};
relationsList[ethPort] = singleEntry;
}
} else {
throw new Error('mac: ' + lldpMac + ' bad format',
+nodeLldpData.node + ' port ' + ethPort);
}
}))
.then(function () {
return Promise.resolve(relationsList);
});
} | [
"function",
"_findMatchingMac",
"(",
"nodeLldpData",
",",
"lldpMacList",
")",
"{",
"var",
"relationsList",
"=",
"{",
"}",
";",
"return",
"Promise",
".",
"all",
"(",
"_",
".",
"forEach",
"(",
"_",
".",
"keys",
"(",
"nodeLldpData",
".",
"data",
")",
",",
"function",
"(",
"ethPort",
")",
"{",
"var",
"lldpMac",
"=",
"catalogSearch",
".",
"getPath",
"(",
"nodeLldpData",
".",
"data",
"[",
"ethPort",
"]",
",",
"'chassis.mac'",
")",
";",
"if",
"(",
"!",
"lldpMac",
")",
"{",
"throw",
"new",
"Error",
"(",
"'cant find mac address in lldp data for node '",
"+",
"nodeLldpData",
".",
"node",
"+",
"' port '",
"+",
"ethPort",
")",
";",
"}",
"if",
"(",
"_validateMacStrFormat",
"(",
"lldpMac",
")",
")",
"{",
"lldpMac",
"=",
"_adjustMacStrFormat",
"(",
"lldpMac",
")",
";",
"if",
"(",
"lldpMacList",
".",
"indexOf",
"(",
"lldpMac",
")",
">=",
"0",
")",
"{",
"var",
"singleEntry",
"=",
"{",
"destMac",
":",
"nodeLldpData",
".",
"data",
"[",
"ethPort",
"]",
".",
"chassis",
".",
"mac",
",",
"destPort",
":",
"nodeLldpData",
".",
"data",
"[",
"ethPort",
"]",
".",
"port",
".",
"ifname",
"}",
";",
"relationsList",
"[",
"ethPort",
"]",
"=",
"singleEntry",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'mac: '",
"+",
"lldpMac",
"+",
"' bad format'",
",",
"+",
"nodeLldpData",
".",
"node",
"+",
"' port '",
"+",
"ethPort",
")",
";",
"}",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"relationsList",
")",
";",
"}",
")",
";",
"}"
]
| Iterate through switch mac addresses list
for a match in nodes lldp catalog
return a promise | [
"Iterate",
"through",
"switch",
"mac",
"addresses",
"list",
"for",
"a",
"match",
"in",
"nodes",
"lldp",
"catalog",
"return",
"a",
"promise"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/switch-node-relations.js#L190-L217 | train |
RackHD/on-tasks | lib/jobs/switch-node-relations.js | _adjustMacStrFormat | function _adjustMacStrFormat(macString) {
macString = macString.toLowerCase();
var mac = macString.split(':');
macString = '';
for (var i = 0; i < mac.length; i += 1) {
if (mac[i].length === 1) {
mac[i] = '0' + mac[i];
}
macString += mac[i];
}
return macString;
} | javascript | function _adjustMacStrFormat(macString) {
macString = macString.toLowerCase();
var mac = macString.split(':');
macString = '';
for (var i = 0; i < mac.length; i += 1) {
if (mac[i].length === 1) {
mac[i] = '0' + mac[i];
}
macString += mac[i];
}
return macString;
} | [
"function",
"_adjustMacStrFormat",
"(",
"macString",
")",
"{",
"macString",
"=",
"macString",
".",
"toLowerCase",
"(",
")",
";",
"var",
"mac",
"=",
"macString",
".",
"split",
"(",
"':'",
")",
";",
"macString",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"mac",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"mac",
"[",
"i",
"]",
".",
"length",
"===",
"1",
")",
"{",
"mac",
"[",
"i",
"]",
"=",
"'0'",
"+",
"mac",
"[",
"i",
"]",
";",
"}",
"macString",
"+=",
"mac",
"[",
"i",
"]",
";",
"}",
"return",
"macString",
";",
"}"
]
| Adjust mac Address format to 2 hex digits
return mac address string | [
"Adjust",
"mac",
"Address",
"format",
"to",
"2",
"hex",
"digits",
"return",
"mac",
"address",
"string"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/switch-node-relations.js#L232-L243 | train |
stadt-bielefeld/wms-downloader | src/helper/cropTile.js | cropTile | function cropTile(oldFile, newFile, tileSizePx, gutterSizePx, callback) {
if (oldFile.endsWith('.svg') && newFile.endsWith('.svg')) {
// vector images
fs.readFile(oldFile, { encoding: 'utf8' }, (err, content) => {
if (err) {
callback(err);
} else {
const parser = new xml2js.Parser({ async: false });
parser.parseString(content, (err, result) => {
if (err) {
callback(err);
} else {
const builder = new xml2js.Builder();
try {
const viewBox = result.svg['$'].viewBox.split(' ');
for (let i = 0; i < viewBox.length; i++) {
viewBox[i] = parseFloat(viewBox[i]);
}
viewBox[0] = viewBox[0] + gutterSizePx;
viewBox[1] = viewBox[1] + gutterSizePx;
viewBox[2] = viewBox[2] - gutterSizePx * 2;
viewBox[3] = viewBox[3] - gutterSizePx * 2;
result.svg['$'].viewBox = viewBox[0] + ' ' + viewBox[1] + ' ' + viewBox[2] + ' ' + viewBox[3];
const xml = builder.buildObject(result);
fs.writeFile(newFile, xml, { encoding: 'utf8' }, callback);
} catch (err) {
callback(err);
}
}
});
}
});
} else {
// raster images (and from vector to raster image as well)
let inExt = oldFile.substring(oldFile.length - 3, oldFile.length);
let outExt = newFile.substring(newFile.length - 3, newFile.length);
/*
* The conversion from to jpg and tif is wrong by default. The
* transparency will convert to black. It is correct, if the transparency will
* convert to white.
*
* That will fixed with the following code.
*/
if ((inExt == '' && outExt == 'jpg') || (inExt == '' && outExt == 'tif')) {
gm(oldFile).flatten().background('white').crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
} else {
gm(oldFile).crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
}
}
} | javascript | function cropTile(oldFile, newFile, tileSizePx, gutterSizePx, callback) {
if (oldFile.endsWith('.svg') && newFile.endsWith('.svg')) {
// vector images
fs.readFile(oldFile, { encoding: 'utf8' }, (err, content) => {
if (err) {
callback(err);
} else {
const parser = new xml2js.Parser({ async: false });
parser.parseString(content, (err, result) => {
if (err) {
callback(err);
} else {
const builder = new xml2js.Builder();
try {
const viewBox = result.svg['$'].viewBox.split(' ');
for (let i = 0; i < viewBox.length; i++) {
viewBox[i] = parseFloat(viewBox[i]);
}
viewBox[0] = viewBox[0] + gutterSizePx;
viewBox[1] = viewBox[1] + gutterSizePx;
viewBox[2] = viewBox[2] - gutterSizePx * 2;
viewBox[3] = viewBox[3] - gutterSizePx * 2;
result.svg['$'].viewBox = viewBox[0] + ' ' + viewBox[1] + ' ' + viewBox[2] + ' ' + viewBox[3];
const xml = builder.buildObject(result);
fs.writeFile(newFile, xml, { encoding: 'utf8' }, callback);
} catch (err) {
callback(err);
}
}
});
}
});
} else {
// raster images (and from vector to raster image as well)
let inExt = oldFile.substring(oldFile.length - 3, oldFile.length);
let outExt = newFile.substring(newFile.length - 3, newFile.length);
/*
* The conversion from to jpg and tif is wrong by default. The
* transparency will convert to black. It is correct, if the transparency will
* convert to white.
*
* That will fixed with the following code.
*/
if ((inExt == '' && outExt == 'jpg') || (inExt == '' && outExt == 'tif')) {
gm(oldFile).flatten().background('white').crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
} else {
gm(oldFile).crop(tileSizePx, tileSizePx, gutterSizePx, gutterSizePx).write(newFile, (err) => {
callback(err);
});
}
}
} | [
"function",
"cropTile",
"(",
"oldFile",
",",
"newFile",
",",
"tileSizePx",
",",
"gutterSizePx",
",",
"callback",
")",
"{",
"if",
"(",
"oldFile",
".",
"endsWith",
"(",
"'.svg'",
")",
"&&",
"newFile",
".",
"endsWith",
"(",
"'.svg'",
")",
")",
"{",
"fs",
".",
"readFile",
"(",
"oldFile",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
",",
"(",
"err",
",",
"content",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"const",
"parser",
"=",
"new",
"xml2js",
".",
"Parser",
"(",
"{",
"async",
":",
"false",
"}",
")",
";",
"parser",
".",
"parseString",
"(",
"content",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"const",
"builder",
"=",
"new",
"xml2js",
".",
"Builder",
"(",
")",
";",
"try",
"{",
"const",
"viewBox",
"=",
"result",
".",
"svg",
"[",
"'$'",
"]",
".",
"viewBox",
".",
"split",
"(",
"' '",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"viewBox",
".",
"length",
";",
"i",
"++",
")",
"{",
"viewBox",
"[",
"i",
"]",
"=",
"parseFloat",
"(",
"viewBox",
"[",
"i",
"]",
")",
";",
"}",
"viewBox",
"[",
"0",
"]",
"=",
"viewBox",
"[",
"0",
"]",
"+",
"gutterSizePx",
";",
"viewBox",
"[",
"1",
"]",
"=",
"viewBox",
"[",
"1",
"]",
"+",
"gutterSizePx",
";",
"viewBox",
"[",
"2",
"]",
"=",
"viewBox",
"[",
"2",
"]",
"-",
"gutterSizePx",
"*",
"2",
";",
"viewBox",
"[",
"3",
"]",
"=",
"viewBox",
"[",
"3",
"]",
"-",
"gutterSizePx",
"*",
"2",
";",
"result",
".",
"svg",
"[",
"'$'",
"]",
".",
"viewBox",
"=",
"viewBox",
"[",
"0",
"]",
"+",
"' '",
"+",
"viewBox",
"[",
"1",
"]",
"+",
"' '",
"+",
"viewBox",
"[",
"2",
"]",
"+",
"' '",
"+",
"viewBox",
"[",
"3",
"]",
";",
"const",
"xml",
"=",
"builder",
".",
"buildObject",
"(",
"result",
")",
";",
"fs",
".",
"writeFile",
"(",
"newFile",
",",
"xml",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
",",
"callback",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"let",
"inExt",
"=",
"oldFile",
".",
"substring",
"(",
"oldFile",
".",
"length",
"-",
"3",
",",
"oldFile",
".",
"length",
")",
";",
"let",
"outExt",
"=",
"newFile",
".",
"substring",
"(",
"newFile",
".",
"length",
"-",
"3",
",",
"newFile",
".",
"length",
")",
";",
"if",
"(",
"(",
"inExt",
"==",
"''",
"&&",
"outExt",
"==",
"'jpg'",
")",
"||",
"(",
"inExt",
"==",
"''",
"&&",
"outExt",
"==",
"'tif'",
")",
")",
"{",
"gm",
"(",
"oldFile",
")",
".",
"flatten",
"(",
")",
".",
"background",
"(",
"'white'",
")",
".",
"crop",
"(",
"tileSizePx",
",",
"tileSizePx",
",",
"gutterSizePx",
",",
"gutterSizePx",
")",
".",
"write",
"(",
"newFile",
",",
"(",
"err",
")",
"=>",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"gm",
"(",
"oldFile",
")",
".",
"crop",
"(",
"tileSizePx",
",",
"tileSizePx",
",",
"gutterSizePx",
",",
"gutterSizePx",
")",
".",
"write",
"(",
"newFile",
",",
"(",
"err",
")",
"=>",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
]
| Crops a tile with the gutter size.
@param {String} oldFile File to be crop
@param {String} newFile New cropped file
@param {Number} tileSizePx Size of the new tile
@param {Number} gutterSizePx Size of gutter in the old tile
@param {Function} callback function(err) {}
@example
const oldFile = __dirname + '/cropTileOld.png';
const newFile = __dirname + '/cropTileNew.png';
const tileSizePx = 1000; // Size of the new tile
const gutterSizePx = 150;
cropTile(oldFile, newFile, tileSizePx, gutterSizePx, (err)=>{
if(err){
console.error(err);
}else{
console.log('Tile cropped!');
}
}); | [
"Crops",
"a",
"tile",
"with",
"the",
"gutter",
"size",
"."
]
| 8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d | https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/cropTile.js#L29-L95 | train |
RackHD/on-tasks | lib/jobs/wait-sel-events-job.js | _verifyFiltering | function _verifyFiltering(filters, counts, data) {
var reading = data.data.alert.reading;
if (_.isEmpty(reading)) {
return false;
}
var filter = filters[0];
var count = counts[0];
var matched = true;
_.map(filter, function(value, key){
if (data.data.alert.reading[key] !== value) {
matched = false;
}
});
if (matched) {
count = count - 1;
if (count === 0){
filters.shift();
counts.shift();
} else {
counts[0] = count;
}
}
if (_.isEmpty(filters)){
return true;
}
return false;
} | javascript | function _verifyFiltering(filters, counts, data) {
var reading = data.data.alert.reading;
if (_.isEmpty(reading)) {
return false;
}
var filter = filters[0];
var count = counts[0];
var matched = true;
_.map(filter, function(value, key){
if (data.data.alert.reading[key] !== value) {
matched = false;
}
});
if (matched) {
count = count - 1;
if (count === 0){
filters.shift();
counts.shift();
} else {
counts[0] = count;
}
}
if (_.isEmpty(filters)){
return true;
}
return false;
} | [
"function",
"_verifyFiltering",
"(",
"filters",
",",
"counts",
",",
"data",
")",
"{",
"var",
"reading",
"=",
"data",
".",
"data",
".",
"alert",
".",
"reading",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"reading",
")",
")",
"{",
"return",
"false",
";",
"}",
"var",
"filter",
"=",
"filters",
"[",
"0",
"]",
";",
"var",
"count",
"=",
"counts",
"[",
"0",
"]",
";",
"var",
"matched",
"=",
"true",
";",
"_",
".",
"map",
"(",
"filter",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"data",
".",
"data",
".",
"alert",
".",
"reading",
"[",
"key",
"]",
"!==",
"value",
")",
"{",
"matched",
"=",
"false",
";",
"}",
"}",
")",
";",
"if",
"(",
"matched",
")",
"{",
"count",
"=",
"count",
"-",
"1",
";",
"if",
"(",
"count",
"===",
"0",
")",
"{",
"filters",
".",
"shift",
"(",
")",
";",
"counts",
".",
"shift",
"(",
")",
";",
"}",
"else",
"{",
"counts",
"[",
"0",
"]",
"=",
"count",
";",
"}",
"}",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"filters",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Validate events data against filtering conditions.
Alert filters will be validated by indexing sequence.
Each alert filter can includes an attribute "count" to indicate how many times this event
should happen continuously
@param {Array} filters: an array of alert filters in sequence
@param {Array} counts: an array of alert filters counting in sequence
@param {Object} data: AMQP data received
@return {Boolean}: true if all filtering conditions are met, false otherwise. | [
"Validate",
"events",
"data",
"against",
"filtering",
"conditions",
".",
"Alert",
"filters",
"will",
"be",
"validated",
"by",
"indexing",
"sequence",
".",
"Each",
"alert",
"filter",
"can",
"includes",
"an",
"attribute",
"count",
"to",
"indicate",
"how",
"many",
"times",
"this",
"event",
"should",
"happen",
"continuously"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/wait-sel-events-job.js#L180-L206 | train |
RackHD/on-tasks | lib/utils/job-utils/os-repo-tool.js | _extractEsxBootCfgValue | function _extractEsxBootCfgValue(data, pattern) {
var pos = data.indexOf(pattern);
if (pos >= 0) {
pos += pattern.length;
var lineEndPos = data.indexOf('\n', pos);
if (lineEndPos >= 0) {
return data.substring(pos, lineEndPos);
}
}
return '';
} | javascript | function _extractEsxBootCfgValue(data, pattern) {
var pos = data.indexOf(pattern);
if (pos >= 0) {
pos += pattern.length;
var lineEndPos = data.indexOf('\n', pos);
if (lineEndPos >= 0) {
return data.substring(pos, lineEndPos);
}
}
return '';
} | [
"function",
"_extractEsxBootCfgValue",
"(",
"data",
",",
"pattern",
")",
"{",
"var",
"pos",
"=",
"data",
".",
"indexOf",
"(",
"pattern",
")",
";",
"if",
"(",
"pos",
">=",
"0",
")",
"{",
"pos",
"+=",
"pattern",
".",
"length",
";",
"var",
"lineEndPos",
"=",
"data",
".",
"indexOf",
"(",
"'\\n'",
",",
"\\n",
")",
";",
"pos",
"}",
"if",
"(",
"lineEndPos",
">=",
"0",
")",
"{",
"return",
"data",
".",
"substring",
"(",
"pos",
",",
"lineEndPos",
")",
";",
"}",
"}"
]
| Extract the value from a whole data by key.
@param {String} data - The whole data that cotains all key-value pairs
@param {String} key - The key for target value including the key-value delimiter
@return {String} The extracted value; If key is not exsited, return empty.
@example
// return "12xyz - pmq"
_extractEsxiBootCfgValue("key1=abc def\nkey2=12xyz - pmq\nkey3=pmq,abq", "key2=") | [
"Extract",
"the",
"value",
"from",
"a",
"whole",
"data",
"by",
"key",
"."
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/utils/job-utils/os-repo-tool.js#L90-L100 | train |
RackHD/on-tasks | lib/jobs/redfish-enable-alerts-job.js | RestJob | function RestJob(options, context, taskId){
var self = this;
self.options = options;
self.context = context;
RestJob.super_.call(self, logger, options, context, taskId);
self.restClient = new HttpTool();
} | javascript | function RestJob(options, context, taskId){
var self = this;
self.options = options;
self.context = context;
RestJob.super_.call(self, logger, options, context, taskId);
self.restClient = new HttpTool();
} | [
"function",
"RestJob",
"(",
"options",
",",
"context",
",",
"taskId",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"options",
"=",
"options",
";",
"self",
".",
"context",
"=",
"context",
";",
"RestJob",
".",
"super_",
".",
"call",
"(",
"self",
",",
"logger",
",",
"options",
",",
"context",
",",
"taskId",
")",
";",
"self",
".",
"restClient",
"=",
"new",
"HttpTool",
"(",
")",
";",
"}"
]
| The interface that runs Rest Job from tasks
@constructor | [
"The",
"interface",
"that",
"runs",
"Rest",
"Job",
"from",
"tasks"
]
| 18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea | https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/lib/jobs/redfish-enable-alerts-job.js#L37-L44 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.