language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Queue {
constructor() {
this.front = null;
this.end = null;
this.queue = null;
this.length = 0;
}
get size() {
return this.length;
}
enqueue(element) {
const newNode = new ListNode(element);
if (!this.queue) {
this.front = newNode;
this.end = newNode;
this.queue = newNode;
} else {
newNode.next = this.queue;
this.queue = newNode;
this.end = newNode;
}
this.length++;
return this.queue;
}
dequeue() {
let outElem = null;
if (this.queue) {
outElem = this.front.value;
this.front = this.queue.next;
this.queue = this.front;
this.length--;
}
return outElem;
}
} |
JavaScript | class NrButtonController {
/**
*
* @returns {NrTag|string}
*/
static get nrName () {
return NrTag.BUTTON;
}
/**
*
* @returns {typeof NrButtonController}
*/
get Class () {
return NrButtonController;
}
/**
*
* @returns {NrTag|string}
*/
get nrName () {
return this.Class.nrName;
}
/**
*
* @returns {Object.<string, string>}
*/
static getComponentBindings () {
return {
bindType: `@?${NrAttribute.TYPE}`
, __style: `@?${NrAttribute.STYLE}`
, __id: `@?${NrAttribute.ID}`
, __name: `@?${NrAttribute.NAME}`
, __label: `@?${NrAttribute.LABEL}`
, __icon: `@?${NrAttribute.ICON}`
, __click: `&?${NrAttribute.BUTTON_CLICK}`
, __enabled: `&?${NrAttribute.ENABLED}`
, __nrModel: `<?${NrAttribute.MODEL}`
};
}
/**
*
* @returns {Object.<string, string>}
*/
static getComponentRequire () {
return {};
}
/**
*
* @param template {string}
* @returns {angular.IComponentOptions}
*/
static getComponentConfig (template) {
// noinspection JSValidateTypes
return {
template
, bindings: this.getComponentBindings()
, require: this.getComponentRequire()
, controller: this
};
}
/**
*
* @param $scope {angular.IScope}
* @param $attrs {angular.IAttributes}
* @ngInject
*/
constructor ($scope, $attrs) {
'ngInject';
/**
*
* @member {boolean}
* @private
*/
this._hasTypeAttribute = !!$attrs[NrAttribute.TYPE];
/**
*
* @member {boolean}
* @private
*/
this._hasStyleAttribute = !!$attrs[NrAttribute.STYLE];
/**
*
* @member {boolean}
* @private
*/
this._hasIdAttribute = !!$attrs[NrAttribute.ID];
/**
*
* @member {boolean}
* @private
*/
this._hasNameAttribute = !!$attrs[NrAttribute.NAME];
/**
*
* @member {boolean}
* @private
*/
this._hasLabelAttribute = !!$attrs[NrAttribute.LABEL];
/**
*
* @member {boolean}
* @private
*/
this._hasIconAttribute = !!$attrs[NrAttribute.ICON];
/**
*
* @member {boolean}
* @private
*/
this._hasClickAttribute = !!$attrs[NrAttribute.BUTTON_CLICK];
/**
*
* @member {boolean}
* @private
*/
this._hasEnabledAttribute = !!$attrs[NrAttribute.ENABLED];
/**
*
* @member {angular.IScope}
* @private
*/
this._$scope = $scope;
/**
*
* @member {NrIconValue|string|undefined}
* @private
*/
this.__style = undefined;
/**
*
* @member {string|undefined}
* @private
*/
this.__id = undefined;
/**
*
* @member {string|undefined}
* @private
*/
this.__name = undefined;
/**
*
* @member {boolean|undefined}
* @private
*/
this.__enabled = undefined;
/**
*
* @member {string|undefined}
* @private
*/
this.__label = undefined;
/**
*
* @member {string|undefined}
* @private
*/
this.__icon = undefined;
/**
*
* @member {Function|function|undefined}
* @private
*/
this.__click = undefined;
/**
* Optional button model
* @member {NrButton|undefined}
* @private
*/
this.__nrModel = undefined;
}
/**
*
* @returns {Object}
*/
getClasses () {
return {
"nr-icon": this.style === NrButton.Style.ICON || !this.label,
"nr-submit": this.style === NrButton.Style.SUBMIT,
"nr-cancel": this.style === NrButton.Style.CANCEL,
"nr-default": this.style === NrButton.Style.DEFAULT,
"nr-accept": this.style === NrButton.Style.ACCEPT,
"nr-disabled": !this.enabled
};
}
getButtonType () {
return this.style === NrButton.Style.SUBMIT ? 'submit' : 'button';
}
/**
*
* @param $event
* @return {*}
*/
onClick ($event) {
if ( this._hasClickAttribute && _.isFunction(this.__click)) {
nrLog.trace(`.onClick(): Using nr-click attribute`);
return this.__click({nrButton: this, $event});
} else {
this._$scope.$emit(NrEventName.BUTTON_CLICK, this);
nrLog.trace(`.onClick(): No click action configured; emitted an event BUTTON_CLICK "${NrEventName.BUTTON_CLICK}"`);
}
}
/**
*
* @returns {boolean}
*/
hasIcon () {
if (this._hasIconAttribute) {
return this.__icon !== undefined;
}
return _.has(this.__nrModel, 'icon.value') !== undefined;
}
/**
*
* @returns {NrButton|undefined}
*/
get nrModel () {
return this.__nrModel;
}
/**
*
* Use `.nrModel`
*
* @returns {NrButton|undefined}
* @deprecated
*/
get model () {
return this.__nrModel;
}
/**
*
* @returns {boolean}
*/
get enabled () {
if (this._hasEnabledAttribute) {
return this.__enabled !== false;
} else {
return _.get(this.__nrModel, 'enabled') !== false;
}
}
/**
*
* @returns {string}
*/
get style () {
if (this._hasStyleAttribute) {
return this.__style;
} else {
return _.get(this.__nrModel, 'style');
}
}
/**
*
* **DEPRECATED:** Use `$ctrl.style` instead.
*
* @returns {string}
* @deprecated
*/
get type () {
return this.style;
}
/**
*
* @returns {string}
*/
get name () {
if (this._hasNameAttribute) {
return this.__name;
} else {
return _.get(this.__nrModel, 'name');
}
}
/**
*
* @returns {string}
*/
get id () {
if (this._hasIdAttribute) {
return this.__id;
} else {
return _.get(this.__nrModel, 'id');
}
}
/**
*
* @returns {NrIconValue|string}
*/
get icon () {
if (this._hasIconAttribute) {
return this.__icon;
} else {
return _.get(this.__nrModel, 'icon.value');
}
}
/**
*
* @returns {string}
*/
get label () {
if (this._hasLabelAttribute) {
return this.__label;
} else {
return _.get(this.__nrModel, 'label');
}
}
/**
*
* @returns {string}
*/
get bindType () {
return this.__style;
}
/**
*
* @param value {string}
*/
set bindType (value) {
if (this.__style !== value) {
this.__style = value;
}
}
$onInit () {
if (this._hasTypeAttribute) {
nrLog.warn(`Warning! nr-type attribute for nr-button component is obsolete. Use nr-style instead.`);
}
}
} |
JavaScript | class GirderVtkReaderRegistry {
// Singleton instance
static _instance;
/**
* Singleton instance getter.
*/
static get instance() {
if (!GirderVtkReaderRegistry._instance) {
GirderVtkReaderRegistry._instance = new GirderVtkReaderRegistry();
}
return GirderVtkReaderRegistry._instance;
}
constructor() {
// Two-level map from model type -> resource -> class
this._readerMap = new Map();
}
/**
* Add a reader to the registry.
* @param {string} modelType - The type of model that the reader supports.
* @param {string} resourceType - The Girder resource type that the reader supports.
* @param {class} readerClass - A GirderVtkReader class.
*/
addReader(modelType, resourceType, readerClass) {
modelType = modelType.toLowerCase();
if (!this._readerMap.has(modelType)) {
this._readerMap.set(modelType, new Map());
}
const resourceMap = this._readerMap.get(modelType);
resourceMap.set(resourceType, readerClass);
return this;
}
/**
* Look up a reader in the registry.
* @param {string} modelType - The type of model that the reader should support.
* @param {string} resourceType - The Girder resource that the reader should support.
* @returns {object} A new instance of a GirderVtkReader class, or null.
*/
getReader(modelType, resourceType) {
modelType = modelType.toLowerCase();
const resourceMap = this._readerMap.get(modelType);
if (!resourceMap) {
return null;
}
const readerClass = resourceMap.get(resourceType);
if (!readerClass) {
return null;
}
return new readerClass(); // eslint-disable-line new-cap
}
/**
* Check whether a reader for the given model type is registered.
* @param {} modelType - The type of model that the reader should support.
*/
hasReader(modelType) {
modelType = modelType.toLowerCase();
return this._readerMap.has(modelType);
}
} |
JavaScript | class App extends React.Component{
render(){
return (
<div className="hello-react-daily-shortcut">
<ReactDailyShortcut />
</div>
);
}
} |
JavaScript | class Video {
/**
* Create a video object which controls the video device.
* @param {Object} experiment - The experiment to which the video belongs.
* @param {String} src - The video source name.
*/
constructor(experiment, source) {
// Set class parameter properties.
this._experiment = experiment;
// Set the class public properties.
this.audio = true;
this.duration = 'keypress';
this.full_screen = false;
// Set the class pivate properties.
this._playing = false;
this._script = null;
// Create the video instance
if (source !== null) {
// Set the video object.
this._video = source.data;
// create a video texture from the video.
this._texture = new PIXI.Texture.fromVideo(source.data);
// create a new Sprite using the video texture (yes it's that easy)
this._videoSprite = new PIXI.Sprite(this._texture);
this._video.pause();
// Set the event anchors.
this._video.onended = this._experiment._runner._events._videoEnded.bind(this);
this._video.onplay = this._experiment._runner._events._videoPlay.bind(this);
}
}
/** Update the video rendering. */
_update() {
if (this._playing === true) {
// Update the renderer.
this._experiment._runner._renderer.render(this._videoSprite);
// execute script.
if ((this._script !== null) && (this._event_handler_always === true)) {
// Start the parser
this._experiment._runner._pythonParser._run(null, this._script);
}
}
}
/** Play the actual video. */
play() {
// Enable the video playing.
this._video.play();
// Set the volume
this._video.volume = (this.audio === true) ? 1 : 0;
// Check if the video must be scaled.
if (this.full_screen === true) {
this._videoSprite.width = this._experiment._runner._renderer.width;
this._videoSprite.height = this._experiment._runner._renderer.height;
}
// Render the first frame.
this._experiment._runner._renderer.render(this._videoSprite);
// Set the play toggle.
this._playing = true;
}
/** Stop playing the video. */
stop() {
// Pause the actual sound.
this._video.pause();
this._playing = false;
}
/** Set the blocking of the sound. */
wait() {
this._experiment._runner._events._run(-1, constants.RESPONSE_VIDEO, []);
}
} |
JavaScript | class Preset extends ResponseConfigurator {
/**
* Create a new preset instance that can be configured
* in the same manner than a regular fixture
*
* @version 1.0.0
* @since 2.0.0
* @param {Server} server Server instance
* @param {String} name Preset name
* @param {Object} [preset] Preset configuration object
*/
constructor(server, name, preset = {}) {
super(server);
if (!name) throw new Error('You must provide a name to the preset');
this.name = name;
if (preset) {
if (!(preset instanceof Object)) throw new Error('Preset options must be provided as an object');
this.set(preset);
}
}
/**
* Presets can only handle a default response
* @version 1.0.0
* @since 2.0.0
* @return {Object} Current response configuration
*/
_getCurrentResponseSet() {
return this._any;
}
/**
* Register/update the preset in the global pool. This made the preset available
* into all server's instances created *from* the registration
* @version 1.0.0
* @since 2.2.0
* @return {Preset} Self for chaining
*/
register() {
presets[this.name] = Object.assign({}, this._any);
return this;
}
/**
* Unregister the preset from the global pool.
*
* @version 1.0.0
* @since 2.2.0
* @return {Preset} Self for chaining
*/
unregister() {
delete presets[this.name];
return this;
}
/**
* Remove the preset from the server's instance pool
*
* If the preset is also globally registered, it won't be removed from the
* global pool
*
* @version 1.0.0
* @since 2.2.0
* @return {Preset} self for chaining
*/
remove() {
delete this.server._presets[this.name];
return this;
}
} |
JavaScript | class PublicKeyEd25519 extends PublicKey {
constructor(value) {
super(value, 32);
}
/**
* @return {Object} The PublicKey JSON variant Ed25519.
*/
toJSON() {
return {
Ed25519: this.value,
};
}
} |
JavaScript | class SwaggerLoader {
static extensions = __meta__.extensions
static parsable = __meta__.parsable
static format = __meta__.format
/**
* Resolves a URI and fixes it if necessary.
* @param {Object} namedParams - an object holding the named parameters used for the resolution of
* the URI.
* @param {Object} namedParams.options - an object holding all the settings necessary for
* resolving, loading, parsing and serializing a uri and its dependencies.
* @param {string} uri - the URI to resolve to a file that will be used as the primary file for
* this loader
* @returns {Promise} a Promise containing the `options` and normalized `item` in an object. See
* `methods.fixPrimary` for more information.
* @static
*/
static load({ options, uri }) {
return methods.load({ options, uri })
}
/**
* Tests whether the content of a file is parsable by this loader and associated parser. This is
* used to tell which loader/parser combo should be used.
* @param {string?} content - the content of the file to test
* @returns {boolean} whether it is parsable or not
* @static
*/
static isParsable({ content }) {
return methods.isParsable(content)
}
} |
JavaScript | class Term extends React.Component {
/*
props
postInput()
getOutput() -> writeOutput()
*/
constructor (props) {
super(props);
this.state = {
}
this.termElement = null;
}
componentWillUnmount() {
this.term.dispose();
this.term = null;
}
termRef = element => {
if (!element) {
// unmount
return;
}
this.termElement = element;
//let rect = element.getBoundingClientRect();
//element.style.width = rect.width + "px";
//element.style.height = (this.props.height || rect.height) + "px";
let term = new xterm.Terminal({
cursorBlink: true
});
this.term = term;
term.open(element);
term.winptyCompatInit();
term.webLinksInit();
const stringOptions = {
//bellSound: null,
//bellStyle: 'none', //['none', 'sound'],
//cursorStyle: 'block', //['block', 'underline', 'bar'],
//experimentalCharAtlas: 'none', //['none', 'static', 'dynamic'],
fontFamily: "Consolas, 'Courier New', monospace",
//fontWeight: 'normal', //['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
//fontWeightBold: 'normal', //['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
//rendererType: ['dom', 'canvas'],
//fontColor: "#cccccc",
theme: {
background: "#1e1e1e",
foreground: "#cccccc",
cursor: "#cccccc",
}
};
for (let k in stringOptions) {
term.setOption(k, stringOptions[k]);
}
//
this.runTerminal(this.term)
term.fit();
term.focus();
term.write2('Hello from \x1B[1;3;31mPresident Kang\x1B[0m');
term.prompt();
element.style.height = term._core.viewport._viewportElement.getBoundingClientRect().height + "px";
this.props.onInit(element.style.height);
}
runTerminal(term) {
if (term._initialized) {
return;
}
term._initialized = true;
/*
x, y: 現在の位置
ix, iy: ユーザ入力の開始
mx, my: 最先端
allowInput: ユーザが入力可能かどうか
*/
term.mx = 0;
term.my = 0;
term.promptStr = '$ ';
term.cmd = '';
term.insertMode = true;
term.history = [];
term.historyIndex = -1;
term._dsr_clbk = [];
//
term.prompt = () => {
term.write2('\r\n' + term.promptStr, () => {
term.ix = term.x;
term.iy = term.y;
//console.log("prompt", term.x, term.y);
term.allowInput = true;
});
};
term.addLineBreak = () => {
term.write2(ansiEscapes.cursorTo(term.mx - 1, term.my - 1));
//console.log(term.mx, term.my)
term.write2('\r\n');
}
term.pushHistory = (cmd) => {
term.history.push(cmd);
}
term.moveHistory = (value) => {
if (term.historyIndex == -1)
term.historyIndex = term.history.length - 1;
else
term.historyIndex += value;
if (term.historyIndex < 0) term.historyIndex = 0;
else if (term.historyIndex >= term.history.length) term.historyIndex = term.history.length - 1;
const txt = term.history[term.historyIndex];
if (txt) {
term.clearCommand();
term.write2(txt);
term.cmd = txt;
}
}
term.insertToCommand = (key, n) => {
let clbk;
if (key.length == 1) {
clbk = () => {
//console.log("insert", key, n, term.x, term.y)
term.write2(term.cmd.substring(n - 1));
term.write2(ansiEscapes.cursorTo(term.x - 1, term.y - 1));
term.cmd = term.cmd.substring(0, n - 1) + (key.length == 1 ? key : "") + term.cmd.substring(n - 1);
};
}
term.write2(key, clbk);
}
term.clearCommand = () => {
if (!term.mx || !term.ix) return;
term.write2(ansiEscapes.eraseEndLine);
term.write2(ansiEscapes.cursorNextLine);
term.write2(ansiEscapes.eraseLines(term.my - term.y));
term.write2(ansiEscapes.cursorTo(term.ix - 1, term.iy - 1));
}
term.setCommand = (text, ox, oy) => {
term.cmd = text;
term.write2(ansiEscapes.cursorTo(term.ix, term.iy));
term.write2(term.cmd);
if (ox && oy) {
term.write2(ansiEscapes.cursorTo(ox, term.oy));
}
}
term.runCommand = () => {
term.addLineBreak();
this.runCommand(term.cmd);
term.pushHistory(term.cmd);
term.cmd = '';
term.historyIndex = -1;
term.allowInput = false;
}
term.isOutOfInput = (rx, ry) => {
const f = term.x + rx >= term.ix && term.y + ry == term.iy || term.y + ry > term.iy;
const b = term.x + rx <= term.mx && term.y + ry <= term.my;
/*
console.log(term.x + rx, term.y + ry)
console.log(term.ix, term.iy)
console.log(term.mx, term.my)
console.log(f, b)
*/
return !f || !b;
}
term.cmdCharN = (x, y) => {
let n = 0;
if (y > term.iy) {
n += Math.max(0, y - term.y - 1) * term.cols;
n += term.cols - term.ix;
} else {
n += x - term.ix + 1;
}
return n;
}
term.onWrite = (d, clbk) => {
//console.log("onWrite:", d, clbk)
term.write(ansiEscapes.cursorGetPosition);
term._dsr_clbk.push(clbk || true);
}
term.write2 = (d, clbk) => {
term.write(d);
term.onWrite(d, clbk);
}
term.on('data', d => {
// term.write だけでは呼ばれない
const m = d.match(DSR);
if (m) {
term.x = parseInt(m[2]);
term.y = parseInt(m[1]);
//console.log("onwrite dsr: ", term.x, term.y)
if (term.x > term.mx) term.mx = term.x;
if (term.y > term.my) term.my = term.y;
if (term._dsr_clbk) {
let clbk = term._dsr_clbk.shift();
if (clbk && typeof(clbk) == 'function') clbk();
}
}
});
term._core.register(term.addDisposableListener('key', (key, ev) => {
//console.log(ev.keyCode, ev.ctrlKey)
if (ev.keyCode === 67 && ev.ctrlKey) {
term.prompt();
return;
}
if (!term.allowInput) return;
const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) { // enter
if (term.cmd.trim() === '') {
term.prompt();
return;
}
term.runCommand();
term.selectLines(1,2);
} else if (ev.keyCode === 8) { // backspace
console.log("ix, iy: ", term.ix, term.iy)
if (term.x > term.ix && term.y == term.iy || term.y > term.iy) {
if (term.insertMode) {
// 一旦クリア
term.clearCommand();
// cmd を調整
let n = term.cmdCharN(term.x, term.y);
term.cmd = term.cmd.substring(0, n - 2) + term.cmd.substring(n - 1);
console.log("backspace", term.cmd)
//console.log(term.cmd);
// 書き込み
term.write2(term.cmd);
term.write2(ansiEscapes.cursorTo(term.x - 2, term.y - 1));
} else {
if (term.x == 1) {
term.write2(ansiEscapes.cursorTo(term.cols + 2, term.y - 2));
term.write2(' ');
}
term.write2('\b \b');
}
}
} else if (printable) {
//console.log(key)
if (key == CU && term.isOutOfInput(0, -1)) {
term.moveHistory(-1);
return;
} else if (key == CD && term.isOutOfInput(0, 1)) {
term.moveHistory(1);
return;
} else if (key == CF && term.isOutOfInput(1, 0)) return;
else if (key == CB && term.isOutOfInput(-1, 0)) return;
if (term.insertMode) {
let n = term.cmdCharN(term.x, term.y);
term.insertToCommand(key, n);
} else {
term.cmd += key
term.write2(key);
}
}
}));
term._core.register(term.addDisposableListener('paste', (data, ev) => {
term.write2(data);
}));
}
updateTerminalSize() {
if (!this.term) return;
/*
const cols = this.term.cols;
const rows = this.term.rows;
const width = (cols * this.term._core.renderer.dimensions.actualCellWidth + this.term._core.viewport.scrollBarWidth).toString() + 'px';
const height = (rows * this.term._core.renderer.dimensions.actualCellHeight).toString() + 'px';
const terminalContainer = this.termElement;
terminalContainer.style.width = width;
terminalContainer.style.height = height;
console.log(this.termElement)
*/
//const terminalContainer = this.termElement.parentNode;
//const rect = terminalContainer.getBoundingClientRect();
//terminalContainer.style.width = rect.width + "px";
//terminalContainer.style.height = rect.height + "px";
this.term.fit();
}
runCommand(text) {
console.log("run cmd:", text);
if (this.props.run) this.props.run(text)
}
getOutput(data) {
this.term.write2(data.replace(/\n/g, '\r\n'));
this.term.prompt();
}
render() {
return (
<div
id="terminal-container"
style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden" }}
ref={this.termRef}
>
</div>
);
}
} |
JavaScript | class Strings{
/**
* formata strings com a primeira letra em UpperCase
* @param {string} str string a ser formatada
* @returns {string} retorna a string formatada
*/
strFirstUpper(str){
return str[0].toUpperCase() + str.substr(1);
}
} |
JavaScript | class CartData extends React.Component {
static contextType = AuthContext;
constructor(props) {
super(props);
this.updateQuantity = this.updateQuantity.bind(this);
this.remove = this.remove.bind(this);
}
updateQuantity = (itemId, index) => {
const _this = this;
const { logState, userId } = this.context;
const [loggedIn, getLoggedIn] = logState;
const [user, setUser] = userId;
var checkInt = /^\+?[1-9][0-9]*$/;
var editQuantity = window.prompt("Please input the new quantity.");
if (editQuantity) {
if (!checkInt.test(editQuantity)) {
alert("Please input a valid number.");
return;
} else if (parseInt(editQuantity) > this.props.carts[index].itemStock) {
alert("There aren't enough phones in stock. (Current stock: " + this.props.carts[index].itemStock + ")");
console.log(itemId);
return;
} else {
axios.get("http://localhost:5000/home/item/api/editcarts?buyerid=" + user + "&itemid=" + itemId + "&quantity=" + editQuantity)
.then(function (response) {
console.log("confirm");
window.location.reload();
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
}
})
itemQuantityArr[index] = editQuantity;
return;
}
} else if (editQuantity === '') {
alert("Please input a valid number.");
return;
} else {
return;
}
}
remove = (itemId, index) => {
const _this = this;
const { logState, userId } = this.context;
const [loggedIn, getLoggedIn] = logState;
const [user, setUser] = userId;
var isDelete = window.confirm("Are you sure that you want to delete this item?");
if (isDelete == true) {
axios.get("http://localhost:5000/home/item/api/deleteitem?buyerid=" + user + "&itemid=" + itemId)
.then(function (response) {
console.log("confirm");
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
}
})
itemArr.splice(index, 1);
itemQuantityArr.splice(index, 1);
} else {
return;
}
window.location.reload();
}
render() {
if (this.props.carts.length > 0) {
return (
this.props.carts.map((cart, i) => {
itemArr.push(cart.itemId);
itemQuantityArr.push(cart.quantity);
return (
<tr key={cart.itemId}>
<td>{cart.itemTitle}</td>
<td>${cart.itemPrice}</td>
<td>{cart.quantity}</td>
<td className="text-end position-relative">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#6c757d" cursor="pointer" className="bi bi-pencil-fill position-absolute top-40 start-50 translate-middle-x" viewBox="0 0 16 16"
onClick={() => this.updateQuantity(cart.itemId, i)}>
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z" />
</svg>
</td>
<td className="text-start position-relative">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#6c757d" cursor="pointer" className="bi bi-trash-fill position-absolute top-40 start-50 translate-middle-x" viewBox="0 0 16 16"
onClick={() => this.remove(cart.itemId, i)}>
<path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z" />
</svg>
</td>
</tr>
)
})
)
} else {
return (
<tr>
<td colSpan="5">You don't have anything in your cart!</td>
</tr>
)
}
}
} |
JavaScript | class TotalPrice extends React.Component {
static contextType = AuthContext;
constructor(props) {
super(props);
}
confirmCart = () => {
//const _this = this;
const { logState, userId } = this.context;
const [loggedIn, getLoggedIn] = logState;
const [user, setUser] = userId;
var isConfirm = window.confirm("Are you sure that you want to buy these items?");
if (isConfirm == true) {
for (var i = 0; i < itemArr.length; i++) {
if (itemQuantityArr[i] > this.props.carts[i].itemStock) {
alert("There aren't enough phones in stock. (Current stock: " + this.props.carts[i].itemStock + ")");
return;
}
}
for (var i = 0; i < itemArr.length; i++) {
var newQuantity = this.props.carts[i].itemStock - itemQuantityArr[i];
axios.get("http://localhost:5000/home/item/api/buyphones?id=" + itemArr[i] + "&quantity=" + newQuantity)
.then(function (response) {
console.log("confirm");
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
}
})
}
axios.get("http://localhost:5000/home/item/api/deletecarts?buyerid=" + user)
.then(function (response) {
console.log("confirm");
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
}
})
//alert(itemQuantityArr[1])
} else {
return;
}
window.location.href = "/main";
}
render() {
var totalPrice = 0;
if (this.props.carts.length > 0) {
this.props.carts.map((cart, i) => {
totalPrice = totalPrice + cart.itemPrice * cart.quantity;
})
return (
<div id="checkoutContrl">
<p id="totalPrice">Total price: ${totalPrice.toFixed(2)}</p>
<button className="btn-hover color-3" id="checkoutConfirm" onClick={this.confirmCart}>Confirm</button>
</div>
)
} else {
return (
<p>Total price: $0</p>
)
}
}
} |
JavaScript | class MyDocument extends Document {
render() {
return (
<Html lang={i18n.language}>
<Head>
<meta charSet="utf-8" />
<meta content="ie=edge" httpEquiv="x-ua-compatible" />
{/*<meta name="theme-color" content={theme.palette.primary.main} />*/}
{/*<Favicons />*/}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
} |
JavaScript | class Label {
/**
* Constructs a new <code>Label</code>.
* Unsubscribe from a resource
* @alias module:model/Label
*/
constructor() {
Label.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>Label</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Label} obj Optional instance to populate.
* @return {module:model/Label} The populated <code>Label</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Label();
if (data.hasOwnProperty('closed_issues_count')) {
obj['closed_issues_count'] = ApiClient.convertToType(data['closed_issues_count'], 'String');
}
if (data.hasOwnProperty('color')) {
obj['color'] = ApiClient.convertToType(data['color'], 'String');
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String');
}
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('open_issues_count')) {
obj['open_issues_count'] = ApiClient.convertToType(data['open_issues_count'], 'String');
}
if (data.hasOwnProperty('open_merge_requests_count')) {
obj['open_merge_requests_count'] = ApiClient.convertToType(data['open_merge_requests_count'], 'String');
}
if (data.hasOwnProperty('priority')) {
obj['priority'] = ApiClient.convertToType(data['priority'], 'String');
}
if (data.hasOwnProperty('subscribed')) {
obj['subscribed'] = ApiClient.convertToType(data['subscribed'], 'String');
}
}
return obj;
}
} |
JavaScript | class StoryblokService{
async createComponentAndStories(storyblokManagementApiKey, spaceId, stories, component){
let Storyblok = new StoryblokClient({
oauthToken: storyblokManagementApiKey,
cache: {type: 'memory',clear: 'auto'}
});
stories.forEach(story => {
Storyblok.post(`spaces/${spaceId}/stories/`, {
story
}).then(res => {
console.log(`Success: ${res.data.story.name} was created.`)
}).catch(err => {
console.log(`Error: ${err}`)
});
});
Storyblok.post(`spaces/${spaceId}/components/`, component).then(res => {
console.log(`Success: ${res.data.component.name} was created.`)
}).catch(err => {
console.log(`Error: ${err}`)
});
return null;
}
async createWebHook(storyblokManagementApiKey, spaceId, webhook){
let Storyblok = new StoryblokClient({
oauthToken: storyblokManagementApiKey,
cache: {type: 'memory',clear: 'auto'}
});
Storyblok.get(`spaces/${spaceId}/`).then(res => {
var space = res.data;
space.story_published_hook = webhook.story_published_hook;
Storyblok.put(`spaces/${spaceId}/`, space).then(res => {
console.log(`Success: ${res.data.space.story_published_hook} was created.`)
}).catch(err => {
console.log(`Error: ${err}`)
});
}).catch(err => {
console.log(`Error: ${err}`)
});
return null;
}
} |
JavaScript | class NamedGraph extends Graph {
constructor(collection, fields, config) {
super(...arguments);
if (config.name) this.name = config.name;
}
_idGenerator(index, link) { return this.name+'/'+index; }
} |
JavaScript | class NamedGraph extends Graph {
constructor(collection, fields, config) {
super(...arguments);
if (config.name) this.name = config.name;
}
_idGenerator(index, link) { return this.name+'/'+index; }
} |
JavaScript | class Rectangle {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
contains(px, py) {
return (px > this.x && px < this.x + this.width && py > this.y && py < this.y + this.height);
}
} |
JavaScript | class Home extends Component {
constructor(props) {
super(props);
this.state = {customerName: '',mobileNumber:'',address:'',deliveryPerson:'',deliveryDate:new Date(),productDropDown:'',orderTakenPerson:staticValues.orderTakenPersonDetails};
this.handleNameChange = this.handleNameChange.bind(this);
this.submit = this.submit.bind(this);
this.handleMobileNumberChange = this.handleMobileNumberChange.bind(this);
this.handleAddressChange = this.handleAddressChange.bind(this);
this.handleDeliveryPersonChange = this.handleDeliveryPersonChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.getData = this.getData.bind(this);
}
getData(data){
console.log('getData',data)
this.setState({childData: data});
}
required (value){
if (!value.toString().trim().length) {
// We can return string or jsx as the 'error' prop for the validated Component
return <span className="error">Required</span>;
}
};
email (value) {
if (!validator.isEmail(value)) {
return <span className="error">{value} is not a valid email.</span>
}
};
lt (value, props) {
// get the maxLength from component's props
if (!value.toString().trim().length > props.maxLength) {
// Return jsx
return <span className="error">The value exceeded {props.maxLength} symbols.</span>
}
};
mobileNumber(value, props, components){
if(!validator.isMobilePhone(value, 'en-IN')){
return <span className="error">Enter a valid number</span>
}
}
submit(event){
console.log('state value',this.state)
console.log('Customer name',this.state.customerName,'Mobile',this.state.mobileNumber,'address',this.state.address,'delivery person',this.state.deliveryPerson,'delivery date',this.state.deliveryDate)
alert("Details submitted successfully")
console.log('data',this.state)
Request
.get('/postData')
.query(
{query:JSON.stringify(this.state)}
)
.send({
//_csrf: this.props._csrf,
// params: {
// method:"GET",
// query:JSON.stringify(this.state)
// }
})
.end((err, res) => {
console.log('er',err,res)
if(err&&res.body.error){
alert(res.body.error)
}
if(res && res.body&&!res.body.error) {
// var result = res.JSON();
console.log('end',res)
//alert("Your details")
window.location.assign("/success");
}
});
// this.callApi()
// .then(res => this.setState({ response: res.express }))
// .catch(err => console.log(err));
// fetch("/postData",{
// method:"GET",
// qs:JSON.stringify(this.state),
// headers: {
// 'Content-Type': 'application/json'
// }})
// .then(function(res) {
// console.log("ok",res.text());
// }).catch(function() {
// console.log("error");
// });
event.preventDefault();
}
loadSuccessPage(){
console.log('succcccc')
return(
<Success/>
)
}
callApi = async () => {
console.log('callapi')
const response = await fetch('/postData',{params:JSON.stringify(this.state)});
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
console.log('body',body)
return body;
};
handleNameChange(event) {
console.log('event',event.target.value)
this.setState({customerName: event.target.value});
}
handleMobileNumberChange(event){
this.setState({mobileNumber: event.target.value});
}
handleAddressChange(event){
this.setState({address: event.target.value});
}
handleDeliveryPersonChange(event){
this.setState({deliveryPerson: event.target.value});
}
handleDateChange(event){
this.setState({deliveryDate: event});
console.log('dattt',this.state.deliveryDate,'ee',event)
}
onToggleBookStatus(prod){
console.log('onToggleBookStatus',prod)
}
setProdDropDown(data){
console.log('data',data)
}
render() {
let orderTaken = this.state.orderTakenPerson;
console.log('orderTaken',orderTaken)
let optionItems = orderTaken.map((persons) =>
<option key={persons.id}>{persons.name}</option>
);
return (
<div className="scroll-div">
<header>
<h2 className="header-class">Welcome to Theertha</h2>
</header>
<div id="content" className="container">
<div className="">
<Form onSubmit={this.submit}>
<div className="row">
<div className="col-sm-12">
<h3 className="track-head">Track Order Details</h3>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<div className="col-sm-6">
<label className="label-cls">
Customer Name*
<Input className="label-cls" placeholder="Customer Name" name='customerName' value={this.state.customerName} onChange={this.handleNameChange} validations={[this.required]} />
</label>
</div>
<div className="col-sm-6">
<label className="label-cls">
Customer Mobile Number *
<Input className="label-cls" type="number" placeholder="Customer Mobile" name='customerMobile' value={this.state.mobileNumber} onChange={this.handleMobileNumberChange} validations={[this.required,this.mobileNumber]}/>
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<div className="col-sm-6">
<label className="label-cls">
Address *
<TextArea className="label-cls" type='address' name='address' value={this.state.address} onChange={this.handleAddressChange} validations={[this.required]}/>
</label>
</div>
<div className="col-sm-6">
<Select className="label-cls delivery-dropdn" name='city' value={this.state.deliveryPerson} onChange={this.handleDeliveryPersonChange} validations={[this.required]}>
<option value=''>Choose Order Taken Person</option>
{optionItems}
</Select>
</div>
</div>
</div>
<div className="col-sm-6">
<label className="label-cls ">
Select date *
<div>
<DatePicker
onChange={this.handleDateChange}
value={this.state.deliveryDate}/>
</div>
</label>
</div>
<div className="col-sm-12">
<Row sendData={this.getData} />
</div>
<div className="col-sm-6 button-cls">
<Button className="label-cls btn btn-success pull-right">Submit</Button>
</div>
</Form>
{/* <div className="col-sm-6">
test1
</div> */}
</div>
</div>
</div>
);
}
} |
JavaScript | class CalcEvent {
/**
* set calc
* data : has "to" and "options". options has properties "val" and "type"
*
*/
static setCalc(calc_formula, $trigger = null) {
return __awaiter(this, void 0, void 0, function* () {
if (!hasValue(calc_formula)) {
return;
}
if (CalcEvent.loopcount > 100) {
if (!CalcEvent.showLoopError) {
alert('calc loop count is over 100. Please check calc setting.');
CalcEvent.showLoopError = true;
}
throw 'calc loop count is over 100. Please check calc setting.';
}
CalcEvent.loopcount++;
// console.log("---------------------------");
let $targetBoxs = Exment.CommonEvent.getBlockElement(calc_formula.target_block);
// get to list. if 1:n form and target is n, $tos is multiple.
let $tos = CalcEvent.getTargetFields($trigger, $targetBoxs, calc_formula);
// loop for calc target.
for (let j = 0; j < $tos.length; j++) {
let $to = $tos.eq(j);
for (let i = 0; i < calc_formula.formulas.length; i++) {
let formula = calc_formula.formulas[i];
// for creating array contains object "value0" and "calc_type" and "value1".
let formula_string = formula.formula_string;
if (!hasValue(formula_string)) {
continue;
}
// console.log("loopcount : " + CalcEvent.loopcount + ", target_block : " + calc_formula.target_block);
// console.log("loopcount : " + CalcEvent.loopcount + ", target_column : " + calc_formula.target_column);
// console.log($to);
// get options
let options = formula.params;
let $targetBox = CalcEvent.getBlockByField($to, $targetBoxs);
let precision = yield CalcEvent.executeCalc(formula_string, options, $targetBox);
Exment.CommonEvent.setValue($to, precision);
}
}
});
}
/**
* Execute calc
* @param formula_string formula string. Replace number etc.
* @param params calc parameter
* @param $targetBox triggered box
*/
static executeCalc(formula_string, params, $targetBox) {
return __awaiter(this, void 0, void 0, function* () {
// console.log("loopcount : " + CalcEvent.loopcount + ", formula_string : " + formula_string);
let notCalc = false;
for (let j = 0; j < params.length; j++) {
let val = 0;
// calc option
let param = params[j];
// console.log("loopcount : " + CalcEvent.loopcount + ", j : " + j + ", formula_column : " + param.formula_column + ", type : " + param.type);
// when dynamic value, get value
if (param.type == 'dynamic') {
val = rmcomma($targetBox.find(Exment.CommonEvent.getClassKey(param.formula_column)).val());
if (!hasValue(val)) {
notCalc = true;
break;
}
}
// when summary value, get value
else if (param.type == 'summary' || param.type == 'sum') {
let sum_count = 0;
let box = Exment.GetBox.make();
box.getBox().find('.has-many-' + param.child_relation_name + '-form:visible, .has-many-table-' + param.child_relation_name + '-row:visible')
.find(Exment.CommonEvent.getClassKey(param.formula_column))
.each(function () {
if (hasValue($(this).val())) {
sum_count += pFloat($(this).val());
}
});
val = sum_count;
}
// when count value, get count
else if (param.type == 'count') {
let box = Exment.GetBox.make();
val = box.getBox().find('.has-many-' + param.child_relation_name + '-form:visible, .has-many-table-' + param.child_relation_name + '-row:visible').length;
if (!hasValue(val)) {
val = 0;
}
}
// when select_table value, get value from table
else if (param.type == 'select_table') {
// find select target table
let $select = $targetBox.find(Exment.CommonEvent.getClassKey(param.select_pivot_column));
let table_name = $select.data('target_table_name');
// get selected table model
let model = yield Exment.CommonEvent.findModel(table_name, $select.val());
// get value
if (hasValue(model)) {
val = model['value'][param.formula_column];
if (!hasValue(val)) {
notCalc = true;
break;
}
}
else {
notCalc = true;
break;
}
}
// when parent value, get value from parent_id or parent form
else if (param.type == 'parent') {
// find parent target table
let $select = $('.parent_id[data-parent_id]');
// if has $select, this default form, so call CommonEvent.findModel
if (hasValue($select)) {
let table_name = $select.data('target_table_name');
// get selected table model
let model = yield Exment.CommonEvent.findModel(table_name, $select.val());
// get value
if (hasValue(model)) {
val = model['value'][param.formula_column];
if (!hasValue(val)) {
notCalc = true;
break;
}
}
else {
notCalc = true;
break;
}
}
// if not parent id, almost 1:n form, so get parent form
else {
let $parentBox = Exment.CommonEvent.getBlockElement('');
val = rmcomma($parentBox.find(Exment.CommonEvent.getClassKey(param.formula_column)).val());
if (!hasValue(val)) {
notCalc = true;
break;
}
}
}
// replace value
formula_string = formula_string.replace(param.key, val);
}
if (notCalc) {
return null;
}
let result = math.evaluate(formula_string);
if (result === Infinity || result === -Infinity || result === NaN) {
return null;
}
return result;
});
}
/**
* Get form block erea by event element. (hasmany or default form)
* @param $target event called target
*/
static getBlockByField($target, $parent) {
// if has has-many-table-row or has-many-form, get parent
let $closest = $target.closest('.has-many-table-row,.has-many-form');
if (hasValue($closest)) {
return $closest;
}
if (hasValue($parent)) {
return $parent;
}
return Exment.CommonEvent.getDefaultBox();
}
/**
* Get target field.
* (1) calc_formula is summary or count, return parent.
* (2) form is 1:n and trigger is n, return closest child.
* (3) form is 1:n and trigger is 1, return children item.
* (4) Otherwise, return 1.
*/
static getTargetFields($trigger, $targetBox, calc_formula) {
if (calc_formula.type == 'sum' || calc_formula.type == 'summary' || calc_formula.type == 'count') {
return Exment.CommonEvent.getDefaultBox().find(Exment.CommonEvent.getClassKey(calc_formula.target_column));
}
// if has has-many-table-row or has-many-form, only return child to
let $closest = $trigger.closest('.has-many-table-row,.has-many-form');
if (hasValue($closest)) {
return $closest.find(Exment.CommonEvent.getClassKey(calc_formula.target_column));
;
}
// get to list. if 1:n form and target is n and trigger is 1, $tos is multiple.
return $targetBox.find(Exment.CommonEvent.getClassKey(calc_formula.target_column));
}
/**
* validate formula string
* @param formula
*/
static validateMathFormula(formula) {
try {
if (!hasValue(formula)) {
return false;
}
let result = math.evaluate(formula);
return true;
}
catch (e) {
return false;
}
}
static resetLoopConnt() {
CalcEvent.loopcount = 0;
}
} |
JavaScript | class Transcript {
constructor(transcriptData) {
// super()
// assign keys and values from transcript to this
this.fileLastModified = transcriptData.file_last_modified
this.createdAt = Helpers.safeDataPath(transcriptData, "transcript_metadata.last_updated_at")
this.filePath = transcriptData.file_path
this.fileSize = transcriptData.file_size
this.fileType = transcriptData.content_type
this.transactionId = transcriptData.transaction_id
this.userId = transcriptData.user_id
this.filename = transcriptData.filename
this.utterances = transcriptData.utterances
this.uploadedAt = transcriptData.uploaded_at
// TODO need to persist this on the transcript not as id, but transcribe_request_id...
this.transcribeRequestId = transcriptData.id
}
// no bells and whistles, just thir
simpleTranscriptionText () {
const { utterances } = this
// TODO don't just take the first alternative, check confidences, or make sure they are in the correct order at this point
const transcription = utterances
.map(utterance => utterance.alternatives[0].transcript)
.join('\n');
console.log(`Transcription: ${transcription}`);
return transcription
}
encodedFilename () {
return encodeURIComponent(this.filename.replace(/\./g, ''))
}
// transcript set for a file is identified by file last modified; each transcript request is identified by it's this.createdAt
fileIdentifier () {
// get rid of stuff react router doesn't like, ie., especially periods
return `${this.encodedFilename()}-lastModified${this.fileLastModified}`
}
showViewUrl () {
// get rid of stuff react router doesn't like, ie., especially periods
return `/transcripts/${this.fileIdentifier()}`
}
displayCreatedAt () {
return moment.utc(this.createdAt, "YYYYMMDDTHHmmss[Z]").tz(moment.tz.guess()).format('MMMM Do YYYY, h:mm:ss a') // moment(this.createdAt, "YYYYMMDDTHHMMss").tz(moment.tz.guess()).format(('MMMM Do YYYY, h:mm:ss a'))
}
displayFileLastModified () {
return moment(parseInt(this.fileLastModified)).tz(moment.tz.guess()).format(('MMMM Do YYYY, h:mm a'))
}
displayFileSize () {
return `${(this.fileSize / 1048576).toFixed(2)} MB`
}
async hideTranscribeRequest () {
let tr = this.getTranscribeRequest()
if (tr && !tr.hidden) {
await tr.markAsHidden()
}
}
getTranscribeRequest () {
const trs = _.values(store.getState().transcribeRequests)
const match = trs.find(tr => tr.id == this.transcribeRequestId)
return match && new TranscribeRequest({transcribeRequestRecord: match})
}
// used only if we're not breaking the words out into separate components
// maps certain spelled out words to their puncuation equivalent
static displayUtterance (utteranceTranscript) {
// TODO probably better to put in unicode bytes here instead for accuracy and ease of reading
// want it to be like: 1 Clement" 1:19 " so spaces before and after. Will change to Khmer
// numbers in the punctuation regex
// TODO make sure references don't get switched over somehow...
const withFixedReferences = utteranceTranscript.replace(Helpers.referencesRegex, (matched) => {
const match = matched.match(Helpers.nonGlobalRegex(Helpers.referencesRegex));
// don't wait to change to Khmer numerals later, since references don't follow the normal
// rule. Keep it separate, and save a lot of grief in regex wasteland
return ` ${Helpers.convertToKhmerNumeral(match[1])}:${Helpers.convertToKhmerNumeral(match[2])} `
})
// first, converting all numbers with លេខ in front to Khmer numerals
// I think it's better to only run one replace for both types of numbers rather than two
// replaces with separate logic, since it has to iterate over whole string. So regex needs to
// match both types, then decide which one to
const withFixedNumerals = withFixedReferences.replace(Helpers.khmerNumberRegex, (matched) => {
const match = matched.match(Helpers.nonGlobalRegex(Helpers.khmerNumberRegex));
// e.g., 1 or 5 etc
const theNumber = match[2]
// if they use the Khmer word for "number" before, or it's more than 9, use Khmer numeral
if (match[1] || theNumber.length > 1) {
return Helpers.convertToKhmerNumeral(theNumber)
} else {
// spell it out
return Helpers.KHMER_NUMBERS[theNumber]
}
})
// set words with alternate spellings
const withPreferredSpellings = withFixedNumerals.replace(Helpers.preferredSpellingRegex, (match) => {console.log(match, Helpers.PREFERRED_SPELLINGS[match]); return Helpers.PREFERRED_SPELLINGS[match]})
const processedUtterance = withPreferredSpellings.replace(Helpers.punctuationRegex, (match) => Helpers.KHMER_PUNCTUATION[match]);
return processedUtterance
}
} |
JavaScript | class Bsp {
constructor(polygons = []) {
this.polygons = polygons || [];
}
getModels = () => {
return this.polygons;
};
} |
JavaScript | class File {
constructor(id, name, index, icon = "file", parentId = null, uploading = false, progress = 0, dir = false, canRename = true) {
this.id = id;
this.name = name;
this.index = index;
this.icon = icon;
this.parentId = parentId;
this.uploading = uploading;
this.progress = progress;
this.children = [];
this.dir = dir;
this.canRename = canRename;
}
} |
JavaScript | @observer class EditPanelChipForOneChip extends React.Component {
/**
* render
* @return {element}
*/
render() {
const data = this.props.data;
let label = this.props.label;
let chipColor= '#bbdefb';
// Match a simple prefix (label) with a formal URI
if (this.props.config) {
const prefixList = this.props.config.prefix;
const foundPrefix = prefixList.find((prefix) => {
return label.startsWith(prefix.equiv);
});
if (foundPrefix) {
label = label.replace(foundPrefix.equiv, foundPrefix.origin);
}
}
if (data != label) {
// Chips added by completion
chipColor = '#ffcdd2';
}
return (
<Chip
style={{backgroundColor: chipColor}}
{...this.props}
/>
);
}
} |
JavaScript | class WebSocketClient {
/**
* Creates a new web socket client object.
*
* @param {WebSocket} webSocket the web socket to use.
* @param {Function} errorFunc the error function.
* @param {Function} openFunc the open function.
* @param {Function} messageFunc the message function.
* @param {Function} closeFunc the close function.
*/
constructor(webSocket, errorFunc, openFunc, messageFunc, closeFunc) {
this.webSocket = webSocket;
WebSocketClient._setFunctions(this.webSocket, errorFunc, openFunc, messageFunc, closeFunc);
}
/**
* Sets the functions for the native socket to use.
*
* @param {WebSocket} webSocket the web socket to use.
* @param {Function} errorFunc the error function.
* @param {Function} openFunc the open function.
* @param {Function} messageFunc the message function.
* @param {Function} closeFunc the close function.
*/
static _setFunctions(webSocket, errorFunc, openFunc, messageFunc, closeFunc) {
webSocket.addEventListener('error', errorFunc);
webSocket.addEventListener('open', openFunc);
webSocket.addEventListener('message', messageFunc);
webSocket.addEventListener('close', closeFunc);
}
/**
* @returns {WebSocket} the native js web socket object.
*/
getNative() {
return this.webSocket;
}
} |
JavaScript | class FileSystemInterface {
constructor({filename, _fs = fs} = {}) {
this.filename = filename;
this.fs = _fs;
this.promise = Promise.resolve();
}
// read :: String -> Promise(Object)
read(filename = this.filename, _fs = this.fs) {
return this.promise = this.promise.then(filename
? () => new Promise(readFn(_fs, filename))
: () => Promise.reject(new Error(ERRORS.INVALID_INPUTS))
);
}
// write :: (String, Object|String) -> Promise(Object)
write(contents, file = this.filename, _fs = this.fs) {
return this.promise = this.promise.then(
contents
? () => new Promise(writeFn(JSON.stringify, _fs)(contents, file))
: () => Promise.reject(new Error('no content provided'))
);
}
// wrapped to try to mitigate errors when the file doesn't exist
create(file = this.filename, _fs = this.fs) {
const createFn = function (resolve, reject) {
try {
if (_fs.existsSync(file)) {
return resolve();
}
} catch (e) {
// assume the reason why we have thrown is because file doesn't exist
// console.log('error creating file: ', e);
}
try {
const fd = _fs.openSync(file, 'w');
_fs.writeSync(fd, Buffer.from('', 'utf8'));
_fs.closeSync(fd);
return resolve();
} catch (e) {
return reject(e);
}
};
this.promise = this.promise.then(() => new Promise(createFn));
return this.promise;
}
static createSync(file, _fs = fs) {
const isCreated = _fs.existsSync(file);
if (isCreated === true) {
return false;
}
try {
const fd = _fs.openSync(file, 'w');
_fs.writeSync(fd, Buffer.from('', 'utf8'));
_fs.closeSync(fd);
return true;
} catch (e) {
return false;
}
}
static doesFileExist(file, _fs = fs) {
try {
return _fs.existsSync(file);
} catch (e) {
return false;
}
}
static doesNSExist(ns, _fs = fs) {
return FileSystemInterface.doesFileExist(path.join('data', ns + '.json'), _fs);
}
static createDirectory(path, _fs = fs) {
return new Promise((resolve, reject) => {
_fs.mkdir(
path,
(data) => {
if (!data || data.code === 'EEXIST') {
return resolve();
}
return reject(data);
}
);
});
}
} |
JavaScript | class App {
constructor() {
_defineProperty(this, "_elements", []);
_defineProperty(this, "_appInfo", {
name: "@sparkdev/onebe",
version: (0, _version.default)(),
appName: _Config.default.string("app.appName"),
appVersion: _Config.default.string("app.appVersion"),
appDescription: _Config.default.string("http.url"),
appURL: _Config.default.string("app.appDescription")
});
}
/**
* Return the application information object.
*/
get app() {
return this._appInfo;
}
/**
* Set the application information object.
*
* @param appInfo The new application information object.
*/
set app(appInfo) {
if (typeof appInfo !== "object") {
return;
}
this._appInfo = Object.assign({
appName: "onebe by Spark",
appVersion: this._appInfo.version,
appDescription: "An application",
appURL: _Config.default.string("http.url")
}, _objectSpread(_objectSpread({}, appInfo), {}, {
name: this._appInfo.name,
version: this._appInfo.version
}));
}
/**
* Add an class instance to the application object.
*
* @param ElementInstance The class we want to create an object from and add to the application object.
*/
use(ElementInstance) {
const element = new ElementInstance();
this._elements[element.constructor.name] = element;
Object.defineProperty(this, element.constructor.name, {
get: () => this._elements[element.constructor.name],
configurable: true
});
}
/**
* Add a function to the application object.
*
* @param fn The function we want to attach to the application object.
*/
hook(fn) {
this._elements[fn.name] = fn.bind(this);
Object.defineProperty(this, fn.name, {
get: () => this._elements[fn.name],
configurable: true
});
}
} |
JavaScript | class DataStorePostgresConn extends besh.DataStoreBapConn {
constructor(log, pool, id) {
super(log);
this._pool = pool;
this._client = null;
this._id = id;
this.log.debug("Creating connId: %d", this._id);
}
async create(collection, fields, id) {
let query = {};
let fieldStr = "",
valuesStr = "",
count = 1;
query.values = [];
for (const f in fields) {
if (count > 1) {
fieldStr += ",";
valuesStr += ",";
}
fieldStr += f;
query.values.push(fields[f]);
valuesStr += `$${count}`;
count++;
}
if (id === undefined) {
query.text =
`INSERT INTO ${collection} (${fieldStr}) VALUES (${valuesStr})`;
} else {
query.text =
`INSERT INTO ${collection} (${fieldStr}) VALUES (${valuesStr})
RETURNING ${id}`.replace(/\s\s+/g, " ").replace(/\n/g, " ");
}
this.log.debug("connId:%d create() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
if (e.code === "23505") {
throw new besh.DataStoreBapConnError(
"Duplicate record exists!",
besh.DataStoreBapConnError.DUP_CODE, this)
}
throw this.Error("Something wrong with your request!", e.code);
});
return res.rows;
}
async read(collection, fields, criteria, opts) {
// opts = { orderBy, orderByDesc, format, distinct }
let query = {},
defaults = {
format: this.JSON,
distinct: false
};
if (fields === undefined) {
fields = [ "*" ];
}
opts = lodashMerge(defaults, opts);
if (opts.distinct) {
query.text =
`SELECT DISTINCT ${fields.join()} FROM ${collection}`;
}
else {
query.text = `SELECT ${fields.join()} FROM ${collection}`;
}
query.values = [];
if (criteria !== undefined && Object.keys(criteria).length > 0) {
query.text += " WHERE ";
let position = 1;
for (const fld in criteria) {
if (position > 1) {
query.text += " AND ";
}
const val = criteria[fld];
if (Array.isArray(val)) {
let inText = `$${position}`;
query.values.push(val[0]);
position++;
// Start from 1, not fom 0!
for (let i = 1; i < val.length; i++) {
inText += `,$${position}`;
query.values.push(val[i]);
position++;
}
query.text += `${fld} IN (${inText})`;
} else if (typeof val === "object") {
query.text += `${fld}${val.op}$${position}`;
query.values.push(val.val);
position++;
} else {
query.text += `${fld}=$${position}`;
query.values.push(val);
position++;
}
}
}
let orderByAdded = false;
if (opts.groupBy !== undefined && opts.groupBy.length > 0) {
query.text += ` GROUP BY ${opts.groupBy.join()}`;
}
if (opts.orderBy !== undefined && opts.orderBy.length > 0) {
query.text += ` ORDER BY ${opts.orderBy.join()}`;
query.text += " ASC"
orderByAdded = true;
}
if (opts.orderByDesc !== undefined && opts.orderByDesc.length > 0) {
if (orderByAdded) {
query.text += `, ${opts.orderByDesc.join()} DESC`;
} else {
query.text += ` ORDER BY ${opts.orderByDesc.join()} DESC`;
}
}
if (opts.format === this.ARRAY ||
opts.format === this.ARRAY_NO_HEADER) {
query.rowMode = "array";
}
this.log.debug("connId:%d retrieve() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
if (opts.format === this.ARRAY_HEADER) {
return res.fields;
}
if (opts.format === this.ARRAY) {
let rows = res.fields.map((f) => f.name);
return [rows, ...res.rows];
}
return res.rows;
}
async update(collection, fields, criteria) {
let query = {};
let fieldStr = "",
count = 1;
query.values = [];
for (const f in fields) {
if (count > 1) {
fieldStr += ",";
}
fieldStr += `${f}=$${count}`;
query.values.push(fields[f]);
count++;
}
query.text = `UPDATE ${collection} SET ${fieldStr}`;
if (criteria !== undefined &&
Object.keys(criteria).length > 0) {
let where = "";
for (const c in criteria) {
if (where.length !== 0) {
where += " AND ";
}
where += `${c}=$${count}`;
query.values.push(criteria[c]);
count++;
}
query.text += ` WHERE ${where}`;
}
this.log.debug("connId:%d update() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
if (e.code === "23505") {
throw new besh.DataStoreBapConnError(
"Duplicate record exists!",
besh.DataStoreBapConnError.DUP_CODE, this)
}
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async delete(collection, criteria) {
let query = {};
query.values = [];
query.text = `DELETE FROM ${collection}`;
let count = 1;
if (criteria !== undefined &&
Object.keys(criteria).length > 0) {
let where = "";
for (const c in criteria) {
if (where.length !== 0) {
where += " AND ";
}
where += `${c}=$${count}`;
query.values.push(criteria[c]);
count++;
}
query.text += ` WHERE ${where}`;
}
this.log.debug("connId:%d delete() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async query(query) {
this.log.debug("connId:%d query() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rows;
}
async exec(query) {
this.log.debug("connId:%d query() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async connect() {
if (this._client !== null) {
throw this.Error(`connId:${this._id} Already have a connection!`);
}
this.log.debug(`connId:${this._id} Getting connection`);
this._client = await this._pool.connect();
}
async release() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Releasing connection`);
await this._client.release();
this._client = null;
}
async begin() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Beginning transaction ...`);
await this._client.query("BEGIN;");
}
async commit() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Commiting transaction ...`);
await this._client.query("COMMIT;");
}
async rollback() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Rolling back transaction ...`);
await this._client.query("ROLLBACK;");
}
get JSON() {
return FORMAT_JSON;
}
get ARRAY() {
return FORMAT_ARRAY;
}
get ARRAY_NO_HEADER() {
return FORMAT_ARRAY_NO_HEADER;
}
} |
JavaScript | class PluginController {
handleToggleMode() {
}
mark() {
}
markAsChanged() {
}
setMode(modeId, ctx) {
this.modeId = modeId;
this.ctx = ctx;
}
update() {
}
} |
JavaScript | class GraphCommands extends GraphHostCommands {
constructor(graph) {
super(graph);
}
selectTrace(applicationId, traceId) {
const trace = allApplications.selection.data.getTrace(applicationId, traceId);
traceSelection.selectTrace(trace);
}
} |
JavaScript | class FileData {
constructor(content, mode = '100644') {
this.mode = mode;
this.content = content;
}
} |
JavaScript | class LocalTasksHandler extends Handler {
initialState() {
return {
projects: []
};
}
updateState(state, newState) {
// We never use this?
return null;
}
editDialog(task) {
return (
<LocalTasksEditWidget task={task} />
);
}
// Called from a button
createTask() {
this.editDialog({});
}
} |
JavaScript | class FilterGroupBy extends BaseGroupBy {
/**
* Constructor.
* @param {boolean=} opt_useUi
*/
constructor(opt_useUi) {
super();
/**
* Whether this groupby will use the filtergroupui
* @type {boolean}
* @private
*/
this.useUi_ = opt_useUi || false;
}
/**
* @inheritDoc
*/
getGroupIds(node) {
/**
* @type {Array<!string>}
*/
var ids = [];
/**
* @type {?string}
*/
var val = /** @type {FilterNode} */ (node).getEntry().type;
if (!val) {
val = 'Unknown';
} else {
try {
var firstHashIdx = val.indexOf('#');
if (firstHashIdx != -1) {
val = val.substring(firstHashIdx + 1);
var secHashIdx = val.indexOf('#');
if (secHashIdx != -1) {
val = val.substring(0, secHashIdx);
}
}
} catch (e) {
// weirdly structured typename
}
}
insert(ids, val);
return ids;
}
/**
* @inheritDoc
*/
createGroup(node, id) {
var group = new SlickTreeNode();
group.setId(id);
group.setLabel(id);
group.setCheckboxVisible(false);
group.collapsed = false;
if (this.useUi_) {
group.setNodeUI(`<${directiveTag}></${directiveTag}>`);
}
var dm = DataManager.getInstance();
var d = dm.getDescriptor(id);
if (d) {
group.setLabel(d.getTitle() + ' (' + d.getProvider() + ')');
}
return group;
}
} |
JavaScript | class ConnectionFactory {
/**
* @param {object} options
* @param {string} options.host host to connect to
* @param {string|number} port port to connect to host on
* @param {function} handshake a function to perform the handshake for a connection
* after it connects
*/
constructor({ host, port, handshake }) {
this.host = host;
this.port = port;
this.handshake = handshake;
this.attempts = 0;
this.onConnectionError = console.warn.bind(console);
}
/**
* Creates a connection for the pool
* connections are not added to the pool until the handshake (server greeting)
* is complete and successful
*/
async create() {
debug('+1');
const connection = new Connection(this.port, this.host);
connection.on('error', this.onConnectionError);
try {
const greeting = await connection.open();
await this.handshake(connection, greeting);
this.attempts = 0;
} catch (e) {
this.attempts += 1;
debug('attempts=%i', this.attempts);
await sleep(200 * Math.min(this.attempts, 20));
throw e;
}
return connection;
}
/**
* Destroys a connection from the pool
*/
destroy(connection) {
debug('-1');
connection.removeListener('error', this.onConnectionError);
return connection.close();
}
/**
* Validates that a connection from the pool is ready
*/
validate(connection) {
return connection.connected;
}
} |
JavaScript | class JRiverService {
/**
* Calls MCWS.
* @returns {Promise<*>}
*/
invoke = async ({serverURL, name, path, requiredParams, suppliedParams = {}, converter, token = undefined}) => {
const url = this._getUrl(serverURL, token, path, requiredParams, suppliedParams);
const response = await fetch(url, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`JRiverService.${name} failed, HTTP status ${response.status}`);
}
const contentType = response.headers.get('Content-Type');
if (contentType && contentType === 'application/json') {
const data = await response.json();
return converter(data);
} else {
const data = await response.text();
const json = xml2js(data, COMPACT);
return converter(json);
}
};
_getParams = (params) => {
const esc = encodeURIComponent;
return Object.keys(params).map(k => esc(k) + '=' + esc(params[k])).join('&');
};
_validateParams = (suppliedParams, requiredParams) => {
if (Object.keys(suppliedParams).length === requiredParams.length) {
return Object.keys(suppliedParams).every(k => requiredParams.findIndex(p => k === p) > -1);
}
return false;
};
_getUrl = (serverURL, token, path, requiredParams, suppliedParams) => {
const root = `${serverURL}/${path}`;
if (Object.keys(suppliedParams).length > 0) {
if (this._validateParams(suppliedParams, requiredParams)) {
return this._withToken(token, `${root}?${this._getParams(suppliedParams)}`, true);
} else {
// TODO format error to show the bad params
throw new Error(`Invalid params for target ${path} - ${suppliedParams}`)
}
} else {
return this._withToken(token, root, false);
}
};
_withToken = (token, url, hasParams) => {
if (token) {
return `${url}${hasParams ? '&' : '?'}Token=${token}`;
}
return url;
};
} |
JavaScript | class FileShare extends models['BaseModel'] {
/**
* Create a FileShare.
* @member {string} [description] Description for file share
* @member {string} shareStatus The Share Status. Possible values include:
* 'Online', 'Offline'
* @member {string} dataPolicy The data policy. Possible values include:
* 'Invalid', 'Local', 'Tiered', 'Cloud'
* @member {string} adminUser The user/group who will have full permission in
* this share. Active directory email address. Example: [email protected] or
* Contoso\xyz.
* @member {number} provisionedCapacityInBytes The total provisioned capacity
* in Bytes
* @member {number} [usedCapacityInBytes] The used capacity in Bytes.
* @member {number} [localUsedCapacityInBytes] The local used capacity in
* Bytes.
* @member {string} monitoringStatus The monitoring status. Possible values
* include: 'Enabled', 'Disabled'
*/
constructor() {
super();
}
/**
* Defines the metadata of FileShare
*
* @returns {object} metadata of FileShare
*
*/
mapper() {
return {
required: false,
serializedName: 'FileShare',
type: {
name: 'Composite',
className: 'FileShare',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'String'
}
},
shareStatus: {
required: true,
serializedName: 'properties.shareStatus',
type: {
name: 'Enum',
allowedValues: [ 'Online', 'Offline' ]
}
},
dataPolicy: {
required: true,
serializedName: 'properties.dataPolicy',
type: {
name: 'Enum',
allowedValues: [ 'Invalid', 'Local', 'Tiered', 'Cloud' ]
}
},
adminUser: {
required: true,
serializedName: 'properties.adminUser',
type: {
name: 'String'
}
},
provisionedCapacityInBytes: {
required: true,
serializedName: 'properties.provisionedCapacityInBytes',
type: {
name: 'Number'
}
},
usedCapacityInBytes: {
required: false,
readOnly: true,
serializedName: 'properties.usedCapacityInBytes',
type: {
name: 'Number'
}
},
localUsedCapacityInBytes: {
required: false,
readOnly: true,
serializedName: 'properties.localUsedCapacityInBytes',
type: {
name: 'Number'
}
},
monitoringStatus: {
required: true,
serializedName: 'properties.monitoringStatus',
type: {
name: 'Enum',
allowedValues: [ 'Enabled', 'Disabled' ]
}
}
}
}
};
}
} |
JavaScript | class StashService{
constructor(...deps){
this.$q = deps[0];
this.$filter = deps[1];
this.apiService = deps[2];
this.localeService = deps[3];
this.formNameToId = {};
this.catIdToSlug = {}; // used with pinned posts
this.stash = {
categories: null,
publishedOn: {},
layoutCommons: {},
posts: {},
forms: {},
geo: null
};
}
getContent(type, param, idx, forceRequest) {
if (idx && this.stash[idx] && !forceRequest) {
return $q.when(this.stash[idx]);
}
this.addLangParam(param);
return this.apiService.get('/get_' + type, param)
.then(function (result) {
return result;
});
};
getMenu(menuLocation, forceRequest, isMainNav) {
if (forceRequest === undefined) {
forceRequest = false;
}
var acLangCode = this.localeService.getActiveLangCode();
if (acLangCode
&& this.stash.layoutCommons[acLangCode]
&& this.stash.layoutCommons[acLangCode][menuLocation]
&& !forceRequest) {
return $q.when(this.stash.layoutCommons[acLangCode][menuLocation]);
}
let path = isMainNav ? '/menus/get_main_menu' : '/menus/get_nav_menu';
let params = {'m': menuLocation};
addLangParam(params);
return this.apiService.get(path, params, false, true)
.then((result) => {
if (!this.stash.layoutCommons) {
this.stash.layoutCommons = {};
}
this.addLangKeys('layoutCommons');
var m = result.data;
var remappedItems = {};
// remap by slug to set active item by state.param
angular.forEach(result.data.items, function (mItem, idx) {
if (mItem['object_slug'].length > 0) {
remappedItems[mItem['object_slug']] = mItem;
} else {
if (mItem['type'] === 'custom' && mItem['url'].length > 0) {
let assumeSlug = '';
if (mItem.url == '#' || mItem.url == '/') {
assumeSlug = mItem.title.toLowerCase().replace(' ', '-');
remappedItems[assumeSlug] = mItem;
} else {
// check and remove trailing '/'
if (mItem.url.slice(-1) == '/') {
mItem.url = mItem.url.slice(0, -1);
}
assumeSlug = mItem.url.split('/').pop();
remappedItems[assumeSlug] = mItem;
}
}
}
});
m.items = remappedItems;
this.stash.layoutCommons[acLangCode][m['theme_location']] = m;
return m;
});
};
getEntirePage(slug) {
var self = this;
if (!this.stash.page) {
this.stash.page = {};
}
var acLangCode = this.localeService.getActiveLangCode();
this.addLangKeys('page');
if (this.stash.page[acLangCode][slug]) {
return $q.when(this.stash.page[acLangCode][slug]);
}
return this.getContent('page', {'slug': slug})
.then(function (result) {
return self.stash.page[acLangCode][slug] = result.page;
})
};
getPostCards(cat, force) {
let excludePosts = [];
let params = {
orderby: 'date',
order: 'DESC',
paged: 0
};
var acLangCode = this.localeService.getActiveLangCode();
if (!this.stash.posts[acLangCode]) {
this.addLangKeys('posts');
}
if (angular.isObject(cat)) {
var catSlug = cat['object_slug'];
params.cat = cat['object_id'];
force = true;
} else {
params['cat-slug'] = cat;
catSlug = cat;
}
/**
* this is good, but for parent categories, the post_count == 0
* so have to look at the total count for child cats
**/
let existing = preventNewRequest(catSlug);
if (!force && existing) {
/**
* If there are posts to exclude, we already have all posts, since there's no
* paging implemented anywhere
*
* TODO: implement paging
**/
return $q.when(existing);
}
if (this.stash.categories[acLangCode] && this.stash.categories[acLangCode][catSlug]) {
angular.forEach(Object.keys(this.stash.categories[acLangCode][catSlug].posts),
function (postSlug) {
excludePosts.push(this.stash.posts[acLangCode][postSlug].id);
});
params.notin = excludePosts.join(',');
params['posts_per_page'] = 10;
}
addLangParam(params);
return this.apiService.get('/monposts/get_post_cards', params)
.then(function (result) {
angular.forEach(result.data, function (post) {
if (!this.stash.posts[acLangCode][post.slug]) {
// decode chars that might have been encoded when creating the JSON
post.title = $.parseHTML(post.title)[0].nodeValue;
this.stash.posts[acLangCode][post.slug] = post;
}
//remapCustomAttachmentsByLang(post);
remapAttachemntsByLang(post);
cacheCats(post);
mapPostsByDate(post);
setPinnedPostForCat(post);
});
return getPostsUnderCat(catSlug);
})
};
getSinglePostCard(postSlug) {
var acLangCode = this.localeService.getActiveLangCode();
if (!this.stash.posts[acLangCode][postSlug]) {
return $q.reject();
}
return $q.when(this.stash.posts[acLangCode][postSlug]);
};
getSinglePostById(postId) {
let theCard = null;
var acLangCode = this.localeService.getActiveLangCode();
if (!acLangCode) {
return $q.reject();
}
if (!this.stash.posts[acLangCode]) {
this.stash.posts[acLangCode] = {};
}
angular.forEach(this.stash.posts[acLangCode], function (post) {
if (post.id == postId) {
theCard = post;
}
});
if (theCard) {
return $q.when(theCard);
}
let params = {
id: postId
};
//addLangParam(params);
return this.apiService.get('/monposts/get_single_post', params)
.then(function (result) {
if (result) {
return getSinglePostSuccessHandler(result.data.post, acLangCode);
} else {
console.warn('no post found with ID: ', postId)
}
});
};
getSinglePost(postSlug) {
let params = {
slug: postSlug
};
var acLangCode = this.localeService.getActiveLangCode();
if (!acLangCode) {
return $q.reject();
}
if (!this.stash.posts[acLangCode]) {
this.stash.posts[acLangCode] = {};
}
if (this.stash.posts[acLangCode] && this.stash.posts[acLangCode][postSlug]) {
if (this.stash.posts[acLangCode][postSlug].content) {
return $q.when(this.stash.posts[acLangCode][postSlug])
}
} else {
this.stash.posts[acLangCode][postSlug] = {};
}
this.addLangKeys('posts');
addLangParam(params);
return this.apiService.get('/monposts/get_single_post', params)
.then(function (result) {
//console.log('######################## ', result)
return getSinglePostSuccessHandler(result.data.post, acLangCode);
});
};
getAllCategories() {
var self = this;
var acLangCode = this.localeService.getActiveLangCode();
if (this.stash.categories && this.stash.categories[acLangCode]) {
return this.$q.when(this.stash.categories[acLangCode]);
}
this.addLangKeys('categories');
let params = {};
this.addLangParam(params);
return this.apiService.get('/get_category_index', params)
.then(function (result) {
//this.stash.categories = {}; // result.categories;
let tmpCatMap = {};
angular.forEach(result.categories, function (cat) {
cat.posts = [];
cat.childSlugs = [];
self.stash.categories[acLangCode][cat.slug] = cat;
catIdToSlug[cat.id] = cat.slug;
if (!cat.parent) {
// top-level category
tmpCatMap[cat.id] = cat.slug;
}
});
// add both-way reference between parents and children
angular.forEach(self.stash.categories[acLangCode], function (cat) {
if (cat.parent) {
let parent = self.stash.categories[acLangCode][tmpCatMap[cat.parent]];
parent.childSlugs.push(cat.slug);
parent['post_count'] += 1;
// replace the parent ID with parent-slug
cat.parent = parent.slug;
}
});
return self.stash.categories[acLangCode];
})
};
getPublishingIntervals() {
return this.stash.publishedOn;
};
getForm(fId) {
//console.log('getForm by ID ', fId, ' ---- ', this.stash.forms);
if (this.stash.forms[fId]) {
return $q.when(this.stash.forms[fId]);
}
let params = {fid: fId};
addLangParam(params);
return this.apiService.get('/forms/get_form', params)
.then(function (result) {
console.log(result);
this.stash.forms[result.id] = result;
return result;
})
};
getFormByName(fName) {
//console.log('getFormByName ', formNameToId, ' ... ', formNameToId[fName]);
if (formNameToId[fName]) {
return this.getForm(formNameToId[fName]);
}
let params = {fname: fName};
addLangParam(params);
return this.apiService.get('/forms/get_form_by_name', params)
.then(function (result) {
formNameToId[result.title.toLowerCase()] = result.id;
this.stash.forms[result.id] = result;
return result;
})
};
submitForm(fId, fields) {
return this.apiService.postJSON('/forms/submit_form', {id: fId, fields: fields})
.then(function (result) {
{
console.log('Submitted form ' + fId + ' => ', result)
return result;
}
})
};
submitDownloadAttForm(fId, fields) {
return this.apiService.postJSON('/forms/submit_download_attachments_form',
{id: fId, fields: fields})
.then(function (result) {
{
console.log('Submitted form ' + fId + ' => ', result)
return result;
}
})
};
getStashedData(keyChain) {
return Object.getByString(this.stash, keyChain);
};
putDataToStash(keyChain, data) {
return Object.setByString(this.stash, keyChain, data);
};
getLatestPost(catSlug) {
let theCat = this.stash.categories[this.localeService.getActiveLangCode()][catSlug];
return theCat ? theCat.latest : false;
};
setLatestPost(cat, post) {
var acLangCode = this.localeService.getActiveLangCode();
if (post && cat && this.stash.categories[acLangCode][cat]) {
this.stash.categories[acLangCode][cat].latest = {
id: post.id,
slug: post.slug
}
}
};
getPinnedPostForCat(catSlug){
if(!catSlug){
return false;
}
let theCat = this.stash.categories[this.localeService.getActiveLangCode()][catSlug];
return theCat.pinned ? theCat.pinned : false;
};
isPostPinned(catId){
if(!catId){
return false;
}
return catIdToSlug[catId]; // return slug || undefined
};
///
cacheCats(post) {
var acLangCode = this.localeService.getActiveLangCode();
if (!this.stash.categories || !this.stash.categories[acLangCode]) {
return false;
}
angular.forEach(post.categories, function (cat) {
// make it a map to ensure unique elements, without looping every time
this.stash.categories[acLangCode][cat.slug]['posts'][post.slug] = post.id;
// also, it allows saving the same slug on multiple levels of cat hierarchy
if (cat.parent) {
let parentSlug = '';
angular.forEach(this.stash.categories[acLangCode], function (aCat, slug) {
if (aCat.id == cat.parent) {
parentSlug = aCat.slug;
return;
}
});
this.stash.categories[acLangCode][parentSlug]['posts'][post.slug] = post.id;
}
});
}
mapPostsByDate(post) {
let date = new Date(post.date),
y = date.getFullYear(),
m = date.getMonth(),
dateKey = y + '-' + m;
if (!this.stash.publishedOn[dateKey]) {
this.stash.publishedOn[dateKey] = []
}
// save this on post for future ref.
post.year = y;
post.month = m;
this.stash.publishedOn[dateKey].push({
id: post.id,
slug: post.slug,
timestamp: post.date
});
this.stash.publishedOn[dateKey] = $filter('orderBy')(this.stash.publishedOn[dateKey], 'timestamp', true);
}
getPostsUnderCat(catSlug) {
let out = [];
var acLangCode = this.localeService.getActiveLangCode();
if (!this.stash.categories[acLangCode][catSlug]) {
return out;
}
angular.forEach(Object.keys(this.stash.categories[acLangCode][catSlug].posts),
function (postSlug) {
out.push(this.stash.posts[acLangCode][postSlug]);
});
return out;
}
remapAttachemntsByLang(post) {
var mapped = {};
if (post.attachments.length > 0) {
angular.forEach(post.attachments, function (att) {
if (att.lang) {
mapped[att.lang] = att;
} else {
mapped[att.id + ''] = att;
}
})
}
post.attachments = mapped;
}
preventNewRequest(catSlug) {
var acLangCode = this.localeService.getActiveLangCode();
if (!catSlug || !this.stash.categories[acLangCode]) {
return false;
}
let out = getPostsUnderCat(catSlug);
let catPostCount = this.stash.categories[acLangCode][catSlug] ? this.stash.categories[acLangCode][catSlug]['post_count'] : null;
return out && out.length >= catPostCount ? out : false;
}
remapCustomAttachmentsByLang(post) {
var mapped = {};
if (post.attachments.length > 0) {
angular.forEach(post.attachments, function (att) {
if (att.lang) {
mapped[att.lang] = att;
} else {
mapped[att.id + ''] = att;
}
})
}
post.attachments = mapped;
}
addLangKeys(keyChain) {
var self = this;
angular.forEach(this.localeService.languages, function (lang, langKey) {
self.putDataToStash(keyChain + '.' + langKey, {});
})
}
addLangParam(params) {
if (this.localeService.defaultLangCode != this.localeService.getActiveLangCode()) {
params.lang = this.localeService.getActiveLangCode();
}
}
getSinglePostSuccessHandler(post, lang) {
//console.log('getSinglePostSuccessHandler - ', post, ' --- ', lang);
if (!this.stash.posts[lang][post.slug]) {
remapAttachemntsByLang(post);
this.stash.posts[lang][post.slug] = post;
} else {
angular.extend(this.stash.posts[lang][post.slug], post);
}
// add the prev and next urls to the post object too (optional)
//this.stash.posts[lang][post.slug]['prev_url'] = data['previous_slug'] || null;
//this.stash.posts[lang][post.slug]['next_url'] = data['next_slug'] || null;
return this.stash.posts[lang][post.slug];
}
setPinnedPostForCat(post){
if(post['custom_fields']['category_sticky_post']){
let acLangCode = this.localeService.getActiveLangCode();
let catId = post['custom_fields']['category_sticky_post'];
if(this.stash.categories[acLangCode][catIdToSlug[catId]]) {
this.stash.categories[acLangCode][catIdToSlug[catId]]['pinned'] = {
id: post.id,
slug: post.slug
}
}
}
}
static factory(...deps) {
return new StashService(...deps);
}
} |
JavaScript | class Fragment {
static create ({applicationHeader}) {
}
static from (transportPayload) {
}
constructor (options) {
}
get applicationBuffer () {
}
get applicationHeader () {
}
get userData () {
}
toString () {
}
} |
JavaScript | class AuthController {
static async signUp(req, res, next) {
const {
userName, password, confirm_password, email, firstName, lastName
} = req.body;
if (password !== confirm_password) {
return res.status(400).json({
msg: 'Password incorrect'
});
}
User.findOne({
userName
}).then((user) => {
if (user) {
return res.status(400).json({
msg: 'Username already taken'
});
}
User.findOne({
email
}).then((user) => {
if (user) {
return res.status(400).json({
msg: 'email already been registerd. did you forget your password'
});
}
const newUser = new User({
userName,
email,
password,
firstName,
lastName,
userType: 'user'
});
console.log(newUser);
// hash password
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then((user) => {
res.status(201).json({
success: true,
msg: `i am please to inform you that ${user.userName} is registerd`
});
})
.catch((err) => {
res.json({
error: err
});
});
});
});
});
});
}
static async login(req, res, next) {
const { email, userName, password } = req.body;
// let me = req.header['x-access-token']
// console.log(me)
User.findOne({ email }).then((user) => {
if (!user) {
res.status(404).json({
msg: 'no email found',
success: false
});
return;
}
User.findOne({ userName }).then((userName) => {
if (!userName) {
res.status(404).json({
msg: 'no user found',
success: false
});
return;
}
bcrypt
.compare(password, user.password)
//
.then((ismatch) => {
if (ismatch) {
const payload = {
_id: user._id,
userName: user.userName,
password: user.password,
email: user.email,
userType: user.userType
};
jwt.sign(
payload,
process.env.SECRET_KEY,
{
expiresIn: '1h'
},
(err, token) => {
res.status(200).json({
success: true,
token: `Bearer ${token}`,
user,
msg: 'you are now logged in'
});
// token
// let me= req.header['x-access-token'] =token
// console.log(me)
}
);
} else {
return res.status(404).json({
success: false,
msg: 'incorrect password'
});
}
});
});
//
});
}
} |
JavaScript | class FireFerret {
constructor (options) {
const mongoOpts = generateOptions(options.mongo, 'mongo')
const cacheOpts = generateOptions(options, 'cache')
const mongoClientOpts = generateOptions(options.mongo, 'mongoClient')
const redisClientOpts = generateOptions(options.redis, 'redisClient')
this.mongo = new MongoClient(mongoOpts.uri, mongoOpts, mongoClientOpts)
this.cache = new Cache(cacheOpts, redisClientOpts)
debug('FireFerret client created')
}
/**
* Establish a connection to both data stores.
* @returns {string} The connection status.
*/
async connect () {
await this.cache.connect()
await this.mongo.connect()
return 'ok'
}
/**
* Gracefully close all active connections.
* @returns {string} The close status.
*/
async close () {
await this.cache.close()
await this.mongo.close()
return 'ok'
}
/**
* @typedef {Object} Query
* You can find more information on querying documents {@link https://docs.mongodb.com/manual/tutorial/query-documents/|here}.
*
* @example
* { name: { $in: ['Foo', 'Bar'] } }
*/
/**
* Fetch MongoDB documents from a query.
*
* @param {Query} [query={}] - An optional cursor query object.
* @param {Object} [options={}] - Optional settings.
* @param {String} [collection=null] - The collection to fetch from when not using the default.
* @param {Boolean} [options.hydrate=false] - JSON.parse documents and attempt to reformat types (performance hit).
* @param {Boolean} [options.stream=false] - Return the documents as a stream.
* @param {Boolean} [options.wideMatch=false] - Use Wide-Match strategy.
*
* @returns {Array|null} documents
*/
async fetch (query, options, collectionName = null) {
if (!options) options = {}
if (!query) query = {}
const queryKey = new QueryKey(
this.mongo.dbName,
collectionName || this.mongo.collectionName,
query,
options
)
const { queryList, matchType } = await this.cache.getQueryList(queryKey)
const verdict =
!queryList || queryList.length === 0
? CACHE_MISS
: queryList && queryList[0] === EMPTY_QUERY.description
? EMPTY_QUERY
: CACHE_HIT
debug(verdict.description, '@', queryKey.toString())
if (CACHE_HIT === verdict) {
/* check match type and cache new QL if needed */
if (matchType === 'wide') {
this.cache.setQueryList(queryKey, queryList)
return this.cache.getDocuments(fastReverse(queryList), queryKey, {
stream: options.stream,
hydrate: options.hydrate
})
}
return this.cache.getDocuments(queryList, queryKey, {
stream: options.stream,
hydrate: options.hydrate
})
}
if (CACHE_MISS === verdict) {
const pageOptions = validatePaginationOpts(options)
const mongoQueryOptions = {}
/* with pagination */
if (pageOptions) {
mongoQueryOptions.skip = pageOptions.start
mongoQueryOptions.limit = pageOptions.size
debug('using pagination', mongoQueryOptions)
}
if (!options.stream) {
const documents = await this.mongo.findDocs(
queryKey,
mongoQueryOptions
)
/* cache query */
this.cache.setDocuments(queryKey, documents)
return documents
}
const { sink, capture } = await this.mongo.findDocsStream(
queryKey,
mongoQueryOptions
)
/* wait for Mongo to finish streaming us docs, then do a cache operation */
sink.on('end', () => {
/* only cache if we need to */
if (capture.length > 0) this.cache.setDocuments(queryKey, capture)
})
return sink
}
if (EMPTY_QUERY === verdict) {
/* no document(s) found */
return null
}
}
/**
* Fetch one MongoDB document from an ID string.
*
* @param {String} documentID - The `_id` of the requested document.
*
* @returns {Object|null} The document.
*/
async fetchById (documentID, options, collectionName = null) {
if (!options) options = {}
const hex = /^[a-fA-F0-9]+$/
if (!documentID || (documentID && !hex.test(documentID))) {
throw new FerretError(
'InvalidArguments',
'documentID is a required parameter and must be a valid 12-byte hexadecimal string or of type ObjectID',
'fetch::fetchById',
{ documentID }
)
}
if (documentID.constructor === ObjectID) {
documentID = documentID.toHexString()
}
if (documentID.constructor !== String) {
return new FerretError(
'InvalidOptions',
'documentID must be of type String or ObjectID',
'client::fetchById',
{ documentID }
)
}
const queryKey = new QueryKey(
this.mongo.dbName,
collectionName || this.mongo.collectionName,
{ _id: documentID },
null
)
const document = await this.cache.getDocument(
documentID,
queryKey.collectionName
)
if (document == null) {
debug('cache miss', { _id: documentID })
let doc = await this.mongo.findDocs(queryKey)
if (!doc || (doc && !doc._id)) {
doc = null
}
this.cache.setDocument(doc, documentID, queryKey.collectionName)
return doc
}
debug('cache hit', { _id: documentID })
if (document === NULL_DOC.description) {
return null
}
const parsed = options.hydrate ? hydrate(document) : JSON.parse(document)
return parsed
}
/**
* Fetch the first MongoDB document from a query.
*
* @param {Object} [query={}] - An optional cursor query object.
*
* @returns {Object|null} The document.
*/
async fetchOne (query, options, collectionName) {
if (!options) options = {}
const queryKey = new QueryKey(
this.mongo.dbName,
collectionName || this.mongo.collectionName,
query,
null
)
const oneKey = queryKey.oneKey()
const queryString = queryKey.queryString()
const documentID = await this.cache.getQueryHash(oneKey, queryString)
if (!documentID) {
debug('cache miss', oneKey, queryString)
let document = await this.mongo.findOne(queryKey)
if (!document || !document._id) {
document = null
}
const documentID = document
? document._id.toHexString()
: EMPTY_QUERY.description
this.cache.setQueryHash(oneKey, queryString, documentID)
if (document) {
this.cache.setDocument(document, null, queryKey.collectionName)
}
return document
}
debug('cache hit', oneKey, queryString)
if (documentID === EMPTY_QUERY.description) {
return null
}
const document = await this.cache.getDocument(
documentID,
queryKey.collectionName
)
if (document === NULL_DOC.description) {
return null
}
const parsed = options.hydrate ? hydrate(document) : JSON.parse(document)
return parsed
}
} |
JavaScript | class Edge {
constructor(vertex, weight) {
this.vertex = vertex;
this.weight = weight;
}
} |
JavaScript | class Tools {
static debug(message) {
console.debug(message)
}
static findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
static setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
static getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
static generateUID() {
// I generate the UID from two parts here
// to ensure the random number provide enough bits.
var firstPart = (Math.random() * 46656) | 0;
var secondPart = (Math.random() * 46656) | 0;
firstPart = ("000" + firstPart.toString(36)).slice(-3);
secondPart = ("000" + secondPart.toString(36)).slice(-3);
return firstPart + secondPart;
}
static hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
static intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "#" + ("00000".substring(0, 6 - c.length) + c);
}
static shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
static get360Angle(angle) {
if (angle > 359) {
return angle - 359;
}
else if (angle < 0) {
return 360 + angle;
}
return angle;
}
} |
JavaScript | class AbortRecoveryRouter extends AuxWorkflowRouterBase {
/**
* Constructor for abort recovery by recovery controller router.
*
* @augments AuxWorkflowRouterBase
*
* @constructor
*/
constructor(params) {
params.workflowKind = workflowConstants.abortRecoveryByRecoveryControllerKind; // Assign workflowKind.
super(params);
}
/**
* Fetch current step config for every router.
*
* @sets oThis.currentStepConfig
*
* @private
*/
_fetchCurrentStepConfig() {
const oThis = this;
oThis.currentStepConfig = abortRecoveryConfig[oThis.stepKind];
}
/**
* Perform step.
*
* @return {Promise<*>}
* @private
*/
async _performStep() {
const oThis = this;
const configStrategy = await oThis.getConfigStrategy(),
ic = new InstanceComposer(configStrategy);
switch (oThis.stepKind) {
case workflowStepConstants.abortRecoveryByRecoveryControllerInit: {
logger.step('**********', workflowStepConstants.abortRecoveryByRecoveryControllerInit);
return oThis.insertInitStep();
}
// Perform transaction to abort recovery.
case workflowStepConstants.abortRecoveryByRecoveryControllerPerformTransaction: {
logger.step('**********', workflowStepConstants.abortRecoveryByRecoveryControllerPerformTransaction);
require(rootPrefix + '/lib/deviceRecovery/byRecoveryController/abortRecovery/PerformTransaction');
oThis.requestParams.pendingTransactionExtraData = oThis._currentStepPayloadForPendingTrx();
oThis.requestParams.workflowId = oThis.workflowId;
const PerformAbortRecoveryByRecoveryControllerTransaction = ic.getShadowedClassFor(
coreConstants.icNameSpace,
'PerformAbortRecoveryByRecoveryControllerTransaction'
),
performAbortRecoveryByRecoveryControllerTransactionObj = new PerformAbortRecoveryByRecoveryControllerTransaction(
oThis.requestParams
);
return performAbortRecoveryByRecoveryControllerTransactionObj.perform();
}
// Verify abort recovery transaction.
case workflowStepConstants.abortRecoveryByRecoveryControllerVerifyTransaction: {
logger.step('**********', workflowStepConstants.abortRecoveryByRecoveryControllerVerifyTransaction);
require(rootPrefix + '/lib/deviceRecovery/byRecoveryController/abortRecovery/VerifyTransaction');
const VerifyAbortRecoveryByRecoveryControllerTransaction = ic.getShadowedClassFor(
coreConstants.icNameSpace,
'VerifyAbortRecoveryByRecoveryControllerTransaction'
),
verifyAbortRecoveryByRecoveryControllerTransactionObj = new VerifyAbortRecoveryByRecoveryControllerTransaction(
oThis.requestParams
);
return verifyAbortRecoveryByRecoveryControllerTransactionObj.perform();
}
case workflowStepConstants.markSuccess: {
logger.step('*** Mark Abort Recovery As Success.');
const preProcessorWebhookDetails = oThis.preProcessorWebhookDetails(true);
await oThis.sendPreprocessorWebhook(preProcessorWebhookDetails.chainId, preProcessorWebhookDetails.payload);
return await oThis.handleSuccess();
}
case workflowStepConstants.markFailure: {
logger.step('*** Mark Abort Recovery As Failed');
const preProcessorWebhookDetails = oThis.preProcessorWebhookDetails(false);
await oThis.sendPreprocessorWebhook(preProcessorWebhookDetails.chainId, preProcessorWebhookDetails.payload);
return await oThis.handleFailure();
}
default: {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_w_dr_brc_ar_r_1',
api_error_identifier: 'something_went_wrong',
debug_options: { workflowId: oThis.workflowId }
})
);
}
}
}
/**
* Get next step configs.
*
* @param {string} nextStep
*
* @return {*}
*/
getNextStepConfigs(nextStep) {
return abortRecoveryConfig[nextStep];
}
/**
* Get config strategy.
*
* @return {Promise<*>}
*/
async getConfigStrategy() {
const oThis = this;
const rsp = await chainConfigProvider.getFor([oThis.chainId]);
return rsp[oThis.chainId];
}
/**
* Get preprocessor webhook details.
*
* @param {boolean} status: true for success, false for failure.
*
* @returns {{chainId: string, payload: {webhookKind: string, clientId: string, tokenId: string,
* oldDeviceAddress: string, newDeviceAddress: string, userId: string}}}
*/
preProcessorWebhookDetails(status) {
const oThis = this;
return {
chainId: oThis.requestParams.auxChainId,
payload: {
webhookKind: status
? webhookSubscriptionsConstants.devicesRecoveryAbortSuccessTopic
: webhookSubscriptionsConstants.devicesRecoveryAbortFailureTopic,
clientId: oThis.requestParams.clientId,
tokenId: oThis.requestParams.tokenId,
userId: oThis.requestParams.userId,
oldDeviceAddress: oThis.requestParams.oldDeviceAddress,
newDeviceAddress: oThis.requestParams.newDeviceAddress
}
};
}
} |
JavaScript | class DBusInterfaceDefinition {
constructor (data) {
this.data = data
Object.defineProperty(this, 'name', {
get: () => {
return this.data.$.name
}
})
}
// return [{ direction: 'in' or 'out', type: 'sig' }]
/**
return the signature of the method
@param {string} name - method name
@returns { object || undefined }
*/
method (name) {
if (this.data && this.data.method) {
let m = this.data.method.find(o => o.$.name === name)
if (m) return m.arg ? m.arg.map(x => x.$) : []
}
}
signal (name) {
}
property (name) {
}
// return [[name, sig]]
properties () {
let props = []
if (this.data.property) {
props = this.data.property.map(o => [o.$.name, o.$.type, o.$.direction])
}
return props
}
} |
JavaScript | class WeekPicker extends HTMLElement {
//Hold the current date end and date starts
dateStart = new Date();
dateEnd = new Date();
constructor(){
super();
this.attachShadow({ mode: 'open' })
const template = document.createElement('template');
template.innerHTML = `
<div class="full-date">
<i class='left-arrow' id="prev"></i>
<h1 id="date"></h1>
<i class='right-arrow' id="next"></i>
</div>
`
let style = document.createElement('style');
style.textContent = `
.full-date {
display: flex;
flex-direction: row;
position: relative;
top: 45px;
left: 100px;
align-items: center;
justify-content: center;
padding-top: 3.0rem;
margin-bottom: 1.4rem;
}
.left-arrow {
color: white;
border-style: solid;
border-width: 1px 1px 0 0;
content: '';
display: inline-block;
height: 1.5em;
width: 1.5em;
position: sticky;
vertical-align: top;
margin-right: 5em;
transform: rotate(-135deg);
}
.right-arrow{
color: white;
border-style: solid;
border-width: 1px 1px 0 0;
content: '';
display: inline-block;
height: 1.5em;
width: 1.5em;
position: sticky;
vertical-align: top;
margin-left: 5em;
transform: rotate(45deg);
}
#date {
display: flex;
position: sticky;
margin-left: 0.5em;
align-items: center;
color: white;
font-family: 'Lato', sans-serif;
font-weight: 300;
}
`
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.appendChild(style);
this.dateEnd.setDate(this.dateStart.getDate() + 7);
let startText = this.dateStart.toLocaleString('default', {month: 'long'}) + " " + this.dateStart.getDate() + ", " + this.dateStart.getFullYear();
let endText = this.dateEnd.toLocaleString('default', {month: 'long'}) + " " + this.dateEnd.getDate() + ", " + this.dateEnd.getFullYear();
//Set beginning text
this.shadowRoot.getElementById("date").innerText = startText + " — " + endText;
//Add event listeners for clicking on the arrows
this.shadowRoot.getElementById("next").addEventListener('click', () => {
//Change week
this.plusWeek();
//Fire event to create entry-creators
document.dispatchEvent(new CustomEvent("weekChange", {
detail: {
start: this.dateStart,
end: this.dateEnd
}
}));
});
this.shadowRoot.getElementById("prev").addEventListener('click', ()=> {
//change week
this.minusWeek();
//Fire event to create entry-creators
document.dispatchEvent(new CustomEvent("weekChange", {
detail: {
start: this.dateStart,
end: this.dateEnd
}
}));
});
this.sendArray();
}
/**
* Function which goes to the next week by changing internal dates and resetting text
*/
plusWeek(){
//this.dateStart = new Date(this.dateEnd.toDateString());
this.dateStart.setDate(this.dateStart.getDate() + 7);
this.dateEnd.setDate(this.dateEnd.getDate() + 7);
let startText = this.dateStart.toLocaleString('default', {month: 'long'}) + " " + this.dateStart.getDate() + ", " + this.dateStart.getFullYear();
let endText = this.dateEnd.toLocaleString('default', {month: 'long'}) + " " + this.dateEnd.getDate() + ", " + this.dateEnd.getFullYear();
//Set text
this.shadowRoot.getElementById("date").innerText = startText + " — " + endText;
}
/**
* Function which goes to the last week by changing internal dates and resetting the text
*/
minusWeek(){
let temp = new Date(this.dateStart.toDateString());
this.dateStart.setDate(this.dateStart.getDate() - 7);
this.dateEnd.setDate(this.dateEnd.getDate() - 7);
let startText = this.dateStart.toLocaleString('default', {month: 'long'}) + " " + this.dateStart.getDate() + ", " + this.dateStart.getFullYear();
let endText = this.dateEnd.toLocaleString('default', {month: 'long'}) + " " + this.dateEnd.getDate() + ", " + this.dateEnd.getFullYear();
//Set text
this.shadowRoot.getElementById("date").innerText = startText + " — " + endText;
}
/**
* Makes and returns an array of date strings between dateStart and dateEnd
* @returns {Array} - Returns the array of date strings between dateStart and dateEnd
*/
sendArray(){
let array = [];
let currDate = new Date(this.dateStart.toDateString());
while (currDate.toDateString() != this.dateEnd.toDateString()){
array.push(currDate.toDateString());
currDate.setDate(currDate.getDate() + 1);
}
array.push(this.dateEnd.toDateString());
return array;
}
} |
JavaScript | class FilterOperation extends AbstractFilterOperation {
/**
*
* @param {*} label
* @param {*} acceptFunction
*/
constructor(label, acceptFunction) {
super();
this.label = label;
this.acceptFunction = acceptFunction;
}
/**
* It returns uniquie string label of the filter representing operator given by the parameter of constructor.
*/
toString() {
return this.label;
}
/**
* It performs the filter operation which compare a value with a pattern.
*
* @param {any} value
* @param {any} pattern
*/
match(value, pattern) {
return this.acceptFunction(value, pattern);
}
} |
JavaScript | class VisualizationModel extends Model {
constructor(server) {
const schema = Joi.object().keys({
title: Joi.string(),
description: Joi.string().default(null),
visState: Joi.object().default({}),
uiStateJSON: Joi.string().default(null),
savedSearchId: Joi.string(),
version: Joi.number().integer(),
kibanaSavedObjectMeta: Joi.object().keys({
searchSourceJSON: Joi.string()
})
});
super(server, 'visualization', schema, 'Visualization');
}
} |
JavaScript | class ComponentManager {
constructor(theme) {
this.theme = theme;
this.components = {
"title": TitleComponent,
"range": RangeComponent,
"button": ButtonComponent,
"checkbox": CheckboxComponent,
"select": SelectComponent,
"text": TextComponent,
"color": ColorComponent,
"folder": FolderComponent,
"file": FileComponent,
"display": DisplayComponent,
"interval": IntervalComponent,
};
}
/**
* Creates the component specified by `opts` and appends it to the
* document as a child of `root`.
*
* @param {HTMLElement} [root] Parent of the created component
* @param {Object} [opts] Options used to create the component
*/
Create(root, opts) {
let initializer = this.components[opts.type];
if(initializer === undefined) {
throw new Error(`No component type named '${opts.type}' exists.`);
}
let newComponent = new initializer(root, opts, this.theme);
return newComponent;
}
} |
JavaScript | class WaffleIron {
#instance = null;
/**
* Create the waffle iron.
*
* @hideconstructor
*/
constructor() {
if (this.#instance) {
return this.#instance;
}
/**
* Cook a waffle.
*
* @param {Batter} batter - The waffle batter.
* @return {Waffle} The cooked waffle.
*/
this.cook = function(batter) {};
this.#instance = this;
}
/**
* Get the WaffleIron instance.
*
* @return {WaffleIron} The WaffleIron instance.
*/
getInstance() {
return new WaffleIron();
}
} |
JavaScript | class EffortColumn extends DurationColumn {
static get type() {
return 'effort';
}
static get $name() {
return 'EffortColumn';
}
//region Config
static get defaults() {
return {
field : 'fullEffort',
text : 'L{Effort}'
};
}
//endregion
get defaultEditor() {
return {
type : EffortField.type,
name : this.field
};
}
// Can only edit leafs
canEdit(record) {
return record.isLeaf;
}
} |
JavaScript | class Node {
constructor(value) {
this.value = value;
this.next = null;
}
} |
JavaScript | class Queue extends queue_base_1.QueueBase {
constructor(scope, id, props = {}) {
super(scope, id);
this.autoCreatePolicy = true;
validate_props_1.validateProps(props);
const redrivePolicy = props.deadLetterQueue
? {
deadLetterTargetArn: props.deadLetterQueue.queue.queueArn,
maxReceiveCount: props.deadLetterQueue.maxReceiveCount
}
: undefined;
const { encryptionMasterKey, encryptionProps } = _determineEncryptionProps.call(this);
const queue = new sqs_generated_1.CfnQueue(this, 'Resource', Object.assign({ queueName: props.queueName }, this.determineFifoProps(props), encryptionProps, { redrivePolicy, delaySeconds: props.deliveryDelaySec, maximumMessageSize: props.maxMessageSizeBytes, messageRetentionPeriod: props.retentionPeriodSec, receiveMessageWaitTimeSeconds: props.receiveMessageWaitTimeSec, visibilityTimeout: props.visibilityTimeoutSec }));
this.encryptionMasterKey = encryptionMasterKey;
this.queueArn = queue.queueArn;
this.queueName = queue.queueName;
this.queueUrl = queue.ref;
function _determineEncryptionProps() {
let encryption = props.encryption || QueueEncryption.Unencrypted;
if (encryption !== QueueEncryption.Kms && props.encryptionMasterKey) {
encryption = QueueEncryption.Kms; // KMS is implied by specifying an encryption key
}
if (encryption === QueueEncryption.Unencrypted) {
return { encryptionProps: {} };
}
if (encryption === QueueEncryption.KmsManaged) {
const masterKey = kms.EncryptionKey.import(this, 'Key', {
keyArn: 'alias/aws/sqs'
});
return {
encryptionMasterKey: masterKey,
encryptionProps: {
kmsMasterKeyId: 'alias/aws/sqs',
kmsDataKeyReusePeriodSeconds: props.dataKeyReuseSec
}
};
}
if (encryption === QueueEncryption.Kms) {
const masterKey = props.encryptionMasterKey || new kms.EncryptionKey(this, 'Key', {
description: `Created by ${this.node.path}`
});
return {
encryptionMasterKey: masterKey,
encryptionProps: {
kmsMasterKeyId: masterKey.keyArn,
kmsDataKeyReusePeriodSeconds: props.dataKeyReuseSec
}
};
}
throw new Error(`Unexpected 'encryptionType': ${encryption}`);
}
}
/**
* Import an existing queue
*/
static import(scope, id, props) {
return new ImportedQueue(scope, id, props);
}
/**
* Export a queue
*/
export() {
return {
queueArn: new cdk.CfnOutput(this, 'QueueArn', { value: this.queueArn }).makeImportValue().toString(),
queueUrl: new cdk.CfnOutput(this, 'QueueUrl', { value: this.queueUrl }).makeImportValue().toString(),
keyArn: this.encryptionMasterKey
? new cdk.CfnOutput(this, 'KeyArn', { value: this.encryptionMasterKey.keyArn }).makeImportValue().toString()
: undefined
};
}
/**
* Look at the props, see if the FIFO props agree, and return the correct subset of props
*/
determineFifoProps(props) {
// Check if any of the signals that we have say that this is a FIFO queue.
let fifoQueue = props.fifo;
if (typeof fifoQueue === 'undefined' && typeof props.queueName === 'string' && props.queueName.endsWith('.fifo')) {
fifoQueue = true;
}
if (typeof fifoQueue === 'undefined' && props.contentBasedDeduplication) {
fifoQueue = true;
}
// If we have a name, see that it agrees with the FIFO setting
if (typeof props.queueName === 'string') {
if (fifoQueue && !props.queueName.endsWith('.fifo')) {
throw new Error("FIFO queue names must end in '.fifo'");
}
if (!fifoQueue && props.queueName.endsWith('.fifo')) {
throw new Error("Non-FIFO queue name may not end in '.fifo'");
}
}
if (props.contentBasedDeduplication && !fifoQueue) {
throw new Error('Content-based deduplication can only be defined for FIFO queues');
}
return {
contentBasedDeduplication: props.contentBasedDeduplication,
fifoQueue,
};
}
} |
JavaScript | class ImportedQueue extends queue_base_1.QueueBase {
constructor(scope, id, props) {
super(scope, id);
this.props = props;
this.autoCreatePolicy = false;
this.queueArn = props.queueArn;
this.queueUrl = props.queueUrl;
this.queueName = this.node.stack.parseArn(props.queueArn).resource;
if (props.keyArn) {
this.encryptionMasterKey = kms.EncryptionKey.import(this, 'Key', {
keyArn: props.keyArn
});
}
}
/**
* Export a queue
*/
export() {
return this.props;
}
} |
JavaScript | class AuthorizationBadge {
constructor(jwtPayload, options) {
var _a, _b;
this.roles = [];
this.scopes = [];
this.effectiveScopes = [];
// eslint-disable-next-line no-console
this.infoLogFunction = console.log.bind(console);
// eslint-disable-next-line no-console
this.errorLogFunction = console.error.bind(console);
if (options) {
this.rolesConfig = options.rolesConfig;
this.infoLogFunction = (_a = options.infoLogFunction) !== null && _a !== void 0 ? _a : this.infoLogFunction;
this.errorLogFunction = (_b = options.errorLogFunction) !== null && _b !== void 0 ? _b : this.errorLogFunction;
}
if (jwtPayload) {
if (jwtPayload.g) {
this.userId = jwtPayload.g.gui;
this.teamMemberId = jwtPayload.g.tmi;
this.merchantId = jwtPayload.g.gmi;
this.valueId = jwtPayload.g.gvi;
this.programId = jwtPayload.g.pid;
this.contactId = jwtPayload.g.coi;
this.serviceId = jwtPayload.g.si;
}
this.metadata = jwtPayload.metadata;
this.audience = jwtPayload.aud;
this.issuer = jwtPayload.iss;
this.roles = jwtPayload.roles || [];
this.scopes = jwtPayload.scopes || [];
this.uniqueIdentifier = jwtPayload.jti;
this.parentUniqueIdentifier = jwtPayload.parentJti;
if (typeof jwtPayload.iat === "number") {
this.issuedAtTime = new Date(jwtPayload.iat * 1000);
}
else if (typeof jwtPayload.iat === "string") {
// This is off-spec but something we did in the past.
this.issuedAtTime = new Date(jwtPayload.iat);
}
if (typeof jwtPayload.exp === "number") {
this.expirationTime = new Date(jwtPayload.exp * 1000);
}
}
if (this.issuer === "MERCHANT") {
this.sanitizeMerchantSigned();
}
this.effectiveScopes = this.getEffectiveScopes();
}
getJwtPayload() {
const payload = {
g: {}
};
if (this.userId) {
payload.g.gui = this.userId;
}
if (this.teamMemberId) {
payload.g.tmi = this.teamMemberId;
}
if (this.merchantId) {
payload.g.gmi = this.merchantId;
}
if (this.valueId) {
payload.g.gvi = this.valueId;
}
if (this.programId) {
payload.g.pid = this.programId;
}
if (this.contactId) {
payload.g.coi = this.contactId;
}
if (this.serviceId) {
payload.g.si = this.serviceId;
}
if (this.metadata) {
payload.metadata = this.metadata;
}
if (this.audience) {
payload.aud = this.audience;
}
if (this.issuer) {
payload.iss = this.issuer;
}
if (this.roles.length) {
payload.roles = this.roles;
}
payload.scopes = this.scopes;
if (this.uniqueIdentifier) {
payload.jti = this.uniqueIdentifier;
}
if (this.parentUniqueIdentifier) {
payload.parentJti = this.parentUniqueIdentifier;
}
if (this.issuedAtTime) {
payload.iat = this.issuedAtTime.getTime() / 1000;
}
if (this.expirationTime) {
payload.exp = this.expirationTime.getTime() / 1000;
}
return payload;
}
getAuthorizeAsPayload() {
return Buffer.from(JSON.stringify(this.getJwtPayload()), "utf-8").toString("base64");
}
sign(secret) {
return jwt.sign(this.getJwtPayload(), secret, {
algorithm: "HS256",
header: {
ver: 2,
vav: 1
}
});
}
assumeJwtIdentity(jwtPayload) {
this.requireScopes("ASSUME");
const j = this.getJwtPayload();
j.g = Object.assign(Object.assign({}, jwtPayload.g), { si: this.userId });
j.parentJti = jwtPayload.jti;
const badge = new AuthorizationBadge(j, {
rolesConfig: this.rolesConfig,
infoLogFunction: this.infoLogFunction,
errorLogFunction: this.errorLogFunction
});
badge.scopes = badge.scopes.filter(scope => scope !== "ASSUME");
badge.effectiveScopes = badge.effectiveScopes.filter(scope => scope !== "ASSUME");
return badge;
}
/**
* Require that the given IDs are set on the badge.
* eg: requireIds("userId", "merchantId");
*/
requireIds(...ids) {
for (const id of ids) {
if (!this[id]) {
this.errorLogFunction(`auth missing required id '${id}'`);
throw new cassava.RestError(cassava.httpStatusCode.clientError.FORBIDDEN);
}
}
}
/**
* Returns true if this badge contains the given scope or any parent of the scope.
*/
hasScope(scope) {
for (; scope; scope = getParentScope(scope)) {
if (this.effectiveScopes.indexOf(scope) !== -1) {
return true;
}
}
return false;
}
/**
* Returns true if the badge has all the given scopes.
*/
hasScopes(...scopes) {
for (const scope of scopes) {
if (!this.hasScope(scope)) {
return false;
}
}
return true;
}
/**
* Require that the given scopes are authorized on the badge.
* Throws a RestError if they are not.
*/
requireScopes(...scopes) {
for (const scope of scopes) {
if (!this.hasScope(scope)) {
this.errorLogFunction(`auth missing required scope '${scope}'`);
throw new cassava.RestError(cassava.httpStatusCode.clientError.FORBIDDEN);
}
}
}
/**
* Save the merchant from themselves.
*/
sanitizeMerchantSigned() {
this.merchantId = this.userId;
if (!this.contactId) {
this.contactId = "defaultShopper";
}
this.roles = ["shopper"]; // This might be a whitelist in the future.
this.scopes.length = 0;
}
getEffectiveScopes() {
const effectiveScopes = [];
if (this.rolesConfig) {
this.roles.forEach(roleName => {
const roleConfig = this.rolesConfig.roles.find(roleConfig => roleConfig.name === roleName);
if (!roleConfig) {
this.errorLogFunction(`JWT ${this.uniqueIdentifier} contains an unknown role ${roleName}`);
return;
}
roleConfig.scopes.forEach(scope => {
if (effectiveScopes.indexOf(scope) === -1) {
effectiveScopes.push(scope);
}
});
});
}
this.scopes
.filter(scope => typeof scope === "string" && !scope.startsWith("-"))
.forEach(scope => {
if (effectiveScopes.indexOf(scope) === -1) {
effectiveScopes.push(scope);
}
});
this.scopes
.filter(scope => typeof scope === "string" && scope.startsWith("-"))
.map(scope => scope.substring(1))
.forEach(scope => {
const scopeColon = scope + ":";
let effectiveScopeIx = 0;
while ((effectiveScopeIx = effectiveScopes.findIndex(effectiveScope => effectiveScope === scope || effectiveScope.startsWith(scopeColon), effectiveScopeIx)) !== -1) {
effectiveScopes.splice(effectiveScopeIx, 1);
}
});
return effectiveScopes;
}
isTestUser() {
return this.userId && this.userId.endsWith("-TEST");
}
} |
JavaScript | class CsdlEntityContainerInfo {
/**
* @param {FullQualifiedName} name - OData CSDL # 13.1.1 Attribute Name
*/
constructor(name) {
validateThat('name', name).truthy().instanceOf(Object);
/**
* OData CSDL # 13.1.1 Attribute Name
* @type {FullQualifiedName}
*/
this.name = name;
}
/**
* OData CSDL # 13.1.2 Attribute Extends
* @type {FullQualifiedName}
*/
get extends() {
return null;
}
} |
JavaScript | class TTSHandler {
/**
* Main function of TTS Handler
* @param {String} msg - message to be spoken by Speech Synthesis
*/
static main(msg) {
let speechSynthesisUtterance = new SpeechSynthesisUtterance()
speechSynthesisUtterance.text = msg
window.speechSynthesis.speak(speechSynthesisUtterance)
}
} |
JavaScript | class Event {
constructor(category, name, startTime, endCallback, timer, ctx) {
this.category = category;
this.name = name;
this.startTime = startTime;
this.endCallback = endCallback;
this.timer = timer;
this.ctx = ctx;
}
end() {
return this.endCallback(this);
}
async checkTimer() {
if (this.ctx === undefined || this.timer === undefined) {
throw new Error('No webgl timer found');
}
else {
this.ctx.endTimer();
return this.ctx.waitForQueryAndGetTime(this.timer);
}
}
} |
JavaScript | class ArrayInput extends TatorElement {
constructor() {
super();
this._div = document.createElement("div");
this._shadow.appendChild(this._div)
this.label = document.createElement("label");
this.label.setAttribute("class", "d-flex flex-justify-between flex-items-center py-1");
this._div.appendChild(this.label);
this._name = document.createTextNode("");
this.label.appendChild(this._name);
//
this._inputs = []
// Add new
this.addNewButton = this.addNewRow({
"labelText" : "+ New",
"callback" : ""
});
this._div.appendChild(this.addNewButton);
this.addNewButton.addEventListener("click", (e) => {
e.preventDefault();
this._newInput("");
this.dispatchEvent(new CustomEvent("new-input", { detail : { name : this._name }}));
});
}
static get observedAttributes() {
return ["name"];
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case "name":
this._name.nodeValue = newValue;
break;
}
}
set default(val) {
this._default = val; // this will be an array
}
reset() {
// Go back to default value
if (typeof this._default !== "undefined") {
this.setValue(this._default);
} else {
this.setValue([]);
}
}
setValue(val) {
// console.log(val);
if( Array.isArray(val) && val.length > 0){
for (let key of val) {
let textInput = document.createElement("text-input");
textInput._input.classList.remove("col-8");
textInput.setValue(key);
textInput.default = key;
this._addInput(textInput);
}
}
}
_newInput(val){
let textInput = document.createElement("text-input");
if(val){
textInput.setValue(val);
textInput.default = val;
}
return this._addInput(textInput);
}
_addInput(input){
input._input.classList.remove("col-8");
const wrapper = document.createElement("div");
//wrapper.setAttribute("class", "offset-lg-4 col-lg-8 pb-2");
wrapper.appendChild(input);
const spaceholder = document.createElement("div");
spaceholder.innerHTML = " ";
wrapper.appendChild(spaceholder);
// keep track of text inputs
this._inputs.push(input);
input.addEventListener("change", () => {
this.dispatchEvent(new Event("change"));
});
return this.addNewButton.before(wrapper);
}
addNewRow({
labelText = '',
callback = null
} = {}){
const labelWrap = document.createElement("label");
labelWrap.setAttribute("class", "d-flex flex-items-center py-1 position-relative f1");
const spanTextNode = document.createElement("span");
const spanText = document.createTextNode("");
const labelDiv = document.createElement("div");
spanTextNode.setAttribute("class", "col-sm-4 col-md-3 text-gray clickable");
spanText.nodeValue = labelText;
spanTextNode.appendChild(spanText);
labelWrap.append(spanTextNode);
labelDiv.setAttribute("class", "py-2 f1 text-semibold");
labelDiv.appendChild(labelWrap);
return labelDiv;
}
getValue(){
const val = [];
// Loop through the inputs
for(let input of this._inputs){
if(input.getValue().trim() != ""){
val.push( input.getValue() );
}
}
return val;
}
changed(){
return this.getValue() !== this._default;
}
} |
JavaScript | class Resolution_Class extends Lightning.Component {
/**
* @static
* @returns
* @memberof general settings
* Renders the template
*/
static _template() {
return {
ResolutionBg: {
RectangleWithGradientLeftRight: {
w: 960,
h: 1080,
rect: true,
colorLeft: Colors.DIM_BLACK,
colorRight: Colors.DARK_BLACK
},
BackArrow: { x: 81, y: 54, src: Utils.asset(ImageConstants.BACK_ARROW) },
SettingsLabel: {
x: 133,
y: 54,
text: {
text: Language.translate('Settings'),
fontSize: 28,
textColor: Colors.TRANSPARENT_GREY,
fontFace: 'Regular'
}
},
GeneralSettingsLabel: {
x: 82,
y: 113,
text: {
text: Language.translate('General_Settings'),
fontSize: 36,
textColor: Colors.LIGHTER_WHITE,
fontFace: 'Medium'
}
},
Divider: { rect: true, w: 959.5, h: 2, x: 0.5, y: 178, color: Colors.LIGHTER_BLACK },
DiscoverResolution: {
x: 81,
y: 209,
label: Language.translate('Resolution Settings'),
type: GeneralSettingsTile
},
ResolutionControl: {
x: 85,
y: 325,
text: {
text: Language.translate('Available Resolutions'),
fontSize: 34,
textColor: Colors.TRANSPARENT_GREY,
fontFace: 'Regular'
}
},
DiscoveredResolution: {
type: Lightning.components.ListComponent,
x: 81,
y: 398,
w: 800,
h: 1080,
visible: false,
itemSize: 120,
horizontal: false,
roll: true,
rollMax: 1080,
rollMin: 0,
invertDirection: true
}
},
ThunderResolutionService: {
type: ThunderResolutionService
}
}
}
_init() {
this.availableresolution = "";
/*this.setbestresolution();*/
if(Storage.get("lastsetresolution"))
{
console.log("ResTag:lastsetresolution from storage :",Storage.get("lastsetresolution"))
this.currentresolution =Storage.get("lastsetresolution")
}
else
{
this.tag('ThunderResolutionService').getcurrentresolution().then(data => {
this.currentresolution = data
});
}
this.scanFlag = 1;
this.removeChildFlag = 0;
}
_active() {
this.flag = 0;
this._setState('DiscoverResolution')
}
startScanResolution() {
Log.info('ResolutionUI: startScanResolution enter.')
this.tag('ResolutionControl').patch({
text: { text: 'Searching for available resolutions...' }
})
this.tag('ThunderResolutionService').getavailableresolutions().then(data => {
console.log("Rtag:available resolution", data);
this.availableresolution = data;
setTimeout( ()=> {
Log.info('ResoltionUI: Available Resolutions:', this.availableresolution);
if (this.availableresolution === "") {
this.tag('DiscoverResolution').visible = true
this.tag('ResolutionControl').patch({
text: { text: 'Could not find any resolution. Please try again..' }
})
this._setState('DiscoverResolution')
}
else {
this.tag('DiscoveredResolution').items = this.availableresolution.map((data, index) => {
if (this.currentresolution === data) {
return {
ref: 'DiscoveredResolution' + index,
type: GeneralSettingsTile,
label: data,
secondarylabel: 'Set',
ready: false
}
}
else {
return {
ref: 'DiscoveredResolution' + index,
type: GeneralSettingsTile,
label: data,
secondarylabel: 'Not Set',
ready: false
}
}
});
this.tag('ResolutionControl').patch({
text: { text: 'Available Resolutions' }
})
this._setState('DiscoveredResolution')
}
},1000);
});
}
static _states() {
return [
class DiscoverResolution extends this {
$enter() {
/*if (this.removeFlag === 1) {
this.removeFlag = 0;
this.childList.remove(this.tag('ConnectingPage'))
this.tag('DiscoveredResolution').visible = false
}
else */
this.tag('DiscoveredResolution').visible = true
//if (this.scanFlag === 1) {
// this.scanFlag = 0;
this.startScanResolution()
// }
}
_getFocused() {
return this.tag('DiscoverResolution')
}
_handleDown() {
if (this.tag('DiscoveredResolution').items.length > 0) {
this._setState('DiscoveredResolution')
}
}
_handleEnter() {
Log.info('ResolutionUI: DiscoverResolution Button entered.')
this.startScanResolution()
}
},
class DiscoveredResolution extends this {
$enter() {
this.tag('ResolutionControl').visible = true
this.tag('DiscoveredResolution').visible = true
}
_getFocused() {
if(this.flag ===0)
{
this.flag++
let highresIndex = this.availableresolution.indexOf(this.currentresolution)
return this.tag('DiscoveredResolution').items[highresIndex]
}
else
{
return this.tag('DiscoveredResolution').element
}
}
_handleUp() {
if (0 === this.tag('DiscoveredResolution').index) {
this._setState('DiscoverResolution')
} else if (0 != this.tag('DiscoveredResolution').index) {
this.tag('DiscoveredResolution').setPrevious()
}
}
_handleDown() {
if (this.tag('DiscoveredResolution').length - 1 != this.tag('DiscoveredResolution').index) {
this.tag('DiscoveredResolution').setNext()
}
}
_handleBack() {
console.log("handle back called")
this.fireAncestors('$setGeneralSettingsScreen')
}
_handleEnter() {
// connect page
Log.info("ResolutionUI: In ResolutionSettings, resolutions", this.tag('DiscoveredResolution').element.label)
this.tag('ThunderResolutionService').setresolution(this.tag('DiscoveredResolution').element.label)
this.currentresolution=this.tag('DiscoveredResolution').element.label
Storage.set("lastsetresolution", this.currentresolution);
setTimeout (() => {
this.startScanResolution()
}, 1000);
}
}
]
}
} |
JavaScript | class ProceduralRenderer extends BaseRenderer {
constructor(THREE, { canvas, init, shouldRotateCamera = false }) {
super(THREE, { canvas, shouldRotateCamera });
this.init = init;
}
async makeParticleSystem() {
const { THREE } = this;
const { scene, camera, webGlRenderer } = this;
this.particleSystem = await this.init(THREE, {
scene,
camera,
renderer: webGlRenderer,
});
return Promise.resolve(this.render());
}
} |
JavaScript | class ServiceNowConnector {
/**
* @memberof ServiceNowConnector
* @constructs
* @description Copies the options parameter to a public property for use
* by class methods.
*
* @param {object} options - API instance options.
* @param {string} options.url - Your ServiceNow Developer instance's URL.
* @param {string} options.username - Username to your ServiceNow instance.
* @param {string} options.password - Your ServiceNow user's password.
* @param {string} options.serviceNowTable - The table target of the ServiceNow table API.
*/
constructor(options) {
this.options = options;
}
/**
* @callback iapCallback
* @description A [callback function]{@link
* https://developer.mozilla.org/en-US/docs/Glossary/Callback_function}
* is a function passed into another function as an argument, which is
* then invoked inside the outer function to complete some kind of
* routine or action.
*
* @param {*} responseData - When no errors are caught, return data as a
* single argument to callback function.
* @param {error} [errorMessage] - If an error is caught, return error
* message in optional second argument to callback function.
*/
/**
* @memberof ServiceNowConnector
* @method get
* @summary Calls ServiceNow GET API
* @description Call the ServiceNow GET API. Sets the API call's method and query,
* then calls this.sendRequest(). In a production environment, this method
* should have a parameter for passing limit, sort, and filter options.
* We are ignoring that for this course and hardcoding a limit of one.
*
* @param {iapCallback} callback - Callback a function.
* @param {(object|string)} callback.data - The API's response. Will be an object if sunnyday path.
* Will be HTML text if hibernating instance.
* @param {error} callback.error - The error property of callback.
*/
get(callback) {
let getCallOptions = { ...this.options };
getCallOptions.method = 'GET';
getCallOptions.query = 'sysparm_limit=1';
this.sendRequest(getCallOptions, (results, error) => callback(results, error));
}
} |
JavaScript | @withProfile
class StatusBar extends Component {
render(){
const { avatar, currentUserFirstName, currentUserLastName } = this.props;
return (
// <Consumer >
// {/* {(context) => ( */}
<section className = {Styles.statusBar}>
<button>
<img src = {avatar}/>
<span>{currentUserFirstName}</span>
<span>{currentUserLastName}</span>
</button>
</section>
// )}
// </Consumer>
);
}
} |
JavaScript | class VigenereCipheringMachine {
constructor (type = true) {
this.type = type;
}
encrypt(string, key) {
if ((string === undefined) || (key === undefined)) throw new SyntaxError('Incorrect arguments!');
string = string.toLowerCase();
key = key.padEnd(string.length, key).toLowerCase();
let res = '', k = 0;
for (let i = 0; i < string.length; i++) {
if ((string.charCodeAt(i) >= 97) && (string.charCodeAt(i) <= 122)) {
res += String.fromCharCode(97 + (string.charCodeAt(i) + key.charCodeAt(k) - 2 * 97) % 26);
k++;
}
else res += string[i];
}
if (!this.type) {
res = res.split('').reverse().join('');
}
return res.toUpperCase();
}
decrypt(string, key) {
if ((string === undefined) || (key === undefined)) throw new SyntaxError('Incorrect arguments!');
string = string.toLowerCase();
key = key.padEnd(string.length, key).toLowerCase();
let res = '', k = 0;
for (let i = 0; i < string.length; i++) {
if ((string.charCodeAt(i) >= 97) && (string.charCodeAt(i) <= 122)) {
res += String.fromCharCode(97 + (26 + string.charCodeAt(i) - key.charCodeAt(k)) % 26);
k++;
}
else res += string[i];
}
if (!this.type) {
res = res.split('').reverse().join('');
}
return res.toUpperCase();
}
} |
JavaScript | class PropertyMapper {
constructor(jabrConfig, jabrProxy) {
this.config = jabrConfig
this.handlers = {}
this.isStrict = !!this.config.options.strict
this.valueMap = { ...this.config.valueMap }
this.wildCards = []
autoBind(this)
}
addWildcardHandler(callback) {
if (!this.wildCards.includes(callback)) {
this.wildCards.push(callback)
Object.values(this.handlers).forEach(handler => {
handler.onChange(callback)
})
}
}
getHandler(prop) {
if (this.isStrict && !this.hasProperty(prop))
throw new Error('That property does not exist, and the store has been flagged as strict')
if (typeof prop != 'string') throw new Error('Must supply a string for the prop')
if (this.handlers.hasOwnProperty(prop)) return this.handlers[prop]
// const propertyConfig =
// ? this.config.properties[prop]
// : PropertyHandler.normalizeConfigInput({}, prop)
let config
if (this.config.properties.hasOwnProperty(prop)) {
config = PropertyHandler.normalizeConfigInput(this.config.properties[prop])
} else {
// if (!this.isStrict)
config = PropertyHandler.normalizeConfigInput(null)
}
const handler = new PropertyHandler(config, this, prop)
this.wildCards.forEach(callback => {
handler.onChange(callback)
})
this.handlers[prop] = handler
return handler
}
export() {
return { ...this.valueMap }
}
getKeys() {
return Object.keys(this.valueMap)
// return Object.entries(this.handlers)
// .filter(([prop, handler]) => handler.exists())
// .map(([prop, handler]) => prop)
// .concat(Object.keys(this.config.properties))
}
getEntries() {
return Object.entries(this.valueMap)
}
hasProperty(prop) {
return this.valueMap.hasOwnProperty(prop)
}
} |
JavaScript | class EscapeError extends Error {
constructor(message, char = null, index = 0) {
super()
this.code = `CMD_TOKENIZE_ESCAPE_ERROR`
this.message = message
this.char = char
this.index = index
}
} |
JavaScript | class ParseError extends Error {
constructor(message, char = null, index = 0) {
super()
this.code = `CMD_TOKENIZE_PARSE_ERROR`
this.message = message
this.char = char
this.index = index
}
} |
JavaScript | class WelcomePage extends AbstractWelcomePage {
/**
* Implements React's {@link Component#componentDidMount()}. Invoked
* immediately after mounting occurs. Creates a local video track if none
* is available and the camera permission was already granted.
*
* @inheritdoc
* @returns {void}
*/
componentDidMount() {
super.componentDidMount();
const { dispatch } = this.props;
if (this.props._settings.startAudioOnly) {
dispatch(destroyLocalTracks());
} else {
dispatch(destroyLocalDesktopTrackIfExists());
// Make sure we don't request the permission for the camera from
// the start. We will, however, create a video track iff the user
// already granted the permission.
navigator.permissions.query({ name: 'camera' }).then(response => {
response === 'granted'
&& dispatch(createDesiredLocalTracks(MEDIA_TYPE.VIDEO));
});
}
}
/**
* Implements React's {@link Component#render()}. Renders a prompt for
* entering a room name.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return <View></View>;
}
} |
JavaScript | class ChatPanelFooter extends Component {
constructor() {
super();
}
render() {
return (
<div className="default-panel chat-panel-footer">
<form>
<div className="input-group input-group-unstyled">
<span className="input-group-addon">
<span className="glyphicon glyphicon-paperclip pull-left" />
</span>
<input type="text" placeholder="Type a message" onChange={this.props.onTextChange} onKeyDown={this.props.onKeyDown} value={this.props.text} />
<span className="input-group-addon">
<span className="glyphicon glyphicon-headphones pull-right" />
</span>
</div>
</form>
</div>
);
}
} |
JavaScript | class StudyCard {
/**
*
* @param {Number} id
* @param {String} title
* @param {Boolean} isLive
* @param {Number} completedNo
* @param {Number} abandonedNo
* @param {Date} launchedDate
* @param {Date} editDate
* @param {Date} endDate
*/
constructor(id, title, isLive, completedNo, abandonedNo,
launchedDate, editDate, endDate) {
this.id = id;
this.title = title;
this.isLive = isLive;
this.completedNo = completedNo;
this.abandonedNo = abandonedNo;
this.launchedDate = launchedDate;
this.editDate = editDate;
this.endDate = endDate;
}
} |
JavaScript | class _Il2CppGC {
/**
* Forces the GC to collect object from the given
* [generation](https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#generations).
* @param generation The category of objects to collect.
*/
static collect(generation) {
api_1.Api._gcCollect(generation);
}
/**
* Like {@link _Il2CppGC.collect | collect}, but I don't know which
* generation it collects.
*/
static collectALittle() {
api_1.Api._gcCollectALittle();
}
/**
* Disables the GC.
*/
static disable() {
api_1.Api._gcDisable();
}
/**
* Enables the GC.
*/
static enable() {
api_1.Api._gcEnable();
}
/**
* @return `true` if the GC is disabled, `false` otherwise.
*/
static isDisabled() {
return api_1.Api._gcIsDisabled();
}
/**
* It reads the GC descriptor of the given class and looks for its objects
* on the heap. During this process, it may stop and start the GC world
* multiple times.\
* A version with callbacks is not really needed because:
* - There aren't performance issues;
* - It cannot be stopped;
* - The `onMatch` callback can only be called when the GC world starts again,
* but the whole thing is enough fast it doesn't make any sense to have
* callbacks.
*
* ```typescript
* const StringClass = Il2Cpp.domain.assemblies.mscorlib.image.classes["System.String"];
* const matches = Il2Cpp.GC.choose<Il2Cpp.String>(StringClass);
* for (const match of matches) {
* console.log(match);
* }
* ```
* @template T Type parameter to automatically cast the objects to other object-like
* entities, like string and arrays. Default is {@link _Il2CppObject}.
* @param klass The class of the objects you are looking for.
* @return An array of ready-to-use objects, strings or arrays. Value types are boxed.
*/
static choose(klass) {
const isString = klass.type.typeEnum == type_enum_1._Il2CppTypeEnum.STRING;
const isArray = klass.type.typeEnum == type_enum_1._Il2CppTypeEnum.SZARRAY;
const matches = [];
const callback = (objects, size, _) => {
for (let i = 0; i < size; i++) {
const pointer = objects.add(i * Process.pointerSize).readPointer();
if (isString)
matches.push(new string_1._Il2CppString(pointer));
else if (isArray)
matches.push(new array_1._Il2CppArray(pointer));
else
matches.push(new Object(pointer));
}
};
const chooseCallback = new NativeCallback(callback, "void", ["pointer", "int", "pointer"]);
const onWorld = new NativeCallback(() => { }, "void", []);
const state = api_1.Api._livenessCalculationBegin(klass.handle, 0, chooseCallback, NULL, onWorld, onWorld);
api_1.Api._livenessCalculationFromStatics(state);
api_1.Api._livenessCalculationEnd(state);
return matches;
}
/**
* It takes a memory snapshot and scans the current tracked objects of the given class.\
* It leads to different results if compared to {@link _Il2CppGC.choose}.
* @template T Type parameter to automatically cast the objects to other object-like
* entities, like string and arrays. Default is {@link _Il2CppObject}.
* @param klass The class of the objects you are looking for.
* @return An array of ready-to-use objects, strings or arrays. Value types are boxed.
*/
static choose2(klass) {
const isString = klass.type.typeEnum == type_enum_1._Il2CppTypeEnum.STRING;
const isArray = klass.type.typeEnum == type_enum_1._Il2CppTypeEnum.SZARRAY;
const matches = [];
const snapshot = new memory_snapshot_1._Il2CppMemorySnapshot();
const count = snapshot.trackedObjectCount.toNumber();
const start = snapshot.objectsPointer;
for (let i = 0; i < count; i++) {
const pointer = start.add(i * Process.pointerSize).readPointer();
const object = new object_1._Il2CppObject(pointer);
if (object.class.handle.equals(klass.handle)) {
if (isString)
matches.push(new string_1._Il2CppString(pointer));
else if (isArray)
matches.push(new array_1._Il2CppArray(pointer));
else
matches.push(object);
}
}
snapshot.free();
return matches;
}
} |
JavaScript | class _Il2CppValueType extends native_struct_1.NativeStruct {
constructor(handle, klass) {
super(handle);
this.klass = klass;
}
/**
* NOTE: the class is hardcoded when a new instance is created.\
* It's not completely reliable.
* @return Its class.
*/
get class() {
return this.klass;
}
/**
* @return Its fields.
*/
get fields() {
return this.class.fields[accessor_1.filterAndMap](field => field.isInstance, field => field.asHeld(this.handle.add(field.offset).sub(object_1._Il2CppObject.headerSize)));
}
/**
* See {@link _Il2CppObject.unbox} for an example.
* @return The boxed value type.
*/
box() {
return new object_1._Il2CppObject(api_1.Api._valueBox(this.klass.handle, this.handle));
}
} |
JavaScript | class UnityVersion {
/** @internal */
constructor(source) {
this.toString = () => this.source;
/** @internal */ this.isEqual = (other) => this.compare(other) == 0;
/** @internal */ this.isAbove = (other) => this.compare(other) == 1;
/** @internal */ this.isBelow = (other) => this.compare(other) == -1;
/** @internal */ this.isEqualOrAbove = (other) => this.compare(other) >= 0;
/** @internal */ this.isEqualOrBelow = (other) => this.compare(other) <= 0;
const matches = source.match(matchPattern);
this.source = matches ? matches[0] : source;
this.major = matches ? Number(matches[1]) : -1;
this.minor = matches ? Number(matches[2]) : -1;
this.revision = matches ? Number(matches[3]) : -1;
if (matches == null) {
console_1.warn(`"${source}" is not a valid Unity version.`);
}
}
/**
* @internal
* `true` if the current version is older than 2018.3.0.
*/
get isLegacy() {
return this.isBelow("2018.3.0");
}
/** @internal */
compare(otherSource) {
const other = new UnityVersion(otherSource);
if (this.major > other.major)
return 1;
if (this.major < other.major)
return -1;
if (this.minor > other.minor)
return 1;
if (this.minor < other.minor)
return -1;
if (this.revision > other.revision)
return 1;
if (this.revision < other.revision)
return -1;
return 0;
}
} |
JavaScript | class Accessor {
/** @internal */
constructor(keyClashProtection = false) {
return new Proxy(this, {
set(target, key, value) {
if (typeof key == "string") {
// const basename = key.replace(/^[^a-zA-Z$_]|[^a-zA-Z0-9$_]/g, "_");
let name = key;
if (keyClashProtection) {
let count = 0;
while (Reflect.has(target, name))
name = key + "_" + ++count;
}
Reflect.set(target, name, value);
}
else {
Reflect.set(target, key, value);
}
return true;
},
get(target, key) {
if (typeof key != "string" || Reflect.has(target, key))
return Reflect.get(target, key);
const closestMatch = fastest_levenshtein_1.closest(key, Object.keys(target));
if (closestMatch)
console_1.raise(`Couldn't find property "${key}", did you mean "${closestMatch}"?`);
else
console_1.raise(`Couldn't find property "${key}"`);
}
});
}
/**
* Iterable.
*/
*[Symbol.iterator]() {
for (const value of Object.values(this))
yield value;
}
/** @internal */
[exports.filterAndMap](filter, map) {
const accessor = new Accessor();
for (const [key, value] of Object.entries(this))
if (filter(value))
accessor[key] = map(value);
return accessor;
}
} |
JavaScript | class PostCentersCenterIdRequest {
/**
* Constructs a new <code>PostCentersCenterIdRequest</code>.
* PostCentersCenterIdRequest
* @alias module:model/PostCentersCenterIdRequest
*/
constructor() {
PostCentersCenterIdRequest.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>PostCentersCenterIdRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PostCentersCenterIdRequest} obj Optional instance to populate.
* @return {module:model/PostCentersCenterIdRequest} The populated <code>PostCentersCenterIdRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PostCentersCenterIdRequest();
if (data.hasOwnProperty('closureReasonId')) {
obj['closureReasonId'] = ApiClient.convertToType(data['closureReasonId'], 'Number');
}
if (data.hasOwnProperty('closureDate')) {
obj['closureDate'] = ApiClient.convertToType(data['closureDate'], 'String');
}
if (data.hasOwnProperty('locale')) {
obj['locale'] = ApiClient.convertToType(data['locale'], 'String');
}
if (data.hasOwnProperty('dateFormat')) {
obj['dateFormat'] = ApiClient.convertToType(data['dateFormat'], 'String');
}
}
return obj;
}
} |
JavaScript | class HorizonLine {
/**
* Horizon line dimensions.
* @enum {number}
*/
static dimensions = {
WIDTH: 600,
HEIGHT: 12,
YPOS: 127
};
constructor(canvas, spritePos) {
this.spritePos = spritePos;
this.canvas = canvas;
this.canvasCtx = canvas.getContext('2d');
this.sourceDimensions = {};
this.dimensions = HorizonLine.dimensions;
this.sourceXPos = [
this.spritePos.x,
this.spritePos.x + this.dimensions.WIDTH
];
this.xPos = [];
this.yPos = 0;
this.bumpThreshold = 0.5;
this.setSourceDimensions();
this.draw();
}
/**
* Set the source dimensions of the horizon line.
*/
setSourceDimensions() {
/* eslint-disable-next-line */
for (const dimension in HorizonLine.dimensions) {
this.sourceDimensions[dimension] = HorizonLine.dimensions[dimension];
this.dimensions[dimension] = HorizonLine.dimensions[dimension];
}
this.xPos = [0, HorizonLine.dimensions.WIDTH];
this.yPos = HorizonLine.dimensions.YPOS;
}
/**
* Return the crop x position of a type.
*/
getRandomType() {
return Math.random() > this.bumpThreshold ? this.dimensions.WIDTH : 0;
}
/**
* Draw the horizon line.
*/
draw() {
this.canvasCtx.drawImage(
getImageSprite(),
this.sourceXPos[0],
this.spritePos.y,
this.sourceDimensions.WIDTH,
this.sourceDimensions.HEIGHT,
this.xPos[0],
this.yPos,
this.dimensions.WIDTH,
this.dimensions.HEIGHT
);
this.canvasCtx.drawImage(
getImageSprite(),
this.sourceXPos[1],
this.spritePos.y,
this.sourceDimensions.WIDTH,
this.sourceDimensions.HEIGHT,
this.xPos[1],
this.yPos,
this.dimensions.WIDTH,
this.dimensions.HEIGHT
);
}
/**
* Update the x position of an indivdual piece of the line.
* @param {number} pos Line position.
* @param {number} increment
*/
updateXPos(pos, increment) {
const line1 = pos;
const line2 = pos === 0 ? 1 : 0;
this.xPos[line1] -= increment;
this.xPos[line2] = this.xPos[line1] + this.dimensions.WIDTH;
if (this.xPos[line1] <= -this.dimensions.WIDTH) {
this.xPos[line1] += this.dimensions.WIDTH * 2;
this.xPos[line2] = this.xPos[line1] - this.dimensions.WIDTH;
this.sourceXPos[line1] = this.getRandomType() + this.spritePos.x;
}
}
/**
* Update the horizon line.
* @param {number} deltaTime
* @param {number} speed
*/
update(deltaTime, speed) {
const increment = Math.floor(speed * (getFPS() / 1000) * deltaTime);
if (this.xPos[0] <= 0) {
this.updateXPos(0, increment);
} else {
this.updateXPos(1, increment);
}
this.draw();
}
/**
* Reset horizon to the starting position.
*/
reset() {
this.xPos[0] = 0;
this.xPos[1] = HorizonLine.dimensions.WIDTH;
}
} |
JavaScript | class ImmediateEncoder {
/**
* Encodes a block signature.
* @param {BinaryWriter} writer
* @param {BlockType} blockType
*/
static encodeBlockSignature(writer, blockType) {
writer.writeVarInt7(blockType.value);
};
/**
*
* @param {*} label
*/
static encodeRelativeDepth(writer, label, depth) {
const relativeDepth = depth - label.block.depth;
writer.writeVarInt7(relativeDepth);
}
static encodeBranchTable(writer, defaultLabel, labels) {
writer.writeVarUInt32(labels.length);
labels.forEach(x => {
writer.writeVarUInt32(x);
});
writer.writeVarUInt32(defaultLabel);
}
static encodeFunction(writer, func) {
//Arg.notNull('func', func);
let functionIndex = 0;
if (func instanceof FunctionBuilder) {
functionIndex = func._index;
}
else if (func instanceof ImportBuilder) {
functionIndex = func.data.index;
}
else if (typeof func === 'number') {
functionIndex = func;
}
else {
throw new Error('Function argument must either be the index of the function or a FunctionBuilder.')
}
return writer.writeVarUInt32(functionIndex);
}
/**
*
* @param {BinaryWriter} writer
* @param {FuncTypeBuilder} funcType
* @param {TableBuilder} table
*/
static encodeIndirectFunction(writer, funcType, table) {
writer.writeVarUInt32(funcType.index);
writer.writeVarUInt1(0);
//call_indirect 0x11 type_index : varuint32, reserved : varuint1 call a function indirect with an expected signature
//The call_indirect operator takes a list of function arguments and as the last operand the index into the table.
//Its reserved immediate is for future :unicorn: use and must be 0 in the MVP.
}
static encodeLocal(writer, local) {
Arg.notNull('local', local);
let localIndex = 0;
if (local instanceof LocalBuilder) {
localIndex = local.index;
}
else if (local instanceof FunctionParameterBuilder) {
localIndex = local.index;
}
else if (typeof local === 'number') {
localIndex = local;
}
else {
throw new Error('Local argument must either be the index of the local variable or a LocalBuilder.')
}
return writer.writeVarUInt32(localIndex);
}
static encodeGlobal(writer, global) {
Arg.notNull('global', global);
let globalIndex = 0;
if (global instanceof GlobalBuilder) {
globalIndex = global.index;
}
else if (global instanceof ImportBuilder){
if (global.externalKind !== ExternalKind.Global){
throw new Error('Import external kind must be global.')
}
}
else if (typeof global === 'number') {
globalIndex = global;
}
else {
throw new Error('Global argument must either be the index of the global variable, GlobalBuilder, or ' +
'an ImportBuilder.')
}
return writer.writeVarUInt32(globalIndex);
}
static encodeFloat32(writer, value) {
writer.writeFloat32(value);
}
static encodeFloat64(writer, value) {
writer.writeFloat64(value);
}
static encodeVarInt32(writer, value) {
writer.writeVarInt32(value);
}
static encodeVarInt64(writer, value) {
writer.writeVarInt64(value);
}
static encodeVarUInt32(writer, value) {
writer.writeVarUInt32(value);
}
static encodeVarUInt1(writer, value) {
writer.writeVarUInt1(value);
}
/**
* Write the memory operand to the binary write.
* @param {BinaryWriter} writer
* @param {*} alignment
* @param {*} offset The offset to an address on the stack that will be consumed by the memory instruction.
*/
static encodeMemoryImmediate(writer, alignment, offset) {
writer.writeVarUInt32(alignment);
writer.writeVarUInt32(offset);
}
} |
JavaScript | class Send extends Component {
componentWillMount() {
const { asset_id } = getParamsFromLocation()
this.asset_id = asset_id
this.asset = getAsset(this.asset_id)
this.Coin = Coins[this.asset.symbol] // Storing Asset api (Asset.BTC, Asset.ETH, ...)
this.send_providers = this.Coin.getSendProviders()
this.observer = createObserver(m => this.forceUpdate())
this.observer.observe(state.view)
this.observer.observe(state.location, 'pathname')
// Initial state
state.view = {
amount: bigNumber(0),
fee: bigNumber(0),
balance: bigNumber(this.asset.balance),
balance_fee: bigNumber(this.asset.balance),
address_input: '',
address_input_error: false,
amount1_input: 0, // BTC
amount2_input: 0, // FIAT
loading_max: false,
fee_recomended: 0,
fee_input: 0,
fee_input_visible: false,
password_input: '',
password_input_invalid: false,
change_address: undefined,
error_when_create: false,
send_provider_selected: 0,
show_tx_raw: false,
loading: false,
error_when_send: '',
is_sent: false
}
// binding
this.fetchFee = this.fetchFee.bind(this)
this.onChangeAddress = this.onChangeAddress.bind(this)
this.onChangeAmount1 = this.onChangeAmount1.bind(this)
this.onChangeAmount2 = this.onChangeAmount2.bind(this)
this.onClickMax = this.onClickMax.bind(this)
this.onChangeFee = this.onChangeFee.bind(this)
this.onClickFee = this.onClickFee.bind(this)
this.onChangePassword = this.onChangePassword.bind(this)
this.onNext = this.onNext.bind(this)
this.onChangeProvider = this.onChangeProvider.bind(this)
this.onShowRawTx = this.onShowRawTx.bind(this)
this.onSend = this.onSend.bind(this)
this.fetchBalance()
this.fetchFee({}).then(fee => {
const collector = collect()
this.updateRecomendedFee(fee)
collector.emit()
})
}
componentWillUnmount() {
this.observer.destroy()
}
shouldComponentUpdate() {
return false
}
fetchBalance() {
return fetchFullBalance(this.asset_id).then(balance => {
const collector = collect()
state.view.balance = bigNumber(balance)
state.view.balance_fee = bigNumber(balance) // balance_fee is used for erc20 tokens
collector.emit()
return balance
})
}
fetchFee({ amount, use_cache }) {
return repeatUntilResolve(
this.Coin.fetchRecomendedFee,
[
{
use_cache,
amount,
addresses: this.asset.addresses
}
],
{ timeout: TIMEOUT_BETWEEN_EACH_FAIL_FETCH_FEE }
).then(fee => this.Coin.cutDecimals(fee))
// return this.Coin.fetchRecomendedFee({
// use_cache,
// amount,
// address: this.asset.address
// })
// .then(fee => this.Coin.cutDecimals(fee))
// .catch(e => {
// console.error(e)
// setTimeout(
// () => this.fetchFee({ use_cache }),
// TIMEOUT_BETWEEN_EACH_FAIL_FETCH_FEE
// )
// })
}
updateAmount(amount_string) {
// console.log('updateAmount', typeof amount_string, amount_string)
state.view.amount = bigNumber(this.Coin.cutDecimals(amount_string))
}
updateFee(fee_string) {
// console.log('updateFee', typeof fee_string, fee_string)
state.view.fee = bigNumber(this.Coin.cutDecimals(fee_string))
}
updateAmounts({ amount1, amount2 }) {
const collector = collect()
const symbol = this.asset.symbol
const price = getPrice(symbol)
if (amount1 !== undefined) {
state.view.amount1_input = amount1
state.view.amount2_input = limitDecimals(
bigNumber(price)
.times(parseNumberAsString(amount1))
.toFixed(),
2
)
} else {
state.view.amount2_input = amount2
state.view.amount1_input =
price === 0
? 0
: this.Coin.cutDecimals(
bigNumber(parseNumberAsString(amount2))
.div(price)
.toFixed()
)
}
this.updateAmount(parseNumberAsString(state.view.amount1_input))
collector.emit()
}
updateRecomendedFee(fee) {
const collector = collect()
state.view.fee_recomended = fee
this.updateFee(
state.view.fee_input_visible
? state.view.fee_input
: state.view.fee_recomended
)
collector.emit()
}
onChangeAmount(amount, type) {
const collector = collect()
this.updateAmounts({ [type]: amount })
this.fetchFee({ amount: state.view.amount, use_cache: true }).then(
fee => {
this.updateRecomendedFee(fee)
collector.emit()
}
)
}
onChangeAmount1(e) {
this.onChangeAmount(e.target.value, 'amount1')
}
onChangeAmount2(e) {
this.onChangeAmount(e.target.value, 'amount2')
}
onClickMax(e) {
let amount_to_calc_fee = state.view.fee_input_visible
? bigNumber(state.view.balance_fee).minus(state.view.fee_input)
: state.view.balance_fee
state.view.loading_max = true
this.fetchFee({ amount: amount_to_calc_fee, use_cache: true }).then(
fee => {
const collector = collect()
this.updateRecomendedFee(fee)
this.updateAmounts({
amount1: this.getMax.toFixed()
})
state.view.loading_max = false
collector.emit()
}
)
}
onChangeAddress(e) {
const collector = collect()
const value = e.target.value.trim()
state.view.address_input = value
state.view.address_input_error = !this.Coin.isAddress(value)
collector.emit()
}
onClickFee(e) {
e.preventDefault()
const collector = collect()
state.view.fee_input_visible = !state.view.fee_input_visible
state.view.fee_input = state.view.fee_recomended
this.updateFee(state.view.fee_recomended)
collector.emit()
}
onChangeFee(e) {
const collector = collect()
this.updateFee(parseNumberAsString(e.target.value))
state.view.fee_input = e.target.value
collector.emit()
}
onChangePassword(e) {
const collector = collect()
state.view.password_input_invalid = false
state.view.password_input = e.target.value.trim()
collector.emit()
}
onNext(e) {
const asset = this.asset
const asset_id = this.asset_id
const address = asset.address
const addresses = asset.addresses
const password = state.view.password_input
const private_keys = getPrivateKeys(asset_id, password)
const collector = collect()
state.view.error_when_create = false
state.view.error_when_send = ''
if (private_keys[0]) {
// Change address
if (this.Coin.changeaddress && isAssetWithSeed(asset_id)) {
const index = addresses.indexOf(address)
if (index === addresses.length - 1) {
// create
const wallet = this.Coin.getNextWalletFromSeed(
asset.address,
asset.addresses,
asset.seed,
password
)
state.view.change_address = wallet.address
} else {
state.view.change_address = addresses[index + 1]
}
}
state.view.loading = true
this.Coin.createSimpleTx({
from_addresses: addresses,
to_address: state.view.address_input, // to/destiny
private_keys: private_keys,
amount: state.view.amount, // amount to send
fee: state.view.fee,
change_address: state.view.change_address,
current_address: address
})
.then(tx_raw => {
this.tx_raw = tx_raw
const collector = collect()
state.view.loading = false
setHref(
routes.assetSend({ asset_id: this.asset_id }) + '/1'
)
collector.emit()
})
.catch(e => {
console.error(e)
const collector = collect()
state.view.error_when_create = true
state.view.loading = false
collector.emit()
})
} else {
state.view.password_input_invalid = true
}
collector.emit()
}
onChangeProvider(index) {
state.view.send_provider_selected = index
}
onShowRawTx(index) {
state.view.show_tx_raw = true
}
onSend(e) {
const asset_id = this.asset_id
const asset = this.asset
const provider = this.send_providers[state.view.send_provider_selected]
const collector = collect()
state.view.loading = true
state.view.error_when_send = ''
collector.emit()
provider
.send(this.tx_raw)
.then(tx_id => {
sendEventToAnalytics(
'send',
this.Coin.symbol,
state.view.amount
)
this.tx_id = tx_id
const collector = collect()
state.view.loading = false
state.view.is_sent = true
state.view.balance = Number(
bigNumber(state.view.balance)
.minus(state.view.amount)
.minus(state.view.fee)
)
// Changing address on UI
const change_address = state.view.change_address
if (change_address !== undefined) {
if (!asset.addresses.includes(change_address))
addAddress(asset_id, change_address)
changeAddress(asset_id, change_address)
}
collector.emit()
})
.catch(error => {
console.error(error)
const collector = collect()
state.view.loading = false
state.view.error_when_send = error
collector.emit()
})
}
get getMax() {
const max = bigNumber(state.view.balance).minus(state.view.fee)
return max.gt(0) ? max : 0
}
get getTotal() {
return state.view.amount.plus(state.view.fee)
}
get isEnoughBalance() {
return this.getTotal.lte(state.view.balance)
}
get isEnoughBalanceForFee() {
return state.view.fee.lte(state.view.balance_fee)
}
get isValidForm() {
const min = bigNumber(10).pow(this.Coin.coin_decimals * -1)
return (
!state.view.address_input_error &&
state.view.address_input.length > 0 &&
state.view.password_input.length > 0 &&
state.view.amount.gte(min) &&
state.view.fee.gte(0) &&
!state.view.password_input_invalid
)
}
render() {
const symbol = this.asset.symbol
const isEnoughBalance = this.isEnoughBalance
const isEnoughBalanceForFee = this.isEnoughBalanceForFee
const step_path = getParamsFromLocation().step
const step = state.view.is_sent
? 2
: step_path !== undefined && this.tx_raw !== undefined
? Number(step_path)
: 0
// Removing tx_raw in case user click back in browser
if (step === 0) delete this.tx_raw
// console.log({ amount: state.view.amount.toFixed(), fee: state.view.fee.toFixed() })
return React.createElement(SendTemplate, {
step: step,
color: this.Coin.color,
address_input: state.view.address_input,
address_input_error: state.view.address_input_error,
amount: state.view.amount.toFixed(),
amount1_input: state.view.amount1_input,
amount2_input: state.view.amount2_input,
symbol_crypto: symbol,
symbol_crypto_fee: this.Coin.symbol_fee,
symbol_currency: state.fiat,
fee: state.view.fee.toFixed(),
fee_input: state.view.fee_input,
fee_input_visible: state.view.fee_input_visible,
fee_input_fiat: formatCurrency(
convertBalance(this.Coin.symbol_fee, state.view.fee.toFixed()),
2
),
fee_recomended: state.view.fee_recomended,
fee_recomended_fiat: formatCurrency(
convertBalance(this.Coin.symbol_fee, state.view.fee_recomended),
2
),
total: this.getTotal.toFixed(),
password_input: state.view.password_input,
password_input_invalid: state.view.password_input_invalid,
isEnoughBalance: isEnoughBalance,
isEnoughBalanceForFee: isEnoughBalanceForFee,
isValidForm:
this.isValidForm && isEnoughBalance && isEnoughBalanceForFee,
isFeeLowerThanRecomended: state.view.fee.lt(
state.view.fee_recomended
),
error_when_create: state.view.error_when_create,
send_provider_selected: state.view.send_provider_selected,
send_providers: this.send_providers,
show_tx_raw: state.view.show_tx_raw,
tx_raw: this.tx_raw,
loading: state.view.loading,
error_when_send: state.view.error_when_send,
tx_id: this.tx_id,
tx_info: this.Coin.urlInfoTx(this.tx_id),
url_decode_tx: this.Coin.urlDecodeTx(this.tx_raw),
loading_max: state.view.loading_max,
onChangeAddress: this.onChangeAddress,
onChangeAmount1: this.onChangeAmount1,
onChangeAmount2: this.onChangeAmount2,
onClickMax: this.onClickMax,
onClickFee: this.onClickFee,
onChangeFee: this.onChangeFee,
onChangePassword: this.onChangePassword,
onNext: this.onNext,
onChangeProvider: this.onChangeProvider,
onShowRawTx: this.onShowRawTx,
onSend: this.onSend
})
}
} |
JavaScript | class AttributeString extends Attribute {
toJSON(val) {
return val;
}
fromJSON(val) {
return (val === null || val === undefined || val === false) ? null : `${val}`;
}
// Public: Returns a {Matcher} for objects starting with the provided value.
startsWith(val) {
return new Matcher(this, 'startsWith', val);
}
columnSQL() {
return `${this.jsonKey} TEXT`;
}
like(val) {
this._assertPresentAndQueryable('like', val);
return new Matcher(this, 'like', val);
}
lessThan(val) {
this._assertPresentAndQueryable('lessThanOrEqualTo', val);
return new Matcher(this, '<', val);
}
lessThanOrEqualTo(val) {
this._assertPresentAndQueryable('lessThanOrEqualTo', val);
return new Matcher(this, '<=', val);
}
greaterThan(val) {
this._assertPresentAndQueryable('greaterThanOrEqualTo', val);
return new Matcher(this, '>', val);
}
greaterThanOrEqualTo(val) {
this._assertPresentAndQueryable('greaterThanOrEqualTo', val);
return new Matcher(this, '>=', val);
}
} |
JavaScript | class Account extends models['Resource'] {
/**
* Create a Account.
* @member {string} vsoAccountId The fully qualified arm id of the vso
* account to be used for this team account.
* @member {string} [accountId] The immutable id associated with this team
* account.
* @member {string} [description] The description of this workspace.
* @member {string} [friendlyName] The friendly name for this workspace. This
* will be the workspace name in the arm id when the workspace object gets
* created
* @member {string} keyVaultId The fully qualified arm id of the user key
* vault.
* @member {string} [seats] The no of users/seats who can access this team
* account. This property defines the charge on the team account.
* @member {string} [discoveryUri] The uri for this machine learning team
* account.
* @member {date} [creationDate] The creation date of the machine learning
* team account in ISO8601 format.
* @member {object} storageAccount The properties of the storage account for
* the machine learning team account.
* @member {string} [storageAccount.storageAccountId] The fully qualified arm
* Id of the storage account.
* @member {string} [storageAccount.accessKey] The access key to the storage
* account.
* @member {string} [provisioningState] The current deployment state of team
* account resource. The provisioningState is to indicate states for resource
* provisioning. Possible values include: 'Creating', 'Succeeded',
* 'Updating', 'Deleting', 'Failed'
*/
constructor() {
super();
}
/**
* Defines the metadata of Account
*
* @returns {object} metadata of Account
*
*/
mapper() {
return {
required: false,
serializedName: 'Account',
type: {
name: 'Composite',
className: 'Account',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
vsoAccountId: {
required: true,
serializedName: 'properties.vsoAccountId',
type: {
name: 'String'
}
},
accountId: {
required: false,
readOnly: true,
serializedName: 'properties.accountId',
type: {
name: 'String'
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'String'
}
},
friendlyName: {
required: false,
serializedName: 'properties.friendlyName',
type: {
name: 'String'
}
},
keyVaultId: {
required: true,
serializedName: 'properties.keyVaultId',
type: {
name: 'String'
}
},
seats: {
required: false,
serializedName: 'properties.seats',
type: {
name: 'String'
}
},
discoveryUri: {
required: false,
readOnly: true,
serializedName: 'properties.discoveryUri',
type: {
name: 'String'
}
},
creationDate: {
required: false,
readOnly: true,
serializedName: 'properties.creationDate',
type: {
name: 'DateTime'
}
},
storageAccount: {
required: true,
serializedName: 'properties.storageAccount',
type: {
name: 'Composite',
className: 'StorageAccountProperties'
}
},
provisioningState: {
required: false,
readOnly: true,
serializedName: 'properties.provisioningState',
type: {
name: 'Enum',
allowedValues: [ 'Creating', 'Succeeded', 'Updating', 'Deleting', 'Failed' ]
}
}
}
}
};
}
} |
JavaScript | class UserDataStore extends BaseStore {
constructor(api = Api.getApi(), endPoint = 'userDataStore') {
super(api, endPoint, UserDataStoreNamespace)
}
/**
* @description
* Tries to get the given namespace from the server, and returns an instance of 'UserDataStore' that
* may be used to interact with this namespace. See {@link module:current-user.UserDataStoreNamespace UserDataStoreNamespace}.
*
* @example <caption>Getting a namespace</caption>
* d2.currentUser.dataStore.get('namespace').then(namespace => {
* namespace.set('new key', value);
*});
*
* @param {string} namespace - Namespace to get.
* @param {boolean} [autoLoad=true] - If true, autoloads the keys of the namespace from the server.
* If false, an instance of the namespace is returned without any keys (no request is sent to the server).
*
* @returns {Promise<UserDataStoreNamespace>} An instance of a UserDataStoreNamespace representing the namespace that can be interacted with.
*/
get(namespace, autoLoad = true) {
return super.get(namespace, autoLoad)
}
/**
* Creates a namespace. Ensures that the namespace does not exists on the server.
* Note that for the namespace to be saved on the server, you need to call {@link module:current-user.UserDataStoreNamespace#set set}.
*
* @example <caption>Creating a namespace</caption>
* d2.currentUser.dataStore.create('new namespace').then(namespace => {
* namespace.set('new key', value);
* });
* @param {string} namespace The namespace to create.
* @returns {Promise<UserDataStoreNamespace>} An instance of the current store-Namespace-instance representing the namespace that can be interacted with, or
* an error if namespace exists.
*/
create(namespace) {
return super.create(namespace)
}
/**
* @static
*
* @returns {UserDataStore} Object with the userDataStore interaction properties
*
* @description
* Get a new instance of the userDataStore object. This will function as a singleton - when a UserDataStore object has been created
* when requesting getUserDataStore again, the original version will be returned.
*/
static getUserDataStore() {
if (!UserDataStore.getUserDataStore.dataStore) {
UserDataStore.getUserDataStore.dataStore = new UserDataStore(
Api.getApi(),
'userDataStore'
)
}
return UserDataStore.getUserDataStore.dataStore
}
} |
JavaScript | class BootstrapProgressbar extends PluginBinder
{
bind(container)
{
var rx = this.rx;
$('.progress .progress-bar', container).progressbar();
}
} |
JavaScript | class BiMap {
/**
* @param {!Object=} map
*/
constructor(map) {
/**
* @private {!Map<K, V>}
*/
this.map_ = new Map();
/**
* @private {!Map<V, K>}
*/
this.inverseMap_ = new Map();
for (const key in map) {
const value = map[key];
this.map_.set(key, value);
this.inverseMap_.set(value, key);
}
}
/**
* @param {K} key
* @return {V}
*/
get(key) {
return this.map_.get(key);
}
/**
* @param {V} key
* @return {K}
*/
invGet(key) {
return this.inverseMap_.get(key);
}
/**
* @param {K} key
* @param {V} value
*/
set(key, value) {
this.map_.set(key, value);
this.inverseMap_.set(value, key);
}
/**
* @param {V} key
* @param {K} value
*/
invSet(key, value) {
this.inverseMap_.set(key, value);
this.map_.set(value, key);
}
/** @return {number} */
size() {
return this.map_.size;
}
} |
JavaScript | class MergeAllSubscriber extends OuterSubscriber_1.OuterSubscriber {
/**
* @param {?} destination
* @param {?} concurrent
*/
constructor(destination, concurrent) {
super(destination);
this.concurrent = concurrent;
this.hasCompleted = false;
this.buffer = [];
this.active = 0;
}
/**
* @param {?} observable
* @return {?}
*/
_next(observable) {
if (this.active < this.concurrent) {
this.active++;
this.add(subscribeToResult_1.subscribeToResult(this, observable));
}
else {
this.buffer.push(observable);
}
}
/**
* @return {?}
*/
_complete() {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
}
/**
* @param {?} innerSub
* @return {?}
*/
notifyComplete(innerSub) {
const /** @type {?} */ buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
}
static _tsickle_typeAnnotationsHelper() {
/** @type {?} */
MergeAllSubscriber.prototype.hasCompleted;
/** @type {?} */
MergeAllSubscriber.prototype.buffer;
/** @type {?} */
MergeAllSubscriber.prototype.active;
/** @type {?} */
MergeAllSubscriber.prototype.concurrent;
}
} |
JavaScript | class Admin extends React.Component {
/**
* Constructor to create the class, set the default
* state values and bind the handling of the
* update click method.
*
* @param props The properties associated with the class
*/
constructor(props) {
super(props);
this.state = {
authenticated: false,
admin: -1,
email: "",
password: "",
page: 1,
pageSize: 4,
query: "",
mounted: false,
data: []
}
this.handleEmail = this.handleEmail.bind(this);
this.handlePassword = this.handlePassword.bind(this);
}
/**
* Post data method call to send the API call.
*
* @param url The URL endpoint
* @param json The JSON data to send
* @param callback The callback to associate with the call
*/
postData = (url, json, callback) => {
fetch(url, {
method: 'POST',
headers: new Headers(),
body: JSON.stringify(json)
})
.then((response) => response.json())
.then((data) => {
callback(data)
})
.catch((err) => {
console.log("something went wrong ", err)
}
);
}
/**
* Handle the clicking of the login button to send the API
* call to log the user in with their entered email and
* password.
*/
handleLoginClick = () => {
const url = "http://unn-w18013094.newnumyspace.co.uk/chi2018/part1/api/login"
let json = {"email": this.state.email, "password": this.state.password};
this.postData(url, json, this.loginCallback);
}
/**
* Handle the clicking of the logout button and subsequently
* remove the states, tokens, and admin tags from local storage.
*/
handleLogoutClick = () => {
this.setState({authenticated: false, admin: 0})
localStorage.removeItem('token');
localStorage.removeItem('admin');
}
/**
* The callback method for handling the login endpoint
* return and updating the class states and local storage.
*
* @param data The data returned by the API endpoint
*/
loginCallback = (data) => {
console.log(data)
if (data.status === 200) {
const {token} = data;
this.setState({authenticated: true, admin: data.admin, token: token});
localStorage.setItem("token", token)
if (data.admin > 0) {
localStorage.setItem("admin", data.admin);
}
}
}
/**
* Handle the input of the password passing in
* the event value.
*
* @param e The event to pass
*/
handlePassword = (e) => {
this.setState({password: e.target.value})
}
/**
* Handle the input of the email passing in
* the event value.
*
* @param e The event to pass
*/
handleEmail = (e) => {
this.setState({email: e.target.value})
}
/**
* The render method to create the JSX/HTML content
* for the page with class states and properties.
*
* @returns {JSX.Element} The fully rendered JSX object
*/
render() {
if (this.state.mounted === false) {
this.mount();
}
let data = this.state.data;
// Store authentication and admin values for repeat usage
const authenticated = this.state.authenticated;
const admin = localStorage.getItem("admin");
let logInOut = <Login handleLoginClick={this.handleLoginClick} email={this.state.email}
password={this.props.password} handleEmail={this.handleEmail}
handlePassword={this.handlePassword}/>
let editable = null;
// If the user is authenticated go ahead with showing logout and sessions
if (authenticated === true) {
logInOut = <div>
<button id="logout-btn" onClick={this.handleLogoutClick}>Log Out</button>
</div>
editable = <div id="session-names-collection">
{
data.map((details, id) => (
<SessionUpdater
id={id}
key={id}
authenticated={authenticated}
admin={admin >= 0 ? 1 : 0}
sessionId={details.sessionId}
name={details.name}
handleLogoutClick={this.handleLogoutClick}
postData={this.postData}
/>
))
}
</div>
}
return (
<div id="admin-content">
<h2 id="admin-title">Admin</h2>
{logInOut}
<br/>
{editable}
</div>
);
}
/**
* Method for handling when the component mounts and
* fetching session data from the API.
*/
componentDidMount() {
if (localStorage.getItem('token')) {
this.setState({authenticated: true});
this.mount();
}
}
mount() {
const url = "http://unn-w18013094.newnumyspace.co.uk/chi2018/part1/api/sessions";
fetch(url)
.then((res) => res.json())
.then((data) => {
this.setState({data: data.data, mounted: true});
})
.catch((err) => {
console.log("Something went wrong: ", err)
})
}
/**
* When the component will unmount.
* Fixes "Warning: Can't perform a React state update on an unmounted component"
*/
componentWillUnmount() {
this.setState = (state, callback) => {
return;
};
}
} |
JavaScript | class OnFocusOutOrTapOutside extends React.Component {
onFocusOutRef = createRef()
onTapOutsideRef = createRef()
componentDidMount() {
const { listenToTouches } = this.props
if (listenToTouches) {
this.listenToTouches()
}
}
componentWillUnmount() {
clearTimeout(this.onTapOutsideTimer)
}
// These're called from outside in `<Expandable/>`.
stopListeningToTouches = () => this.onTapOutsideRef.current.stopListeningToTouches()
listenToTouches = () => this.onTapOutsideRef.current.listenToTouches()
onBlur = (event) => this.onFocusOutRef.current && this.onFocusOutRef.current.onBlur(event)
onFocusOut = (event) => {
// `onFocusOut` is triggered right after `onTapOutside`.
// This workaround prevents duplicate `onFocusOut` call.
if (this.onTapOutsideTimer) {
clearTimeout(this.onTapOutsideTimer)
this.onTapOutsideTimer = undefined
}
const { onFocusOut } = this.props
onFocusOut(event)
}
onTapOutside = (event) => {
const { onTapOutsideDelay } = this.props
clearTimeout(this.onTapOutsideTimer)
this.onTapOutsideTimer = setTimeout(() => {
// `onFocusOut` is triggered right after `onTapOutside`.
// This workaround prevents duplicate `onFocusOut` call.
if (this.onTapOutsideTimer) {
this.onTapOutsideTimer = undefined
const { onFocusOut } = this.props
onFocusOut(event)
}
}, onTapOutsideDelay)
}
render() {
const { getTogglerNode, getContainerNode } = this.props
let { children } = this.props
children = React.cloneElement(children, {
onBlur: this.onBlur
})
children = (
<OnFocusOut
ref={this.onFocusOutRef}
getContainerNode={getContainerNode}
getTogglerNode={getTogglerNode}
onFocusOut={this.onFocusOut}>
{children}
</OnFocusOut>
)
return (
<OnTapOutside
ref={this.onTapOutsideRef}
getContainerNode={getContainerNode}
getTogglerNode={getTogglerNode}
onTapOutside={this.onTapOutside}>
{children}
</OnTapOutside>
)
}
} |
JavaScript | class ZoomHandler {
/**
* Instantiates a new ZoomHandler object.
*
* @param {Plot} plot - The plot to attach the handler to.
* @param {Object} options - The parameters of the animation.
* @param {Number} options.continuousZoom - Whether or not continuous zoom is enabled.
* @param {Number} options.zoomDuration - The duration of the zoom animation.
* @param {Number} options.maxConcurrentZooms - The maximum concurrent zooms in a single batch.
* @param {Number} options.deltaPerZoom - The scroll delta required per zoom level.
* @param {Number} options.zoomDebounce - The debounce duration of the zoom in ms.
*/
constructor(plot, options = {}) {
this.continuousZoom = defaultTo(options.continuousZoom, CONTINUOUS_ZOOM);
this.zoomDuration = defaultTo(options.zoomDuration, ZOOM_ANIMATION_MS);
this.maxConcurrentZooms = defaultTo(options.maxConcurrentZooms, MAX_CONCURRENT_ZOOMS);
this.deltaPerZoom = defaultTo(options.deltaPerZoom, ZOOM_WHEEL_DELTA);
this.zoomDebounce = defaultTo(options.zoomDebounce, ZOOM_DEBOUNCE_MS);
this.plot = plot;
this.enabled = false;
}
/**
* Enables the handler.
*
* @returns {ZoomHandler} The handler object, for chaining.
*/
enable() {
if (this.enabled) {
throw 'Handler is already enabled';
}
const plot = this.plot;
let wheelDelta = 0;
let timeout = null;
let evt = null;
this.dblclick = (event) => {
// get mouse position
const targetPx = plot.mouseToPlotPx(event);
// zoom the plot by one level
//zoom(plot, targetPx, 1, this.zoomDuration);
};
this.wheel = (event) => {
// get normalized delta
const delta = getWheelDelta(plot, event);
if (!this.continuousZoom && Math.abs(delta) < 4) {
// mitigate the hyper sensitivty of a trackpad
return;
}
// increment wheel delta
wheelDelta += delta;
// check zoom type
if (this.continuousZoom) {
// get target pixel from mouse position
const targetPx = plot.mouseToPlotPx(event);
// process continuous zoom immediately
zoomFromWheel(this, plot, targetPx, wheelDelta, true);
// reset wheel delta
wheelDelta = 0;
} else {
// set event
evt = event;
// debounce discrete zoom
if (!timeout) {
timeout = setTimeout(() => {
// get target pixel from mouse position
// NOTE: this is called inside the closure to ensure
// that we use the current viewport of the plot to
// convert from mouse to plot pixels
const targetPx = plot.mouseToPlotPx(evt);
// process zoom event
zoomFromWheel(this, plot, targetPx, wheelDelta, false);
// reset wheel delta
wheelDelta = 0;
// clear timeout
timeout = null;
// clear event
evt = null;
}, this.zoomDebounce);
}
}
// prevent default behavior and stop propagationa
event.preventDefault();
event.stopPropagation();
};
this.plot.container.addEventListener('dblclick', this.dblclick);
this.plot.container.addEventListener('wheel', this.wheel);
this.enabled = true;
}
/**
* Disables the handler.
*
* @returns {ZoomHandler} The handler object, for chaining.
*/
disable() {
if (this.enabled) {
throw 'Handler is already disabled';
}
this.plot.container.removeEventListener('dblclick', this.dblclick);
this.plot.container.removeEventListener('wheel', this.wheel);
this.dblclick = null;
this.wheel = null;
this.enabled = false;
}
/**
* Zooms in to the target zoom level. This is bounded by the plot objects
* minZoom and maxZoom attributes.
*
* @param {Number} level - The target zoom level.
* @param {boolean} animate - Whether or not to animate the zoom. Defaults to `true`.
*/
zoomTo(level, animate = true) {
const plot = this.plot;
const targetPx = this.plot.viewport.getCenter();
const zoomDelta = level - plot.zoom;
if (!animate) {
// do not animate
zoom(plot, targetPx, zoomDelta, 0);
} else {
// animate
zoom(plot, targetPx, zoomDelta, this.zoomDuration);
}
}
} |
JavaScript | class AbstractControlDirective {
get control() { return exceptions_1.unimplemented(); }
get value() { return lang_1.isPresent(this.control) ? this.control.value : null; }
get valid() { return lang_1.isPresent(this.control) ? this.control.valid : null; }
get errors() {
return lang_1.isPresent(this.control) ? this.control.errors : null;
}
get pristine() { return lang_1.isPresent(this.control) ? this.control.pristine : null; }
get dirty() { return lang_1.isPresent(this.control) ? this.control.dirty : null; }
get touched() { return lang_1.isPresent(this.control) ? this.control.touched : null; }
get untouched() { return lang_1.isPresent(this.control) ? this.control.untouched : null; }
get path() { return null; }
} |
JavaScript | class Obsidian {
constructor() {
this.lists = {};
this.fields = {};
this._options = {};
this._redirects = {};
this.express = express;
// Set default options
this.options({
env: process.env.NODE_ENV || /* istanbul ignore next */ "development",
// Project Configuration
views: "/templates/views",
"view engine": "handlebars",
// Admin UI
"admin ui": true,
// Connection Details
port: process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 3000,
host: process.env.HOST || process.env.OPENSHIFT_NODEJS_IP || process.env.IP,
// Middleware Configuration
compress: true
});
this.version = version;
}
} |
JavaScript | class Question {
/**
* @param {string} question The question that shall be posed
* @param {!Array<string>} answers The potential responses to the question
* @param {number} correctAnswerIndex The index in answers that leads to the correct response
*/
constructor(question, answers, correctAnswerIndex) {
/**
* @private @const {string}
*/
this.question_ = question;
/**
* @private @const {Array<string>}
*/
this.answers_ = answers;
/**
* @private @const {number}
*/
this.correctAnswerIndex_ = correctAnswerIndex;
}
/**
* @return {string}
*/
getQuestion() {
return this.question_;
}
/**
* @return {!Array<string>}
*/
getAnswers() {
return this.answers_;
}
/**
* @return {number}
*/
getCorrectAnswerIndex() {
return this.correctAnswerIndex_;
}
} |
JavaScript | class Component extends GoogUiComponent {
/**
* @param {?dom.DomHelper=} opt_domHelper
*/
constructor(opt_domHelper) {
super(opt_domHelper);
/** @private @type {?string} */
this.name_ = null;
/** @private @type {?BgColorTransform} */
this.fx_ = null;
}
/**
* @param {string} name
*/
setName(name) {
this.name_ = name;
}
/**
* @return {?string}
*/
getName() {
return this.name_;
}
/**
* @param {string} name
* @return {!Node}
*/
getComponentLabel(name) {
if (name) {
name = strings.capitalize(name);
}
return this.getDomHelper().createTextNode(name);
}
/**
* @return {!Array<string>}
*/
getPath() {
var current = this;
var path = [];
while (current) {
var name = current.getName();
if (name) {
path.push(name);
// } else {
// console.log('path: no name', current);
}
current = current.parent();
}
path.reverse();
return path;
}
/**
* @return {string}
*/
getPathUrl() {
return this.getPath().join('/');
}
/**
* @param {!Route} route
*/
go(route) {
route.progress(this);
if (route.atEnd()) {
this.goHere(route);
} else {
// console.warn(`Component ${this.getName()} going down to: "${route.peek()}"`);
this.goDown(route);
}
}
/**
* @param {!Route} route
*/
goHere(route) {
this.show();
route.done(this);
}
/**
* @param {!Route} route
*/
goDown(route) {
// console.warn(`Component ${this.getName()} failed at ${route.peek()}`);
route.fail(this);
}
/**
* @return {?Component}
*/
parent() {
return /** @type {?Component} */ (
this.getParent()
);
}
// /**
// * @override
// */
// dispatchEvent(e) {
// console.log("dispatching event", e, this);
// var ancestorsTree, ancestor = this.getParentEventTarget();
// if (ancestor) {
// ancestorsTree = [];
// for (; ancestor; ancestor = ancestor.getParentEventTarget()) {
// ancestorsTree.push(ancestor);
// }
// }
// console.log("ancestors tree", ancestorsTree);
// return super.dispatchEvent(e);
// }
// /**
// * Handle a keydown event. Base implementation just propagates to parent
// * component. Can be used to implement key handling.
// * @param {!goog.events.BrowserEvent=} e
// */
// handleKeyDown(e) {
// const parent = this.parent();
// if (parent) {
// parent.handleKeyDown(e);
// }
// }
/**
* Callback function that bubbles up the active component along the component
* hairarachy.
* @param {!Component} target
*/
handleComponentActive(target) {
const parent = this.parent();
if (parent) {
parent.handleComponentActive(target);
}
}
/**
* @param {string} id
* @return {?Component}
*/
child(id) {
return /** @type {?Component} */ (
this.getChild(id)
);
}
/**
* @param {number} index
* @return {!Component}
*/
childAt(index) {
return /** @type {!Component} */ (
asserts.assertObject(this.getChildAt(index))
);
}
/**
* @param {string} id
* @return {!Component}
*/
strictchild(id) {
return /** @type {!Component} */ (
asserts.assertObject(this.getChild(id))
);
}
/**
* Return the root component.
*
* @return {!Component}
*/
getRoot() {
/** @type {?Component} */
let current = this;
while (current) {
if (!current.parent()) {
return current;
}
current = current.parent();
}
throw new ReferenceError('Root reference not available');
}
/**
* @return {!stack.ui.App}
*/
getApp() {
return /** @type {!stack.ui.App} */ (this.getRoot());
}
/**
* Default is no-op.
*/
focus() {
}
/**
* Show this component.
*/
show() {
style.setElementShown(this.getShowHideElement(), true);
this.dispatchEvent(ComponentEventType.SHOW);
}
/**
* Flash this component.
*/
flash() {
style.setElementShown(this.getShowHideElement(), true);
}
/**
* Hide this component.
*/
hide() {
style.setElementShown(this.getShowHideElement(), false);
this.dispatchEvent(ComponentEventType.HIDE);
}
/**
* @return {!Element}
*/
getShowHideElement() {
return this.getElementStrict();
}
/**
* @param {!Array<number>=} opt_start 3D Array for RGB of start color.
* @param {!Array<number>=} opt_end 3D Array for RGB of end color.
* @param {number=} opt_time Length of animation in milliseconds.
* @param {?Function=} opt_accel Acceleration function, returns 0-1 for inputs 0-1.
* @param {?Element=} opt_element Dom Node to be used in the animation.
* @param {?events.EventHandler=} opt_eventHandler Optional event handler
* to use when listening for events.
*/
bgColorFadeIn(opt_start, opt_end, opt_time, opt_accel, opt_element, opt_eventHandler) {
var fx = this.fx_;
if (fx) {
fx.stop();
fx.dispose();
}
var start = opt_start || [128, 128, 128];
var end = opt_end || [256, 256, 256];
var time = opt_time || 250;
var accel = opt_accel || easing.easeOutLong;
var element = opt_element || asserts.assertElement(this.getContentElement());
fx = this.fx_ =
new BgColorTransform(element, start, end, time, accel);
fx.play();
}
/**
* @param {string} src
*/
setBackgroundImage(src) {
var style = this.getContentElement().style;
var url = `url(${src})`;
style.backgroundImage = url;
style.backgroundSize = 'cover';
//style.backgroundOpacity = '0.3';
style.backgroundPosition = 'center center';
style.height = '100%';
}
/**
* @return {?Array<!GoogUiControl>}
*/
getMenuItems() {
return null;
}
} |
JavaScript | class DatasetSelector extends React.Component {
handleToggleDataset = value => () => {
this.props.clientFSToggleDataset(value)
};
generateLabel = id => {
const { perspectiveID } = this.props
return (
<div className={this.props.classes.checkboxLabel}>
<span>{intl.get(`perspectives.${perspectiveID}.datasets.${id}.label`)}</span>
<a
className={this.props.classes.link}
href={intl.get(`perspectives.${perspectiveID}.datasets.${id}.aboutLink`)}
target='_blank'
rel='noopener noreferrer'
>
<InfoIcon />
</a>
</div>
)
}
render () {
const { classes } = this.props
return (
<div className={classes.root}>
<FormControl component='fieldset' className={classes.formControl}>
<FormGroup className={classes.formGroup}>
{Object.keys(this.props.datasets).map(id => (
<FormControlLabel
classes={{
root: classes.formControlLabelRoot,
label: classes.formControlLabelLabel
}}
key={id}
control={
<Checkbox
checked={this.props.datasets[id].selected}
onChange={this.handleToggleDataset(id)}
tabIndex={-1}
disableRipple
/>
}
label={this.generateLabel(id)}
/>
))}
</FormGroup>
</FormControl>
</div>
)
}
} |
JavaScript | class ZIMContainer extends Component {
componentDidMount() {
// or set size in React and do not add dimensions here
const frame = new Frame(this.zimRootElement.id, 1024, 768)
frame.on("ready", () => {
const stage = frame.stage
const stageW = frame.width
const stageH = frame.height
// ZIM code here
new Circle(60, "red").center().drag();
stage.update()
})
}
render() {
return <div ref={element => (this.zimRootElement = element)} />
}
} |
JavaScript | class TimeOutError extends Error {
constructor() {
super('Prompt timed out.');
if(Error.captureStackTrace) {
Error.captureStackTrace(this, TimeOutError);
}
this.name = 'TimeOutError';
}
} |
JavaScript | class CancelError extends Error {
constructor() {
super('Prompt was canceled by user.');
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CancelError);
}
this.name = 'CancelError';
}
} |
JavaScript | class Phantasialand extends Park {
/**
* Create a new Phantasialand Park object
* @param {object} options
*/
constructor(options = {}) {
options.name = 'Phantasialand';
options.timezone = 'Europe/Berlin';
// Setting the parks entrance as it's default location
options.latitude = 50.798954;
options.longitude = 6.879314;
// Options for our park Object
options.supportswaittimes = true;
options.supportsschedule = false;
options.supportsrideschedules = true;
options.fastPass = false;
options.FastPassReturnTimes = false;
// Options for location faking
options.longitudeMin = 6.878342628;
options.longitudeMax = 6.877570152;
options.latitudeMin = 50.800659529;
options.latitudeMax = 50.799683077;
// Api options
options.apiKey = process.env.PHANTASIALAND_API_KEY;
options.poiUrl = process.env.PHANTASIALAND_POI_URL;
options.waitTimesURL = process.env.PHANTASIALAND_WAITTIMES_URL;
options.hoursURL = process.env.PHANTASIALAND_HOURS_URL;
// Language options
options.languages = process.env.LANGUAGES;
options.langoptions = `{'en', 'fr', 'de', 'nl'}`;
super(options);
// Check for existance
if (!this.config.poiUrl) throw new Error('Missing Phantasialand poi url!');
if (!this.config.apiKey) throw new Error('Missing Phantasialand apiKey!');
if (!this.config.waitTimesURL) throw new Error('Missing Phantasialand waittimes url!');
if (!this.config.hoursURL) throw new Error('Missing Phantasialand Operating Hours url!');
if (!this.config.languages) {
this.config.languages = 'en';
};
this.config.langpref = [`${this.config.languages}`, 'de'];
}
/**
* Get Phantasialand POI data
* This data contains general ride names, descriptions etc.
* @example
* import tpapi from '@alexvv13/tpapi';
*
* const park = new tpapi.park.Phantasialand();
*
* park.getPois().then((pois) => {
* console.log(pois)
* });
* @return {string} All P POIS without queuetimes
*/
async getPOIS() {
// So phantasialand is kinda strange with this, but it provides ALL languages at once, set your env var as no one lang.
const pickName = (title) => {
const n = this.config.langpref.find((lang) => title[lang]);
return n !== undefined ? title[n] : title;
};
return fetch(`${this.config.poiUrl}`,
{
method: 'GET',
},
)
.then((res) => res.json())
.then((rideData) => {
const rides = {};
rideData.forEach((ride) => {
const category = [];
const tags = [];
if (ride.tags) {
ride.tags.forEach((tag) => {
// Category
if (tag === 'ATTRACTION_TYPE_CHILDREN') {
category.push(entityCategory.youngest);
}
if (tag === 'ATTRACTION_TYPE_FAMILY') {
category.push(entityCategory.family);
}
if (tag === 'ATTRACTION_TYPE_ACTION') {
category.push(entityCategory.thrill);
}
// Tags
if (tag === 'ATTRACTION_TYPE_ROOFED') {
tags.push(entityTags.indoor);
}
if (tag === 'ATTRACTION_TYPE_PICTURES') {
tags.push(entityTags.onridePhoto);
}
if (tag === 'ATTRACTION_TYPE_CHILDREN_MAY_SCARE') {
tags.push(entityTags.scary);
}
});
}
let minAge = undefined;
let maxAge = undefined;
let minHeight = undefined;
let maxHeight = undefined;
let minHeightAccompanied = undefined;
if (ride.minAge) {
minAge = ride.minAge;
}
if (ride.maxAge) {
maxAge = ride.maxAge;
}
if (ride.minSize) {
minHeight = ride.minSize;
}
if (ride.maxSize) {
maxHeight = ride.maxSize;
}
if (ride.minSizeEscort) {
minHeightAccompanied = ride.minSizeEscort;
}
const restrictions = {
minAge,
minHeight,
minHeightAccompanied,
maxHeight,
maxAge,
};
const location = (ride.entrance && ride.entrance.world) ? ride.entrance.world : undefined;
rides[ride.id] = {
name: pickName(ride.title),
id: ride.id,
location: {
area: ride.area,
longitude: location ? location.lng : null,
latitude: location ? location.lat : null,
},
meta: {
category,
type: ride.category,
descriptions: {
description: pickName(ride.description),
short_description: pickName(ride.tagline),
},
tags,
restrictions,
},
};
});
return Promise.resolve(rides);
});
}
/**
* Fetch service data
*/
async buildServicePOI() {
return await this.cache.wrap(`servicedata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want services
if (rideData[ride].meta.type !== 'SERVICE') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch shop data
*/
async buildMerchandisePOI() {
return await this.cache.wrap(`shopdata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want shops
if (rideData[ride].meta.type !== 'SHOPS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch event data
*/
async buildEventPOI() {
return await this.cache.wrap(`eventdata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want event locations
if (rideData[ride].meta.type !== 'EVENT_LOCATIONS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch hotel data
*/
async buildHotelPOI() {
return await this.cache.wrap(`hoteldata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want hotels
if (rideData[ride].meta.type !== 'PHANTASIALAND_HOTELS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch hotel bar data
*/
async buildHotelBarPOI() {
return await this.cache.wrap(`hotelbardata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want hotel bars
if (rideData[ride].meta.type !== 'PHANTASIALAND_HOTELS_BARS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch restaurant data
*/
async buildRestaurantPOI() {
return await this.cache.wrap(`restdata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want restaurants
if (rideData[ride].meta.type !== 'RESTAURANTS_AND_SNACKS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch ride data
*/
async buildRidePOI() {
return await this.cache.wrap(`ridedata`, async () => {
const rideData = await this.getPOIS();
const rides = {};
Object.keys(rideData).forEach((ride) => {
// We only want rides
if (rideData[ride].meta.type !== 'ATTRACTIONS') return undefined;
const id = rideData[ride].id;
rides[id] = {
name: rideData[ride].name,
id: `Phantasialand_${id}`,
location: {
area: rideData[ride].location.area,
longitude: rideData[ride].location.longitude,
latitude: rideData[ride].location.latitude,
},
meta: {
category: rideData[ride].meta.category,
type: entityType.ride,
descriptions: {
description: rideData[ride].meta.descriptions.description,
short_description: rideData[ride].meta.descriptions.short_description,
},
tags: rideData[ride].meta.tags,
restrictions: rideData[ride].meta.restrictions,
},
};
});
return Promise.resolve(rides);
}, 1000 * 60 * 60 * this.config.cachepoistime /* cache for 12 hours */);
}
/**
* Fetch wait times
* @return {string} ride wait times of Phantasialand
*/
async getQueue() {
return this.buildRidePOI().then((poi) => {
// We'll pretend we're actually in Phantasialand, cause we're cool
const RandomLocation = Location.randomBetween(this.config.longitudeMin, this.config.latitudeMin, this.config.longitudeMax, this.config.latitudeMax);
return fetch(`${this.config.waitTimesURL}?loc=${RandomLocation.latitude},${RandomLocation.longitude}&compact=true&access_token=${this.config.apiKey}`,
{
method: 'GET',
},
)
.then((res) => res.json())
.then((ride) => {
const rides = [];
// console.log(ride);
if (!ride) throw new Error('No queuedata found!');
Object.keys(ride).forEach((rideData) => {
console.log(ride[rideData].waitTime);
let waitTime = '0';
let active = false;
let state = queueType.closed;
// Check if ride is open and if it actually has a queuetime attached
if (ride[rideData].open && ride[rideData].waitTime !== null) {
waitTime = ride[rideData].waitTime;
active = true;
state = queueType.operating;
}
// Attach schedule if known, api communicates closingtimes at least (Shown on park signage)
let openTime = undefined;
let closingTime = undefined;
let opType = undefined;
if (ride[rideData].opening && ride[rideData].closing) { // We got ridetimes so display them
openTime = moment(ride[rideData].opening).format();
closingTime = moment(ride[rideData].closing).format();
opType = scheduleType.operating;
} else { // Park is probably closed || Before park opening & after opening hours are purged automatically...
openTime = moment('23:59', 'HH:mm a').format();
closingTime = moment('23:59', 'HH:mm a').format();
opType = scheduleType.closed;
}
const schedule = {
openingtTime: openTime,
closingTime: closingTime,
type: opType,
};
if (poi[ride[rideData].poiId]) {
poi[ride[rideData].poiId].meta.schedule = schedule; // Attach the schedule data to the meta object.
const rideobj = {
name: poi[ride[rideData].poiId].name,
id: poi[ride[rideData].poiId].id,
status: state,
waitTime: waitTime,
active: active,
changedAt: ride[rideData].updatedAt,
location: poi[ride[rideData].poiId].location,
meta: poi[ride[rideData].poiId].meta,
};
rides.push(rideobj);
}
});
return Promise.resolve(rides);
});
});
}
/**
* Get operating hours of phantasialand
* @return {string} calendar data
*/
async getOpHours() {
const hours = [];
return fetch(`https://www.phantasialand.de/en/theme-park/opening-hours/`)
.then((res) => res.text())
.then((text) => {
const $ = cheerio.load(text);
const calendarData = JSON.parse($('.phl-date-picker').attr('data-calendar'));
calendarData.forEach((calendar) => {
if (calendar.title === 'Geschlossen') {
Object.keys(calendar.days_selected).forEach((time) => {
const cal = {
date: calendar.days_selected[time],
openingTime: moment('23:59', 'HH:mm a').format(),
closingTime: moment('23:59', 'HH:mm a').format(),
type: scheduleType.closed,
special: [],
};
hours.push(cal);
});
} else if (calendar.title === 'Park\u00f6ffnung: 09:00 \u2013 18:00 Uhr') {
Object.keys(calendar.days_selected).forEach((time) => {
const cal = {
date: calendar.days_selected[time],
openingTime: moment('09:00', 'HH:mm a').format(),
closingTime: moment('18:00', 'HH:mm a').format(),
type: scheduleType.operating,
special: [],
};
hours.push(cal);
});
} else if (calendar.title === 'Park\u00f6ffnung: 09:00 \u2013 19:00 Uhr') {
Object.keys(calendar.days_selected).forEach((time) => {
const cal = {
date: calendar.days_selected[time],
openingTime: moment('09:00', 'HH:mm a').format(),
closingTime: moment('19:00', 'HH:mm a').format(),
type: scheduleType.operating,
special: [],
};
hours.push(cal);
});
} else if (calendar.title === 'Silvester: 11:00 \u2013 18:00 Uhr') {
Object.keys(calendar.days_selected).forEach((time) => {
const cal = {
date: calendar.days_selected[time],
openingTime: moment('11:00', 'HH:mm a').format(),
closingTime: moment('18:00', 'HH:mm a').format(),
type: scheduleType.operating,
special: [],
};
hours.push(cal);
});
} else if (calendar.title === 'Wintertraum: 11:00 \u2013 20:00 Uhr') {
Object.keys(calendar.days_selected).forEach((time) => {
const cal = {
date: calendar.days_selected[time],
openingTime: moment('09:00', 'HH:mm a').format(),
closingTime: moment('20:00', 'HH:mm a').format(),
type: scheduleType.operating,
special: [],
};
hours.push(cal);
});
}
});
return Promise.resolve(hours);
});
}
} |
JavaScript | class Raw extends Component {
static propTypes = {
content: PropTypes.string.isRequired,
format: PropTypes.oneOf(['json', 'xml']).isRequired,
onError: PropTypes.func,
}
constructor(props) {
super(props)
this.state = {}
if (props.content && props.format) {
try {
this.state = {
...this.state,
prettyContent: Raw.prettifyContent(props.content, props.format),
}
} catch (error) {
if (props.onError) {
props.onError(error)
}
}
}
this.highlightCode = this.highlightCode.bind(this)
}
componentDidMount() {
this.highlightCode()
}
componentDidUpdate() {
this.highlightCode()
}
componentWillReceiveProps(nextProps) {
if (nextProps.content && nextProps.format) {
try {
this.setState(() => ({
prettyContent: Raw.prettifyContent(
nextProps.content,
nextProps.format,
),
}))
} catch (error) {
if (this.props.onError) {
this.props.onError(error)
}
}
}
}
shouldComponentUpdate(nextProps, nextState) {
return (
this.props.content !== nextProps.content ||
this.props.format !== nextProps.format ||
this.state.prettyContent !== nextState.prettyContent
)
}
highlightCode() {
if (this.code) {
let attMatches = this.code.textContent.match(/"[a-zA-Z0-9-]+"[ ]*:/g)
if (!attMatches || attMatches.length < 5000) {
Highlight.highlightBlock(this.code)
}
}
}
render() {
const { format } = this.props
const { prettyContent } = this.state
return (
<div className="raw">
<pre
className={format}
ref={el => {
this.code = el
}}
>
{prettyContent}
</pre>
</div>
)
}
static prettifyContent(content, format) {
if (format === 'json') {
return Raw.prettifyJSONContent(content)
} else if (format === 'xml') {
return Raw.prettifyXMLContent(content)
} else {
throw new Error('Unsupported content type.')
}
}
static prettifyJSONContent(content) {
return JSON.stringify(JSON.parse(content), null, 2)
}
static prettifyXMLContent(content) {
return beautify.xml(content, 4)
}
} |
JavaScript | class ObjectController {
/**
* Finds an object based on url parameters.
*
* Data from related entities are joined using sequelize.
*
* Related objects are selected using sequelize by submitting multiple queries
* for other objects matching specific attributes of the original object and
* selecting the first four closest matches.
*
* Reply is JSON-API serialized encoding of the object data.
*
* If the ID does not exist then the reply is 404.
*
* @param {fastify.Request} req Fastify request instance.
* @param {fastify.Reply} rep Fastify reply instance.
*/
static async handleGetObject(req, rep) {
// Find object in datastore and join all the related entities.
const object = await this.models.collectionsObject.findOne({
where: {
id: req.params.objectId
},
include: [{
model: this.models.collectionsObjectImage,
as: 'collectionsObjectImages',
where: {
isThumb: false
},
required: false
}, {
model: this.models.collectionsObjectCategory,
as: 'category'
}, {
model: this.models.collectionsObjectMaker,
as: 'collectionsObjectMakers',
include: {
model: this.models.collectionsPerson,
as: 'person'
}
}, {
model: this.models.collectionsObjectPerson,
as: 'collectionsObjectPeople',
include: {
model: this.models.collectionsPerson,
as: 'person'
}
}, {
model: this.models.collectionsObjectPlace,
as: 'collectionsObjectPlaces',
include: {
model: this.models.collectionsPlace,
as: 'place'
}
}, {
model: this.models.collectionsFacility,
as: 'facility'
}]
});
if(object === null) {
rep
.code(404)
.send('Not found');
} else {
const relatedObjectsIncludes = [];
// Include objects with the same makers.
for(const maker of object.collectionsObjectMakers) {
relatedObjectsIncludes.push({
model: this.models.collectionsObjectMaker,
as: 'collectionsObjectMakers',
where: {
personId: maker.personId
}
});
}
// Include objects with the same related people.
for(const person of object.collectionsObjectPeople) {
relatedObjectsIncludes.push({
model: this.models.collectionsObjectPerson,
as: 'collectionsObjectPeople',
where: {
personId: person.personId
}
});
}
// Include objects with the same place.
for(const place of object.collectionsObjectPlaces) {
relatedObjectsIncludes.push({
model: this.models.collectionsObjectPlace,
as: 'collectionsObjectPlaces',
where: {
placeId: place.placeId
}
});
}
const relatedObjectsQueries = [];
// Submit all queries for each attribute match query.
for(const include of relatedObjectsIncludes) {
relatedObjectsQueries.push(this.models.collectionsObject.findAll({
limit: 4,
include: [{
model: this.models.collectionsObjectImage,
as: 'collectionsObjectImages',
where: {
isThumb: true
},
required: false
}, {
model: this.models.collectionsObjectCategory,
as: 'category'
}, include],
where: {
[Op.not]: {
id: object.id
}
}
}));
}
// Submit seperate query for only objects which match in category.
relatedObjectsQueries.push(this.models.collectionsObject.findAll({
limit: 4,
include: [{
model: this.models.collectionsObjectImage,
as: 'collectionsObjectImages',
where: {
isThumb: true
},
required: false
}, {
model: this.models.collectionsObjectCategory,
as: 'category'
}],
where: {
categoryId: object.categoryId,
[Op.not]: {
id: object.id
}
}
}));
// Collect all results asynchronously.
const queryResults = await Promise.all(relatedObjectsQueries);
// Return the four best matching results.
const relatedObjects = queryResults.flat().filter((object, index, self) =>
index === self.findIndex((o) => (
o.id === object.id
))
).slice(0, 4);
let serializedObject = ObjectSerializer.serialize(object);
serializedObject = {
...serializedObject,
meta: {
relatedObjects: ObjectResultSerializer.serialize(relatedObjects)
}
};
rep.send(serializedObject);
}
}
} |
JavaScript | class SelfRenderSystem extends System
{
/**
* @param {Renderer} renderer - The renderer to use.
* @param {number} priority - The priority of the system, higher means earlier.
* @param {number} frequency - How often to run the update loop. `1` means every
* time, `2` is every other time, etc.
*/
constructor(renderer, priority = SelfRenderSystem.defaultPriority, frequency = 1)
{
super(renderer, priority, frequency);
}
/**
* Returns true if the entity is eligible to the system, false otherwise.
*
* @param {Entity} entity - The entity to test.
* @return {boolean} True if entity should be included.
*/
test(entity)
{
return entity.hasComponent(SelfRenderComponent);
}
/**
* Tells the entity to render itself by calling the `render()` method with
* the renderer and elapsed time.
*
* @param {Entity} entity - The entity to update.
* @param {number} elapsed - The time elapsed since last update call.
*/
update(entity, elapsed)
{
entity.render(this.renderer, elapsed);
}
} |
JavaScript | class DebtInstrumentNotationScreenerSearchDataValidationCategorization {
/**
* Constructs a new <code>DebtInstrumentNotationScreenerSearchDataValidationCategorization</code>.
* Debt instrument categorization. See endpoint `/category/listBySystem` with `id=18` for valid values.
* @alias module:model/DebtInstrumentNotationScreenerSearchDataValidationCategorization
*/
constructor() {
DebtInstrumentNotationScreenerSearchDataValidationCategorization.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>DebtInstrumentNotationScreenerSearchDataValidationCategorization</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/DebtInstrumentNotationScreenerSearchDataValidationCategorization} obj Optional instance to populate.
* @return {module:model/DebtInstrumentNotationScreenerSearchDataValidationCategorization} The populated <code>DebtInstrumentNotationScreenerSearchDataValidationCategorization</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new DebtInstrumentNotationScreenerSearchDataValidationCategorization();
if (data.hasOwnProperty('restrict')) {
obj['restrict'] = DebtInstrumentNotationScreenerSearchDataValidationCategorizationRestrict.constructFromObject(data['restrict']);
}
if (data.hasOwnProperty('exclude')) {
obj['exclude'] = DebtInstrumentNotationScreenerSearchDataValidationCategorizationExclude.constructFromObject(data['exclude']);
}
}
return obj;
}
} |
JavaScript | class Selection {
constructor () {
this._selection = new Map()
this._references = []
}
set (pattern, servers) {
this._references.push(pattern)
this._selection.set(stringifyPattern(pattern), servers)
}
get (pattern) {
// try to find containment first
const refPattern = patternContainment(pattern, this._references)
if (refPattern === null) return null
return this._selection.get(stringifyPattern(refPattern))
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.