language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class StoryArea extends Component { constructor(props) { super(props); this.state = { emotion: 'happy' }; } render() { const storyChanged = _.debounce((storytext) => { this.storyChanged(storytext) }, 250); return ( <div className="row"> <div className="col-md-8"> <StoryText onStoryChange = { storyChanged } refresh = { this.props.storytext }/> </div> <div className="col-md-4"> <div className="row"> <ClassScale emotion = { this.state.emotion } classifier = {this.props.classifier.classifier} scale = {this.props.classifier.scale}/> </div> </div> </div> ); } storyChanged(storytext) { // this.setState( { storytext }); this.props.onStoryChange(storytext); this.props.classifyText(storytext); } componentDidUpdate() { const emotion = this.props.emotion; if (emotion != this.state.emotion) { this.setState({emotion}); } } }
JavaScript
class ComputeGLMModule extends BaseModule { constructor() { super(); this.name = 'computeGLM'; } createDescription() { let des= { "name": "Compute GLM", "description": "Calculates the Generalized linear model (GLM) for fMRI data sets", "author": "Zach Saltzman", "version": "1.0", "outputs": baseutils.getImageToImageOutputs("Output beta map image"), "buttonName": "Calculate", "shortname" : "glm", "params": [ { "name": "Num Tasks", "description": "How many of the actual columns in the regressor are actual tasks -- if 0 then all.", "priority": 1, "advanced": false, "gui": "slider", "type": "int", "varname": "numtasks", "default" : 0, "low" : 0, "high": 20, }, baseutils.getDebugParam() ] }; des.inputs= baseutils.getImageToImageInputs('Load the image to fit the model to'); des.inputs.push(baseutils.getRegressorInput()); des.inputs.push( { 'type': 'image', 'name': 'Load Mask Image', 'description': 'Load the mask for the input', 'varname': 'mask', 'required' : false, }); return des; } directInvokeAlgorithm(vals) { console.log('oooo invoking: computeGLM with vals', JSON.stringify(vals)); return new Promise( (resolve, reject) => { let input = this.inputs['input']; //'0' indicates no mask let mask = this.inputs['mask'] || 0; let usemask=false; if (mask) usemask=true; let regressor = this.inputs['regressor']; let sz=numeric.dim(regressor); let numtasks=parseInt(vals.numtasks); if (numtasks<=0 || numtasks>=sz[1]) numtasks=sz[1]; biswrap.initialize().then( () => { this.outputs['output'] = biswrap.computeGLMWASM(input, mask, regressor, { 'numtasks' : numtasks, 'usemask' : usemask }, vals.debug); resolve(); }).catch( (e) => { reject(e.stack); }); }); } }
JavaScript
class AuthenticateUser { /** * @method verifyUser * @description verifies the user token * @param {object} req - The Request Object * @param {object} res - The Response Object * @param {object} next - The next Object * @returns {object} JSON API Response */ static verifyUser(req, res, next) { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, secretKey, (err, decoded) => { if (err) { return res.status(401).send({ status: res.statusCode, error: 'Authentication Failed', }); } req.user = decoded; }); if (req.user.type !== 'client') { return res.status(403).json({ status: res.statusCode, error: 'Please sign in with a client account to access this endpoint', }); } return next(); } /** * @method verifyStaff * @description verifies the user token to determine if the user is a staff or not * @param {object} req - The Request Object * @param {object} res - The Response Object * @param {object} next - The next Object * @returns {object} JSON API Response */ static verifyStaff(req, res, next) { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, secretKey, (err, decoded) => { if (err) { return res.status(401).send({ status: res.statusCode, error: 'Authentication Failed', }); } req.user = decoded; }); if (req.user.type !== 'staff') { return res.status(403).send({ status: res.statusCode, error: 'Unauthorized', }); } return next(); } /** * @method verifyCashier * @description verifies the user token to determine if the user is a cashier * @param {object} req - The Request Object * @param {object} res - The Response Object * @param {object} next - The next Object * @returns {object} JSON API Response */ static verifyCashier(req, res, next) { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, secretKey, (err, decoded) => { if (err) { return res.status(401).send({ status: res.statusCode, error: 'Authentication Failed', }); } req.user = decoded; }); if (req.user.type !== 'staff' || req.user.isAdmin) { return res.status(403).send({ status: res.statusCode, error: 'Unauthorized', }); } return next(); } /** * @method verifyAdmin * @description verifies the user token to determine if the user is admin or not * @param {object} req - The Request Object * @param {object} res - The Response Object * @param {object} next - The next Object * @returns {object} JSON API Response */ static verifyAdmin(req, res, next) { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, secretKey, (err, decoded) => { if (err) { return res.status(401).send({ status: res.statusCode, error: 'Authentication Failed', }); } req.user = decoded; }); if (!req.user.isAdmin) { return res.status(403).send({ status: res.statusCode, error: 'Unauthorized', }); } return next(); } }
JavaScript
class ShareableMap extends Map { /** * Construct a new ShareableMap. * * @param expectedSize How many items are expected to be stored in this map? Setting this to a good estimate from * the beginning is important not to trash performance. * @param averageBytesPerValue What's the expected average size of one serialized value that will be stored in this * map? * @param serializer Custom serializer to convert the objects stored in this map as a value to an ArrayBuffer and * vice-versa. */ constructor(expectedSize = 1024, averageBytesPerValue = 256, serializer) { super(); this.serializer = serializer; this.textEncoder = new TextEncoder(); this.textDecoder = new TextDecoder(); this.reset(expectedSize, averageBytesPerValue); } /** * Get the internal buffers that represent this map and that can be transferred without cost between threads. Use * setBuffers() to rebuild a ShareableMap after the buffers have been transferred. */ getBuffers() { return [this.index, this.data]; } /** * Set the internal buffers that represent this map and that can be transferred without cost between threads. * * @param indexBuffer Index table buffer that's used to keep track of which values are stored where in the * dataBuffer. * @param dataBuffer Portion of memory in which all the data itself is stored. */ setBuffers(indexBuffer, dataBuffer) { this.index = indexBuffer; this.indexView = new DataView(this.index); this.data = dataBuffer; this.dataView = new DataView(this.data); } [Symbol.iterator]() { return this.entries(); } *entries() { for (let i = 0; i < this.buckets; i++) { let dataPointer = this.indexView.getUint32(ShareableMap.INDEX_TABLE_OFFSET + i * ShareableMap.INT_SIZE); while (dataPointer !== 0) { const key = this.readTypedKeyFromDataObject(dataPointer); const value = this.readValueFromDataObject(dataPointer); yield [key, value]; dataPointer = this.dataView.getUint32(dataPointer); } } } *keys() { for (let i = 0; i < this.buckets; i++) { let dataPointer = this.indexView.getUint32(ShareableMap.INDEX_TABLE_OFFSET + i * ShareableMap.INT_SIZE); while (dataPointer !== 0) { yield this.readTypedKeyFromDataObject(dataPointer); dataPointer = this.dataView.getUint32(dataPointer); } } } *values() { for (let i = 0; i < this.buckets; i++) { let dataPointer = this.indexView.getUint32(ShareableMap.INDEX_TABLE_OFFSET + i * 4); while (dataPointer !== 0) { yield this.readValueFromDataObject(dataPointer); dataPointer = this.dataView.getUint32(dataPointer); } } } clear(expectedSize = 1024, averageBytesPerValue = 256) { this.reset(expectedSize, averageBytesPerValue); } delete(key) { throw new Error("Deleting a key from a ShareableMap is not supported at this moment."); } forEach(callbackfn, thisArg) { super.forEach(callbackfn, thisArg); } get(key) { let stringKey; if (typeof key !== "string") { stringKey = JSON.stringify(key); } else { stringKey = key; } const hash = fnv.fast1a32(stringKey); // Bucket in which this value should be stored. const bucket = (hash % this.buckets) * ShareableMap.INT_SIZE; const returnValue = this.findValue(this.indexView.getUint32(bucket + ShareableMap.INDEX_TABLE_OFFSET), stringKey); if (returnValue) { return returnValue[1]; } return undefined; } has(key) { return this.get(key) !== undefined; } set(key, value) { let stringKey; if (typeof key !== "string") { stringKey = JSON.stringify(key); } else { stringKey = key; } const hash = fnv.fast1a32(stringKey); // Bucket in which this value should be stored. const bucket = (hash % this.buckets) * 4; const nextFree = this.freeStart; // Pointer to next block is empty at this point this.storeDataBlock(key, value); // Increase size this.increaseSize(); const bucketPointer = this.indexView.getUint32(bucket + ShareableMap.INDEX_TABLE_OFFSET); if (bucketPointer === 0) { this.incrementBucketsInUse(); this.indexView.setUint32(bucket + ShareableMap.INDEX_TABLE_OFFSET, nextFree); } else { // Update linked list pointers this.updateLinkedPointer(bucketPointer, nextFree); } // If the load factor exceeds the recommended value, we need to rehash the map to make sure performance stays // acceptable. if ((this.getBucketsInUse() / this.buckets) >= ShareableMap.LOAD_FACTOR) { this.doubleIndexStorage(); } return this; } get size() { // Size is being stored in the first 4 bytes of the index table return this.indexView.getUint32(0); } /** * @return The amount of buckets that are currently available in this map (either taken or not-taken, the total * number of buckets is returned). */ get buckets() { return (this.indexView.byteLength - ShareableMap.INDEX_TABLE_OFFSET) / ShareableMap.INT_SIZE; } /** * @return The amount of buckets that currently point to a data object. */ getBucketsInUse() { return this.indexView.getUint32(4); } /** * Increase the amount of buckets that currently point to a data object by one. */ incrementBucketsInUse() { return this.indexView.setUint32(4, this.getBucketsInUse() + 1); } /** * At what position in the data-array does the next block of free space start? This position is returned as number * of bytes since the start of the array. */ get freeStart() { // At what position in the data table does the free space start? return this.indexView.getUint32(8); } /** * Update the position where the next block of free space in the data array starts. * * @param position The new position that should be set. Must indicate the amount of bytes from the start of the * data array. */ set freeStart(position) { this.indexView.setUint32(8, position); } /** * @return Total current length of the data array in bytes. */ get dataSize() { return this.indexView.getUint32(12); } /** * Update the total length of the data array. * * @param size New length value, in bytes. */ set dataSize(size) { this.indexView.setUint32(12, size); } /** * Increase the size counter by one. This counter keeps track of how many items are currently stored in this map. */ increaseSize() { this.indexView.setUint32(0, this.size + 1); } /** * Allocate a new ArrayBuffer that's twice the size of the previous buffer and copy all contents from the old to the * new buffer. This method should be called when not enough free space is available for elements to be stored. */ doubleDataStorage() { let newData; try { newData = new SharedArrayBuffer(this.dataSize * 2); } catch (error) { newData = new ArrayBuffer(this.dataSize * 2); } const newView = new DataView(newData, 0, this.dataSize * 2); for (let i = 0; i < this.dataSize; i += 4) { newView.setUint32(i, this.dataView.getUint32(i)); } this.data = newData; this.dataView = newView; this.dataSize *= 2; } /** * Call this function if the effective load factor of the map is higher than the allowed load factor (default 0.75). * This method will double the amount of available buckets and make sure all pointers are placed in the correct * location. */ doubleIndexStorage() { let newIndex; try { newIndex = new SharedArrayBuffer(ShareableMap.INDEX_TABLE_OFFSET + ShareableMap.INT_SIZE * (this.buckets * 2)); } catch (error) { newIndex = new ArrayBuffer(ShareableMap.INDEX_TABLE_OFFSET + ShareableMap.INT_SIZE * (this.buckets * 2)); } const newView = new DataView(newIndex, 0, ShareableMap.INDEX_TABLE_OFFSET + ShareableMap.INT_SIZE * (this.buckets * 2)); let bucketsInUse = 0; // Now, we need to rehash all previous values and recompute the bucket pointers for (let bucket = 0; bucket < this.buckets; bucket++) { let startPos = this.indexView.getUint32(ShareableMap.INDEX_TABLE_OFFSET + bucket * 4); while (startPos !== 0) { // Read key and rehash const key = this.readKeyFromDataObject(startPos); const hash = fnv.fast1a32(key); const newBucket = hash % (this.buckets * 2); const currentBucketContent = newView.getUint32(ShareableMap.INDEX_TABLE_OFFSET + newBucket * 4); // Should we directly update the bucket content or follow the links and update those? if (currentBucketContent === 0) { bucketsInUse++; newView.setUint32(ShareableMap.INDEX_TABLE_OFFSET + newBucket * 4, startPos); } else { this.updateLinkedPointer(currentBucketContent, startPos); } // Follow link in the chain and update it's properties. const newStartPos = this.dataView.getUint32(startPos); this.dataView.setUint32(startPos, 0); startPos = newStartPos; } } // Set metadata newView.setUint32(0, this.indexView.getUint32(0)); newView.setUint32(4, bucketsInUse); newView.setUint32(8, this.indexView.getUint32(8)); newView.setUint32(12, this.indexView.getUint32(12)); this.index = newIndex; this.indexView = newView; } encodeObject(obj) { let stringVal; if (typeof obj !== "string") { stringVal = JSON.stringify(obj); } else { stringVal = obj; } const buffer = new ArrayBuffer(2 * stringVal.length); const view = new Uint8Array(buffer); const keyLength = this.encodeString(stringVal, view); return [buffer, keyLength]; } /** * Encode a string value and store into the given view. This function returns the amount of bytes that are used * for the encoded string. * * @param stringValue String value that should be encoded into the array. * @param view View of the array in which the encoded result is stored. * @return The number of bytes that are used for the encoded string result. */ encodeString(stringValue, view) { // Safari does not support the encodeInto function if (this.textEncoder.encodeInto !== undefined) { const writeResult = this.textEncoder.encodeInto(stringValue, view); return writeResult.written ? writeResult.written : 0; } else { const encodedString = this.textEncoder.encode(stringValue); for (let i = 0; i < encodedString.byteLength; i++) { view[i] = encodedString[i]; } return encodedString.byteLength; } } encodeKey(key) { return this.encodeObject(key); } encodeValue(value) { if (this.serializer) { const encodedBuffer = this.serializer.encode(value); return [encodedBuffer, encodedBuffer.byteLength]; } else { return this.encodeObject(value); } } /** * Allocates some space in the data array to store a new data object. Such a data object keeps track of it's * internal length, points to the next item in the current linked list of objects and keeps track of it's key and * value. * * @param key The key that identifies the given value. * @param value The value that's associated with the given key. */ storeDataBlock(key, value) { const nextFree = this.freeStart; const [keyBuffer, keyLength] = this.encodeKey(key); const [valueBuffer, valueLength] = this.encodeValue(value); const keyView = new Uint8Array(keyBuffer); const valueView = new Uint8Array(valueBuffer); // Determine if the data storage needs to be resized. (Every character of a string needs 2 bytes when decoded). if (2 * (valueLength + keyLength) + nextFree + ShareableMap.DATA_OBJECT_OFFSET > this.dataSize) { this.doubleDataStorage(); } // Store key in data structure for (let byte = 0; byte < keyLength; byte++) { this.dataView.setUint8(nextFree + ShareableMap.DATA_OBJECT_OFFSET + byte, keyView[byte]); } for (let byte = 0; byte < valueLength; byte++) { this.dataView.setUint8(nextFree + ShareableMap.DATA_OBJECT_OFFSET + keyLength + byte, valueView[byte]); } // Store key length this.dataView.setUint32(nextFree + 4, keyLength); // Store value length this.dataView.setUint32(nextFree + 8, valueLength); // Keep track of key and value datatypes this.dataView.setUint16(nextFree + 12, typeof key === "string" ? 1 : 0); this.dataView.setUint16(nextFree + 14, typeof value === "string" ? 1 : 0); this.freeStart = nextFree + ShareableMap.DATA_OBJECT_OFFSET + keyLength + valueLength; } /** * Update a data object's pointer to the next object in a linked list. * * @param startPos The starting position of the data object whose "next"-pointer needs to be updated. * @param nextBlock Value of the "next"-pointer that either points to a valid starting position of a data object, or * a 0 if this is the last object in a linked chain of objects. */ updateLinkedPointer(startPos, nextBlock) { while (this.dataView.getUint32(startPos) !== 0) { startPos = this.dataView.getUint32(startPos); } this.dataView.setUint32(startPos, nextBlock); } /** * Start looking for a specific key in a given link of data objects and return the associated value. The starting * position given to this function should point to the first data object in the link that's to be examined. If the * key is not found at this position, the pointer to the next data object is followed until either the key is found, * or no link to the following object exists. * * @param startPos Position of the first data object in the linked list that should be examined. * @param key The key that we're currently looking for. * @return The starting position of the data object and value associated with the given key. If no such key was * found, undefined is returned. */ findValue(startPos, key) { while (startPos !== 0) { const readKey = this.readKeyFromDataObject(startPos); if (readKey === key) { return [startPos, this.readValueFromDataObject(startPos)]; } else { startPos = this.dataView.getUint32(startPos); } } return undefined; } /** * Returns the key associated with the data object starting at the given starting position. * * @param startPos The starting position of the data object from which the associated key should be extracted. */ readKeyFromDataObject(startPos) { const keyLength = this.dataView.getUint32(startPos + 4); const keyArray = new ArrayBuffer(keyLength); const keyView = new Uint8Array(keyArray); for (let byte = 0; byte < keyLength; byte++) { keyView[byte] = this.dataView.getUint8(startPos + ShareableMap.DATA_OBJECT_OFFSET + byte); } return this.textDecoder.decode(keyArray); } readTypedKeyFromDataObject(startPos) { const stringKey = this.readKeyFromDataObject(startPos); if (this.dataView.getUint16(startPos + 12) === 1) { return stringKey; } else { return JSON.parse(stringKey); } } /** * Returns the value associated with the data object starting at the given starting position. * * @param startPos The starting position of the data object from which the associated value should be returned. */ readValueFromDataObject(startPos) { const keyLength = this.dataView.getUint32(startPos + 4); const valueLength = this.dataView.getUint32(startPos + 8); const valueArray = new ArrayBuffer(valueLength); const valueView = new Uint8Array(valueArray); for (let byte = 0; byte < valueLength; byte++) { valueView[byte] = this.dataView.getUint8(startPos + ShareableMap.DATA_OBJECT_OFFSET + byte + keyLength); } if (this.dataView.getUint16(startPos + 14) === 1) { // V should be a string in this case return this.textDecoder.decode(valueArray); } else { // V is not a string and needs to be decoded into the expected result. if (this.serializer) { return this.serializer.decode(valueArray); } else { return JSON.parse(this.textDecoder.decode(valueArray)); } } } /** * Clear all contents of this map and return to the initial configuration. * * @param expectedSize How many elements are expected to be stored in this map? Setting this value initially to a * good estimate could help with improving performance for this map. * @param averageBytesPerValue how large do we expect one value element to be on average. Setting this to a good * estimate can improve performance of this map. */ reset(expectedSize, averageBytesPerValue) { if (averageBytesPerValue % 4 !== 0) { throw new Error("Average bytes per value must be a multiple of 4."); } // First 4 bytes are used to store the amount of items in the map. Second 4 bytes keep track of how many buckets // are currently being used. Third set of 4 bytes is used to track where the free space in the data table // starts. Fourth set of 4 bytes keep tracks of the length of the DataBuffer. Rest of the index maps buckets // onto their starting position in the data array. const buckets = Math.ceil(expectedSize / ShareableMap.LOAD_FACTOR); const indexSize = 4 * 4 + buckets * ShareableMap.INT_SIZE; try { this.index = new SharedArrayBuffer(indexSize); } catch (error) { this.index = new ArrayBuffer(indexSize); } this.indexView = new DataView(this.index, 0, indexSize); // Set buckets this.indexView.setUint32(4, 0); // Free space starts from position 1 in the data array (instead of 0, which we use to indicate the end). this.indexView.setUint32(8, 4); // Size must be a multiple of 4 const dataSize = averageBytesPerValue * expectedSize; try { this.data = new SharedArrayBuffer(dataSize); } catch (error) { this.data = new ArrayBuffer(dataSize); } this.dataView = new DataView(this.data, 0, dataSize); // Keep track of the size of the data part of the map. this.indexView.setUint32(12, dataSize); } }
JavaScript
class CanvasFull { constructor(canvasId, redraw=null) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext('2d'); window.addEventListener('resize', this.resizeCanvas.bind(this), false); document.body.style.margin = 0; document.body.style.overflow = "hidden"; this.redraw = redraw; this.resizeCanvas(); } resizeCanvas() { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; if (this.redraw !== null) { this.redraw(this.ctx, this.canvas.width, this.canvas.height); } } }
JavaScript
class ActionBar_Right extends BaseComponent { render() { let { proposal, subNavBarWidth } = this.props; return (React.createElement("nav", { style: { position: "absolute", zIndex: manager.actionBarZIndex, left: `calc(50% + ${subNavBarWidth / 2}px)`, right: 0, top: 0, textAlign: "center", //background: "rgba(0,0,0,.5)", boxShadow: "3px 3px 7px rgba(0,0,0,.07)", } }, React.createElement(Row, { style: { justifyContent: "flex-end", background: "rgba(0,0,0,.7)", boxShadow: colors.navBarBoxShadow, width: "100%", height: 30, borderRadius: "0 0 0 10px", } }))); } }
JavaScript
class TrieNode { /** * Constructor of a new node of Trie data structure * @param {Object} parent Parent config object * @param {string} parent.key Index for this node in its parent node * @param {TrieNode} parent.node Reference to the parent node * @param {boolean} [isRoot] Boolean flag of root node. If the node is root it is not check for parent */ constructor(parent = {key: "", node: null}, isRoot = false) { if (!isRoot && (!parent.key || !(typeof parent.key === 'string'))) throw new Error("Parent key cannot be null, empty or not type of string!"); if (!isRoot && (!parent.node || !(parent.node instanceof TrieNode))) throw new Error("Parent node cannot be null, empty or not class of TrieNode"); this._parent = parent; this._children = {}; this.data = null; this.isEndOfWord = false; this.word = null; } /** * Get parent object consisting of the child index and parent node. * @returns {{key: string, node: TrieNode}} */ get parent() { return this._parent; } /** * Get map of all node's children. * @returns {{}|{TrieNode}} Child index is one character of a inserted word and value is child's node object. */ get children() { return this._children; } /** * Update indexed data of the node. * @param {*} data If data is set to some value the node is automatically set as the end of a word. If data has false value indexed word is removed from the node. */ update(data) { this.isEndOfWord = !!data; this.data = data; if (!this.isEndOfWord) this.word = null; } /** * Remove parent object from this node. * If this function is finished all reference to this node from the Trie root is lost. */ unlink() { this._parent = { key: "", node: null }; } /** * Check if the node has any child nodes attached to it. * @returns {boolean} True if has any children, otherwise false. */ hasChildren() { return Object.keys(this._children).length > 0; } /** * Delete child indexed by the provided character. * If the child does not exists nothing happens. * If the child does exists, the child node object is deleted. * @param {string} char */ deleteChild(char) { if (!this._children[char]) return; this._children[char].update(null); this._children[char].unlink(); this._children[char].word = null; delete this._children[char]; } /** * Add a child to the node. * If a child already exists on the index it is overridden by the new child. * @param {string} char * @param {TrieNode} node * @returns {TrieNode|null} If a child is overridden the old child node is return, otherwise false. */ addChild(char, node) { if (!char || !node) return null; const old = this._children[char]; this._children[char] = node; return old; } /** * Check is the node has a child indexed by the provided character. * @param {string} char * @returns {boolean} True if a child exists, otherwise false. */ hasChild(char) { return !!this._children[char]; } }
JavaScript
class SharedService { // -- // public /** * Getter for All Columns in the grid (hidden/visible) * @return {?} */ get allColumns() { return this._allColumns; } /** * Setter for All Columns in the grid (hidden/visible) * @param {?} allColumns * @return {?} */ set allColumns(allColumns) { this._allColumns = allColumns; } /** * Getter for the Column Definitions pulled through the Grid Object * @return {?} */ get columnDefinitions() { return (this._grid && this._grid.getColumns) ? this._grid.getColumns() : []; } /** * Getter for SlickGrid DataView object * @return {?} */ get dataView() { return this._dataView; } /** * Setter for SlickGrid DataView object * @param {?} dataView * @return {?} */ set dataView(dataView) { this._dataView = dataView; } /** * Getter for SlickGrid Grid object * @return {?} */ get grid() { return this._grid; } /** * Setter for SlickGrid Grid object * @param {?} grid * @return {?} */ set grid(grid) { this._grid = grid; } /** * Getter for the Grid Options pulled through the Grid Object * @return {?} */ get gridOptions() { return (this._grid && this._grid.getOptions) ? this._grid.getOptions() : {}; } /** * Setter for the Grid Options pulled through the Grid Object * @param {?} gridOptions * @return {?} */ set gridOptions(gridOptions) { this.gridOptions = gridOptions; } /** * Getter for the Grid Options * @return {?} */ get groupItemMetadataProvider() { return this._groupItemMetadataProvider; } /** * Setter for the Grid Options * @param {?} groupItemMetadataProvider * @return {?} */ set groupItemMetadataProvider(groupItemMetadataProvider) { this._groupItemMetadataProvider = groupItemMetadataProvider; } /** * Getter for the Visible Columns in the grid * @return {?} */ get visibleColumns() { return this._visibleColumns; } /** * Setter for the Visible Columns in the grid * @param {?} visibleColumns * @return {?} */ set visibleColumns(visibleColumns) { this._visibleColumns = visibleColumns; } }
JavaScript
class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } }
JavaScript
class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') } }
JavaScript
class PackageMetadata extends PackageElement { constructor(items = [], attributes = {}) { const attr = Object.assign( { "xmlns:dc": "http://purl.org/dc/elements/1.1/", }, attributes ); super("metadata", undefined, attr); const requiredMetadata = [ // { element: "dc:identifier", value: `urn:uuid:${uuidv4()}` }, { element: "dc:title", value: "Untitled" }, { element: "dc:language", value: "en-US" }, // { element: "meta", value: undefined, attributes: {property: "dcterms:modified"}} ]; const neededMetadata = requiredMetadata.filter((requiredItem) => { return ( items.findIndex((item) => { return item.element === requiredItem.element; }) === -1 ); }); this.items = items.concat(neededMetadata).map((itemData) => { return new PackageMetadataItem( itemData.element, itemData.value, itemData?.attributes ); }); } addItem(element, value = "", attributes = {}) { this.items.push(new PackageMetadataItem(element, value, attributes)); } removeItemsWithName(element) { this.items = this.items.filter((item) => { item.element !== element; }); } findItemsWithName(element) { return this.items.filter((item) => { return item.element === element; }); } findItemWithId(element, id) { return this.items.find((item) => { return item.element === element && item.id === id; }); } removeItemWithId(element, id) { this.items = this.items.filter((item) => { item.element !== element && item.id !== id; }); } /** * Finds items that have all of the attributes listed in the provided object. * If the object attribute's value is undefined, then only the attribute name * is matched. * @param {object} attributes */ findItemsWithAttributes(attributes) { return this.items.filter((item) => { return Object.keys(attributes).every((key) => { if (item.hasOwnProperty(key)) { if (attributes[key] !== undefined) { return item[key] === attributes[key]; } else { return true; } } return false; }); }); } }
JavaScript
class AudioTrackList extends TrackList { /** * Create an instance of this class. * * @param {AudioTrack[]} [tracks=[]] * A list of `AudioTrack` to instantiate the list with. */ constructor(tracks = []) { let list; // make sure only 1 track is enabled // sorted from last index to first index for (let i = tracks.length - 1; i >= 0; i--) { if (tracks[i].enabled) { disableOthers(tracks, tracks[i]); break; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = document.createElement('custom'); for (const prop in TrackList.prototype) { if (prop !== 'constructor') { list[prop] = TrackList.prototype[prop]; } } for (const prop in AudioTrackList.prototype) { if (prop !== 'constructor') { list[prop] = AudioTrackList.prototype[prop]; } } } list = super(tracks, list); list.changing_ = false; return list; } /** * Add an {@link AudioTrack} to the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to add to the list * * @fires TrackList#addtrack */ addTrack(track) { if (track.enabled) { disableOthers(this, track); } super.addTrack(track); // native tracks don't have this if (!track.addEventListener) { return; } /** * @listens AudioTrack#enabledchange * @fires TrackList#change */ track.addEventListener('enabledchange', () => { // when we are disabling other tracks (since we don't support // more than one track at a time) we will set changing_ // to true so that we don't trigger additional change events if (this.changing_) { return; } this.changing_ = true; disableOthers(this, track); this.changing_ = false; this.trigger('change'); }); } }
JavaScript
class InkTower extends Tower { /** * Defender Ink Tower constructor * @param {Number} id * @param {Number} row * @param {Number} col * @param {Number} boardSize */ constructor(id, row, col, boardSize) { super(); this.type = "Ink"; this.name = "Ink Tower"; this.special = "Ink-Bolt Tower"; this.text = "Deals damage over time. Ground only"; this.levels = 6; this.size = 2; this.sound = "ink"; this.bleeds = true; this.costs = [ 60, 105, 150, 195, 240, 480 ]; this.damages = [ 12, 24, 36, 48, 60, 120 ]; this.ranges = [ 60, 60, 60, 60, 60, 60 ]; this.speeds = [ 6, 6, 6, 6, 6, 12 ]; this.ammoRange = 20; this.init(id, row, col, boardSize); } /** * Creates a new Ammo * @param {Mob[]} targets * @returns {InkAmmo} */ createAmmo(targets) { return new InkAmmo(this, targets, this.boardSize); } /** * Returns a list of Mobs close to the given one * @param {List} mobs * @param {Mob} mob * @returns {Mob[][]} */ getTargets(mobs, mob) { return [ this.getCloseTargets(mobs, mob) ]; } }
JavaScript
class TokenObj { constructor(token) { this.ID = token.id; this.xPos = token.get('left'); this.yPos = token.get('top'); this.xSize = token.get('width'); this.ySize = token.get('height'); const character = getObj('character', token.get('represents')); if (character !== undefined) { this.characterID = character.id; this.isNPC = this.characterID === undefined || getAttrByName(character.id, 'npc') === '1'; if (this.isNPC === false) { const paladinClass = charIsPaladin(this.characterID); if (paladinClass !== false) { this.paladinProps = new PaladinProps(token, paladinClass); Paladin.initFromStoredInclusionList(this); STATE.PaladinList.push(token.id); } } } else { this.isNPC = true; } } }
JavaScript
class home extends React.Component { render(){ return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <text><h1>ADMU</h1></text> <Image source={{ uri: 'https://cdn.pixabay.com/photo/2013/07/12/18/54/smiley-153977_640.png', }} style={{ width: 200, height: 200 }} /> <p> <FadeInView style={{width: 350, height: 290, backgroundColor: '#90ee90'}}> <Text style={{fontSize: 28, textAlign: 'center', margin: 5}}>Bienvenidos a ADMU, una aplicacion para el uso estudiantil en el cual puedas ver las actividades de la universidad, su horario de estudios y sus notas.</Text> </FadeInView> </p> <View style={{flex: 1, flexDirection: 'row'}}> <View style={{width: 150, height: 50}}> <Button color="gray" title="Actividades" onPress={() => this.props.navigation.navigate('actividades',{name:'actividades'})} /> </View> <View style={{width: 150, height: 50}}> <Button color="gray" title="Horario" onPress={() => this.props.navigation.navigate('horario',{name:'horario'})} /> </View> <View style={{width: 150, height: 50}}> <Button color="gray" title="Notas" onPress={() => this.props.navigation.navigate('notas',{name:'notas'})} /> </View> </View> </View> ) } }
JavaScript
class LoanRepo { /** * Method to get all loans * @param {func} applyPagination * @param {string} key * @return {array} Array of loans */ static async getAll(applyPagination, key = '') { const cachedData = key && (await myStore.get(key)); if (cachedData) { return { ...cachedData, cache: true }; } const loans = Loan.findAndCountAll({ ...applyPagination(), include: [{ model: LoanType, as: 'LoanType' }, { model: Customer, as: 'Customer' }], }).catch((error) => { throw new Error(error); }); myStore.save(key, loans); return loans; } /** * Method to get a loan by the id * @param {string} id * @return {object} LoanType */ static async getById(id) { return Loan.findOne({ where: { [Op.or]: [{ id }], }, include: [{ model: LoanType, as: 'LoanType' }, { model: Customer, as: 'Customer' }], }).catch((error) => { throw new Error(error); }); } /** * Method to get a loan by the loanRefNo * @param {string} loanRefNo * @param {string} key * @return {object} LoanType */ static async getByLoanRefNo(loanRefNo) { return Loan.findOne({ where: { [Op.or]: [{ loanRefNo }], }, include: [{ model: LoanType, as: 'LoanType' }], }).catch((error) => { throw new Error(error); }); } /** * Method to create a loan and include gaurantors * @param {object} loanDetails * @return {object} LoanType */ static createLoan(loanDetails) { const { loanRefNo, requestAmount, purpose, accountNumber, customerId, staffId, loanTypeId, gaurantorsArray, duration, } = loanDetails; return Loan.create( { loanRefNo, duration, purpose, accountNumber, customerId, staffId, loanTypeId, requestAmount: Number(requestAmount), Gaurantors: [...gaurantorsArray], }, { include: [{ model: LoanGaurantor, as: 'Gaurantors' }], }, ).catch((error) => { throw new Error(error); }); } /** * Method to approve a loan * @param {object} loan * @param {number} approvedAmount * @return {object} repamentData */ static async approveLoan(loan, approvedAmount) { const { duration, LoanType: { interestRate, payCycle }, } = loan; const durationCount = duration[0]; const payCycleCount = payCycle === 'Monthly' ? 1 : 4; const numberOfPayments = Number(durationCount) * Number(payCycleCount); const interest = approvedAmount * durationCount * (interestRate / 100); const totalPaybackAmount = Number(approvedAmount) + Number(interest); let transaction; try { transaction = await sequelize.transaction(); const approvedLoan = await loan.update( { approvedAmount, approvalStatus: 'approved' }, { transaction }, ); const repayments = await RepaymentRepo.createRepayments( approvedLoan, transaction, totalPaybackAmount, numberOfPayments, ); await transaction.commit(); return { approvedLoan, repayments, totalPaybackAmount, numberOfPayments, }; } catch (error) { await transaction.rollback(); throw error; } } /** * Method to reject a loan given the loan instance * @param {object} loan instance * @return {object} loan */ static rejectLoan(loan) { return loan.update({ approvalStatus: 'rejected' }, { returning: true }).catch((error) => { throw new Error(error); }); } }
JavaScript
class ExposedPromise { constructor() { this._resolve = notInitialized; this._reject = notInitialized; this._status = ExposedPromiseStatus.PENDING; this._promise = new Promise((innerResolve, innerReject) => { this._resolve = (value) => { if (this.isSettled()) { return; } this._promiseResult = value; innerResolve(value); this._status = ExposedPromiseStatus.RESOLVED; return; }; this._reject = (reason) => { if (this.isSettled()) { return; } this._promiseError = reason; innerReject(reason); this._status = ExposedPromiseStatus.REJECTED; return; }; }); } get promise() { return this._promise; } get resolve() { return this._resolve; } get reject() { return this._reject; } get status() { return this._status; } get promiseResult() { return this._promiseResult; } get promiseError() { return this._promiseError; } static resolve(value) { const promise = new ExposedPromise(); promise.resolve(value); return promise; } static reject(reason) { const promise = new ExposedPromise(); promise.reject(reason); return promise; } isPending() { return this.status === ExposedPromiseStatus.PENDING; } isResolved() { return this.status === ExposedPromiseStatus.RESOLVED; } isRejected() { return this.status === ExposedPromiseStatus.REJECTED; } isSettled() { return this.isResolved() || this.isRejected(); } }
JavaScript
class MysqlUser { constructor(connection) { this.connection = connection; this.name = ''; } /** * Wrapper of {@link base-functions.database.mysql~grantPrivileges grantPrivileges} for a specific user * @function handler.databases.mysql.user~grantPrivileges * @example * handler.user('user').grantPrivileges('mydb') */ grantPrivileges(database, options) { const _options = _.defaults(options || {}, this.connection); return mysqlCore.grantPrivileges(database, this.name, _options); } /** * Wrapper of {@link base-functions.database.mysql~createUser createUser} for a specific user * @function handler.databases.mysql.user~create * @example * handler.user('user').create() */ create(options) { const _options = _.defaults(options || {}, this.connection); return mysqlCore.createUser(this.name, _options); } /** * Wrapper of {@link base-functions.database.mysql~dropUser dropUser} for a specific user * @function handler.databases.mysql.user~drop * @example * handler.user('user').drop() */ drop(options) { const _options = _.defaults(options || {}, this.connection); return mysqlCore.dropUser(this.name, _options); } }
JavaScript
class PView extends Command { /** * @param {Client} client The instantiating client * @param {CommandData} data The data for the command */ constructor(bot) { super(bot, { name: 'p-view', guildOnly: true, dirname: __dirname, aliases: ['playlist-view'], botPermissions: ['SEND_MESSAGES', 'EMBED_LINKS'], description: 'View a playlist', usage: 'p-view <playlist name>', cooldown: 3000, examples: ['p-view Songs'], }); } /** * Function for recieving message. * @param {bot} bot The instantiating client * @param {message} message The message that ran the command * @readonly */ async run(bot, message) { // Find all playlists made by the user PlaylistSchema.find({ creator: message.author.id, }, async (err, p) => { // if an error occured if (err) { if (message.deletable) message.delete(); bot.logger.error(`Command: '${this.help.name}' has error: ${err.message}.`); return message.channel.error('misc:ERROR_MESSAGE', { ERROR: err.message }).then(m => m.timedDelete({ timeout: 5000 })); } if (!p[0]) { message.channel.error('music/p-view:NO_PLAYLIST'); } else { // Get all playlists name const playlistNames = p.map(pl => pl.name); // no playlist name was entered if (!message.args[0]) return message.channel.send(message.translate('music/p-view:AVAIABLE', { NAMES: playlistNames.join('`, `') })); // A valid playlist name was entered if (playlistNames.includes(message.args[0])) { p = p.find(obj => obj.name == message.args[0]); // Show information on that playlist let pagesNum = Math.ceil(p.songs.length / 10); if (pagesNum === 0) pagesNum = 1; // Get total playlist duration const totalQueueDuration = p.songs.reduce((a, b) => a + b.duration, 0); const pages = []; let n = 1; for (let i = 0; i < pagesNum; i++) { const str = `${p.songs.slice(i * 10, i * 10 + 10).map(song => `**${n++}.** ${song.title} \`[${getReadableTime(song.duration)}]\``).join('\n')}`; const embed = new Embed(bot, message.guild) .setAuthor({ name: message.author.tag, iconURL: message.author.displayAvatarURL() }) .setThumbnail(p.thumbnail) .setTitle(p.name) .setDescription(str) .setTimestamp() .setFooter({ text: `Page ${i + 1}/${pagesNum} | ${p.songs.length} songs | ${getReadableTime(totalQueueDuration)} total duration` }); pages.push(embed); if (i == pagesNum - 1 && pagesNum > 1) paginate(bot, message.channel, pages, message.author.id); else if (pagesNum == 1) message.channel.send({ embeds: [embed] }); } } else { message.channel.error('music/p-view:NO_PLAYLIST'); } } }); } }
JavaScript
class Modal extends React.Component { constructor(props) { super(props); // Create a div that we'll render the modal into. Because each // Modal component has its own element, we can render multiple // modal components into the modal container. this.el = document.createElement('div'); this.el.style.display = "block"; } componentDidMount() { // Append the element into the DOM on mount. We'll render // into the modal container element (see the HTML tab). modalRoot.appendChild(this.el); } componentWillUnmount() { // Remove the element from the DOM when we unmount modalRoot.removeChild(this.el); } render() { // Use a portal to render the children into the element return ReactDOM.createPortal( // Any valid React child: JSX, strings, arrays, etc. this.props.children, // A DOM element this.el, ); } }
JavaScript
class CourseSelectionView extends React.Component { constructor(props) { super(props); this.state = { loading: true, fosId: "", fos: [], courses: [], unis: [] }; this.handleUniDropdown = this.handleUniDropdown.bind(this); this.filterByTextfield = this.filterByTextfield.bind(this); this.handleFosDropdown = this.handleFosDropdown.bind(this); } componentWillMount() { CourseService.getCourses().then((courses) => UniversityService.getUniversities().then((unis) => { this.setState({ originalCourses: JSON.parse(JSON.stringify(courses)), courses: courses, unis: unis, loading: false }); }).catch((e) => { console.error(e) }) ).catch((e) => { console.error(e) }); } handleUniDropdown(uniId) { UniversityService.getCoursesFromUniversity(uniId) .then(courses => UniversityService.getFosFromUniversity(uniId).then((fos) => { this.setState({ originalCourses: JSON.parse(JSON.stringify(courses)), courses: courses, fos: fos }); }).catch((e) => { console.error(e) }) ).catch((e) => { console.error(e) }); } handleFosDropdown(fosId) { FieldOfStudyService.getCoursesForFos(fosId).then((courses) => { this.setState({ originalCourses: JSON.parse(JSON.stringify(courses)), courses: courses }) }) } filterByTextfield(value) { const courses = this.state.originalCourses; const filteredCourses = courses.filter((course) => { return course.name.toLowerCase().includes(value.toLowerCase()) }); this.setState({ courses: filteredCourses }); } render() { if (this.state.loading) { return <Page> <div style={{display: "flex", flexDirection: "column", alignItems: "center", margin: 200}}> <CircularProgress color={"primary"}/> </div> </Page>} else { return ( <Page> <CourseListWithDropDowns courses={this.state.courses} unis={this.state.unis} fos={this.state.fos} onUniDropdown={this.handleUniDropdown} onFosDropdown={this.handleFosDropdown} handleTextField={this.filterByTextfield}/> </Page> ) } } }
JavaScript
class WidgetPart { constructor(part) { /** * Stores part element. * * @property container * @type {HTMLElement} * @since 1.0.0 */ this.this = part; } /** * Shows WidgetPart . * * @method show * @since 1.0.0 * @return {WidgetPart} Returns the current WidgetPart object. */ show(){ this.this.style.display = 'block'; return this; }; /** * Checks if WidgetPart is displayed. * * @method isActive * @since 1.0.0 * @return {Boolean} Returns true if WidgetPart is displayed and false otherwise. */ isActive(){ return (window.getComputedStyle(this.this, null).getPropertyValue('display') !== 'none'); }; /** * Hides WidgetPart. * * @method hide * @since 1.0.0 * @return {WidgetPart} Returns the current WidgetPart object. */ hide(){ this.this.style.display = 'none'; return this; }; /** * Sets string as WidgetPart content. * * @method text * @param {String} text Content of WidgetPart. * @since 1.0.0 * @return {WidgetPart} Returns an instance of WidgetPart object. */ text(text){ this.this.textContent = text; return this; }; /** * Sets HTML string as WidgetPart content. * * @method html * @param {String} html Content of WidgetPart. * @since 1.0.0 * @return {WidgetPart} Returns an instance of WidgetPart object. */ html(html){ this.this.innerHTML = html; return this; }; /** * Adds child element to WidgetPart. * * @method addChild * @param {HTMLElement} child Child to add. * @since 1.0.0 * @return {WidgetPart} Returns an instance of WidgetPart object. */ addChild(child){ this.this.appendChild(child); return this; }; /** * Adds class to WidgetPart. * * @method addClass * @param {String} name Class name. * @since 1.0.0 * @return {WidgetPart} Returns an instance of WidgetPart object. */ addClass(name){ this.this.classList.add(name); return this; }; /** * Removes class from WidgetPart. * * @method removeClass * @param {String} name Class name. * @since 1.0.0 * @return {WidgetPart} Returns an instance of WidgetPart object. */ removeClass(name){ this.this.classList.remove(name); return this; }; /** * Removes WidgetPart element from DOM. * * @method remove * @since 1.0.0 * @return {WidgetPart} Returns the current WidgetPart object. */ remove(){ this.this.parentNode.removeChild(this.this); return this; }; /** * Adds event to WidgetPart element. * * @method addEvent * @param {String} event Event name. * @param {Function} callback Event callback. * @since 1.0.0 * @return {WidgetPart} Returns the current WidgetPart object. */ addEvent(event, callback){ Helper.addEvent(this.this, event, callback); return this; }; /** * Removes event from WidgetPart element. * * @method removeEvent * @param {String} event Event name. * @param {Function} callback Event callback. * @since 1.0.0 * @return {WidgetPart} Returns the current WidgetPart object. */ removeEvent(event, callback){ Helper.removeEvent(this.this, event, callback); return this; }; }
JavaScript
class AddItemForm extends React.Component { constructor(props) { super(props); this.state = { item: '', submission: [], activity: props.activity, perspective: props.perspective, position: props.position } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } // todo: only return matching submissions for user in activity in perspective loadSubmissionsFromServer() { var cur = this; $.ajax({ url: "/api/LearnerPerspectiveSubmission/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "GET", cache: false, success: function (data) { this.setState({submission: data}); }.bind(this) }); } //This will need to be updated with proper user info ! componentDidMount() { this.loadSubmissionsFromServer(); /* setInterval(() => this.loadSubmissionsFromServer(), this.props.pollInterval); */ } handleChange(event) { this.setState({item: event.target.value}) } handleSubmit(event) { var activity = this.state.activity; var perspective = this.state.perspective; var submissionArray = this.state.submission.filter(function (submission) { return (submission.activity == activity.id && submission.selected_perspective == perspective && submission.created_by == user_id); }); var submission = submissionArray[0]; event.preventDefault(); if (submission == undefined) { //Create new submission $.ajax({ url: "/api/LearnerPerspectiveSubmission/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "POST", beforeSend: function(xhr, settings) { //console.log("before send run", csrftoken) xhr.setRequestHeader("X-CSRFToken", csrftoken); }, data: JSON.stringify( { "sharing": "Share with other learners", "selected_perspective": "" + perspective, "created_by": user_id, //username is a global variable "activity": "" + activity.id }), success: function (data) { submission = data; $.ajax({ url: "/api/LearnerSubmissionItem/", datatype: 'json', contentType: 'application/json; charset=utf-8', crossDomain: true, type: "POST", data: JSON.stringify( { "learner_submission": "" + submission.id, "item": this.state.item, "description": "enter description", "position": this.state.position }), cache: false, beforeSend: function(xhr, settings) { //console.log("before send run", csrftoken) xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function () { this.props.submissionschanged(); this.state.item = ""; /* $.ajax({ url: "/perspectivesX/GetSubmissionScore/" + submission.id + "/", datatype: 'json', contentType: 'application/json', type: "GET", cache: false, success: function (data) { var object = data['0']; alert("Submission updated ! \n" + " Your new score is: \n" + "curation grade: " + object['curation_grade'] + "\n" + "participation grade: " + object['participation_grade'] + "\n" + "total grade: " + object['total_grade'], 3000); }.bind(this) }); */ }.bind(this) }); }.bind(this), }) } else { $.ajax({ url: "/api/LearnerSubmissionItem/", datatype: 'json', contentType: 'application/json; charset=utf-8', crossDomain: true, type: "POST", beforeSend: function(xhr, settings) { //console.log("before send run", csrftoken) xhr.setRequestHeader("X-CSRFToken", csrftoken); }, data: JSON.stringify( { "learner_submission": "" + submission.id, "item": this.state.item, "description": "enter description", "position": this.state.position }), cache: false, success: function () { this.props.submissionschanged(); this.state.item = ""; /* $.ajax({ url: "/perspectivesX/GetSubmissionScore/" + submission.id + "/", datatype: 'json', contentType: 'application/json', type: "GET", cache: false, success: function (data) { var object = data['0']; alert("Submission updated ! \n" + " Your new score is: \n" + "curation grade: " + object['curation_grade'] + "\n" + "participation grade: " + object['participation_grade'] + "\n" + "total grade: " + object['total_grade'], 3000); }.bind(this) }); */ }.bind(this) }); } } render() { return ( <div className="add-item" style={{float: "right"}}> <form onSubmit={this.handleSubmit}> <div className="input-group"> <input type="text" value={this.state.item} onChange={this.handleChange} className="form-control input-sm chat-input" placeholder={`Enter your ${item_terminology} here...`} /> <span className="input-group-btn"> <button type="submit" className="btn btn-primary btn-sm"> <span className="glyphicon glyphicon-comment"></span> Add {item_terminology} </button> </span> </div> <br/> </form> </div> ) } }
JavaScript
class CuratedItemComponent extends React.Component { //React component to display a single submission Item. //Displays the text and author of a Perspective Item constructor(props) { super(props); this.state = { item: props.item, inner: { "id": -1, "description": " ", "item": " ", "position": 0, "created_at": " ", "learner_submission": -1 } } } loadInnerItemFromServer() { var cur = this; $.ajax({ url: "/api/LearnerSubmissionItem/" + this.state.item.item + "/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "GET", cache: false, success: function (data) { this.setState({inner: data}); }.bind(this) }); } componentDidMount() { this.loadInnerItemFromServer(); } deleteItem() { $.ajax({ url: "/api/CuratedItem/" + this.state.item.id + "/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "DELETE", cache: false, beforeSend: function(xhr, settings) { console.log("before send run", csrftoken) xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function () { $.ajax({ url: "/api/LearnerPerspectiveSubmission/" + this.state.inner.learner_submission + "/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "GET", cache: false, success: function (data) { $.ajax({ url: "/perspectivesX/GetSubmissionScore/" + data.id + "/", datatype: 'json', contentType: 'application/json; charset=utf-8', type: "GET", cache: false, success: function (data) { var object = data['0']; alert("Submission updated ! \n" + " Your new score is: \n" + "curation grade: " + object['curation_grade'] + "\n" + "participation grade: " + object['participation_grade'] + "\n" + "total grade: " + object['total_grade']); }.bind(this) }); }.bind(this) }); }.bind(this) }); } render() { const liStyle = { borderStyle: 'outset', backgroundColor: 'lightgrey', marginBottom: '10px' }; var dateString = new Date(this.state.inner['created_at']); dateString = dateString.getDate() + "/" + dateString.getMonth() + "/" + dateString.getFullYear(); return <li key={this.state.item.id} className="list-group-item"> <div className="media"> <div className="media-body"> <div className="media-meta pull-right action-buttons"> <button id='d1' onClick={() => this.deleteItem()} className="btn btn-sm trash"><span className="glyphicon glyphicon-trash"></span></button> </div> <p className="summary">{this.state.inner['item']}</p> <p className="title small"> Author: {this.state.inner['description'].split("from")[1]} | Submitted on: {dateString} | Curated by: 5 users </p> </div> </div> </li> } }
JavaScript
class ObserveChanges extends BasePlugin { constructor(hotInstance) { super(hotInstance); /** * Instance of {@link DataObserver}. * * @type {DataObserver} */ this.observer = null; } /** * Check if the plugin is enabled in the handsontable settings. * * @returns {Boolean} */ isEnabled() { return this.hot.getSettings().observeChanges; } /** * Enable plugin for this Handsontable instance. */ enablePlugin() { if (this.enabled) { return; } if (!this.observer) { this.observer = new DataObserver(this.hot.getSourceData()); this._exposePublicApi(); } this.observer.addLocalHook('change', (patches) => this.onDataChange(patches)); this.addHook('afterCreateRow', () => this.onAfterTableAlter()); this.addHook('afterRemoveRow', () => this.onAfterTableAlter()); this.addHook('afterCreateCol', () => this.onAfterTableAlter()); this.addHook('afterRemoveCol', () => this.onAfterTableAlter()); this.addHook('afterChange', (changes, source) => this.onAfterTableAlter(source)); this.addHook('afterLoadData', (firstRun) => this.onAfterLoadData(firstRun)); super.enablePlugin(); } /** * Disable plugin for this Handsontable instance. */ disablePlugin() { if (this.observer) { this.observer.destroy(); this.observer = null; this._deletePublicApi(); } super.disablePlugin(); } /** * Data change observer. * * @private * @param {Array} patches An array of objects which every item defines coordinates where data was changed. */ onDataChange(patches) { if (!this.observer.isPaused()) { const sourceName = `${this.pluginName}.change`; const actions = { add: (patch) => { if (isNaN(patch.col)) { this.hot.runHooks('afterCreateRow', patch.row, 1, sourceName); } else { this.hot.runHooks('afterCreateCol', patch.col, 1, sourceName); } }, remove: (patch) => { if (isNaN(patch.col)) { this.hot.runHooks('afterRemoveRow', patch.row, 1, sourceName); } else { this.hot.runHooks('afterRemoveCol', patch.col, 1, sourceName); } }, replace: (patch) => { this.hot.runHooks('afterChange', [[patch.row, patch.col, null, patch.value]], sourceName); }, }; arrayEach(patches, (patch) => { if (actions[patch.op]) { actions[patch.op](patch); } }); this.hot.render(); } this.hot.runHooks('afterChangesObserved'); } /** * On after table alter listener. Prevents infinity loop between internal and external data changing. * * @private * @param source */ onAfterTableAlter(source) { if (source !== 'loadData') { this.observer.pause(); this.hot.addHookOnce('afterChangesObserved', () => this.observer.resume()); } } /** * On after load data listener. * * @private * @param {Boolean} firstRun `true` if event was fired first time. */ onAfterLoadData(firstRun) { if (!firstRun) { this.observer.setObservedData(this.hot.getSourceData()); } } /** * Destroy plugin instance. */ destroy() { if (this.observer) { this.observer.destroy(); this._deletePublicApi(); } super.destroy(); } /** * Expose plugins methods to the core. * * @private */ _exposePublicApi() { const hot = this.hot; hot.pauseObservingChanges = () => this.observer.pause(); hot.resumeObservingChanges = () => this.observer.resume(); hot.isPausedObservingChanges = () => this.observer.isPaused(); } /** * Delete all previously exposed methods. * * @private */ _deletePublicApi() { const hot = this.hot; delete hot.pauseObservingChanges; delete hot.resumeObservingChanges; delete hot.isPausedObservingChanges; } }
JavaScript
class UISpawner extends Requestable { /** * Constructor * @param {JsXnat} jsXnat */ constructor(jsXnat) { super(jsXnat); } /** * Returns a single preference and value for this XNAT application. * @param {function} [cb] - Callback function * @returns {string[]} A list of spawner element namespaces. */ getElementNamespaces(cb = undefined) { return this._request('GET', `/xapi/spawner/namespaces`, undefined, cb); } /** * Get list of element IDs in the system's default namespace. * @param {string} [namespace] - if empty, element Ids in the default namespace will be looked up * @param {function} [cb] Callback function * @returns {string[]} A list of spawner element namespaces. */ getElementIdsInNamespace(namespace = undefined, cb = undefined) { const path = namespace ? `/xapi/spawner/ids/${namespace}` : `/xapi/spawner/ids`; return this._request('GET', path, undefined, cb); } }
JavaScript
class Verification { constructor () { this._vendor = null this._javaScriptResources = [] this._flashResources = [] this._viewableImpression = null } // Attribute(s). /** * The home page URL for the verification service provider that supplies the * resource file. * * @type {string} */ get vendor () { return this._vendor } set vendor (value) { this._vendor = value } // Children. /** * The JavaScript resources for this verification vendor. * * @type {JavaScriptResource[]} */ get javaScriptResources () { return this._javaScriptResources } /** * The Flash resources for this verification vendor. * * @type {FlashResource[]} */ get flashResources () { return this._flashResources } /** * The viewable impression for this verification vendor. * * @type {ViewableImpression} */ get viewableImpression () { return this._viewableImpression } set viewableImpression (value) { this._viewableImpression = value } get $type () { return 'Verification' } }
JavaScript
class FileController { // Permitir que o user crie novas Boxes/pastas dentro da aplicação async store(req, res) { const box = await Box.findById(req.params.id); const file = await File.create({ title: req.file.originalname, path: req.file.key, }); box.files.push(file); await box.save(); req.io.sockets.in(box._id).emit('file', file) // Criar um arquivo return res.json(file); } }
JavaScript
class GradeMenu extends React.PureComponent { // Checks the state of the menu, and changes if a gradeLevel is clicked state = { anchorEl: null, }; // Function onClick get the current target that was clicked. handleClick = event => { this.setState({ anchorEl: event.currentTarget }); }; // Function onClose closes the drop down menu. handleClose = e => { this.setState({ anchorEl: null }); }; render() { const { anchorEl } = this.state; return ( <div> <Button aria-owns={anchorEl ? 'simple-menu' : null} aria-haspopup="true" onClick={this.handleClick} className="grade-menu" > Grade <i className="material-icons">arrow_drop_down</i> </Button> <Menu id="simple-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={this.handleClose} > <NavLink to="/sections/Kindergarten" style={{ textDecoration: 'none' }} > <MenuItem id="Kindergarten" onClick={this.handleClose}> Kindergarten </MenuItem> </NavLink> <NavLink to="/sections/1st Grade" style={{ textDecoration: 'none' }}> <MenuItem id="1st Grade" onClick={this.handleClose}> 1st Grade </MenuItem> </NavLink> <NavLink to="/sections/2nd Grade" style={{ textDecoration: 'none' }}> <MenuItem id="2nd Grade" onClick={this.handleClose}> 2nd Grade </MenuItem> </NavLink> <NavLink to="/sections/3rd Grade" style={{ textDecoration: 'none' }}> <MenuItem id="3rd Grade" onClick={this.handleClose}> 3rd Grade </MenuItem> </NavLink> <NavLink to="/sections/4th Grade" style={{ textDecoration: 'none' }}> <MenuItem id="4th Grade" onClick={this.handleClose}> 4th Grade </MenuItem> </NavLink> <NavLink to="/sections/5th Grade" style={{ textDecoration: 'none' }}> <MenuItem id="5th Grade" onClick={this.handleClose}> 5th Grade </MenuItem> </NavLink> </Menu> </div> ); } }
JavaScript
class AveragePooling1D extends _Pooling1D { /** * Creates a AveragePooling1D layer */ constructor(attrs = {}) { super(attrs); this.layerClass = 'AveragePooling1D'; this.poolingFunc = 'average'; } }
JavaScript
class Manager { //Constructor constructor(objects, bufferSize) { this.objects = objects; this.activeObjectIndex = 0; this.bufferSize = bufferSize; if(bufferSize <= 0) this.bufferSize = 1000; if(objects === undefined) this.objects = []; if(bufferSize === undefined) this.bufferSize = 1000; } //Non-chainable methods getActiveObject(){ if(this.objects.length <= 0) return null; if(this.activeObjectIndex >= this.objects.length) this.activeObjectIndex %= this.object.length; return this.objects[this.activeObjectIndex]; }; getLastObject(){ if(this.objects.length <= 0) return null; return this.objects[this.objects.length-1]; } //Chainable methods addObject(object){ this.objects.push(object); if(this.bufferSize >= 0) return this; if(this.objects.length > this.bufferSize) this.objects.shift(); return this; } clear(){ this.objects = []; return this; }; //TODO increase index //TODO decrease index }
JavaScript
class BisWebGridTransformation extends BisWebBaseTransformation { constructor(ii_dims=[4,4,4], ii_spacing=[40,50,40], ii_origin=[0,0,0], ii_nonewfield=false, ii_linearinterpmode=false) { super(); this.jsonformatname='BisGridTransformation'; this.legacyextension="grd"; this.internal = { dispfield: null, origin: [0, 0, 0], spacing: [0, 0, 0], dimensions: [0, 0, 0], minusdim: [0, 0, 0], slicesize: 0, volsize: 0, linearinterpmode: 0, Y: [0, 0, 0], }; this.initialize(ii_dims,ii_spacing,ii_origin,ii_nonewfield,ii_linearinterpmode); } // ---- Get Object Information ------------------------------------------------- /** returns a textual description of the object for GUIs etc. * @returns {string} description */ getDescription() { return "Dimensions:" + this.internal.dimensions[0] + " " + this.internal.dimensions[1] + " " + this.internal.dimensions[2] +", "+ "Spacing:" + this.internal.spacing[0].toFixed(4) + " " + this.internal.spacing[1].toFixed(4) + " " + this.internal.spacing[2].toFixed(4) + ", "+ "Origin:" + this.internal.origin[0].toFixed(4) + " " + this.internal.origin[1].toFixed(4) + " " + this.internal.origin[2].toFixed(4); } /** compute hash * @returns {String} - hash string identifying the object */ computeHash() { return util.SHA256(this.internal.dispfield); } /** returns the memory used in bytes by this object * @returns {number} -- the size or 0 if not implemented or small */ getMemorySize() { return this.getNumberOfDOF()*4+128; } /** serializes object to a javascript dictionary object @returns {Object} dictionary containing all key elements */ serializeToDictionary() { let obj= super.serializeToDictionary(); let bytesarr=new Uint8Array(this.internal.dispfield.buffer); let b=genericio.tozbase64(bytesarr); obj.origin=this.internal.origin; obj.spacing=this.internal.spacing; obj.dimensions=this.internal.dimensions; obj.dispfield=b; obj.linearinterpmode=this.internal.linearinterpmode; return obj; } /** parses from Dictionary Object * @param {Object} b -- dictionary object * @returns {Boolean} true if OK */ parseFromDictionary(b) { let bytesarr=genericio.fromzbase64(b.dispfield); this.initialize(b.dimensions, b.spacing, b.origin, true, b.linearinterpmode); this.internal.dispfield=new Float32Array(bytesarr.buffer); super.parseFromDictionary(b); return true; } /** deserializes an object from WASM array (with an optional second input to help with header stuff) * @param {EmscriptenModule} Module - the emscripten Module object * @param {Pointer} wasmarr - the unsined char wasm object */ deserializeWasm(Module,wasmarr) { // No image, forcing type to float var wasmobj = biswasm.unpackStructure(Module, wasmarr, false, 16); if (wasmobj.magic_type !== biswasm.get_grid_magic_code(Module)) { console.log('Bad wasmobj, can not deserialize grid Transformation'); return 0; } // Now do the header this.identity(); let dim = [0, 0, 0], spa = [0, 0, 0], ori = [0, 0, 0], linearinterp = false; let int_header = new Int32Array(wasmobj.header_array.buffer, 0, 4); let float_header = new Float32Array(wasmobj.header_array.buffer, 16, 6); if (int_header[0] === 0) linearinterp = true; for (let i = 0; i <= 2; i++) { dim[i] = int_header[i + 1]; spa[i] = float_header[i]; ori[i] = float_header[i + 3]; } this.initialize(dim, spa, ori, true, linearinterp); this.internal.dispfield = wasmobj.data_array; } // ---- Testing utility ---------------------------------------------------- /** compares an image with a peer object of the same class and returns true if similar or false if different * @param{BisWebDataObject} other - the other object * @param{String} method - the comparison method one of maxabs,ssd,cc etc. * @param{Number} threshold - the threshold to use for comparison * @returns{Object} - { testresult: true or false, value: comparison value, metric: metric name } */ compareWithOther(other,method="maxabs",threshold=0.01) { let out = { testresult : false, value : null, metric : "maxabs" }; if (other.constructor.name !== this.constructor.name) return out; let myfield=this.getDisplacementField(); let otherfield=other.getDisplacementField(); console.log('....\t comparing grids:',numeric.dim(myfield),numeric.dim(otherfield)); if (method==='maxabs') { out.value=numeric.norminf(numeric.sub(myfield,otherfield)); } else { out.value=numeric.norm2(numeric.sub(myfield,otherfield)); out.method="ssd"; } if (out.value < threshold) out.testresult=true; return out; } // ---------- BisWebBaseTransformation Functions ------------------------------------------- /** This is to set the current transformation to identity. */ identity() { var numdof = this.getNumberOfDOF(); var newfield = true; if (this.internal.dispfield !== null) { if (this.internal.dispfield.length === numdof) { newfield = false; } } if (newfield) this.internal.dispfield = new Float32Array(numdof); for (var i = 0; i < numdof; i++) this.internal.dispfield[i] = 0.0; } /** transforms input point in mm to a mm coordinate using this matrix * @param {array} X - 3 vector of x,y,z coordinates in mm * @param {array} TX - OUTPUT 3 vector of x,y,z coordinates in mm */ transformPoint(X,TX) { if (this.internal.linearinterpmode) this.linearTransformPoint(X, TX); else this.bsplineTransformPoint(X, TX); } // ------------------------------------------ // Other Code // ------------------------------------------ /** transforms input point in mm to a mm coordinate using JUST the b-spline grid * @param {array} X - 3 vector of x,y,z coordinates in mm * @param {array} TX - OUTPUT 3 vector of x,y,z coordinates in mm */ bsplineTransformPoint(X, TX) { var minusdim0 = this.internal.minusdim[0]; var minusdim1 = this.internal.minusdim[1]; var minusdim2 = this.internal.minusdim[2]; var data = this.internal.dispfield; var X0 = (X[0] - this.internal.origin[0]) / this.internal.spacing[0]; var X1 = (X[1] - this.internal.origin[1]) / this.internal.spacing[1]; var X2 = (X[2] - this.internal.origin[2]) / this.internal.spacing[2]; var t, coord; // X-Coordinate var B01 = X0 | 0, B00; t = X0 - B01; if (B01 < 0) { B01 = 0; B00 = 0; } else if (B01 > minusdim0) { B01 = minusdim0; } B00 = B01 - 1; if (B00 < 0) B00 = 0; var B02 = B01 + 1; var B03 = B01 + 2; if (B02 > minusdim0) { B02 = minusdim0; B03 = minusdim0; } else if (B03 > minusdim0) { B03 = minusdim0; } var W00 = Math.pow(1 - t, 3.0) / 6.0; var W01 = (3 * t * t * t - 6 * t * t + 4) / 6.0; var W02 = (-3 * t * t * t + 3 * t * t + 3 * t + 1) / 6.0; var W03 = (t * t * t) / 6.0; // Y-Coordinate var B11 = X1 | 0, B10; t = X1 - B11; if (B11 < 0) { B11 = 0; B10 = 0; } else { B10 = B11 - 1; if (B10 < 0) B10 = 0; } var B12 = B11 + 1; var B13 = B11 + 2; if (B12 > minusdim1) { B12 = minusdim1; B13 = minusdim1; } else if (B13 > minusdim1) { B13 = minusdim1; } var W10 = Math.pow(1 - t, 3.0) / 6.0; var W11 = (3 * t * t * t - 6 * t * t + 4) / 6.0; var W12 = (-3 * t * t * t + 3 * t * t + 3 * t + 1) / 6.0; var W13 = (t * t * t) / 6.0; // Z-Coordinate var B21 = X2 | 0, B20; t = X2 - B21; if (B21 < 0) { B21 = 0; B20 = 0; } else { B20 = B21 - 1; if (B20 < 0) B20 = 0; } var B22 = B21 + 1; var B23 = B21 + 2; if (B22 > minusdim2) { B22 = minusdim2; B23 = minusdim2; } else if (B23 > minusdim2) { B23 = minusdim2; } var W20 = Math.pow(1 - t, 3.0) / 6.0; var W21 = (3 * t * t * t - 6 * t * t + 4) / 6.0; var W22 = (-3 * t * t * t + 3 * t * t + 3 * t + 1) / 6.0; var W23 = (t * t * t) / 6.0; // Scale by raster-size B10 *= this.internal.dimensions[0]; B11 *= this.internal.dimensions[0]; B12 *= this.internal.dimensions[0]; B13 *= this.internal.dimensions[0]; B20 *= this.internal.slicesize; B21 *= this.internal.slicesize; B22 *= this.internal.slicesize; B23 *= this.internal.slicesize; for (coord = 0; coord <= 2; coord++) { TX[coord] = X[coord] + (W20 * W10 * W00 * data[B20 + B10 + B00] + W20 * W10 * W01 * data[B20 + B10 + B01] + W20 * W10 * W02 * data[B20 + B10 + B02] + W20 * W10 * W03 * data[B20 + B10 + B03] + W20 * W11 * W00 * data[B20 + B11 + B00] + W20 * W11 * W01 * data[B20 + B11 + B01] + W20 * W11 * W02 * data[B20 + B11 + B02] + W20 * W11 * W03 * data[B20 + B11 + B03] + W20 * W12 * W00 * data[B20 + B12 + B00] + W20 * W12 * W01 * data[B20 + B12 + B01] + W20 * W12 * W02 * data[B20 + B12 + B02] + W20 * W12 * W03 * data[B20 + B12 + B03] + W20 * W13 * W00 * data[B20 + B13 + B00] + W20 * W13 * W01 * data[B20 + B13 + B01] + W20 * W13 * W02 * data[B20 + B13 + B02] + W20 * W13 * W03 * data[B20 + B13 + B03] + W21 * W10 * W00 * data[B21 + B10 + B00] + W21 * W10 * W01 * data[B21 + B10 + B01] + W21 * W10 * W02 * data[B21 + B10 + B02] + W21 * W10 * W03 * data[B21 + B10 + B03] + W21 * W11 * W00 * data[B21 + B11 + B00] + W21 * W11 * W01 * data[B21 + B11 + B01] + W21 * W11 * W02 * data[B21 + B11 + B02] + W21 * W11 * W03 * data[B21 + B11 + B03] + W21 * W12 * W00 * data[B21 + B12 + B00] + W21 * W12 * W01 * data[B21 + B12 + B01] + W21 * W12 * W02 * data[B21 + B12 + B02] + W21 * W12 * W03 * data[B21 + B12 + B03] + W21 * W13 * W00 * data[B21 + B13 + B00] + W21 * W13 * W01 * data[B21 + B13 + B01] + W21 * W13 * W02 * data[B21 + B13 + B02] + W21 * W13 * W03 * data[B21 + B13 + B03] + W22 * W10 * W00 * data[B22 + B10 + B00] + W22 * W10 * W01 * data[B22 + B10 + B01] + W22 * W10 * W02 * data[B22 + B10 + B02] + W22 * W10 * W03 * data[B22 + B10 + B03] + W22 * W11 * W00 * data[B22 + B11 + B00] + W22 * W11 * W01 * data[B22 + B11 + B01] + W22 * W11 * W02 * data[B22 + B11 + B02] + W22 * W11 * W03 * data[B22 + B11 + B03] + W22 * W12 * W00 * data[B22 + B12 + B00] + W22 * W12 * W01 * data[B22 + B12 + B01] + W22 * W12 * W02 * data[B22 + B12 + B02] + W22 * W12 * W03 * data[B22 + B12 + B03] + W22 * W13 * W00 * data[B22 + B13 + B00] + W22 * W13 * W01 * data[B22 + B13 + B01] + W22 * W13 * W02 * data[B22 + B13 + B02] + W22 * W13 * W03 * data[B22 + B13 + B03] + W23 * W10 * W00 * data[B23 + B10 + B00] + W23 * W10 * W01 * data[B23 + B10 + B01] + W23 * W10 * W02 * data[B23 + B10 + B02] + W23 * W10 * W03 * data[B23 + B10 + B03] + W23 * W11 * W00 * data[B23 + B11 + B00] + W23 * W11 * W01 * data[B23 + B11 + B01] + W23 * W11 * W02 * data[B23 + B11 + B02] + W23 * W11 * W03 * data[B23 + B11 + B03] + W23 * W12 * W00 * data[B23 + B12 + B00] + W23 * W12 * W01 * data[B23 + B12 + B01] + W23 * W12 * W02 * data[B23 + B12 + B02] + W23 * W12 * W03 * data[B23 + B12 + B03] + W23 * W13 * W00 * data[B23 + B13 + B00] + W23 * W13 * W01 * data[B23 + B13 + B01] + W23 * W13 * W02 * data[B23 + B13 + B02] + W23 * W13 * W03 * data[B23 + B13 + B03]); // Shift to y and then z B20 += this.internal.volsize; B21 += this.internal.volsize; B22 += this.internal.volsize; B23 += this.internal.volsize; } } linearTransformPoint(X, TX) { var ia, ja, ka, sum = 0.0; var B = [[0, 0], [0, 0], [0, 0]]; var W = [[0, 0], [0, 0], [0, 0]]; for (ia = 0; ia <= 2; ia++) { var p = (X[ia] - this.internal.origin[ia]) / this.internal.spacing[ia]; B[ia][0] = p | 0; B[ia][1] = B[ia][1] + 1; for (var ib = 0; ib <= 1; ib++) { if (B[ia][ib] < 0) B[ia][ib] = 0; else if (B[ia][ib] > this.internal.minusdim[ia]) B[ia][ib] = this.internal.minusdim[ia]; } W[ia][0] = B[ia][1] - TX[ia]; W[ia][1] = 1.0 - W[ia][0]; } for (ia = 0; ia <= 1; ia++) { B[1][ia] = B[1][ia] * this.internal.dimensions[0]; B[2][ia] = B[2][ia] * this.internal.slicesize; } for (var coord = 0; coord <= 2; coord++) { sum = X[coord]; for (ka = 0; ka <= 1; ka++) { for (ja = 0; ja <= 1; ja++) { for (ia = 0; ia <= 1; ia++) { sum += W[2][ka] * W[1][ja] * W[0][ia] * this.internal.dispfield[B[2][ka] + B[1][ja] + B[0][ia]]; } } } TX[coord] = sum; for (ia = 0; ia <= 1; ia++) B[2][ia] += this.internal.volsize; } } /** * This reinitializes the transformation. * @param {array} dims - [x,y,z] dimensions of grid * @param {array} spacing - [x,y,z] spacing of grid * @param {array} origin - position of first cntrol point * @param {boolean} nonewfield - if false, no new disp field is created * @param {boolean} linearinterpmode - if true, use linear interpolation, else bspline. Default=true. */ initialize(dims, spacing, origin, in_nonewfield, linearinterpmode) { this.internal.dimensions = dims || this.internal.dimensions; for (var i = 0; i <= 2; i++) { this.internal.dimensions[i] = Math.floor(util.range(this.internal.dimensions[i], 1, 1000)); this.internal.minusdim[i] = this.internal.dimensions[i] - 1; } this.internal.slicesize = this.internal.dimensions[0] * this.internal.dimensions[1]; this.internal.volsize = this.internal.dimensions[2] * this.internal.slicesize; this.internal.spacing = spacing || this.internal.spacing; this.internal.origin = origin || this.internal.origin; in_nonewfield = in_nonewfield || false; if (!in_nonewfield) this.identity(); this.internal.linearinterpmode = linearinterpmode || false; } /** This returns the number of DOFs * @returns {number} - number of degrees of freedom */ getNumberOfDOF() { return this.internal.dimensions[0] * this.internal.dimensions[1] * this.internal.dimensions[2] * 3; } /** This returns the number of control points * @returns {number} - number of control points */ getNumberOfControlPoints() { return this.internal.dimensions[0] * this.internal.dimensions[1] * this.internal.dimensions[2]; } /*** Creates an optimized cached mapping to spped up the point to voxel transformation * @param {array} spa - spacing of target image */ optimize() { } /** serializes the grid * with the legacy BioImage Suite .matr format * @return {string} string - containing output * @memberof BisBSplineGridTransformation.prototype */ legacySerialize() { let s = "#vtkpxBaseGridTransform2 File\n"; s = s + "#Origin\n" + this.internal.origin[0].toFixed(4) + " " + this.internal.origin[1].toFixed(4) + " " + this.internal.origin[2].toFixed(4) + "\n"; s = s + "#Spacing\n" + this.internal.spacing[0].toFixed(4) + " " + this.internal.spacing[1].toFixed(4) + " " + this.internal.spacing[2].toFixed(4) + "\n"; s = s + "#Dimensions\n" + this.internal.dimensions[0] + " " + this.internal.dimensions[1] + " " + this.internal.dimensions[2] + "\n"; if (this.internal.linearinterpmode) s = s + "#Interpolation Mode\n1\n#Displacements\n"; else s = s + "#Interpolation Mode\n4\n#Displacements\n"; var np = this.getNumberOfControlPoints(); var np2 = 2 * np; for (var i = 0; i < np; i++) { s += i.toFixed(0) + " " + this.internal.dispfield[i].toFixed(4) + " " + this.internal.dispfield[i + np].toFixed(4) + " " + this.internal.dispfield[i + np2].toFixed(4) + "\n"; } return s; } /** deserializes the landmark set from a string consistent * with the legacy BioImage Suite .land format * @param {string} inpstring - input string * @param {string} filename - filename of original file * @param {number} offset - line to begin * @return {boolean} val - true or false * @memberof BisBSplineGridTransformation.prototype */ legacyParseFromText(inpstring, filename, offset) { offset = offset || 0; var lines = inpstring.split("\n"); var s1 = (lines[offset + 0].trim() === "#vtkpxBaseGridTransform2 File"); var s2 = (lines[8].trim() === "#vtkpxBaseGridTransform2 File"); if (s1 === false && s2 === false) { console.log(filename + ' is not a valid legacy tensor b-spline grid file .grd' + lines[offset + 0].trim() + ',' + lines[offset + 8].trim()); return false; } // Line 0 =#vtkpxBaseGridTransform2 File // Origin = 2, Spacing=4, Dimenions=6, Mode = 8, Displacements start at 10 var origin = lines[offset + 2].trim().split(" "); var spacing = lines[offset + 4].trim().split(" "); var dims = lines[offset + 6].trim().split(" "); for (var k = 0; k <= 2; k++) { origin[k] = parseFloat(origin[k]); spacing[k] = parseFloat(spacing[k]); dims[k] = parseInt(dims[k]); } let interp = lines[offset + 8].trim().split(" "); if (interp !== 4) this.internal.linearinterpmode = true; else this.internal.linearinterpmode = false; var np = dims[0] * dims[1] * dims[2]; this.initialize(dims, spacing, origin, null); for (var cp = 0; cp < np; cp++) { var x = lines[offset + 10 + cp].trim().split(" "); for (var j = 0; j <= 2; j++) { this.internal.dispfield[np * j + cp] = parseFloat(x[j + 1]); } } return true; } /** Returns displacement field array * @returns {array} - displacement field in x,y,z,c order (c=component 3 3 of these) */ getDisplacementField() { return this.internal.dispfield; } /** Returns info about structure of displacement field * @returns {object} - { object.dimensions,object.origin,object.spacing} -- describing the grid */ getGridInfo() { return { origin: [this.internal.origin[0], this.internal.origin[1], this.internal.origin[2]], spacing: [this.internal.spacing[0], this.internal.spacing[1], this.internal.spacing[2]], dimensions: [this.internal.dimensions[0], this.internal.dimensions[1], this.internal.dimensions[2]] }; } /** Sets value from displacement field (nearest voxel). Crude initialization for fitting * @param {BisImage} displacementfield * @param {boolean} inverse -- if true approximate -disp_field. Default = false */ initializeFromDisplacementField(displacement_field, inverse) { var sc = 1.0; inverse = inverse || false; if (inverse) sc = -1.0; var dim = displacement_field.getDimensions(); var data = displacement_field.getImageData(); if (dim[3] !== 3) throw new Error("Need a displacement field here, 3 components!"); var spa = displacement_field.getSpacing(); var slicesize = dim[0] * dim[1]; var volsize = slicesize * dim[2]; var outindex = 0, i, j, k, coord; for (k = 0; k < this.internal.dimensions[2]; k++) { var z = util.range(Math.round((k * this.internal.spacing[2] + this.internal.origin[2]) / spa[2]), 0, dim[2] - 1) * slicesize; for (j = 0; j < this.internal.dimensions[1]; j++) { var y = util.range(Math.round((j * this.internal.spacing[1] + this.internal.origin[1]) / spa[1]), 0, dim[1] - 1) * dim[0]; for (i = 0; i < this.internal.dimensions[0]; i++) { var x = util.range(Math.round((i * this.internal.spacing[0] + this.internal.origin[0]) / spa[0]), 0, dim[0] - 1); var index = x + y + z; for (coord = 0; coord <= 2; coord++) this.internal.dispfield[coord * this.internal.volsize + outindex] = sc * data[index + volsize * coord]; ++outindex; } } } } /** Computes gradient for a process. * @param {array} params -- the current parameters * @param {array} grad - the gradient array to be computed * @param {number} stepsize - the stepsize for computing the gradient * @param {array} imgbounds - the dimensions of the underlying image (with optional margin) * @param {array} imgspa - the spacing of the underlying image * @param {number} windowsize - a number 1 to 2 to specify window around controlpoint * @param {function} computeValueFunctionPiece - a function to evaluate a piece * @returns {number} - the gradient magnitude */ computeGradientForOptimization(params, grad, stepsize, imgbounds, imgspa, windowsize, computeValueFunctionPiece) { var radius = [windowsize * this.internal.spacing[0], windowsize * this.internal.spacing[1], windowsize * this.internal.spacing[2]]; var bounds = [0, 0, 0, 0, 0, 0]; var computeBounds = ( (axis, value) => { var pos = value * this.internal.spacing[axis] + this.internal.origin[axis]; bounds[2 * axis] = util.range(Math.round((pos - radius[axis]) / imgspa[axis]), imgbounds[2 * axis], imgbounds[2 * axis + 1]); bounds[2 * axis + 1] = util.range(Math.round((pos + radius[axis]) / imgspa[axis]), imgbounds[2 * axis], imgbounds[2 * axis + 1]); }); if (params.length !== this.internal.dispfield.length) throw new Error('Bad dimensions for computing grdient optimization in grid transform'); var nc = this.getNumberOfControlPoints(), cp = 0, i, j, k, coord; var GradientNorm = 0.000001; for (k = 0; k < this.internal.dimensions[2]; k++) { computeBounds(2, k); for (j = 0; j < this.internal.dimensions[1]; j++) { computeBounds(1, j); for (i = 0; i < this.internal.dimensions[0]; i++) { computeBounds(0, i); for (coord = 0; coord <= 2; coord++) { var index = cp + coord * nc; this.internal.dispfield[index] = params[index] + stepsize; var a = computeValueFunctionPiece(this, bounds); this.internal.dispfield[index] = params[index] - stepsize; var b = computeValueFunctionPiece(this, bounds); this.internal.dispfield[index] = params[index]; var g = -0.5 * (b - a) / stepsize; grad[index] = g; GradientNorm += g * g; } cp++; } } } GradientNorm = Math.sqrt(GradientNorm); for (i = 0; i < grad.length; i++) grad[i] = grad[i] / GradientNorm; return GradientNorm; } /** Initialize from another displacement grid * @param {BisGridTransform} other - the input disp grid * @param {BisImage} displacements - last good displacements image * @param {number} cps - control point spacing */ initializeFromOtherGrid(original_grid, displacements, cps) { var hd = original_grid.getGridInfo(); var spa = [0, 0, 0], origin = [0, 0, 0], dim = [0, 0, 0], i; for (i = 0; i <= 2; i++) { var sz = (hd.dimensions[i] - 1) * hd.spacing[i]; dim[i] = Math.round(sz / cps) + 1; if (dim[i] < 4) dim[i] = 4; spa[i] = sz / (dim[i] - 1.05); var newsz = (dim[i] - 1) * spa[i]; var offset = newsz - sz; origin[i] = util.scaledround(-0.5 * offset, 100); } this.initialize(dim, spa, origin); this.initializeFromDisplacementField(displacements); return; } /** returns number of bytes needed for WASM serialization * @returns {number} -- number of bytes for serialized array */ getWASMNumberOfBytes() { // 16 = main header, 40=my header + 4 bytes per DOF return 16 + 40 + this.getNumberOfDOF() * 4; } /** serializes the grid to a WASM array * @param {EmscriptenModule} Module - the emscripten Module object * @param {Pointer} inDataPtr - store results here * @returns {number} -- number of bytes stored */ serializeWasmInPlace(Module, inDataPtr) { let header_arr = new Uint8Array(40); let int_header = new Int32Array(header_arr.buffer, 0, 4); let float_header = new Float32Array(header_arr.buffer, 16, 6); if (this.internal.linearinterpmode) int_header[0] = 0; else int_header[0] = 1; for (let i = 0; i <= 2; i++) { int_header[i + 1] = this.internal.dimensions[i]; float_header[i] = this.internal.spacing[i]; float_header[i + 3] = this.internal.origin[i]; } return biswasm.packRawStructureInPlace(Module, inDataPtr, header_arr, this.internal.dispfield, biswasm.get_grid_magic_code(Module)); } }
JavaScript
class DhPurchaseTakePaymentCommand extends Command { constructor(ctx) { super(ctx); this.logger = ctx.logger; this.blockchain = ctx.blockchain; } /** * Executes command and produces one or more events * @param command * @param transaction */ async execute(command, transaction) { const { purchase_id, blockchain_id } = command.data; const dataTrade = await Models.data_trades.findOne({ where: { purchase_id, }, }); const bcPurchase = await this.blockchain.getPurchase(purchase_id, blockchain_id).response; if (bcPurchase.stage === '2') { try { await this.blockchain.takePayment(purchase_id, blockchain_id).response; dataTrade.status = 'COMPLETED'; await dataTrade.save({ fields: ['status'] }); await Models.data_sellers.create({ data_set_id: dataTrade.data_set_id, blockchain_id, ot_json_object_id: dataTrade.ot_json_object_id, seller_node_id: dataTrade.buyer_node_id, seller_erc_id: dataTrade.buyer_erc_id, price: dataTrade.price, }); this.logger.info(`Payment has been taken for purchase ${purchase_id}`); } catch (error) { if (error.message.includes('Complaint window has not yet expired!')) { if (command.retries !== 0) { return Command.retry(); } } this.logger.error(error.message); dataTrade.status = 'FAILED'; await dataTrade.save({ fields: ['status'] }); await this._handleError( purchase_id, `Couldn't execute takePayment command. Error: ${error.message}`, ); } } else { dataTrade.status = 'DISPUTED'; await dataTrade.save({ fields: ['status'] }); await this._handleError( purchase_id, `Couldn't execute takePayment command for purchase with purchaseId ${purchase_id}. Error: Data mismatch proven in dispute`, ); } return Command.empty(); } /** * Builds default DhPurchaseTakePaymentCommand * @param map * @returns {{add, data: *, delay: *, deadline: *}} */ default(map) { const command = { name: 'dhPurchaseTakePaymentCommand', delay: 5 * 60 * 1000, transactional: false, }; Object.assign(command, map); return command; } async _handleError( purchase_id, errorMessage, ) { this.logger.error(errorMessage); await Models.data_trades.update( { status: 'FAILED', }, { where: { purchase_id, status: { [Op.ne]: 'FAILED' }, }, }, ); } }
JavaScript
class WorkflowStepEditor extends React.Component { getStepEditor() { return this.props.stepEditor; } getStep() { return this.getStepEditor().step; } get canDelete() { return this.props.canDelete === undefined ? true : this.props.canDelete; } get canMove() { return this.props.canMove === undefined ? true : this.props.canMove; } handleDelete = step => { const onDelete = this.props.onDelete || _.noop; onDelete(step); }; handleSave = async () => { const onSave = this.props.onSave || _.noop; return onSave(); }; handleConfigSave = async configs => { const onSave = this.props.onSave || _.noop; const stepEditorModel = this.getStepEditor(); stepEditorModel.applyConfigs(configs); return onSave(); }; render() { const className = this.props.className; const stepEditor = this.getStepEditor(); const canDelete = this.canDelete; const canMove = this.canMove; return ( <WorkflowCommonStepEditorCard stepEditor={stepEditor} canDelete={canDelete} canMove={canMove} className={className} onDelete={this.handleDelete} > <> {this.renderDescription()} {this.renderConfiguration()} {this.renderProps()} </> </WorkflowCommonStepEditorCard> ); } renderDescription() { const editorModel = this.getStepEditor(); return <WorkflowCommonStepDescEditor stepEditor={editorModel} onSave={this.handleSave} className="mb4" />; } renderConfiguration() { const editorModel = this.getStepEditor(); return <WorkflowCommonStepConfigEditor stepEditor={editorModel} onSave={this.handleConfigSave} className="mb4" />; } renderProps() { const editorModel = this.getStepEditor(); return <WorkflowCommonStepPropsEditor stepEditor={editorModel} onSave={this.handleSave} className="mb2" />; } }
JavaScript
class DatepickerMobile extends Widget { /** * @type {string} */ static get selector() { return '.or-appearance-month-year input[type="date"]'; } /** * @param {Element} element - the element to instantiate the widget on * @return {boolean} to instantiate or not to instantiate, that is the question */ static condition(element) { // Do not instantiate if DatepickerExtended was instantiated on element or if non-mobile device is used. return ( !data.has(element, 'DatepickerExtended') && support.touch && support.inputTypes.month ); } _init() { this.element.classList.add('hide'); const fragment = document .createRange() .createContextualFragment( '<input class="ignore widget datepicker-mobile" type="month"/>' ); this.element.after(fragment); this.widgetInput = this.question.querySelector('input.widget'); // set default value this.value = this.originalInputValue; this.widgetInput.addEventListener('change', () => { this.originalInputValue = this.value; }); } /** * @type {string} */ get value() { return this.widgetInput.value ? `${this.widgetInput.value}-01` : ''; } set value(value) { const toSet = value ? value.substring(0, value.lastIndexOf('-')) : ''; this.widgetInput.value = toSet; } /** * Updates value */ update() { this.value = this.originalInputValue; } }
JavaScript
class CheckoutCartInterceptor { constructor(routingService, multiCartService) { this.routingService = routingService; this.multiCartService = multiCartService; } intercept(request, next) { return this.routingService.getRouterState().pipe(take(1), switchMap((state) => { return next.handle(request).pipe(catchError((response) => { var _a; if (response instanceof HttpErrorResponse && this.isUserInCheckoutRoute((_a = state.state) === null || _a === void 0 ? void 0 : _a.semanticRoute)) { if (this.isCartNotFoundError(response)) { this.routingService.go({ cxRoute: 'cart' }); const cartCode = this.getCartIdFromError(response); if (cartCode) { this.multiCartService.reloadCart(cartCode); } } } return throwError(response); })); })); } /** * Returns true if the parameter semantic route is part of "checkout" * Checkout semantic routes: * checkout * checkoutPaymentType * CheckoutShippingAddress * checkoutDeliveryMode * checkoutPaymentDetails * checkoutReviewOrder * checkoutLogin * @param semanticRoute */ isUserInCheckoutRoute(semanticRoute) { return semanticRoute === null || semanticRoute === void 0 ? void 0 : semanticRoute.toLowerCase().startsWith('checkout'); } /** * Checks of the error is for a cart not found, i.e. the cart doesn't exist anymore * * @param response */ isCartNotFoundError(response) { var _a, _b, _c, _d, _e, _f; return (response.status === 400 && ((_c = (_b = (_a = response.error) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.type) === 'CartError' && ((_f = (_e = (_d = response.error) === null || _d === void 0 ? void 0 : _d.errors) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.reason) === 'notFound'); } getCartIdFromError(response) { var _a, _b, _c; return (_c = (_b = (_a = response.error) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.subject; } }
JavaScript
class Search extends React.Component{ createMenuItem(item) { return ( { text: item.title, value: <MenuItem primaryText = {item.title} secondaryText = {new Date(item.release_date).toLocaleDateString()} /> } ) } render() { const style = { backgroundColor: `rgb(48, 48, 48)` } return ( <AppBar title={ <AutoComplete dataSource={ this.props.items.map(item => this.createMenuItem(item)) } onNewRequest={this.props.handleSelect} onUpdateInput={debounce(200, this.props.handleChange)} fullWidth={true} floatingLabelText={this.props.label} filter={AutoComplete.noFilter} /> } iconElementRight={this.props.menu} style={style} showMenuIconButton={false} /> ); } }
JavaScript
class EventHubFactory { /** * Constructor. * @param {Channel} channel Channel used to create event hubs. */ constructor(channel) { if (!channel) { const message = 'Channel not set'; logger.error('constructor:', message); throw new Error(message); } logger.debug('constructor:', channel.getName()); this.channel = channel; } /** * Gets event hubs for all specified peers. * @param {ChannelPeer[]} peers Peers for which event hubs should be obtained. * @returns {ChannelEventHub[]} Event hubs, which may or may not be connected. */ getEventHubs(peers) { return peers.map((peer) => this.channel.getChannelEventHub(peer.getName())); } }
JavaScript
class LevelController { /** * Show a list of all levels. * GET levels * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ //async index ({ request, response, view }) { // const levels = Level.all() // return levels //} async index (request, response) { return await Database .table('Levels') .where('curso_id', 1) //ALTERAR HARDCODED //.fetch() } // async index ({ request }) { // const { curso } = request.all() // // const levels = Level.query() // .nearBy(curso, 10) // .fetch() // // return properties // } async show ({ params }) { const level = await Level.findOrFail(params.id) await level.load('livro') await level.load('modalidade') return level } async destroy ({ params, auth, response }) { const level = await Level.findOrFail(params.id) await level.delete() } /** * Create/save a new level. * POST levels * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store ({ auth, request, response }) { const { id } = auth.user const data = request.only([ 'curso_id', 'livro_id', 'modalidade_id', 'proximo_nivel', 'equiv_1', 'equiv_2', 'equiv_3', 'equiv_4', 'ativo', 'descricao', 'ordem', 'gera_certificado', 'carga_horaria', 'iniciante', 'idade_inicial', 'idade_final', 'idade', 'falta_reprova', 'nota_reprova', 'font_color', 'background', 'frequencia_minima', 'peso_participacao', 'peso_aval_1', 'peso_aval_2', 'peso_aval_3', 'permite_recuperacao' ]) const level = await Level.create({ ...data }) return level } /** * Display a single level. * GET levels/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show ({ params, request, response, view }) { } /** * Update level details. * PUT or PATCH levels/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update ({ params, request, response }) { const level = await Level.findOrFail(params.id) const data = request.only([ 'curso_id', 'livro_id', 'modalidade_id', 'proximo_nivel', 'equiv_1', 'equiv_2', 'equiv_3', 'equiv_4', 'ativo', 'descricao', 'ordem', 'gera_certificado', 'carga_horaria', 'iniciante', 'idade_inicial', 'idade_final', 'idade', 'falta_reprova', 'nota_reprova', 'font_color', 'background', 'frequencia_minima', 'peso_participacao', 'peso_aval_1', 'peso_aval_2', 'peso_aval_3', 'permite_recuperacao' ]) level.merge(data) await level.save() return level } /** * Delete a level with id. * DELETE levels/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy ({ params, request, response }) { } }
JavaScript
class MipMapGenerator { constructor() { if (!isNode) { this.m_paddingCanvas = document.createElement("canvas"); this.m_paddingContext = this.m_paddingCanvas.getContext("2d"); this.m_resizeCanvas = document.createElement("canvas"); this.m_resizeContext = this.m_resizeCanvas.getContext("2d"); } } /** * Gets size of an image padded to the next bigger power-of-two size * @param width - Width of image * @param height - Height of image */ static getPaddedSize(width, height) { return { width: THREE.MathUtils.ceilPowerOfTwo(width), height: THREE.MathUtils.ceilPowerOfTwo(height) }; } /** * Generate downsampled mip map levels from an image. * If the input image is not power-of-two the image is padded to the * next bigger power-of-two size. * @param image - Input image * @returns A list of images with mip maps of the input image */ generateTextureAtlasMipMap(image) { if (isNode) { throw new Error("MipMapGenerator only works in browser."); } if (image.imageData === undefined) { throw new Error("Can not generate mip maps. Image data not loaded!"); } const imageData = image.imageData; const mipMaps = []; // Add initial texture with padding as level 0 const { width: paddedWidth, height: paddedHeight } = MipMapGenerator.getPaddedSize(imageData.width, imageData.height); this.copyImageWithPadding(imageData, paddedWidth, paddedHeight); mipMaps.push(this.m_paddingContext.getImageData(0, 0, paddedWidth, paddedHeight)); let width = paddedWidth * 0.5; let height = paddedHeight * 0.5; // HARP-10765 WebGL complains if we don't generate down to a 1x1 texture (this was the case // previously when height != width), and thus the final texture generated was 2x1 texture // and not 1x1. while (width >= 1 || height >= 1) { const mipMapLevel = mipMaps.length; const previousImage = mipMaps[mipMapLevel - 1]; // Resize previous mip map level mipMaps.push(this.resizeImage(previousImage, Math.max(width, 1), Math.max(height, 1))); width *= 0.5; height *= 0.5; } return mipMaps; } /** * Copy image to a canvas and add padding if necessary. * @param image - Input image. * @param width - Width of output image * @param height - Width of output image * @returns Canvas with image and padding. */ copyImageWithPadding(image, width, height) { this.m_paddingCanvas.width = width; this.m_paddingCanvas.height = height; this.m_paddingContext.clearRect(0, 0, width, height); if (image instanceof ImageBitmap) { this.m_paddingContext.drawImage(image, 0, 0); } else { this.m_paddingContext.putImageData(image, 0, 0); } // Add horizontal padding if (image.width !== width) { this.m_paddingContext.drawImage(this.m_paddingCanvas, image.width - 1, 0, 1, image.height, image.width, 0, width - image.width, image.height); } // Add vertical padding if (image.height !== height) { this.m_paddingContext.drawImage(this.m_paddingCanvas, 0, image.height - 1, width, 1, 0, image.height, width, height - image.height); } return this.m_paddingCanvas; } /** * Resize an image. * * Quality of resized image is best when * image.width and image.height are even numbers and the image * is resized by factor 0.5 or 2. * @param image - Input image * @param width - Width of output image * @param height - Height of output image * @return Resized image */ resizeImage(image, width, height) { // Copy image data to canvas because ImageData can't be resized directly const paddedImage = this.copyImageWithPadding(image, image.width, image.height); // Resize image to resize canvas this.m_resizeCanvas.width = width; this.m_resizeCanvas.height = height; this.m_resizeContext.clearRect(0, 0, width, height); this.m_resizeContext.drawImage(paddedImage, 0, 0, width, height); return this.m_resizeContext.getImageData(0, 0, width, height); } }
JavaScript
class Create extends Command { constructor() { super(); this.name = `create`; this.description = `Create a wallet for user.`; this.options = []; } async execute(Interaction) { let member; try { member = await Interaction.guild.members.fetch(Interaction.user.id); } catch (err) { console.log(err); } try { const um = new UserManager(); const userWallet = await um.getOrCreateWallet(member.user.username, Interaction.user.id); const walletUrl = `${process.env.LNBITS_HOST}/wallet?usr=${userWallet.user}`; const row = new Discord.MessageActionRow() .addComponents([ new Discord.MessageButton({ label: `Go to my wallet`, emoji: { name: `💰` }, style: `LINK`, url: `${walletUrl}`, }) ]); Interaction.reply({ content: `You have a wallet!`, ephemeral: true, components: [row] }); } catch(err) { console.log(err); } } }
JavaScript
class BioPathwaysPanel extends PolymerElement { static get properties() { return { databases: { type: Map, value: function() { return new Map([ ["kegg", "KEGG"], ["biocarta", "BioCarta"], ["netpath", "NetPath"], ["reactome", "Reactome"], ["pid", "PID"], ["humancyc", "HumanCyc"], ["wikipathways", "WikiPathways"] ]); } }, databaseUrlMap: { type: Map, value: function() { return new Map([ ["kegg", "KEGG"], ["biocarta", "BioCarta"], ["netpath", "NetPath"], ["reactome", "Reactome"], ["pid", "PID"], ["wikipathways", "WikiPathways"] ]); } }, /** An array of database names. */ databaseNames: { type: Array, computed: "__computeDatabaseNames(databases)" }, model: { type: Object, value: null } }; } static get template() { return html` <style> :host { display: block; } fieldset { border-radius: 5px; border-color: var(--app-header-color); color: var(--app-header-color); @apply --layout-horizontal; @apply --layout-wrap; } bio-pathway-card { margin-top: 5px; width: 100%; } </style> <fieldset> <legend>Pathways</legend> <template is="dom-repeat" items="[[databaseNames]]"> <template is="dom-if" if="{{__val(model, item)}}"> <bio-pathway-card type="[[item]]" databases="[[databases]]" model="{{__val(model, item)}}" ></bio-pathway-card> </template> </template> </fieldset> `; } /** * Instance of the element is created/upgraded. Use: initializing state, * set up event listeners, create shadow dom. * @constructor */ constructor() { super(); } /** * Use for one-time configuration of your component after local * DOM is initialized. */ ready() { super.ready(); } /** * This method gets a user-friendly database name. * @param {Map<String, String>} databases the map of database abbreviations and names * @return {String} a user-friendly database name */ __computeDatabaseNames(databases) { let names = []; for (let name of databases.keys()) { names.push(name); } return names; } __val(model, item) { let val = this.get(`model.${item}`); return val; } }
JavaScript
class Engine { constructor(options) { this.options = merge({}, defaults, options); this.myXVFB = new XVFB(this.options); this.myExtensionServer = new ExtensionServer(this.options); this.options.viewPort = engineUtils.calculateViewport(this.options); this.engineDelegate = engineDelegate.createDelegate(this.options); } /** * Start the engine. Will prepare everything before you will start your run: * * Start XVFB (if it is configured) * * Set connectivity * * Start the extension server */ start() { return Promise.all([ this.myXVFB.start(), connectivity.set(this.options), this.myExtensionServer.start() ]); } /** * Run the engine and test a URL and collect metrics with the scripts. * @param {string} url - the URL that will be tested * @param {*} scriptsByCategory - hmm promises, I think we should change this * @param {*} asyncScriptsByCategory - hmm promises, I think we should change this */ run(url, scriptsByCategory, asyncScriptsByCategory) { const options = this.options; const storageManager = new StorageManager(url, options); const iterations = new Array(options.iterations); const engineDelegate = this.engineDelegate; const statistics = new Statistics(); const collector = new Collector(statistics, storageManager, options); const iteration = new Iteration( url, storageManager, this.myExtensionServer, engineDelegate, scriptsByCategory, asyncScriptsByCategory, options ); // Put all the result from the iterations here const result = { info: { browsertime: { version }, url, timestamp: engineUtils.timestamp(), connectivity: { engine: get(this.options, 'connectivity.engine'), profile: get(this.options, 'connectivity.profile') } }, timestamps: [], browserScripts: [], visualMetrics: [], cpu: [] }; return storageManager .createDataDir() .then(baseDir => (options.baseDir = baseDir)) .then(() => engineDelegate.onStartRun(url, options)) .then(() => Promise.reduce( iterations, (totalResult, item, index, totalIterations) => { let promise = iteration .run(index) .then(data => collector .perIteration(data, totalResult, index) .then(() => totalResult) ); if (shouldDelay(index, totalIterations, options.delay)) { promise = promise.delay(options.delay); } return promise; }, result ) ) .then(() => engineDelegate.onStopRun(result)) .then(() => { // add the options metrics we want result.statistics = statistics.summarizeDeep(options); }) .then(() => { // Add extra fields to the HAR // to make the HAR files better when we use them in // compare.sitespeed.io if (result.har) { const numPages = result.har.log.pages.length; if (numPages !== options.iterations) { log.error( `Number of HAR pages (${numPages}) does not match number of iterations (${ options.iterations })` ); return; } for (let index = 0; index < numPages; index++) { const page = result.har.log.pages[index]; const visualMetric = result.visualMetrics[index]; const browserScript = result.browserScripts[index] || {}; const cpu = result.cpu[index] || {}; harUtil.addExtrasToHAR( page, visualMetric, browserScript.timings, cpu, options ); } } }) .then(() => { log.info(util.getResultLogLine(result)); return result; }) .catch(Promise.TimeoutError, e => { throw new UrlLoadError( 'Failed to load ' + url + ', cause: ' + e.message, url, { cause: e } ); }); } /** * Stop the engine. Will stop everything started in start(). * * Stop XVFB (if it is configured) * * Remove connectivity * * Stop the extension server */ stop() { return Promise.all([ this.myXVFB.stop(), connectivity.remove(this.options), this.myExtensionServer.stop() ]); } }
JavaScript
class LineGraph extends Object3DFacade { constructor(parent) { super(parent, new Group()); // Use a single Line2D buffer geometry for both stroke and fill meshes let geometry = new Line2DGeometry(); // Stroke mesh with custom shader material this.strokeMesh = new Mesh( geometry, new ShaderMaterial({ uniforms: { thickness: { value: 1 }, color: { value: new Color() }, opacity: { value: 1 } }, transparent: true, vertexShader: strokeVertexShader, fragmentShader: strokeFragmentShader, //depthTest: false, side: DoubleSide }) ); // Fill mesh with custom shader material this.fillMesh = new Mesh( geometry, new ShaderMaterial({ uniforms: { color: { value: new Color() }, opacity: { value: 1 }, gradientScale: { value: 1 }, gradientPercent: { value: 1 }, gradientExp: { value: 1 }, maxY: { value: 1 } }, transparent: true, vertexShader: fillVertexShader, fragmentShader: fillFragmentShader, //depthTest: false, side: DoubleSide }) ); this.strokeMesh.frustumCulled = this.fillMesh.frustumCulled = false; // Add both meshes to the Group this.threeObject.add(this.strokeMesh, this.fillMesh); } afterUpdate() { // Update the shared geometry let geometry = this.strokeMesh.geometry; geometry.update( this.pathShape === "step" ? valuesToSquarePoints(this.values, this.width, this.height) : valuesToCurvePoints(this.values, this.width, this.height) ); // Update the stroke mesh let hasStroke = this.strokeWidth && this.strokeColor && this.strokeOpacity > 0; if (hasStroke) { let strokeUniforms = this.strokeMesh.material.uniforms; strokeUniforms.color.value.set(this.strokeColor); strokeUniforms.opacity.value = this.strokeOpacity; strokeUniforms.thickness.value = this.strokeWidth; } this.strokeMesh.visible = !!hasStroke; // Update the fill mesh let hasFill = this.fillColor && this.fillOpacity > 0; if (hasFill) { let fillUniforms = this.fillMesh.material.uniforms; fillUniforms.color.value.set(this.fillColor); fillUniforms.opacity.value = this.fillOpacity; fillUniforms.gradientScale.value = this.fillGradientScale === "max-value" ? 1 : 0; fillUniforms.maxY.value = this.height; fillUniforms.gradientPercent.value = this.fillGradientPercent || 0; fillUniforms.gradientExp.value = this.fillGradientExp || 1; } this.fillMesh.visible = !!hasFill; this.fillMesh.renderOrder = this.strokeMesh.renderOrder = this.renderOrder || 0; super.afterUpdate(); } }
JavaScript
class WeatherForecastCtrl { constructor() { this.menus = [ { name: 'current', state: 'current' }, { name: 'forecast', state: 'forecast' } ] } }
JavaScript
class UnresolvedPinObservableError extends Error { constructor() { super('Unresolved pin observable.'); } }
JavaScript
class Cliente{ nome; cpf; agencia; saldo; }
JavaScript
class FilterTable extends Component { static signalMessage = ""; static signal = 0; static firstMACD = 0; static secondMACD = 0; static upperBand = 0; static middleBand = 0; static lowerBand = 0; static SMA = 0; static RSI = 0; static Volume = 0; constructor(props) { super(props); this.date = new Date(); // ************************************************** // Static Variables // ************************************************** let style = { color: "white;" }; this.timeout = null; this.map = new HashMap(); this.data = new HashMap(); // ************************************************** // History Calc Table // ************************************************** this.HistoryCalcMap = new HashMap(); this.HistoryCalcBool = []; // Settings this.applyChanges = this.applyChanges.bind(this); this.setPerformanceStocksSettings = this.setPerformanceStocksSettings.bind(this); this.setMacdStocksSettings = this.setMacdStocksSettings.bind(this); this.setBollingerBandSettings = this.setBollingerBandSettings.bind(this); this.updateHistoryCalc = this.updateHistoryCalc.bind(this); // Update Hash Map this.initialiseHashMap = this.initialiseHashMap.bind(this); this.updateSettingsHashMap = this.updateSettingsHashMap.bind(this); // Update Table this.updateFilterTable = this.updateFilterTable.bind(this); this.addToFilterTable = this.addToFilterTable.bind(this); this.setUpdateFilterCache = this.setUpdateFilterCache.bind(this); this.setMaxNumberOfPortfolioRows = this.setMaxNumberOfPortfolioRows.bind(this); this.setFilterCache = this.setFilterCache.bind(this); this.updateFilterCache = this.updateFilterCache.bind(this); this.updateVariables = this.updateVariables.bind(this); this.filterCache = new cache(); // Set in database this.idHashMap = new HashMap(); this.settings = new HashMap(); this.called = false; // ************************************************** this.state = { // ************************************************** // History calc states // ************************************************** // Check Box performanceStocksSettings: [], macdStocksSettings: [], bollingerBandSettings: [], updateHistoryCalc: false, filterTableStack: [], filterTable: [], // ************************************************** green: false, red: false, priceChangeUp: false, validInput: false, display: [], stockRecordID: 0, scroll: 0, query: {}, start: 0, tb2: [], tb2_temp: [], tb2_scrollPosition: 0, tb2_updateTable: false, tb2_stack: [], // Render 100 elements per scroll tb2_cache: [], tb2_count: 0, tb2_numberOfClicks: [], // Alert Table States alertTableStack: [], portfolioTable: [], isScrolled: false, scrollUp_: 0, scrollDown_: 0, componentSize: 'default', // ************************************************** // Form // ************************************************** addStockFormVisible: "visible", editStockFormVisible: "hidden", closeForm: true, stockFormID: null, selectedRecordValue: "", clearRecord: false, date: "", shares: 0, price: 0, target: 0, portfolioTableRowBool: true, // ************************************************** // Portfolio Table Variables // ************************************************** highlightTableRow: false, addToHistoricalTableBool: false, updatePortfolioTableData: false, editPortfolioTable: false, removePortfolioTableRowBool: false, portfolioTableStocks: [], portfolioTableStack: [], clickedPortfolioTableRowID: 0, maxNumberOfPortfolioTableRows: 0, maxNumberOfPortfolioRows: 0, updateFilterTable: false, updateFilterCache: false, called: false, name: [], newName: [] }; } onFormLayoutChange = ({ size }) => { this.setState({ componentSize: size }) }; componentDidMount() { this.interval = setInterval(() => { if (this.props.state.updateCache) { this.setState({ called: true }) clearInterval(this.interval); } }, 1000); /* window.onload(() => { this.updateData = setInterval(() => { if (this.date.getHours() + 8 >= 9) { clearInterval(this.interval); } }, 60000); }*/ } componentDidUpdate(prevProps, prevState, snapshot) { if (this.state.updateFilterCache) { this.setFilterCache(); this.setState({ updateFilterCache: false }); } if (this.state.updateFilterTable || prevState.updateFilterTable) { this.addToFilterTable(); this.updateFilterTable(); this.setState({ updateFilterTable: false }); } } shouldComponentUpdate(nextProps, nextState) { if (!nextProps.state.updateCache) { return false; } else { if ( this.state.updateFilterCache !== nextState.updateFilterCache || this.state.updateFilterTable !== nextState.updateFilterTable || this.state.updateHistoryCalc !== nextState.updateHistoryCalc || this.state.highlightTableRow !== nextState.highlightTableRow || this.state.editPortfolioTable !== nextState.editPortfolioTable || this.state.closeForm !== nextState.closeForm || this.state.addToHistoricalTableBool !== nextProps.addToHistoricalTableBool || this.state.updatePortfolioTableData !== nextState.updatePortfolioTableData || this.state.validInput || this.state.queryRes || nextState.selectedRecordValue !== this.state.selectedRecordValue) { return true; } } return false; } // ************************************************** // Initalise Cache // ************************************************** // Initialised when the page is loaded initialiseHashMap( tableID) { // Update Data this.updateVariables(tableID); // User settings (to be added) /* this.settings.set( tableID, { bollingerBandsNo: bollingerBandsNo, deviations: deviations, firstMovingAverageDays: firstMovingAverageDays, secondMovingAverageDays: secondMovingAverageDays, smoothing: smoothing, rsiWeight: rsiWeight , Volume: Volume } );*/ } // ************************************************** // ************************************************** // Update Filter Cache // ************************************************** setMaxNumberOfPortfolioRows(length, name) { this.setState({ maxNumberOfPortfolioRows: length }); this.setState({ name: name }); } setUpdateFilterCache(update) { this.setState({ updateFilterCache: update }); } // Called Once setFilterCache() { let count; for (count = 0; count < this.state.maxNumberOfPortfolioRows; count++) { this.initialiseHashMap(count); } console.log(' count ' + this.state.maxNumberOfPortfolioRows) this.setState({ updateFilterTable: true }); } // Utility for setting cache updateFilterCache(tableID, json) { this.filterCache.set( tableID.toString(), { signalMessage: json.signalMessage, signal: json.signal, firstMACD: json.firstMACD, secondMACD: json.secondMACD, upperBand: json.upperBand, middleBand: json.middleBand, lowerBand: json.lowerBand, SMA: json.SMA, RSI: json.RSI, Volume: json.Volume } ); } // Update variables and set updateVariables(tableID) { HistoryCalc.setID(tableID); // Set variables const json = HistoryCalc.getJSON(); this.updateFilterCache(tableID, json); } // Set at the very beggining updateSettingsHashMap( tableID, bollingerBandsNo, deviations, firstMovingAverageDays, secondMovingAverageDays, smoothing, rsiWeight, Volume) { this.props.updateSettingsHashMap(tableID, bollingerBandsNo, deviations, firstMovingAverageDays, secondMovingAverageDays, smoothing, rsiWeight, Volume); } // ************************************************** // ************************************************** // History Calc // ************************************************** // Checked Options //................................................... setPerformanceStocksSettings(checked) { this.setState({ performanceStocksSettings: checked }); } setMacdStocksSettings(checked) { this.setState({ macdStocksSettings: checked }); } setBollingerBandSettings(checked) { this.setState({ bollingerBandSettings: checked }); } //.................................................... applyChanges() { this.setState({ updateHistoryCalc: true }); } updateHistoryCalc() { // Initialise History Calculations const id = this.state.stockRecordID; /* Index | Bool array[0] = bollingerBandsNo array[1] = deviations array[2] = firstMovingAverageDays array[3] = secondMovingAverageDays array[4] = smoothing array[5] = rsiWeight array[6] = volume */ // Checked options const performanceStocksSettings = this.state.performanceStocksSettings; for (let index = 0; index < performanceStocksSettings.length; index++) { const element = performanceStocksSettings[index]; switch (element) { case 'High Momentum': break; case 'Low Momentum': break; case 'Growth Stocks': break; case 'Shorted Stocks': break; } } // Checked options const macdStocksSettings = this.state.macdStocksSettings; for (let index = 0; index < macdStocksSettings.length; index++) { const element = macdStocksSettings[index]; switch (element) { case 'Golden Cross': break; case 'MACD': break; } } // Checked options const bollingerBandSettings = this.state.bollingerBandSettings; for (let index = 0; index < bollingerBandSettings.length; index++) { const element = bollingerBandSettings[index]; switch (element) { case 'UpperBand': break; case 'MiddleBand': break; case 'LowerBand': break; } } // Set regardless of settings this.initialiseHashMap(id, 2, 2, 25, 199, 0.2, 1, 250000); // Save to database } // Fill the whole table (called on component did mount) addToFilterTable() { var t = []; let pointer; let start = 0; const end = this.state.maxNumberOfPortfolioRows; const name = this.state.name; for (pointer = start; pointer < end; pointer++) { const item = this.filterCache.get(pointer.toString()); t.push( <tbody key={pointer}> <tr> <td id={pointer}>{name[pointer]}</td> <td id={pointer}>{item.signalMessage}</td> <td id={pointer}>{item.signal}</td> <td id={pointer}>{item.firstMACD}</td> <td id={pointer}>{item.secondMACD}</td> <td id={pointer}>{item.upperBand}</td> <td id={pointer}>{item.middleBand}</td> <td id={pointer}>{item.lowerBand}</td> <td id={pointer}>{item.SMA}</td> <td id={pointer}>{item.RSI}</td> <td id={pointer}>{item.Volume}</td> </tr> </tbody> ); } this.setState({ filterTableStack: t }); this.setState({ updateFilterTable: true }); } // Update the historical table updateFilterTable() { let t = <div class="filter"> <div> <table class="filterTable" aria-labelledby="tabelLabel"> <thead></thead> {this.state.filterTableStack} </table> </div> </div>; this.setState({ filterTable: t }); this.setState({ updateFilterTable: true }); this.forceUpdate(); } // ************************************************** render() { let filterTableHeader = <table class="filterTableHeader" aria-labelledby="tabelLabel" style={{ zIndex: '999', position: 'absolute', left: '675px' }}> <thead> <tr> <th>Stock <br /> Code</th> <th>Signal <br /> Message </th> <th>First <br /> MACD</th> <th>Second <br /> MACD</th> <th>Upper <br /> Band</th> <th>Middle <br /> Band</th> <th>Lower <br />Band</th> <th>SMA </th> <th>RSI</th> <th>Volume</th> </tr> </thead> </table> return ( <div> <div class="wrap" style={{ width: '48rem' }}> <div class="cell-wrap left"> <div class="filter"> {/* PORTFOLIO TABLE */} <Box style={{ position: 'absolute', top: '125px', left: '80px' }} // bg='rgb(30,30,30)' boxShadow='sm' textAlign='center' height='45px' width='48rem' rounded="lg" margin='auto' color='white' zIndex='999' > {filterTableHeader} <Box style={{ position: 'absolute', overflowY: 'auto', top: '45px' }} overflowX='hidden' boxShadow='sm' textAlign='center' height='1110px' width='48rem' rounded="lg" margin='auto' color='white' zIndex='999' > </Box> {this.state.filterTable} </Box> </div> </div> </div> <HistoricalTable {...this} /> </div> ); } }
JavaScript
class ExportMapping extends mappings_1.mappings.MappingDocument { constructor(model, structureTypeName, id, isPartial, container) { super(model, structureTypeName, id, isPartial, container); /** @internal */ this.__parameterName = new internal.PrimitiveProperty(ExportMapping, this, "parameterName", "", internal.PrimitiveTypeEnum.String); /** @internal */ this.__parameterTypeName = new internal.PrimitiveProperty(ExportMapping, this, "parameterTypeName", "", internal.PrimitiveTypeEnum.String); /** @internal */ this.__isHeader = new internal.PrimitiveProperty(ExportMapping, this, "isHeader", false, internal.PrimitiveTypeEnum.Boolean); /** @internal */ this.__nullValueOption = new internal.EnumProperty(ExportMapping, this, "nullValueOption", microflows_1.microflows.NullValueOption.LeaveOutElement, microflows_1.microflows.NullValueOption); this._containmentName = "documents"; } get containerAsFolderBase() { return super.getContainerAs(projects_1.projects.FolderBase); } get parameterName() { return this.__parameterName.get(); } set parameterName(newValue) { this.__parameterName.set(newValue); } /** * In version 6.1.0: deleted */ get parameterTypeName() { return this.__parameterTypeName.get(); } set parameterTypeName(newValue) { this.__parameterTypeName.set(newValue); } get isHeader() { return this.__isHeader.get(); } set isHeader(newValue) { this.__isHeader.set(newValue); } /** * In version 6.7.0: introduced */ get nullValueOption() { return this.__nullValueOption.get(); } set nullValueOption(newValue) { this.__nullValueOption.set(newValue); } /** * Creates a new ExportMapping unit in the SDK and on the server. * Expects one argument, the projects.IFolderBase in which this unit is contained. */ static createIn(container) { return internal.instancehelpers.createUnit(container, ExportMapping); } /** @internal */ _isByNameReferrable() { return true; } /** @internal */ _initializeDefaultProperties() { super._initializeDefaultProperties(); if (this.__nullValueOption.isAvailable) { this.nullValueOption = microflows_1.microflows.NullValueOption.LeaveOutElement; } } }
JavaScript
class ExportObjectMappingElement extends mappings_1.mappings.ObjectMappingElement { constructor(model, structureTypeName, id, isPartial, unit, container) { super(model, structureTypeName, id, isPartial, unit, container); if (arguments.length < 4) { throw new Error("new ExportObjectMappingElement() cannot be invoked directly, please use 'model.exportmappings.createExportObjectMappingElement()'"); } } get containerAsMappingDocument() { return super.getContainerAs(mappings_1.mappings.MappingDocument); } get containerAsObjectMappingElement() { return super.getContainerAs(mappings_1.mappings.ObjectMappingElement); } /** * Creates and returns a new ExportObjectMappingElement instance in the SDK and on the server. * The new ExportObjectMappingElement will be automatically stored in the 'rootMappingElements' property * of the parent mappings.MappingDocument element passed as argument. */ static createInMappingDocumentUnderRootMappingElements(container) { return internal.instancehelpers.createElement(container, ExportObjectMappingElement, "rootMappingElements", true); } /** * Creates and returns a new ExportObjectMappingElement instance in the SDK and on the server. * The new ExportObjectMappingElement will be automatically stored in the 'children' property * of the parent mappings.ObjectMappingElement element passed as argument. */ static createInObjectMappingElementUnderChildren(container) { return internal.instancehelpers.createElement(container, ExportObjectMappingElement, "children", true); } /** * Creates and returns a new ExportObjectMappingElement instance in the SDK and on the server. * Expects one argument: the IModel object the instance will "live on". * After creation, assign or add this instance to a property that accepts this kind of objects. */ static create(model) { return internal.instancehelpers.createElement(model, ExportObjectMappingElement); } /** @internal */ _initializeDefaultProperties() { super._initializeDefaultProperties(); } }
JavaScript
class ExportValueMappingElement extends mappings_1.mappings.ValueMappingElement { constructor(model, structureTypeName, id, isPartial, unit, container) { super(model, structureTypeName, id, isPartial, unit, container); if (arguments.length < 4) { throw new Error("new ExportValueMappingElement() cannot be invoked directly, please use 'model.exportmappings.createExportValueMappingElement()'"); } } get containerAsObjectMappingElement() { return super.getContainerAs(mappings_1.mappings.ObjectMappingElement); } /** * Creates and returns a new ExportValueMappingElement instance in the SDK and on the server. * The new ExportValueMappingElement will be automatically stored in the 'children' property * of the parent mappings.ObjectMappingElement element passed as argument. */ static createIn(container) { return internal.instancehelpers.createElement(container, ExportValueMappingElement, "children", true); } /** * Creates and returns a new ExportValueMappingElement instance in the SDK and on the server. * Expects one argument: the IModel object the instance will "live on". * After creation, assign or add this instance to a property that accepts this kind of objects. */ static create(model) { return internal.instancehelpers.createElement(model, ExportValueMappingElement); } /** @internal */ _initializeDefaultProperties() { super._initializeDefaultProperties(); } }
JavaScript
class PDFObjectJS extends PluginBinder { constructor(rx, settings) { super(rx, settings) settings = settings || {}; } bind(container) { var pb = this; $('.pdfobject', container).each(function() { PDFObject.embed($(this).attr('data-pdf-url'), $(this)); }); } }
JavaScript
class TypeHandlerNumberDouble { fromRdf(literal, validate) { const parsed = parseFloat(literal.value); if (validate) { if (isNaN(parsed)) { Translator_1.Translator.incorrectRdfDataType(literal); } // TODO: validate more } return parsed; } toRdf(value, { datatype, dataFactory }) { datatype = datatype || dataFactory.namedNode(TypeHandlerNumberDouble.TYPES[0]); if (isNaN(value)) { return dataFactory.literal('NaN', datatype); } if (!isFinite(value)) { return dataFactory.literal(value > 0 ? 'INF' : '-INF', datatype); } if (value % 1 === 0) { return null; } return dataFactory.literal(value.toExponential(15).replace(/(\d)0*e\+?/, '$1E'), datatype); } }
JavaScript
class TagDiffVisualization extends Component { state = { showChangeset: false, // XML-changeset view instead of tag-list view editing: false, // edit mode (table/list view only) tagEdits: null, // user-made edits to tags addingTag: false, // user is adding a new tag newTagName: null, // name of new tag being added newTagValid: false, // whether new tag name can be added } componentDidMount() { if (this.props.editMode) { this.beginEditing() } } /** * Switch to changeset/XML view of tag changes */ switchToChangeset() { if (!this.props.xmlChangeset && !this.props.loadingChangeset && this.props.loadXMLChangeset) { this.props.loadXMLChangeset() } this.setState({showChangeset: true}) } /** * Switch to table/list view of tag changes */ switchToTable() { this.setState({showChangeset: false}) } /** * Switch to edit mode (table/list view only) */ beginEditing() { this.setState({ showChangeset: false, editing: true, tagEdits: _cloneDeep(this.props.tagDiff) || {} }) } updateTagValue(tagName, updatedValue) { const tagEdits = this.state.tagEdits tagEdits[tagName].newValue = updatedValue // type-agnostic comparison // eslint-disable-next-line if (updatedValue == tagEdits[tagName].value) { tagEdits[tagName].status = 'unchanged' } else if (tagEdits[tagName].status === 'unchanged') { tagEdits[tagName].status = 'changed' } this.setState({tagEdits}) } keepTag(tagName) { const tagEdits = this.state.tagEdits if (tagEdits[tagName].status === 'removed') { tagEdits[tagName].newValue = tagEdits[tagName].value tagEdits[tagName].status = 'unchanged' } this.setState({tagEdits}) } deleteTag(tagName) { const tagEdits = this.state.tagEdits if (tagEdits[tagName].status === 'added') { delete tagEdits[tagName] } else { tagEdits[tagName].status = 'removed' tagEdits[tagName].newValue = null } this.setState({tagEdits}) } beginAddingTag() { this.setState({addingTag: true, newTagName: '', newTagValid: false}) } setNewTagName(name) { const isValid = !_isEmpty(name) && !this.state.tagEdits[name] this.setState({newTagName: name, newTagValid: isValid}) } addNewTag() { if (!this.state.newTagValid) { return } const tagEdits = this.state.tagEdits tagEdits[this.state.newTagName] = { name: this.state.newTagName, value: null, newValue: '', status: 'added', } this.setState({tagEdits, addingTag: false, newTagName: null, newTagValid: false}) } cancelNewTag() { this.setState({addingTag: false, newTagName: null, newTagValid: false}) } saveEdits() { this.props.setTagEdits(this.state.tagEdits) this.setState({showChangeset: false, editing: false, tagEdits: null}) } cancelEdits() { this.setState({showChangeset: false, editing: false, tagEdits: null}) } restoreOriginalFix() { this.props.revertTagEdits() this.setState({showChangeset: false, editing: false, tagEdits: null}) } render() { if (this.props.loadingOSMData || this.props.loadingChangeset) { return ( <div className="mr-bg-blue-dark mr-p-4 mr-rounded-sm mr-flex mr-justify-center mr-items-center"> <BusySpinner /> </div> ) } let tagChanges = _values(this.state.editing ? this.state.tagEdits : this.props.tagDiff) if (this.props.onlyChanges && !this.state.editing) { tagChanges = justChanges(tagChanges) } const toolbar = this.props.suppressToolbar ? null : ( <div className="mr-flex mr-mb-1 mr-px-4"> <div className="mr-text-base mr-text-yellow mr-mr-4"> {this.props.onlyChanges ? <FormattedMessage {...messages.justChangesHeader} /> : <FormattedMessage {...messages.allTagsHeader} /> } </div> <div className="mr-flex mr-justify-end"> {this.state.editing && <button className="mr-button mr-button--xsmall mr-button--danger" onClick={() => this.restoreOriginalFix()} title={this.props.intl.formatMessage(messages.restoreFixTooltip)} > <FormattedMessage {...messages.restoreFixLabel} /> </button> } {!this.props.compact && !this.state.editing && <React.Fragment> <button className={classNames( "mr-mr-4", this.state.showChangeset ? "mr-text-green-light" : "mr-text-green-lighter" )} onClick={() => this.switchToTable()} title={this.props.intl.formatMessage(messages.tagListTooltip)} > <SvgSymbol sym="list-icon" viewBox="0 0 20 20" className="mr-transition mr-fill-current mr-w-4 mr-h-4" /> </button> <button className={classNames( "mr-mr-4", this.state.showChangeset ? "mr-text-green-lighter" : "mr-text-green-light" )} onClick={() => this.switchToChangeset()} title={this.props.intl.formatMessage(messages.changesetTooltip)} > <span className="mr-transition">&lt;/&gt;</span> </button> <button className="mr-mr-4 mr-text-green-light" onClick={() => this.beginEditing()} title={this.props.intl.formatMessage(messages.editTagsTooltip)} > <SvgSymbol sym="edit-icon" viewBox="0 0 20 20" className="mr-transition mr-fill-current mr-w-4 mr-h-4" /> </button> </React.Fragment> } {this.props.compact && <button className="mr-text-green-light" onClick={this.props.showDiffModal}> <SvgSymbol sym="expand-icon" viewBox="0 0 32 32" className="mr-transition mr-fill-current mr-w-4 mr-h-4" /> </button> } </div> </div> ) if (this.props.onlyChanges && (this.props.hasTagChanges === false || tagChanges.length === 0)) { return ( <div className="mr-bg-blue-dark mr-p-4 mr-rounded-sm mr-flex-columns"> {toolbar} <div className="mr-px-4 mr-mt-4"> <FormattedMessage {...messages.noChanges} /> </div> </div> ) } if (this.state.showChangeset && this.props.xmlChangeset) { if (this.props.hasTagChanges === false || tagChanges.length === 0) { return ( <div className="mr-bg-blue-dark mr-p-4 mr-rounded-sm mr-flex-columns"> {toolbar} <div className="mr-px-4 mr-mt-4"> <FormattedMessage {...messages.noChangeset} /> </div> </div> ) } return ( <div className="mr-bg-blue-dark mr-py-2 mr-rounded-sm"> {toolbar} <div className="mr-px-4"> <SyntaxHighlighter language="xml" style={highlightColors} customStyle={{background: 'transparent'}} > {vkbeautify.xml(this.props.xmlChangeset)} </SyntaxHighlighter> </div> </div> ) } const tagNames = tagChanges.map(change => ( <li className='mr-border-2 mr-border-transparent mr-my-2 mr-py-3 mr-flex mr-h-6 mr-items-center' key={`${change.name}_name`} > {changeSymbol(change)} <div className="mr-flex-shrink-1 mr-overflow-x-hidden mr-truncate" title={change.name} > {change.name} </div> </li> )) tagNames.unshift( <li key='name_header' className='mr-font-bold mr-pb-1 mr-h-6'>&nbsp;</li> ) const tagValues = (tagChanges.map(change => ( <li className={classNames('mr-border-2 mr-rounded-sm mr-my-2 mr-py-3 mr-h-6 mr-flex mr-items-center', { 'mr-border-orange mr-bg-black-15': change.status === 'changed', 'mr-border-lavender-rose mr-bg-black-15': change.status === 'removed', 'mr-border-transparent': (change.status !== 'changed' && change.status !== 'removed'), })} key={`${change.name}_value`} > <div className="mr-px-2 mr-overflow-x-hidden mr-truncate mr-text-base" title={change.value} > {change.value} </div> </li> ))) tagValues.unshift( <li key='value_header' className='mr-text-base mr-font-bold mr-pb-1 mr-pl-2 mr-h-6'> <FormattedMessage {...messages.currentLabel} /> </li> ) const newValues = (tagChanges.map(change => ( <li className={classNames( 'mr-border-2 mr-rounded-sm mr-my-2 mr-py-3 mr-h-6 mr-flex mr-items-center', this.state.editing ? 'mr-border-transparent' : { 'mr-border-picton-blue mr-bg-black-15': change.status === 'added', 'mr-border-orange mr-bg-black-15': change.status === 'changed', 'mr-border-transparent': (change.status !== 'added' && change.status !== 'changed'), } )} key={`${change.name}_newvalue`} > {this.state.editing && <React.Fragment> {change.status === 'removed' ? <button className="mr-button mr-button--xsmall" onClick={() => this.keepTag(change.name)} > <FormattedMessage {...messages.keepTagLabel} /> </button> : <React.Fragment> <input type="text" className="mr-text-black mr-px-2" value={change.newValue} onChange={e => this.updateTagValue(change.name, e.target.value)} /> <button className="mr-ml-2 mr-text-red" onClick={() => this.deleteTag(change.name)} title={this.props.intl.formatMessage(messages.deleteTagTooltip)} > <SvgSymbol sym="trash-icon" viewBox="0 0 20 20" className="mr-transition mr-fill-current mr-w-4 mr-h-4" /> </button> </React.Fragment> } </React.Fragment> } {!this.state.editing && <div className="mr-px-2 mr-overflow-x-hidden mr-truncate mr-text-base" title={change.newValue} > {change.newValue} </div> } </li> ))) newValues.unshift( <li key='newvalue_header' className='mr-text-base mr-font-bold mr-pb-1 mr-pl-2 mr-flex mr-h-6'> <FormattedMessage {...messages.proposedLabel} /> </li> ) return ( <div> {toolbar} <div className="mr-flex mr-justify-between"> <ul className="mr-w-1/3 mr-px-4 mr-border-r-2 mr-border-white-10"> {tagNames} {this.state.editing && <AddTagControl addingTag={this.state.addingTag} beginAddingTag={() => this.beginAddingTag()} newTagName={this.state.newTagName} newTagValid={this.state.newTagValid} setNewTagName={name => this.setNewTagName(name)} addNewTag={() => this.addNewTag()} cancelNewTag={() => this.cancelNewTag()} intl={this.props.intl} /> } </ul> <ul className="mr-w-1/3 mr-px-4 mr-border-r-2 mr-border-white-10">{tagValues}</ul> <ul className="mr-w-1/3 mr-px-4">{newValues}</ul> </div> {this.state.editing && <div className="mr-flex mr-justify-end"> <button className="mr-button mr-mr-4" onClick={() => this.saveEdits()}> <FormattedMessage {...messages.saveLabel} /> </button> <button className="mr-button mr-button--white" onClick={() => this.cancelEdits()} > <FormattedMessage {...messages.cancelLabel} /> </button> </div> } </div> ) } }
JavaScript
class ReuseLoader { constructor(viewer, reuseLowerThreshold, bimServerApi, fieldsToInclude, roids, quantizationMap, geometryCache, geometryDataToReuse) { debugger; this.settings = viewer.settings; this.viewer = viewer; this.reuseLowerThreshold = reuseLowerThreshold; this.bimServerApi = bimServerApi; this.fieldsToInclude = fieldsToInclude; this.roids = roids; this.quantizationMap = quantizationMap; this.geometryCache = geometryCache; this.geometryDataToReuse = geometryDataToReuse; this.nrReused = 0; this.bytesReused = 0; this.loaderCounter = 0; } /* * Load an array of geometry data ids */ load(geometryDataIds) { if (geometryDataIds.length == 0) { return; } var start = performance.now(); var query = { oids: geometryDataIds, include: { type: "GeometryData", fieldsDirect: this.fieldsToInclude }, loaderSettings: JSON.parse(JSON.stringify(this.settings.loaderSettings)) }; // The returned data (GeometryData) objects should be processed as normal, not as a preparedBuffer query.loaderSettings.prepareBuffers = false; var geometryLoader = new BimserverGeometryLoader(this.loaderCounter++, this.bimServerApi, this, this.roids, this.settings.loaderSettings, this.quantizationMap, this.viewer.stats, this.settings, query, null); var p = geometryLoader.start(); p.then(() => { var end = performance.now(); }); return p; } /* * This class acts as if it's a RenderLayer, the createGeometry is called} from the BimserverGeometryLoader * We just store the incoming geometry in the (global) GeometryCache */ createGeometry(loaderId, roid, uniqueModelId, geometryId, positions, normals, colors, color, indices, lineIndices, hasTransparency, reused) { this.nrReused++; var bytes = Utils.calculateBytesUsed(this.settings, positions.length, colors.length, indices.length, lineIndices ? lineIndices.length : 0, normals.length); this.bytesReused += bytes; var geometry = { id: geometryId, roid: roid, uniqueModelId: uniqueModelId, positions: positions, normals: normals, colors: colors, color: color, indices: indices, lineIndices: lineIndices, hasTransparency: hasTransparency, reused: reused, // How many times this geometry is reused, this does not necessarily mean the viewer is going to utilize this reuse reuseMaterialized: 0, // How many times this geometry has been reused in the viewer, when this number reaches "reused" we can flush the buffer fo' sho' bytes: bytes, matrices: [], objects: [] }; geometry.isReused = this.settings.gpuReuse; this.geometryCache.set(geometryId, geometry); geometry.isReused = geometry.reused > 1 && this.geometryDataToReuse != null && this.geometryDataToReuse.has(geometry.id); if (geometry.isReused) { this.viewer.stats.inc("Models", "Geometries reused"); } else { this.viewer.stats.inc("Models", "Geometries"); } } }
JavaScript
class Bombo{ //If rootElement (DOM) is not undefined means bombo is used in frontend constructor(rootElement=undefined){ const templateBombo = Array.from({length:90},(_,i) => i + 1); let boles = [...templateBombo]; let bolesExtracted = []; let lastBall; let shuffle = () => boles.sort((a,b) => Math.random()-0.5); this.getExtractedNumbers= () => bolesExtracted; this.getRemainingBoles = () => boles; this.pickNumber = () => { shuffle(); boles[0] && bolesExtracted.push(boles[0]); if (rootElement && boles[0]){ //si existe una ultima bola le quitamos la animacion if(lastBall){ document.getElementById(lastBall).className = 'bingoBall'; } //a la bola actual le ponemos la animacion document.getElementById(boles[0]).className = 'bingoBall blink' lastBall = boles[0]; } return (boles.length>0 && boles.splice(0,1))?bolesExtracted[bolesExtracted.length-1]:false; } //el render solo lo realiza una vez (añadiendo id a cada bola) let render = () => { if (rootElement) rootElement.innerHTML += `${boles.map(ball => `<div class='bingoBallEmpty' id='${ball}'>${ball}</div>`).join("")}`; } if (rootElement) render() //Only rendered if rootElement is not undefined } }
JavaScript
class StepLegend extends SimpleLegend { /** * Initializes an instance of the class * * @static * @param {Object} dependencies Set of dependencies required by the legend * @return {Instance} returns a new instance of Legend * @memberof Legend */ static create (dependencies) { return new StepLegend(dependencies); } /** * * * @static * * @memberof StepLegend */ static type () { return STEP; } /** * * * @static * * @memberof StepLegend */ static defaultConfig () { STEP_DEFAULT_CONFIG.buffer[HORIZONTAL] = 0; return STEP_DEFAULT_CONFIG; } /** * * * @param {*} scale * * @memberof StepLegend */ dataFromScale () { let domainLeg = []; const scale = this.scale(); const { scaleType, domain, steps, scaleFn } = getScaleInfo(scale); const isFraction = ele => ele % 1 !== 0; // defining scaleParams const scaleParams = { smartLabel: this.labelManager(), measures: this.measurement(), alignment: this.config().position, minTickDistance: this.minTickDistance() }; if (steps instanceof Array) { if (domain[0] < steps[0]) { domainLeg[0] = domain[0]; } domainLeg = [...domainLeg, ...steps]; if (domain[domain.length - 1] > steps[steps.length - 1]) { domainLeg.push(domain[1]); } domainLeg = [...new Set(domainLeg)].sort((a, b) => a - b); } else { domainLeg = getInterpolatedData(domain, steps, scaleParams); } domainLeg = [...new Set(domainLeg)].sort((a, b) => a - b); domainLeg = domainLeg.map((ele, i) => { let value = null; let range; if (i < domainLeg.length - 1) { const left = isFraction(ele) ? ele.toFixed(1) : ele; const numRight = +domainLeg[i + 1]; const right = isFraction(numRight) ? numRight.toFixed(1) : numRight; value = `${left} - ${right}`; range = [left, right]; } else if (domainLeg.length === 1) { value = isFraction(ele) ? ele.toFixed(1) : ele; const numRight = +domainLeg[i + 1]; const right = isFraction(numRight) ? numRight.toFixed(1) : numRight; range = [value, right]; } return { [scaleType]: scaleType === SIZE ? scale[scaleFn](ele) * scale.getScaleFactor() : scale[scaleFn](ele), value, id: i + 1, range }; }).filter(d => d.value !== null); return domainLeg; } /** * * * @param {*} effPadding * @param {*} align * * @memberof Legend */ getLabelSpaces () { this.config({ item: { text: { orientation: this.config().position } } }); const { item } = this.config(); const stepItemBuffer = DEFAULT_MEASUREMENT.padding * 2; return getItemMeasures(this, 'range', item.text.formatter, stepItemBuffer); } /** * * * * @memberof Legend */ elemType () { return RECT; } /** * Render the legend with its title * * @param {DOM} mountPoint Point where the legend and title are to be appended * @return {Instance} Current instance of legend * @memberof Legend */ render () { const firebolt = this.firebolt(); const { classPrefix, position } = this.config(); const data = stepData(this.data())[position]; const legendContainer = super.render(this.mount()); // create Legend const { legendItem } = createLegendSkeleton(this, legendContainer, classPrefix, data); const { itemSkeleton } = createItemSkeleton(this, legendItem); renderStepItem(this, itemSkeleton); legendContainer.selectAll('div').style('float', LEFT); firebolt.mapActionsAndBehaviour(); return legendContainer; } getCriteriaFromData (data) { const fieldName = this.fieldName(); return { [fieldName]: data.range }; } }
JavaScript
class DraggablePlugins extends React.Component { constructor(props) { super(props); this.state = { index: null }; this.handleClick = this.handleClick.bind(this); console.log(this.props.image); } /* * This function captures the event and determines the id of the clicked plugin. * This id is in turn sent up to PluginApp.js in order to tick the element at * the index of the id. */ handleClick = (e) => { e.preventDefault(); this.props.handlerFromParent(e.currentTarget.dataset.id); } render() { return ( <div className="cardbody" key={this.props.id} data-id={this.props.id} onClick={(this.handleClick)}> <div> <img src={window.location.origin + this.props.image} alt="Avatar"></img> <div> <p className="cardtext">{this.props.pluginName}</p> </div> </div> </div> ); } }
JavaScript
class EventAdd extends CommonForm { constructor(props) { super(props); this.onFormSubmit = this.onFormSubmit.bind(this); this.setFormRef = this.setFormRef.bind(this); } setFormRef(element) { this.form = element; } handleClose(event){ event.preventDefault(); const { dispatch } = this.props; dispatch(hideModal()); } handleTimeStart(e,timeEnd,setFieldValue){ if (!e) return false if (timeEnd){ if(e.diff(timeEnd)>0) setFieldValue('timeEnd',e); } setFieldValue('timeStart',e); } handleTimeStartRaw(e,timeEnd,setFieldValue){ const { value } = e.target; if (value && /^([0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(value)){ const newTimeStart = moment(value,'HH:mm'); if (timeEnd){ if(newTimeStart.diff(timeEnd)>0) setFieldValue('timeEnd',newTimeStart); } setFieldValue('timeStart',newTimeStart); } } handleTimeEnd(e,timeStart,setFieldValue){ if (!e) return false if (timeStart){ if(e.diff(timeStart)<0) setFieldValue('timeStart',e); } setFieldValue('timeEnd',e); } handleTimeEndRaw(e,timeStart,setFieldValue){ const { value } = e.target; if (value && /^([0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(value)){ const newTimeEnd = moment(value,'HH:mm'); if (timeStart){ if(newTimeEnd.diff(timeStart)<0) setFieldValue('timeStart',newTimeEnd); } setFieldValue('timeEnd',newTimeEnd); } } handleDateRaw(e,setFieldValue){ const { value } = e.target; if (value && /^\s*(3[01]|[12][0-9]|0?[1-9])\.(1[012]|0?[1-9])\.((?:19|20)\d{2})\s*$/.test(value)){ const newDate = moment(value,'DD:MM:YYYY'); setFieldValue('date',newDate); } } handleSubmit(values){ const meetupID = this.props.match.params.id; const entryType = this.getEntriesType(); const form = this.form; const newValues = { event_id: Number(meetupID), title: values.title, description: values.description, type: Number(values.type), startDate: values.date.format('YYYY-MM-DD')+values.timeStart.format('THH:mm:ssZ'), endDate: values.date.format('YYYY-MM-DD')+values.timeEnd.format('THH:mm:ssZ') }; if (values.curator_id !== null && values.curator_id !== undefined) { newValues.curator_id = Number(values.curator_id); } this.props.actions.create(entryType, { form: form, body: newValues, headers: { event_id: meetupID }, map: { meetup: meetupID } }); } handleRemove(){ const { dispatch,data } = this.props; const { event,meetupID } = data; const {_uniq} = event; dispatch(deleteEntry('events',{headers: { event_id: data.meetupID },uniq:_uniq,map:{event:event.id}})); this.props.onClose(); } getCurrentCuratorInfo(currentId,curators){ if (currentId === null || currentId === undefined){ return ( <CuratorInfo> <div></div> <div className="no-curator">Куратор не выбран</div> </CuratorInfo> ) } const current = curators.filter(c=>c.id===Number(currentId)); if(!current.length) return null; const p = current[0]; return ( <CuratorInfo> <div className="curator-avatar" style={{backgroundImage:`url(${p.photoSmallUrl})`}}></div> <div> {p.fio}<br/> <span>{p.department.title}</span> </div> </CuratorInfo> ) } render(){ const { entries } = this.props.state; const events = entries.events.items; const participants = entries.participants.items; const types = { 0: 'Обычное', 1: 'Перерыв' }; if (!events || !participants) return null; let modalTitle = 'Новое событие'; let submitButtonText = 'Добавить'; let submitButtonColor = 'rgb(54, 155, 0)'; const curators = participants.filter(p=>p.type===3); return( <> <Formik ref={e => { this.formik = e; }} initialValues={{ date: null, timeStart: null, timeEnd: null, title: null, description: null, type: 0, curator_id: null, }} onSubmit={e=>this.handleSubmit(e)} render={({ values, errors, touched, handleSubmit, handleChange, setFieldValue, isSubmitting, status, }) => { return ( <form onSubmit={handleSubmit} ref={this.setFormRef}> <InputWrapper> <label>Тип события</label> <SelectWrapper> {types[values.type]} <select id="type" currentValue={values.type} onChange={handleChange}> {Object.keys(types).map(key => ( <option key={`event_modal_type_option_${key}`} value={key}>{types[key]}</option> ))}; </select> </SelectWrapper> </InputWrapper> <Subtitle style={{marginTop:'32px'}}>Дата и время проведения</Subtitle> <ThreeColumns style={{marginTop:'8px'}}> <InputWrapper> <label>Дата</label> <DatePicker id="date" selected={values.date} onChange={e=>setFieldValue('date',e)} onChangeRaw={e=>this.handleDateRaw(e,setFieldValue)} customInput={ <MaskedTextInput type="text" mask={[/\d/, /\d/, ".", /\d/, /\d/, ".", /\d/, /\d/, /\d/, /\d/]} /> } disabledKeyboardNavigation /> </InputWrapper> <InputWrapper> <label>Время начала</label> <DatePicker id="timeStart" selected={values.timeStart} onChange={e=>this.handleTimeStart(e,values.timeEnd,setFieldValue)} onChangeRaw={e=>this.handleTimeStartRaw(e,values.timeEnd,setFieldValue)} //customInput={<TimePickerInput moment={values.timeStart} />} showTimeSelect showTimeSelectOnly timeIntervals={1} dateFormat="LT" timeCaption="Время начала" disabledKeyboardNavigation /> </InputWrapper> <InputWrapper> <label>Время окончания</label> <DatePicker id="timeEnd" selected={values.timeEnd} onChange={e=>this.handleTimeEnd(e,values.timeStart,setFieldValue)} onChangeRaw={e=>this.handleTimeEndRaw(e,values.timeStart,setFieldValue)} showTimeSelect showTimeSelectOnly timeIntervals={1} dateFormat="LT" minTime={values.timeStart} maxTime={moment().hours(23).minutes(59)} timeCaption="Время окончания" /> </InputWrapper> </ThreeColumns> <Subtitle style={{marginTop:'32px'}}>Подробная информация</Subtitle> <InputWrapper style={{marginTop:'8px'}}> <label>Название события</label> <input type="text" placeholder="Укажите название" id="title" value={values.title} onChange={handleChange} /> </InputWrapper> <InputWrapper style={{marginTop:'8px'}}> <label>Описание события</label> <textarea placeholder="Введите описание" id="description" onChange={handleChange}>{values.description}</textarea> </InputWrapper> <InputWrapper style={{marginTop:'32px'}}> <label>Куратор события</label> <SelectWrapper className="curator-select"> {this.getCurrentCuratorInfo(values.curator_id,curators)} <select id="curator_id" currentValue={values.type} onChange={handleChange}> <option key={`event_modal_curator_option_null`} value={''}>Выберите...</option> {curators.map(c => ( <option key={`event_modal_curator_option_${c.id}`} value={c.id}>{c.fio}</option> ))}; </select> </SelectWrapper> </InputWrapper> <Form.Footer> <ActionButtons.Cancel /> <Form.Submit caption="Добавить" /> </Form.Footer> </form> )}} /> </> ) } // render() { // const { match } = this.props; // const meetup = (match && match.params.id) || null; // return ( // <Form.Wrapper onSubmit={this.onFormSubmit}> // <Form.Hidden name="meetup" value={meetup} /> // <Form.Row> // <Form.Column> // <Form.Text // label="Название события" // name="title" // placeholder="Введите название события" // required={true} // /> // <Form.TextArea // label="Описание события" // name="description" // placeholder="Введите описание события" // required={true} // /> // </Form.Column> // <Form.Column> // <Form.Row> // <Form.Column> // <Form.Datepicker // label="Дата" // placeholder="" // name="date" // isRequired={true} // /> // </Form.Column> // <Form.Column> // <Form.Datepicker // label="Время начала" // placeholder="" // name="start_time" // id="event-manage-start-time" // relatedTo="#event-manage-end-time" // mode="time" // isRequired={true} // /> // </Form.Column> // <Form.Column> // <Form.Datepicker // label="Время окончания" // placeholder="" // name="end_time" // id="event-manage-end-time" // mode="time" // isRequired={true} // /> // </Form.Column> // </Form.Row> // <Form.Row> // <Form.Column> // <CuratorsList // label="Куратор события" // name="curator_id" // className="form__field form__field_type_select" // /> // </Form.Column> // </Form.Row> // <Form.Row> // <Form.Column> // <Form.Radio // label="Тип события" // name="type" // type="inline" // choices={{ // 0: 'Обычное', // 1: 'Перерыв' // }} // isRequired={true} // /> // </Form.Column> // </Form.Row> // </Form.Column> // </Form.Row> // <Form.Footer> // <Form.Submit caption="Добавить" /> // </Form.Footer> // </Form.Wrapper> // ); // } getEntriesType() { return 'events'; } }
JavaScript
class Movies extends Component { render() { const screenProps = this.props.screenProps; const { movies, handleRefresh, loading, handleLoadmore, isRefreshing, hasMore } = screenProps; const navigate = this.props.navigation.navigate; return ( <MovieList movies={movies} handleRefresh={handleRefresh} loading={loading} handleLoadmore={handleLoadmore} isRefreshing={isRefreshing} navigate={navigate} type='movie' hasMore={hasMore}/> ); } }
JavaScript
class QgridModel extends widgets.DOMWidgetModel { defaults() { return _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name : 'QgridModel', _view_name : 'QgridView', _model_module : 'qgrid2', _view_module : 'qgrid', _model_module_version : '^1.1.3', _view_module_version : '^1.1.3', _df_json: '', _columns: {} }); } }
JavaScript
class QgridView extends widgets.DOMWidgetView { render() { // subscribe to incoming messages from the QGridWidget this.model.on('msg:custom', this.handle_msg, this); this.initialize_qgrid(); } /** * Main entry point for drawing the widget, * including toolbar buttons if necessary. */ initialize_qgrid() { this.$el.empty(); if (!this.$el.hasClass('q-grid-container')){ this.$el.addClass('q-grid-container'); } this.initialize_toolbar(); this.initialize_slick_grid(); } initialize_toolbar() { if (!this.model.get('show_toolbar')){ this.$el.removeClass('show-toolbar'); } else { this.$el.addClass('show-toolbar'); } if (this.toolbar){ return; } this.toolbar = $("<div class='q-grid-toolbar'>").appendTo(this.$el); let append_btn = (btn_info) => { return $(` <button class='btn btn-default' data-loading-text='${btn_info.loading_text}' data-event-type='${btn_info.event_type}' data-btn-text='${btn_info.text}'> ${btn_info.text} </button> `).appendTo(this.toolbar); }; append_btn({ loading_text: 'Adding...', event_type: 'add_row', text: 'Add Row' }); append_btn({ loading_text: 'Removing...', event_type: 'remove_row', text: 'Remove Row' }); this.buttons = this.toolbar.find('.btn'); this.buttons.attr('title', 'Not available while there is an active filter'); this.buttons.tooltip(); this.buttons.tooltip({ show: {delay: 300} }); this.buttons.tooltip({ hide: {delay: 100, 'duration': 0} }); this.buttons.tooltip('disable'); this.full_screen_btn = null; if (dialog) { this.full_screen_modal = $('body').find('.qgrid-modal'); if (this.full_screen_modal.length == 0) { this.full_screen_modal = $(` <div class="modal qgrid-modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"></div> </div> </div> </div> `).appendTo($('body')); } this.full_screen_btn = $(` <button class='btn btn-default fa fa-arrows-alt full-screen-btn'/> `).appendTo(this.toolbar); this.close_modal_btn = $(` <button class='btn btn-default fa fa-times close-modal-btn' data-dismiss="modal"/> `).appendTo(this.toolbar); } this.bind_toolbar_events(); } bind_toolbar_events() { this.buttons.off('click'); this.buttons.click((e) => { let clicked = $(e.target); if (clicked.hasClass('disabled')){ return; } if (this.in_progress_btn){ alert(` Adding/removing row is not available yet because the previous operation is still in progress. `); } this.in_progress_btn = clicked; clicked.text(clicked.attr('data-loading-text')); clicked.addClass('disabled'); this.send({'type': clicked.attr('data-event-type')}); }); if (!this.full_screen_btn) { return; } this.full_screen_btn.off('click'); this.full_screen_btn.click((e) => { this.$el_wrapper = this.$el.parent(); this.$el_wrapper.height(this.$el_wrapper.height()); this.$el.detach(); var modal_options = { body: this.$el[0], show: false }; if (IPython && IPython.keyboard_manager) { modal_options.keyboard_manager = IPython.keyboard_manager; } var qgrid_modal = dialog.modal(modal_options); qgrid_modal.removeClass('fade'); qgrid_modal.addClass('qgrid-modal'); qgrid_modal.on('shown.bs.modal', (e) => { this.slick_grid.resizeCanvas(); }); qgrid_modal.on('hidden.bs.modal', (e) => { this.$el.detach(); this.$el_wrapper.height('auto'); this.$el_wrapper.append(this.$el); this.update_size(); this.slick_grid.bindAllEvents(); this.bind_toolbar_events(); }); qgrid_modal.modal('show'); }); } /** * Create the grid portion of the widget, which is an instance of * SlickGrid, plus automatically created filter controls based on the * type of data in the columns of the DataFrame provided by the user. */ initialize_slick_grid() { if (!this.grid_elem) { this.grid_elem = $("<div class='q-grid'>").appendTo(this.$el); } // create the table var df_json = JSON.parse(this.model.get('_df_json')); var columns = this.model.get('_columns'); this.data_view = this.create_data_view(df_json.data); this.grid_options = this.model.get('grid_options'); this.index_col_name = this.model.get("_index_col_name"); this.row_styles = this.model.get("_row_styles"); this.columns = []; this.index_columns = []; this.filters = {}; this.filter_list = []; this.date_formats = {}; this.last_vp = null; this.sort_in_progress = false; this.sort_indicator = null; this.resizing_column = false; this.ignore_selection_changed = false; this.vp_response_expected = false; this.next_viewport_msg = null; var number_type_info = { filter: slider_filter.SliderFilter, validator: editors.validateNumber, formatter: this.format_number }; var self = this; this.type_infos = { integer: Object.assign( { editor: Slick.Editors.Integer }, number_type_info ), number: Object.assign( { editor: Slick.Editors.Float }, number_type_info ), string: { filter: text_filter.TextFilter, editor: Slick.Editors.Text, formatter: this.format_string }, datetime: { filter: date_filter.DateFilter, editor: class DateEditor extends Slick.Editors.Date { constructor(args) { super(args); this.loadValue = (item) => { this.date_value = item[args.column.field]; var formatted_val = self.format_date( this.date_value, args.column.field ); this.input = $(args.container).find('.editor-text'); this.input.val(formatted_val); this.input[0].defaultValue = formatted_val; this.input.select(); this.input.on("keydown.nav", function (e) { if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) { e.stopImmediatePropagation(); } }); }; this.isValueChanged = () => { return this.input.val() != this.date_value; }; this.serializeValue = () => { if (this.input.val() === "") { return null; } var parsed_date = moment.parseZone( this.input.val(), "YYYY-MM-DD HH:mm:ss.SSS" ); return parsed_date.format("YYYY-MM-DDTHH:mm:ss.SSSZ"); }; } }, formatter: (row, cell, value, columnDef, dataContext) => { if (value === null){ return "NaT"; } return this.format_date(value, columnDef.name); } }, any: { filter: text_filter.TextFilter, editor: editors.SelectEditor, formatter: this.format_string }, interval: { formatter: this.format_string }, boolean: { filter: boolean_filter.BooleanFilter, editor: Slick.Editors.Checkbox, formatter: (row, cell, value, columngDef, dataContext) => { return value ? `<span class="fa fa-check"/>` : ""; } } }; $.datepicker.setDefaults({ gotoCurrent: true, dateFormat: $.datepicker.ISO_8601, constrainInput: false, "prevText": "", "nextText": "" }); var sorted_columns = Object.values(columns).sort( (a, b) => a.position - b.position ); for(let cur_column of sorted_columns){ if (cur_column.name == this.index_col_name){ continue; } var type_info = this.type_infos[cur_column.type] || {}; var slick_column = cur_column; Object.assign(slick_column, type_info); if (cur_column.type == 'any'){ slick_column.editorOptions = { options: cur_column.constraints.enum }; } if (slick_column.filter) { var cur_filter = new slick_column.filter( slick_column.field, cur_column.type, this ); this.filters[slick_column.id] = cur_filter; this.filter_list.push(cur_filter); } if (cur_column.width == null){ delete slick_column.width; } if (cur_column.maxWidth == null){ delete slick_column.maxWidth; } // don't allow editing index columns if (cur_column.is_index) { slick_column.editor = editors.IndexEditor; if (cur_column.first_index){ slick_column.cssClass += ' first-idx-col'; } if (cur_column.last_index){ slick_column.cssClass += ' last-idx-col'; } slick_column.name = cur_column.index_display_text; slick_column.level = cur_column.level; if (this.grid_options.boldIndex) { slick_column.cssClass += ' idx-col'; } this.index_columns.push(slick_column); continue; } if (cur_column.editable == false) { slick_column.editor = null; } this.columns.push(slick_column); } if (this.index_columns.length > 0) { this.columns = this.index_columns.concat(this.columns); } var row_count = 0; // set window.slick_grid for easy troubleshooting in the js console window.slick_grid = this.slick_grid = new Slick.Grid( this.grid_elem, this.data_view, this.columns, this.grid_options ); this.grid_elem.data('slickgrid', this.slick_grid); if (this.grid_options.forceFitColumns){ this.grid_elem.addClass('force-fit-columns'); } if (this.grid_options.highlightSelectedCell) { this.grid_elem.addClass('highlight-selected-cell'); } // compare to false since we still want to show row // selection if this option is excluded entirely if (this.grid_options.highlightSelectedRow != false) { this.grid_elem.addClass('highlight-selected-row'); } setTimeout(() => { this.slick_grid.init(); this.update_size(); }, 1); this.slick_grid.setSelectionModel(new Slick.RowSelectionModel()); this.slick_grid.setCellCssStyles("grouping", this.row_styles); this.slick_grid.render(); this.update_size(); var render_header_cell = (e, args) => { var cur_filter = this.filters[args.column.id]; if (cur_filter) { cur_filter.render_filter_button($(args.node), this.slick_grid); } }; if (this.grid_options.filterable != false) { this.slick_grid.onHeaderCellRendered.subscribe(render_header_cell); } // Force the grid to re-render the column headers so the // onHeaderCellRendered event is triggered. this.slick_grid.setColumns(this.slick_grid.getColumns()); $(window).resize(() => { this.slick_grid.resizeCanvas(); }); this.slick_grid.setSortColumns([]); this.grid_header = this.$el.find('.slick-header-columns'); var handle_header_click = (e) => { if (this.resizing_column) { return; } if (this.sort_in_progress){ return; } var col_header = $(e.target).closest(".slick-header-column"); if (!col_header.length) { return; } var column = col_header.data("column"); if (column.sortable == false){ return; } this.sort_in_progress = true; if (this.sorted_column == column){ this.sort_ascending = !this.sort_ascending; } else { this.sorted_column = column; if ('defaultSortAsc' in column) { this.sort_ascending = column.defaultSortAsc; } else{ this.sort_ascending = true; } } var all_classes = 'fa-sort-asc fa-sort-desc fa fa-spin fa-spinner'; var clicked_column_sort_indicator = col_header.find('.slick-sort-indicator'); if (clicked_column_sort_indicator.length == 0){ clicked_column_sort_indicator = $("<span class='slick-sort-indicator'/>").appendTo(col_header); } this.sort_indicator = clicked_column_sort_indicator; this.sort_indicator.removeClass(all_classes); this.grid_elem.find('.slick-sort-indicator').removeClass(all_classes); this.sort_indicator.addClass(`fa fa-spinner fa-spin`); var msg = { 'type': 'change_sort', 'sort_field': this.sorted_column.field, 'sort_ascending': this.sort_ascending }; this.send(msg); }; if (this.grid_options.sortable != false) { this.grid_header.click(handle_header_click) } this.slick_grid.onViewportChanged.subscribe((e) => { if (this.viewport_timeout){ clearTimeout(this.viewport_timeout); } this.viewport_timeout = setTimeout(() => { this.last_vp = this.slick_grid.getViewport(); var cur_range = this.model.get('_viewport_range'); if (this.last_vp.top != cur_range[0] || this.last_vp.bottom != cur_range[1]) { var msg = { 'type': 'change_viewport', 'top': this.last_vp.top, 'bottom': this.last_vp.bottom }; if (this.vp_response_expected){ this.next_viewport_msg = msg } else { this.vp_response_expected = true; this.send(msg); } } this.viewport_timeout = null; }, 100); }); // set up callbacks let editable_rows = this.model.get('_editable_rows'); if (editable_rows && Object.keys(editable_rows).length > 0) { this.slick_grid.onBeforeEditCell.subscribe((e, args) => { editable_rows = this.model.get('_editable_rows'); return editable_rows[args.item[this.index_col_name]] }); } this.slick_grid.onCellChange.subscribe((e, args) => { var column = this.columns[args.cell].name; var data_item = this.slick_grid.getDataItem(args.row); var msg = {'row_index': data_item.row_index, 'column': column, 'unfiltered_index': data_item[this.index_col_name], 'value': args.item[column], 'type': 'edit_cell'}; this.send(msg); }); this.slick_grid.onSelectedRowsChanged.subscribe((e, args) => { if (!this.ignore_selection_changed) { var msg = {'rows': args.rows, 'type': 'change_selection'}; this.send(msg); } }); setTimeout(() => { this.$el.closest('.output_wrapper') .find('.out_prompt_overlay,.output_collapsed').click(() => { setTimeout(() => { this.slick_grid.resizeCanvas(); }, 1); }); this.resize_handles = this.grid_header.find('.slick-resizable-handle'); this.resize_handles.mousedown((e) => { this.resizing_column = true; }); $(document).mouseup(() => { // wait for the column header click handler to run before // setting the resizing_column flag back to false setTimeout(() => { this.resizing_column = false; }, 1); }); }, 1); } processPhosphorMessage(msg) { super.processPhosphorMessage(msg) switch (msg.type) { case 'resize': case 'after-show': if (this.slick_grid){ this.slick_grid.resizeCanvas(); } break; } } has_active_filter() { for (var i=0; i < this.filter_list.length; i++){ var cur_filter = this.filter_list[i]; if (cur_filter.is_active()){ return true; } } return false; } /** * Main entry point for drawing the widget, * including toolbar buttons if necessary. */ create_data_view(df) { let df_range = this.df_range = this.model.get("_df_range"); let df_length = this.df_length = this.model.get("_row_count"); return { getLength: () => { return df_length; }, getItem: (i) => { if (i >= df_range[0] && i < df_range[1]){ var row = df[i - df_range[0]] || {}; row.row_index = i; return row; } else { return { row_index: i }; } } }; } set_data_view(data_view) { this.data_view = data_view; this.slick_grid.setData(data_view); } format_date(date_string, col_name) { if (!date_string) { return ""; } var parsed_date = moment.parseZone(date_string, "YYYY-MM-DDTHH:mm:ss.SSSZ"); var date_format = null; if (parsed_date.millisecond() != 0){ date_format = `YYYY-MM-DD HH:mm:ss.SSS`; } else if (parsed_date.second() != 0){ date_format = "YYYY-MM-DD HH:mm:ss"; } else if (parsed_date.hour() != 0 || parsed_date.minute() != 0) { date_format = "YYYY-MM-DD HH:mm"; } else { date_format = "YYYY-MM-DD"; } if (col_name in this.date_formats){ var old_format = this.date_formats[col_name]; if (date_format.length > old_format.length){ this.date_formats[col_name] = date_format; setTimeout(() => { this.slick_grid.invalidateAllRows(); this.slick_grid.render(); }, 1); } else { date_format = this.date_formats[col_name]; } } else { this.date_formats[col_name] = date_format; } return parsed_date.format(date_format); } format_string(row, cell, value, columnDef, dataContext) { return value; } format_number(row, cell, value, columnDef, dataContext) { if (value === null){ return 'NaN'; } return value; } /** * Handle messages from the QGridWidget. */ handle_msg(msg) { if (msg.type === 'draw_table') { this.initialize_slick_grid(); } else if (msg.type == 'show_error') { alert(msg.error_msg); if (msg.triggered_by == 'add_row' || msg.triggered_by == 'remove_row'){ this.reset_in_progress_button(); } } else if (msg.type == 'update_data_view') { if (this.buttons) { if (this.has_active_filter()) { this.buttons.addClass('disabled'); this.buttons.tooltip('enable'); } else if (this.buttons.hasClass('disabled')) { this.buttons.removeClass('disabled'); this.buttons.tooltip('disable'); } } if (this.update_timeout) { clearTimeout(this.update_timeout); } this.update_timeout = setTimeout(() => { var df_json = JSON.parse(this.model.get('_df_json')); this.row_styles = this.model.get("_row_styles"); this.multi_index = this.model.get("_multi_index"); var data_view = this.create_data_view(df_json.data); if (msg.triggered_by === 'change_viewport') { if (this.next_viewport_msg) { this.send(this.next_viewport_msg); this.next_viewport_msg = null; return; } else { this.vp_response_expected = false; } } if (msg.triggered_by == 'change_sort' && this.sort_indicator) { var asc = this.model.get('_sort_ascending'); this.sort_indicator.removeClass( 'fa-spinner fa-spin fa-sort-asc fa-sort-desc' ); var fa_class = asc ? 'fa-sort-asc' : 'fa-sort-desc'; this.sort_indicator.addClass(fa_class); this.sort_in_progress = false; } let top_row = null; if (msg.triggered_by === 'remove_row') { top_row = this.slick_grid.getViewport().top; } this.set_data_view(data_view); var skip_grouping = false; if (this.multi_index) { for (var i = 1; i < this.filter_list.length; i++) { var cur_filter = this.filter_list[i]; if (cur_filter.is_active()) { skip_grouping = true; } } } if (skip_grouping) { this.slick_grid.removeCellCssStyles("grouping"); } else { this.slick_grid.setCellCssStyles("grouping", this.row_styles); } this.slick_grid.render(); if ((msg.triggered_by == 'add_row' || msg.triggered_by == 'remove_row') && !this.has_active_filter()) { this.update_size(); } this.update_timeout = null; this.reset_in_progress_button(); if (top_row) { this.slick_grid.scrollRowIntoView(top_row); } else if (msg.triggered_by === 'add_row') { this.slick_grid.scrollRowIntoView(msg.scroll_to_row); this.slick_grid.setSelectedRows([msg.scroll_to_row]); } else if (msg.triggered_by === 'change_viewport' && this.last_vp.bottom >= this.df_length) { this.slick_grid.scrollRowIntoView(this.last_vp.bottom); } var selected_rows = this.slick_grid.getSelectedRows().filter((row) => { return row < Math.min(this.df_length, this.df_range[1]); }); this.send({ 'rows': selected_rows, 'type': 'change_selection' }); }, 100); } else if (msg.type == 'change_grid_option') { var opt_name = msg.option_name; var opt_val = msg.option_value; if (this.slick_grid.getOptions()[opt_name] != opt_val) { this.slick_grid.setOptions({[opt_name]: opt_val}); this.slick_grid.resizeCanvas(); } } else if (msg.type == 'change_selection') { this.ignore_selection_changed = true; this.slick_grid.setSelectedRows(msg.rows); if (msg.rows && msg.rows.length > 0) { this.slick_grid.scrollRowIntoView(msg.rows[0]); } this.ignore_selection_changed = false; } else if (msg.type == 'change_show_toolbar') { this.initialize_toolbar(); } else if (msg.col_info) { var filter = this.filters[msg.col_info.name]; filter.handle_msg(msg); } } reset_in_progress_button() { if (this.in_progress_btn){ this.in_progress_btn.removeClass('disabled'); this.in_progress_btn.text( this.in_progress_btn.attr('data-btn-text') ); this.in_progress_btn = null; } } /** * Update the size of the dataframe. */ update_size() { var row_height = this.grid_options.rowHeight; var min_visible = 'minVisibleRows' in this.grid_options ? this.grid_options.minVisibleRows : 8; var max_visible = 'maxVisibleRows' in this.grid_options ? this.grid_options.maxVisibleRows : 15; var min_height = row_height * min_visible; // add 2 to maxVisibleRows to account for the header row and padding var max_height = 'height' in this.grid_options ? this.grid_options.height : row_height * (max_visible + 2); var grid_height = max_height; var total_row_height = (this.data_view.getLength() + 1) * row_height + 1; if (total_row_height <= max_height){ grid_height = Math.max(min_height, total_row_height); this.grid_elem.addClass('hide-scrollbar'); } else { this.grid_elem.removeClass('hide-scrollbar'); } this.grid_elem.height(grid_height); this.slick_grid.render(); this.slick_grid.resizeCanvas(); } }
JavaScript
class Settings extends Component { componentDidMount() { googleanalytics.SendScreen('Settings'); window.addEventListener('contextmenu', this.setupcontextmenu, false); } componentWillUnmount() { window.removeEventListener('contextmenu', this.setupcontextmenu); } /** * Set up context menu * * @param {*} e * @memberof Settings */ setupcontextmenu(e) { e.preventDefault(); const contextmenu = new ContextMenuBuilder().defaultContext; //build default let defaultcontextmenu = remote.Menu.buildFromTemplate(contextmenu); defaultcontextmenu.popup(remote.getCurrentWindow()); } /** * React Render * * @returns * @memberof Settings */ render() { const { match } = this.props; return ( <Panel bodyScrollable={false} icon={settingsIcon} title={<Text id="Settings.Settings" />} > <SettingsComponent> <SettingsTabBar> <Tab link={`${match.url}/App`} icon={logoIcon} text={<Text id="Settings.Application" />} /> <Tab link={`${match.url}/Core`} icon={coreIcon} text={<Text id="Settings.Core" />} /> <Tab link={`${match.url}/Security`} icon={lockIcon} text={<Text id="Settings.Security" />} /> <Tab link={`${match.url}/Style`} icon={developerIcon} text={<Text id="Settings.Style" />} /> </SettingsTabBar> <SettingsContent> <Switch> <Redirect exact from={`${match.path}/`} to={`${match.path}/App`} /> <Route path={`${match.path}/App`} render={props => <SettingsApp {...this.props} />} /> <Route path={`${match.path}/Core`} component={SettingsCore} /> <Route path={`${match.path}/Style`} component={SettingsStyle} /> <Route path={`${match.path}/Security`} component={Security} /> </Switch> </SettingsContent> </SettingsComponent> </Panel> ); } }
JavaScript
class TestcaseCollection extends Model { /** * get ViewModel class bind with Model * @return {ViewModel} - ViewModel class */ getViewModel() { return require('../vm/TestcaseCollection'); } }
JavaScript
class Device { /** * Constructs a new <code>Device</code>. * @alias module:model/Device * @implements module:model/DeviceAllOf * @implements module:model/DeviceCreate * @param tenantId {String} * @param managed {Boolean} * @param onboardType {String} * @param name {String} * @param model {String} * @param type {String} */ constructor(tenantId, managed, onboardType, name, model, type) { DeviceAllOf.initialize(this);DeviceCreate.initialize(this, tenantId, managed, onboardType, name, model, type); Device.initialize(this, tenantId, managed, onboardType, name, model, type); } /** * 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, tenantId, managed, onboardType, name, model, type) { obj['tenantId'] = tenantId; obj['managed'] = managed || false; obj['onboardType'] = onboardType; obj['name'] = name; obj['model'] = model; obj['type'] = type; } /** * Constructs a <code>Device</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/Device} obj Optional instance to populate. * @return {module:model/Device} The populated <code>Device</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Device(); DeviceAllOf.constructFromObject(data, obj); DeviceCreate.constructFromObject(data, obj); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('userId')) { obj['userId'] = ApiClient.convertToType(data['userId'], 'String'); } if (data.hasOwnProperty('providerId')) { obj['providerId'] = ApiClient.convertToType(data['providerId'], 'String'); } if (data.hasOwnProperty('vulnerabilityState')) { obj['vulnerabilityState'] = DeviceVulnerabilityState.constructFromObject(data['vulnerabilityState']); } if (data.hasOwnProperty('createdOn')) { obj['createdOn'] = ApiClient.convertToType(data['createdOn'], 'Date'); } if (data.hasOwnProperty('modifiedOn')) { obj['modifiedOn'] = ApiClient.convertToType(data['modifiedOn'], 'Date'); } if (data.hasOwnProperty('serviceInstanceId')) { obj['serviceInstanceId'] = ApiClient.convertToType(data['serviceInstanceId'], 'String'); } if (data.hasOwnProperty('subscriptionId')) { obj['subscriptionId'] = ApiClient.convertToType(data['subscriptionId'], 'String'); } if (data.hasOwnProperty('tenantId')) { obj['tenantId'] = ApiClient.convertToType(data['tenantId'], 'String'); } if (data.hasOwnProperty('serviceType')) { obj['serviceType'] = ApiClient.convertToType(data['serviceType'], 'String'); } if (data.hasOwnProperty('tags')) { obj['tags'] = ApiClient.convertToType(data['tags'], {'String': 'String'}); } if (data.hasOwnProperty('managed')) { obj['managed'] = ApiClient.convertToType(data['managed'], 'Boolean'); } if (data.hasOwnProperty('onboardType')) { obj['onboardType'] = ApiClient.convertToType(data['onboardType'], 'String'); } if (data.hasOwnProperty('onboardInformation')) { obj['onboardInformation'] = ApiClient.convertToType(data['onboardInformation'], {'String': Object}); } if (data.hasOwnProperty('attributes')) { obj['attributes'] = ApiClient.convertToType(data['attributes'], {'String': Object}); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('model')) { obj['model'] = ApiClient.convertToType(data['model'], 'String'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('subType')) { obj['subType'] = ApiClient.convertToType(data['subType'], 'String'); } if (data.hasOwnProperty('serialKey')) { obj['serialKey'] = ApiClient.convertToType(data['serialKey'], 'String'); } if (data.hasOwnProperty('version')) { obj['version'] = ApiClient.convertToType(data['version'], 'String'); } if (data.hasOwnProperty('complianceState')) { obj['complianceState'] = DeviceComplianceState.constructFromObject(data['complianceState']); } } return obj; } }
JavaScript
class Header extends Component { constructor(props) { super(props); this.state = { hoverAccount: null, }; } getAuthIdentifier() { const { userData } = this.props; const { user } = userData || {}; const { authIdentifier } = user || {}; return authIdentifier; } getConnectionErrorStatusMsg() { const { intl, socket } = this.props; const { formatMessage } = intl; const { connected, message, watcherConnected, watcherMessage } = socket || {}; if (!connected) { return message || formatMessage(messages.disconnected); } if (!watcherConnected) { return watcherMessage; } return null; } getRoleName() { const { userData } = this.props; const { user } = userData || {}; const { accountRoles = [] } = user || {}; const accountId = sessionGetAccount(); const accountRole = accountRoles.find(ar => ar.accountId === accountId); const { roleName } = accountRole || {}; return roleName; } getUsername() { const { userData } = this.props; const { user } = userData || {}; const { authIdentifier, profile } = user || {}; const { userName } = profile || {}; const { value } = userName || {}; return value || authIdentifier || ''; } renderAccountToggle() { const { sessionAccountName, socket } = this.props; const { connecting } = socket || {}; return ( <div className="header-menu-title"> <div className="header-menu-title-icon"> {this.renderIconToggle(this.getRoleName())} {connecting ? <Spinner className="header-menu-title-icon-loader" name="three-bounce" /> : null} </div> {`${this.getUsername()} | ${sessionAccountName}`} <KeyboardArrowDown className="header-menu-caret" /> </div> ); } renderBreadcrumbs() { const { intl, location, resourceName } = this.props; const { formatMessage } = intl; const { pathname = '' } = location; const pathItems = pathname.split('/') || []; const base = pathItems[1] || ''; const basePath = `/${base}`; const identifier = pathItems[2]; const menuItem = MENU_ITEMS.find(item => item.href === basePath) || {}; const { id: menuMsgId } = menuItem || {}; const menuName = menuMsgId ? formatMessage(menuMsgs[menuMsgId]) : null; return ( <div> <span className="header-breadcrumbs-base"> {identifier ? ( <Link className="header-link" to={basePath}> {menuName} </Link> ) : ( menuName )} </span> {resourceName ? ( <Fragment> <span className="header-breadcrumbs-divider">/</span> {resourceName} </Fragment> ) : null} </div> ); } renderIcon(roleName) { switch (roleName) { case constants.ROLE_NAME_SYSTEM_ADMIN: return <IcoSystemAdmin id="icon-system-admin" />; case constants.ROLE_NAME_TENANT_ADMIN: return <IcoTenantAdmin />; default: return <AccountCircle />; } } renderIconToggle(roleName) { const { socket } = this.props; const { connected, watcherConnected } = socket || {}; const className = connected && watcherConnected ? 'header-account-dropdown-socket-connected' : 'header-account-dropdown-socket-disconnected'; switch (roleName) { case constants.ROLE_NAME_SYSTEM_ADMIN: case constants.ROLE_NAME_TENANT_ADMIN: return <div className={`${className}-fill`}>{this.renderIcon(roleName)}</div>; default: return <div className={className}>{this.renderIcon(roleName)}</div>; } } renderIconSelect(roleName, isSelected, isHover) { const className = isHover ? 'header-account-dropdown-select-bg-hover' : 'header-account-dropdown-select-bg'; const fillClassName = `${className} ${className}-fill header-account-dropdown-accounts-select-box-fill ${ isSelected ? 'header-account-dropdown-select-box-selected-fill' : '' }`; switch (roleName) { case constants.ROLE_NAME_SYSTEM_ADMIN: case constants.ROLE_NAME_TENANT_ADMIN: return <div className={fillClassName}>{this.renderIcon(roleName)}</div>; default: return <div className={className}>{this.renderIcon(roleName)}</div>; } } renderUserNav(simple) { const { intl, onChangeAccount, sessionAccountName, socket, userData } = this.props; const { formatMessage } = intl; const { connected, message, watcherConnected } = socket || {}; const { user } = userData || {}; const { accountRoles = [] } = user || {}; const { hoverAccount } = this.state; const sessionAccountId = sessionGetAccount(); const errorMsg = this.getConnectionErrorStatusMsg(); return ( <Dropdown className="nv-dropdown" id="nav-user-dropdown" pullRight> <Dropdown.Toggle bsStyle="link" noCaret={simple}> {this.renderAccountToggle()} </Dropdown.Toggle> <Dropdown.Menu> <div className="header-account-dropdown-menu-title"> <div> {this.getAuthIdentifier()} <div className={`header-account-dropdown-socket-message ${ connected && watcherConnected ? 'header-account-dropdown-socket-connected' : 'header-account-dropdown-socket-disconnected' } `} > {errorMsg || message} </div> </div> <OverlayTrigger placement="left" overlay={<Tooltip id="logout-tooltip">{formatMessage(menuMsgs.userLogOut)}</Tooltip>} > <PowerSettingsNew className="header-account-dropdown-logout" id="logout-icon" onClick={() => { const { logout } = this.props; if (logout) { logout(); } }} /> </OverlayTrigger> </div> <div className="header-account-dropdown-accounts"> {_.sortBy(accountRoles, ['roleName', 'accountName']).map((accountRole, idx) => { const { accountId, accountName, roleName } = accountRole || {}; const { hoverAccount } = this.state; const { accountId: hoverAccountId } = hoverAccount || {}; return ( <div className={`header-account-dropdown-select-box ${ accountId === sessionAccountId ? 'header-account-dropdown-select-box-selected' : '' } ${!hoverAccount ? 'header-account-dropdown-select-box-disabled' : ''}`} id={accountName} key={idx} onClick={() => onChangeAccount(accountId, this.getAuthIdentifier())} onMouseEnter={() => { if (accountId !== sessionAccountId) { this.setState({ hoverAccount: accountRole }); } }} onMouseLeave={() => { this.setState({ hoverAccount: null }); }} > {this.renderIconSelect( roleName, accountId === sessionAccountId, accountId === hoverAccountId )} </div> ); })} </div> <div className={ hoverAccount ? 'header-account-dropdown-description-hover' : 'header-account-dropdown-description' } > <div className="header-account-dropdown-description-title"> {hoverAccount ? hoverAccount.roleName : this.getRoleName()} </div> {hoverAccount ? hoverAccount.accountName : sessionAccountName} </div> </Dropdown.Menu> </Dropdown> ); } renderFilterTitle(simple) { const { intl } = this.props; const { formatMessage } = intl; return ( <span className="header-menu-title"> <i className={`fa fa-filter ${simple ? '' : 'pad-10-r'}`} aria-hidden="true" /> {simple ? null : <b>{formatMessage(menuMsgs.filter)}</b>} </span> ); } renderFilterOptions(simple) { return ( <DropdownButton bsStyle="link" id="nav-dashboard-filter" noCaret={simple} pullRight title={this.renderFilterTitle(simple)} > <TimePeriodSelectionContainer /> </DropdownButton> ); } render() { return ( <div id="nuvoloso-header" className="header"> <div className="header-breadcrumbs">{this.renderBreadcrumbs()}</div> <div className="header-info"> <TasksContainer /> {this.renderUserNav(true)} </div> </div> ); } }
JavaScript
class AsyncPreloader { constructor() { // Properties /** * Object that contains the loaded items */ this.items = new Map(); /** * Default body method to be called on the Response from fetch if no body option is specified on the LoadItem */ this.defaultBodyMethod = "blob"; /** * Default loader to use if no loader key is specified in the [[LoadItem]] or if the extension doesn't match any of the [[AsyncPreloader.loaders]] extensions */ this.defaultLoader = LoaderKey.Text; // API /** * Load the specified manifest (array of items) * * @param {LoadItem[]} items Items to load * @returns {Promise<LoadedValue[]>} Resolve when all items are loaded, reject for any error */ this.loadItems = async items => { return await Promise.all(items.map(this.loadItem)); }; /** * Load a single item * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Resolve when item is loaded, reject for any error */ this.loadItem = async item => { const extension = AsyncPreloader.getFileExtension(item.src); const loaderKey = item.loader || AsyncPreloader.getLoaderKey(extension); const loadedItem = await this[`load` + loaderKey](item); this.items.set(item.id || item.src, loadedItem); return loadedItem; }; // Special loaders /** * Load a manifest of items * * @param {string} src Manifest src url * @param {string} [key="items"] Manifest key in the JSON object containing the array of LoadItem. * @returns {Promise<LoadedValue[]>} */ this.loadManifest = async (src, key = "items") => { const loadedManifest = await this.loadJson({ src }); const items = AsyncPreloader.getProp(loadedManifest, key); return await this.loadItems(items); }; // Text loaders /** * Load an item and parse the Response as text * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response */ this.loadText = async item => { const response = await AsyncPreloader.fetchItem(item); return await response.text(); }; /** * Load an item and parse the Response as json * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response */ this.loadJson = async item => { const response = await AsyncPreloader.fetchItem(item); return await response.json(); }; /** * Load an item and parse the Response as arrayBuffer * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response */ this.loadArrayBuffer = async item => { const response = await AsyncPreloader.fetchItem(item); return await response.arrayBuffer(); }; /** * Load an item and parse the Response as blob * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response */ this.loadBlob = async item => { const response = await AsyncPreloader.fetchItem(item); return await response.blob(); }; /** * Load an item and parse the Response as formData * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response */ this.loadFormData = async item => { const response = await AsyncPreloader.fetchItem(item); return await response.formData(); }; // Custom loaders /** * Load an item in one of the following cases: * - item's "loader" option set as "Image" * - item's "src" option extensions matching the loaders Map * - direct call of the method * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response according to the "body" option. Defaults to an HTMLImageElement with a blob as srcObject or src. */ this.loadImage = async item => { const response = await AsyncPreloader.fetchItem(item); const data = await response[item.body || this.defaultBodyMethod](); if (item.body) return data; const image = new Image(); return await new Promise((resolve, reject) => { image.addEventListener("load", function load() { image.removeEventListener("load", load); resolve(image); }); image.addEventListener("error", function error() { image.removeEventListener("error", error); reject(image); }); image.src = URL.createObjectURL(data); }); }; /** * Load an item in one of the following cases: * - item's "loader" option set as "Video" * - item's "src" option extensions matching the loaders Map * - direct call of the method * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response according to the "body" option. Defaults to an HTMLVideoElement with a blob as src. */ this.loadVideo = async item => { const response = await AsyncPreloader.fetchItem(item); const data = await response[item.body || this.defaultBodyMethod](); if (item.body) return data; const video = document.createElement("video"); return await new Promise((resolve, reject) => { video.addEventListener("canplaythrough", function canplaythrough() { video.removeEventListener("canplaythrough", canplaythrough); resolve(video); }); video.addEventListener("error", function error() { video.removeEventListener("error", error); reject(video); }); try { if (isSafari) throw ""; video.srcObject = data; } catch (error) { video.src = URL.createObjectURL(data); } video.load(); }); }; /** * Load an item in one of the following cases: * - item's "loader" option set as "Audio" * - item's "src" option extensions matching the loaders Map * - direct call of the method * * @param {LoadItem} item Item to load * @returns {Promise<LoadedValue>} Fulfilled value of parsed Response according to the "body" option. Defaults to an HTMLAudioElement with a blob as srcObject or src. */ this.loadAudio = async item => { const response = await AsyncPreloader.fetchItem(item); const data = await response[item.body || this.defaultBodyMethod](); if (item.body) return data; const audio = document.createElement("audio"); audio.autoplay = false; audio.preload = "auto"; return await new Promise((resolve, reject) => { audio.addEventListener("canplaythrough", function canplaythrough() { audio.removeEventListener("canplaythrough", canplaythrough); resolve(audio); }); audio.addEventListener("error", function error() { audio.removeEventListener("error", error); reject(audio); }); try { if (isSafari) throw ""; audio.srcObject = data; } catch (error) { audio.src = URL.createObjectURL(data); } audio.load(); }); }; /** * Load an item in one of the following cases: * - item's "loader" option set as "Xml" * - item's "src" option extensions matching the loaders Map * - direct call of the method * * @param {LoadItem} item Item to load (need a mimeType specified or default to "application/xml") * @returns {Promise<LoadedXMLValue>} Result of Response parsed as a document. */ this.loadXml = async item => { if (!item.mimeType) { const extension = AsyncPreloader.getFileExtension(item.src); item = { ...item, mimeType: AsyncPreloader.getMimeType(LoaderKey.Xml, extension) }; } const response = await AsyncPreloader.fetchItem(item); const data = await response.text(); return AsyncPreloader.domParser.parseFromString(data, item.mimeType); }; /** * Load a font via a FontFaceObserver instance * * @param {LoadItem} item Item to load (id correspond to the fontName). * @returns {Promise<string>} Fulfilled value with fontName initial id. */ this.loadFont = async item => { const fontName = item.id; const font = new FontFaceObserver(fontName, item.options || {}); await font.load(); return fontName; }; } // Utils /** * Fetch wrapper for LoadItem * * @param {LoadItem} item Item to fetch * @returns {Promise<Response>} Fetch response */ static fetchItem(item) { return fetch(item.src, item.options || {}); } /** * Get an object property by its path in the form 'a[0].b.c' or ['a', '0', 'b', 'c']. * Similar to [lodash.get](https://lodash.com/docs/4.17.5#get). * * @param {any} object Object with nested properties * @param {(string | string[])} path Path to the desired property * @returns {any} The returned object property */ static getProp(object, path) { const p = Array.isArray(path) ? path : path.split(".").filter(index => index.length); if (!p.length) return object; return AsyncPreloader.getProp(object[p.shift()], p); } /** * Get file extension from path * * @param {(RequestInfo | string)} path * @returns {string} */ static getFileExtension(path) { return (path.match(/[^\\/]\.([^.\\/]+)$/) || [null]).pop(); } /** * Retrieve loader key from extension (when the loader option isn't specified in the LoadItem) * * @param {string} extension * @returns {LoaderKey} */ static getLoaderKey(extension) { const loader = Array.from(AsyncPreloader.loaders).find(loader => loader[1].extensions.includes(extension)); return loader ? loader[0] : LoaderKey.Text; } /** * Retrieve mime type from extension * * @param {LoaderKey} loaderKey * @param {string} extension * @returns {string} */ static getMimeType(loaderKey, extension) { const loader = AsyncPreloader.loaders.get(loaderKey); return loader.mimeType[extension] || loader.defaultMimeType; } }
JavaScript
class Logger { /** * @param {Config} config Configuration */ constructor(config) { this.config = config || new Config(); } /** * Prints out application version. * * @returns {Logger} This object */ init() { this.log(`${kleur.green('Díjnet')}${kleur.blue('Bot')} v${packageInfo.version} ${kleur.reset('by juzraai | https://github.com/juzraai/dijnet-bot')}\n`, kleur.white, true, true, false); return this; } /** * Prints out the given message to standard output. Clears the current * line before writing out the message. Applying newlines before or * after the message is configurable. * * @param {string} message Message * @param {kleur.Color} colorFunc Kleur color function * @param {boolean} bold Whether message should be displayed with bold font * @param {boolean} closeLineAfter Whether newline is needed after message (otherwise the current line will be overwritten by the next one) * @param {boolean} closeLineBefore Whether newline is needed before message (otherwise the current line will overwrite the previous one) */ log(message, colorFunc, bold, closeLineAfter, closeLineBefore) { if (this.config.quiet) { return; } let s = message; if (this.config.verbose) { s = s.trim() .split('\n') .filter(line => line.trim().length > 0) .join('\n'); } if (this.config.tty) { if (bold) { s = kleur.bold(s); } if (colorFunc) { s = colorFunc(s); } } if (this.config.verbose || !this.config.tty) { const ts = getTimestamp(); console.log(s.split('\n').map(line => kleur.reset().gray(`${ts} | `) + line).join('\n')); return; } // not quiet, not verbose, not TTY -> progress screen! if (closeLineBefore) { process.stdout.write('\n'); } process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(s); if (closeLineAfter) { process.stdout.write('\n'); } } /** * Prints out an error message in red. Makes sure it will be printed into a * new line and also closes the line after the message to prevent * overwrites. If error stack is available it will be printed to file. * * @param {(string|Error)} error Error message or object */ error(error) { this.log(error.message || error, kleur.red, true, true, true); if (error.stack) { const s = '\nHa biztos vagy abban, hogy helyesen konfiguráltad a Díjnet Bot-ot, akkor a hiba a programban lehet.\nKérlek, az alábbi linken nyiss egy új issue-t, másold be a hiba részleteit, és írd le röviden, milyen szituációban jelentkezett a hiba!\n\n--> https://github.com/juzraai/dijnet-bot/issues\n\n'; this.log(s, kleur.red, true, false); try { fs.writeFileSync(this.config.errorFile, `${getTimestamp()}: ${error.message}\n${error.stack}`); this.log(`A hiba részleteit megtalálod a(z) ${this.config.errorFile} fájlban.`, kleur.red, true); } catch (_) { this.log('A hiba részletei:', kleur.red, true, false); this.log(error.stack, kleur.red, false, false); } } } /** * Prints out a success message in green. Overwrites the previous line, but * makes sure this message won't be overwritten. * * @param {string} message Message indicating success */ success(message) { this.log(message, kleur.green, true, true, false); } /** * Prints out an info message. Overwrites the previous line and this * message will also be overwritten by the next one. * * @param {string} message Message informing about an operation in progress */ info(message) { this.log(message, null, false, false, false); } /** * Prints out a verbose-level (trace) message in grey. Overwrites the * previous line and this message will also be overwritten by the next one. * * @param {string} message Message describing a detail of a process */ verbose(message) { if (this.config.verbose) { this.log(message, kleur.grey, false, false, false); } } }
JavaScript
class Network { /** * Initializes a new instance of the {@link Network} class with the given devices and connections. * @param {!Array.<Device>} devices The devices in the network. * @param {!Array.<Connection>} connections The connections in the network. */ constructor(devices, connections) { // The devices in the model. this.devices = devices // The connections in the model. this.connections = connections } /** * Returns the connections having the given device as either sender or receiver. * @param {!Device} device The device to find connected connections of. * @returns {!Array.<Connection>} The connections that are connected to the device. */ getAdjacentConnections(device) { return this.connections.filter(connection => Network.isAdjacentConnection(connection, device)) } /** * Checks whether the given connection is adjacent to the given device. * @private * @param {!Connection} connection * @param {!Device} device * @returns {boolean} */ static isAdjacentConnection(connection, device) { return connection.sender === device || connection.receiver === device } /** * Returns the devices that are neighbors of the given device, that is, devices that are * directly connected to the given device via an connection. * @param {!Device} device The device to find neighbors of. * @returns {!Array.<Device>} The neighboring devices. */ getNeighborDevices(device) { return this.getAdjacentConnections(device).map(connection => Network.getOppositeDevice(device, connection) ) } /** * Returns the device at the opposite side of the connection with respect to the given device. * @private * @param {!Device} device * @param {!Connection} connection * @returns {!Device} */ static getOppositeDevice(device, connection) { return connection.sender === device ? connection.receiver : connection.sender } }
JavaScript
class ContentRewriter { constructor(content) { this.content = content; } element(element) { element.setInnerContent(this.content); } }
JavaScript
class AttributeRewriter { constructor(attributeName, content) { this.attributeName = attributeName; this.content = content; } element(element) { if (element.getAttribute(this.attributeName)) { element.setAttribute(this.attributeName, this.content); } } }
JavaScript
class ToastService { @observable toasts = []; /** * Creates a new toast that is added to the list. * * @param toast object with the following shape: * { * text: string, message text to display * action: string, text for action link * onActionClick: function, callback to invoke when action link is clicked * onDismiss: function, callback to invoke when toast is dismissed (immediately, or after timeout) * dismissDelay: number, duration in millis after which to auto-dismiss this Toast * id: unique identifier (optional, will be autogenerated if omitted) * } * @returns {number} unique ID of toast */ @action newToast(toast) { // prevent duplicate toasts from appearing when multiple UI elements // are listening for an event that triggers creation of a toast if (this._hasDuplicate(toast)) { return null; } const newToast = toast; if (!newToast.id) { newToast.id = Math.random() * Math.pow(10, 16); } this.toasts.push(newToast); return newToast.id; } /** * Removes a toast with the matching value of toast.id. * * @param toast */ @action removeToast(toast) { this.toasts = this.toasts.filter(item => toast.id !== item.id); } @computed get count() { return this.toasts ? this.toasts.length : 0; } /** * Returns true if a toast with the same 'text' and 'action' already exists * @param newToast * @returns {boolean} * @private */ _hasDuplicate(newToast) { for (const toast of this.toasts) { if (toast.text === newToast.text && toast.action === newToast.action) { return true; } } return false; } }
JavaScript
class Every extends Component { render() { const { collection, predicate, fallback, ...baseProps } = this.props; const filteredCollection = filterBy({ collection, predicate, component: 'Every', }); const isEmpty = collection.length === 0; const notAllMatch = filteredCollection.length < collection.length; if (isEmpty || notAllMatch) { return fallback; } return ( <BaseCollectionHelper collection={collection} {...baseProps} /> ); } }
JavaScript
class AccountName extends React.PureComponent { static propTypes = { /** @ignore */ wallet: PropTypes.object.isRequired, /** @ignore */ accountNames: PropTypes.array.isRequired, /** @ignore */ additionalAccountMeta: PropTypes.object.isRequired, /** @ignore */ additionalAccountName: PropTypes.string.isRequired, /** @ignore */ setAccountInfoDuringSetup: PropTypes.func.isRequired, /** @ignore */ history: PropTypes.object.isRequired, /** @ignore */ generateAlert: PropTypes.func.isRequired, /** @ignore */ t: PropTypes.func.isRequired, }; state = { name: this.props.additionalAccountName && this.props.additionalAccountName.length ? this.props.additionalAccountName : '', }; /** * 1. Check for valid accout name * 2. In case onboarding seed does not exists, navigate to Seed generation view * 3. In case of additional seed, navigate to Login view * 4. In case of first seed, but seed already set, navigate to Account name view * @param {Event} event - Form submit event * @returns {undefined} */ setName = async (event) => { event.preventDefault(); const { wallet, accountNames, history, generateAlert, t } = this.props; const name = this.state.name.replace(/^\s+|\s+$/g, ''); if (!name.length) { generateAlert('error', t('addAdditionalSeed:noNickname'), t('addAdditionalSeed:noNicknameExplanation')); return; } if (name.length > MAX_ACC_LENGTH) { generateAlert( 'error', t('addAdditionalSeed:accountNameTooLong'), t('addAdditionalSeed:accountNameTooLongExplanation', { maxLength: MAX_ACC_LENGTH }), ); return; } if (accountNames.map((accountName) => accountName.toLowerCase()).indexOf(name.toLowerCase()) > -1) { generateAlert('error', t('addAdditionalSeed:nameInUse'), t('addAdditionalSeed:nameInUseExplanation')); return; } this.props.setAccountInfoDuringSetup({ name: this.state.name, completed: !Electron.getOnboardingGenerated() && accountNames.length > 0, }); if (Electron.getOnboardingGenerated()) { history.push('/onboarding/seed-save'); } else { if (accountNames.length > 0) { const seedStore = await new SeedStore.keychain(wallet.password); await seedStore.addAccount(this.state.name, Electron.getOnboardingSeed()); history.push('/onboarding/login'); } else { history.push('/onboarding/account-password'); } } }; stepBack = (e) => { if (e) { e.preventDefault(); } const { history, additionalAccountMeta } = this.props; if (additionalAccountMeta.type === 'ledger') { return history.push('/onboarding/seed-ledger'); } if (Electron.getOnboardingGenerated()) { history.push('/onboarding/seed-generate'); } else { Electron.setOnboardingSeed(null); history.push('/onboarding/seed-verify'); } }; render() { const { t } = this.props; const { name } = this.state; return ( <form onSubmit={this.setName}> <section> <h1>{t('setSeedName:letsAddName')}</h1> <p>{t('setSeedName:canUseMultipleSeeds')}</p> <Input value={name} focus label={t('addAdditionalSeed:accountName')} onChange={(value) => this.setState({ name: value })} /> </section> <footer> <Button id="account-name-prev" onClick={this.stepBack} className="square" variant="dark"> {t('goBackStep')} </Button> <Button id="account-name-next" type="submit" className="square" variant="primary"> {t('continue')} </Button> </footer> </form> ); } }
JavaScript
class InterceptorInvocation { constructor(_next, _interceptor) { this._next = _next; this._interceptor = _interceptor; } get design() { return this._next.design; } invoke(params, receiver) { return this._interceptor.intercept(this._next, params, receiver); } }
JavaScript
class StateOptions { /** * Constructor. * @param {string} title The state title */ constructor(title) { /** * The state description * @type {?string} */ this.description = null; /** * If the state should be loaded on save * @type {boolean} */ this.load = false; /** * The persistence method to use when saving the state * @type {IPersistenceMethod} */ this.method = null; /** * The states to save/load * @type {Array<!IState>} */ this.states = null; /** * The state tags/keywords * @type {?string} */ this.tags = null; /** * The state title * @type {string} */ this.title = title; } }
JavaScript
class ScriptManager { /** * Create the ScriptManager. * <p> * <strong>Note: Only to be called by framework code. Applications should * retrieve instances from {@link BusinessNetworkDefinition}</strong> * </p> * @param {ModelManager} modelManager - The ModelManager to use for this ScriptManager */ constructor(modelManager) { this.modelManager = modelManager; this.scripts = {}; } /** * Visitor design pattern * @param {Object} visitor - the visitor * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ accept(visitor,parameters) { return visitor.visit(this, parameters); } /** * Creates a new Script from a string. * * @param {string} identifier - the identifier of the script * @param {string} language - the language identifier of the script * @param {string} contents - the contents of the script * @returns {Script} - the instantiated script */ createScript(identifier, language, contents) { return new Script(this.modelManager, identifier, language, contents ); } /** * Adds a Script to the ScriptManager * @param {Script} script - The script to add to the ScriptManager */ addScript(script) { this.scripts[script.getIdentifier()] = script; } /** * Update an existing Script in the ScriptManager * @param {Script} script - The script to add to the ScriptManager */ updateScript(script) { if (!this.scripts[script.getIdentifier()]) { throw new Error('Script file does not exist'); } this.addScript(script); } /** * Remove the Script * @param {string} identifier - The identifier of the script to remove * delete. */ deleteScript(identifier) { if (!this.scripts[identifier]) { throw new Error('Script file does not exist'); } delete this.scripts[identifier]; } /** * Get the array of Script instances * @return {Script[]} The Scripts registered * @private */ getScripts() { let keys = Object.keys(this.scripts); let result = []; for(let n=0; n < keys.length;n++) { result.push(this.scripts[keys[n]]); } return result; } /** * Remove all registered Composer files */ clearScripts() { this.scripts = {}; } /** * Get the Script associated with an identifier * @param {string} identifier - the identifier of the Script * @return {Script} the Script * @private */ getScript(identifier) { return this.scripts[identifier]; } /** * Get the identifiers of all registered scripts * @return {string[]} The identifiers of all registered scripts */ getScriptIdentifiers() { return Object.keys(this.scripts); } }
JavaScript
class Vector { constructor(x = 0, y = 0) { this.x = x; this.y = y; } get val() { return [this.x, this.y] } set val(arr) { this.x = arr[0]; this.y = arr[1]; } copy() { return new Vector(this.x, this.y); } randomise(factor = 1) { let l = this.length; this.x = 2 * Math.random() - 1; this.y = 2 * Math.random() - 1; this.length = l === 0 ? factor : factor * l; } random(factor = 1) { let result = new Vector(); result.randomise(factor); return result; } plus(vector) { return new Vector(this.x + vector.x, this.y + vector.y); } add(vector) { this.x += vector.x; this.y += vector.y; } minus(vector) { return new Vector(this.x - vector.x, this.y - vector.y); } subtract(vector) { this.x -= vector.x; this.y -= vector.y; } times(num) { return new Vector(this.x * num, this.y * num); } multiply(num) { this.x *= num; this.y *= num; } get length() { return Math.sqrt(this.x ** 2 + this.y ** 2); } set length(new_length) { this.norm(); this.multiply(new_length) } get direction() { let result = this.copy(); result.norm(); return result; } norm() { let factor = 1 / this.length; if (isFinite(factor)) { this.multiply(factor); } } stretch(new_length = 1) { let result = this.copy(); result.length = new_length; return result; } to(vector) { return vector.minus(this); } distanceTo(vector) { return this.to(vector).length; } equals(vector) { return this.distanceTo(vector) < 0.0001; } dot(vector) { return (this.x * vector.x) + (this.y * vector.y); } }
JavaScript
class Interval { constructor(start, end, open = false) { let sorted = [start, end].sort((a,b) => a - b); this.start = sorted[0]; this.end = sorted[1]; this.open = false; } intersect(interval) { return !(interval.end < this.start || this.end < interval.start); } closestValueTo(num) { if (num < this.start) { return this.start; } else if (this.end < num) { return this.end; } else { return num; } } whereis(num) { if (this.open) { if (num <= this.start) { return 'lo'; } else if (this.end <= num) { return 'hi'; } else { return 'in'; } } else { if (num < this.start) { return 'lo'; } else if (this.end < num) { return 'hi'; } else { return 'in'; } } } }
JavaScript
class RefHolder { constructor() { this.emitter = new Emitter(); this.value = undefined; } isEmpty() { return this.value === undefined || this.value === null; } get() { if (this.isEmpty()) { throw new Error('RefHolder is empty'); } return this.value; } getOr(def) { if (this.isEmpty()) { return def; } return this.value; } getPromise() { if (this.isEmpty()) { return new Promise(resolve => { const sub = this.observe(value => { resolve(value); sub.dispose(); }); }); } return Promise.resolve(this.get()); } map(present, absent = () => this) { return RefHolder.on(this.isEmpty() ? absent() : present(this.get())); } setter = value => { const oldValue = this.value; this.value = value; if (value !== oldValue && value !== null && value !== undefined) { this.emitter.emit('did-update', value); } } observe(callback) { if (!this.isEmpty()) { callback(this.value); } return this.emitter.on('did-update', callback); } static on(valueOrHolder) { if (valueOrHolder instanceof this) { return valueOrHolder; } else { const holder = new this(); holder.setter(valueOrHolder); return holder; } } }
JavaScript
class RedditHover { constructor(node, CURRENT_TAB) { this.boundNode = node; this.redirectLink = node.href; this.linkType = this.checkLinkType(); this.CURRENT_TAB = CURRENT_TAB; } /* Description: This function is unique to every Hover class, * its goal is to determine which type of embed should be chosen for the link. * it can also delete the whole class if there is no point in having an embed. */ checkLinkType() { /* As comments are the only thing implemented for now let's ignore the rest TODO : - Implement users when on other sites - Implement discussions (couldn't get discussion embed code from reddit when I tried (bug?)) if (this.redirectLink.includes('/user/')) { return 'user'; } else if (this.redirectLink.replace('https://', '').split('/').length == 7 && !this.boundNode.classList.length && !this.redirectLink.includes('#')) { return 'post'; } else */ if (this.redirectLink.replace('https://', '').split('/').length == 8 && !this.boundNode.classList.length && !this.redirectLink.includes('#')) { return 'comment'; } else { return 'unknown'; } } bindToNode() { if (this.linkType == 'comment') { /* Building node using js functions is required by Firefox to get the permission to publish the extension officialy * (At least I had to do it the last time I did one). * Also the commentContainer is needed as rembeddit overwrites the comment to an iframe and the iframe is not affected by class change. */ let commentContainer = document.createElement('div'); commentContainer.className = 'tooltiptext'; /* This is a reconstitution of the reddit embed code when sharing a comment.*/ let comment = document.createElement('div'); comment.setAttribute('data-embed-media', 'www.redditmedia.com'); comment.setAttribute('data-embed-parent', 'false'); comment.setAttribute('data-embed-live', 'false'); comment.setAttribute('data-embed-created', `${new Date().toISOString()}`); comment.className = 'reddit-embed'; let commentDirectLink = document.createElement('a'); commentDirectLink.href = `${this.redirectLink}?`; commentDirectLink.appendChild(document.createTextNode('Comment')); let discussionDirectLink = document.createElement('a'); discussionDirectLink.href = `${this.redirectLink.split('/').slice(0, this.redirectLink.split('/').length - 1).join('/')}?`; discussionDirectLink.appendChild(document.createTextNode('discussion')); comment.appendChild(commentDirectLink); comment.appendChild(document.createTextNode('from discussion')); comment.appendChild(discussionDirectLink); commentContainer.appendChild(comment); this.boundNode.appendChild(commentContainer); /* Because for some reason embed code doesn't init itself directly when added dynamically, depends directly of reddit-comment-embed.js */ window.rembeddit.init(); this.boundNode.classList.add('tooltip'); comment.classList.add('tooltiptext'); } } }
JavaScript
class TesterAppWithReleaseResponse { /** * Create a TesterAppWithReleaseResponse. * @property {string} [id] The unique ID (UUID) of the app * @property {object} [release] * @property {number} [release.id] ID identifying this unique release. * @property {string} [release.version] The release's version.<br> * For iOS: CFBundleVersion from info.plist.<br> * For Android: android:versionCode from AppManifest.xml. * @property {string} [release.origin] The release's origin. Possible values * include: 'hockeyapp', 'appcenter' * @property {string} [release.shortVersion] The release's short version.<br> * For iOS: CFBundleShortVersionString from info.plist.<br> * For Android: android:versionName from AppManifest.xml. * @property {boolean} [release.mandatoryUpdate] A boolean which determines * whether the release is a mandatory update or not. * @property {string} [release.uploadedAt] UTC time in ISO 8601 format of the * uploaded time. * @property {boolean} [release.enabled] This value determines the whether a * release currently is enabled or disabled. * @property {boolean} [release.isExternalBuild] This value determines if a * release is external or not. * @property {number} [release.size] The release's size in bytes. * @property {string} [release.installUrl] The href required to install a * release on a mobile device. On iOS devices will be prefixed with * `itms-services://?action=download-manifest&url=` * @property {string} [release.releaseNotes] The release's release notes. * @property {string} [name] The app's name. * @property {string} [displayName] The app's display name. * @property {string} [description] The description of the app * @property {string} [iconUrl] A URL to the app's icon. * @property {string} [os] The app's os. * @property {object} [owner] The information about the app's owner * @property {string} [owner.id] The unique id (UUID) of the owner * @property {string} [owner.avatarUrl] The avatar URL of the owner * @property {string} [owner.displayName] The owner's display name * @property {string} [owner.email] The owner's email address * @property {string} [owner.name] The unique name that used to identify the * owner * @property {string} [owner.type] The owner type. Can either be 'org' or * 'user'. Possible values include: 'org', 'user' */ constructor() { } /** * Defines the metadata of TesterAppWithReleaseResponse * * @returns {object} metadata of TesterAppWithReleaseResponse * */ mapper() { return { required: false, serializedName: 'TesterAppWithReleaseResponse', type: { name: 'Composite', className: 'TesterAppWithReleaseResponse', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, release: { required: false, serializedName: 'release', type: { name: 'Composite', className: 'TesterAppWithReleaseResponseRelease' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, displayName: { required: false, serializedName: 'display_name', type: { name: 'String' } }, description: { required: false, serializedName: 'description', type: { name: 'String' } }, iconUrl: { required: false, serializedName: 'icon_url', type: { name: 'String' } }, os: { required: false, serializedName: 'os', type: { name: 'String' } }, owner: { required: false, serializedName: 'owner', type: { name: 'Composite', className: 'TesterAppWithReleaseResponseOwner' } } } } }; } }
JavaScript
class CardanoExplorer extends Driver { constructor(options) { super({ blockchain: 'Cardano', timeout: 200, // 5 requests per second supports: { balances: true, }, options, }); } /** * @augments Driver.fetchTotalSupply */ async fetchTotalSupply() { const data = await this.request('https://cardanoexplorer.com/api/genesis/summary/'); const redeemed = parseInt(data.Right.cgsRedeemedAmountTotal.getCoin, 10); const unredeemed = parseInt(data.Right.cgsNonRedeemedAmountTotal.getCoin, 10); return (redeemed + unredeemed) / 1000000; } /** * @augments Driver.fetchBalance * @param {modifierParam} modifier {@link modifierParam} * @async */ async fetchBalance(modifier) { const data = await this.request(`https://cardanoexplorer.com/api/addresses/summary/${modifier}`); const balance = data.Right.caBalance.getCoin / 1000000; if (data.Right.caBalance.getCoin < 0) { return 0; } return balance; } /** * @augments Driver.getSupply * @param {coinParam} coin {@link coinParam} */ async getSupply(coin) { const total = await this.fetchTotalSupply(); const modifiersWithBalances = await promisesMap( coin.modifiers, (modifier) => this .fetchBalance(modifier) .then((balance) => ({ reference: modifier, balance })), ); const circulating = modifiersWithBalances .reduce((current, modifier) => current - modifier.balance, total); return new Supply({ total, circulating, modifiers: modifiersWithBalances, }); } }
JavaScript
class AccordionElement extends HTMLElement { #title #id #isOpen #group #titleElement #bodyElement #parentAccordion #initialParentAccordionHeight constructor({title, id, isOpen, group} = {}) { super(); // TODO make these variables private once all major browsers support private variables this.#title = title ?? this.dataset.title ?? ''; this.#id = id ?? this.dataset.id ?? idCounter++; this.#isOpen = isOpen ?? this.dataset.isOpen ?? false; this.#group = group ?? this.dataset.group ?? ''; // add the accordion to the list window.accordions.push(this); this.#parentAccordion = null; } // ============================================================================== // TODO make this method private once safari supports private fields and methods // ============================================================================== _createTitleElement() { // if we already have a div with the class ploiu-accordion-title, skip all this and just return the element. This allows the developer to set their own custom html titles const existingTitle = this.querySelector('div.ploiu-accordion-title') if (existingTitle) { existingTitle.addEventListener('click', () => this.toggle()); return existingTitle; } else { const element = document.createElement('div'); element.classList.add('ploiu-accordion-title'); element.innerText = this.#title; element.addEventListener('click', () => this.toggle()); return element; } } _createBodyElement() { // if the developer already specified an accordion body, just return that instead of creating it all ourselves const existingBody = this.querySelector('div.ploiu-accordion-body') if (existingBody) { return existingBody; } else { const element = document.createElement('div'); element.classList.add('ploiu-accordion-body'); // add all the child nodes from this element to the body element const trueChildren = [...this.childNodes].filter(it => !it.classList?.contains('ploiu-accordion-title')) for (let child of trueChildren) { // always get the 0th index since we'll be removing the node later const node = child; element.appendChild(node.cloneNode(true)); node.remove(); } return element; } } /** * the internal, read only id of this accordion element * @returns {number} */ get id() { return this.#id; } get group() { return this.#group; } set group(value) { this.#group = value; this.dataset.group = value; } get title() { return this.#title; } /** * sets the contents of our title * @param {string|Node} value */ set title(value) { if (typeof value === 'string') { this.#title = value; this.#titleElement.innerText = value; } else if (value instanceof Node) { this.#title = ''; this.#titleElement.innerText = ''; // first clear the titleElement's children [...this.#titleElement.children].forEach(it => it.remove()); // now append our value to the title element this.#titleElement.appendChild(value) } } get isOpen() { return this.#isOpen; } /** * make this private once private fields and methods are a thing * @returns {HTMLDivElement} the div element that acts as the wrapper for the accordion's body * * @private */ get bodyElement() { return this.#bodyElement; } /** * Sets the contents of this accordion's body element. * @param {HTMLElement} value */ set body(value) { // first remove all the contents from our accordion body Array.from(this.#bodyElement.children).forEach(el => el?.remove()); // now add the contents of the value to the body element this.#bodyElement.appendChild(value); } /** * Opens the accordion and displays the contents inside of it */ expand() { // hide all other open accordions in the same group AccordionElement.findAccordionsByGroup(this.#group).filter(accordion => accordion !== this && accordion !== this.#parentAccordion).forEach(accordion => accordion.collapse()); this.#isOpen = true; // set the height of the body to be the scroll height of the body and all other accordion bodies underneath this.#bodyElement.style.height = `${this.#bodyElement.scrollHeight}px`; // if the parent element is an accordion, increase the height of it to accommodate if (this.#parentAccordion?.isOpen) { // add the height of our accordion minus the height of our title element. this.#parentAccordion.bodyElement.style.height = Number.parseFloat(this.#parentAccordion.bodyElement.style.height.replace(/px/, '')) // we manually set the pixel height of the element, so this is ok to do + this.bodyElement.scrollHeight + 'px'; } this.classList.add('open'); } /** * Closes the accordion and hides the contents inside of it */ collapse() { if (this.#isOpen) { this.#isOpen = false; // if our parent is an accordion element, reduce the size back to the initial height if (this.#parentAccordion) { this.#parentAccordion.bodyElement.style.height = this.#parentAccordion.bodyElement.clientHeight - this.bodyElement.scrollHeight + 'px'; } this.#bodyElement.style.height = '0'; this.classList.remove('open'); // close all child accordions Array.from(this.querySelectorAll('accordion-element')).forEach(accordion => accordion.collapse()); } } /** * Toggles the open/closed state of the accordion */ toggle() { if (this.#isOpen) { this.collapse(); } else { this.expand(); } } /** * gets the first parent element whose tag matches 'ACCORDION-ELEMENT' and returns it * @returns {AccordionElement|null} the first accordion parent element if their is one, else null * @private */ _getParentAccordion() { let parents = []; let currentNode = this; while (currentNode?.parentNode) { parents.push(currentNode.parentNode); currentNode = currentNode.parentNode; } parents = parents.filter(el => el?.tagName === 'ACCORDION-ELEMENT'); return parents.length > 0 ? parents[0] : null; } /** * called when this node is connected to the DOM. * * An editor may say it's unused, but it's called by the browser and should not be removed * * @override */ connectedCallback() { // make sure we're actually connected before we do anything if (this.isConnected) { this.#titleElement = this._createTitleElement(); this.#bodyElement = this._createBodyElement(); // append children here and set up other dom-based attributes this.appendChild(this.#titleElement); this.appendChild(this.#bodyElement); // if the data-open attribute is set, expand this accordion if (this.dataset.open !== undefined || this.#isOpen) { this.expand(); } this.#parentAccordion = this._getParentAccordion(); if (this.#parentAccordion !== null) { this.#initialParentAccordionHeight = this.#parentAccordion.scrollHeight; } else { this.#initialParentAccordionHeight = 0; // reset this } } } /** * finds the registered accordion with the passed `id`, or `null` if none could be found. If there are multiple accordions with the same id, * the first one created on the page will be returned. * @param id {number} * @returns {null|AccordionElement} */ static findAccordionById(id) { try { return window.accordions.filter(accordion => accordion.id === id)[0]; } catch (exception) { return null; } } /** * Finds all accordions with the passed group, case insensitive, and returns them. * @param {string} group * @returns {AccordionElement[]} */ static findAccordionsByGroup(group) { return [...document.querySelectorAll('accordion-element')].filter(accordion => accordion.group.toLowerCase() === group.toLowerCase()); } }
JavaScript
class AccordionFan extends HTMLElement { connectedCallback() { if(this.isConnected) { // for each of our child accordion elements, set its group to be this object Array.from(this.querySelectorAll('accordion-element')).forEach(el => el.group = `fan-${idCounter}`); idCounter++; } } }
JavaScript
class Parameters { constructor(parameters) { this._parameters = parameters || [ ]; } /** * The list of {@link Parameter} items. * * @public * @returns {Parameter[]} */ get parameters() { return this._parameters; } /** * Throws an {@link Error} if the instance is invalid. * * @public */ validate() { if (!is.array(this._parameters)) { throw new Error('Parameters must be an array.'); } if (this._parameters.some(p => !(p instanceof Parameter))) { throw new Error('All parameter items must be instances of Parameters.'); } this._parameters.forEach(p => p.validate()); } static merge(a, b) { return new Parameters(a.parameters.slice(0).concat(b.parameters.filter(candidate => !a.parameters.some(existing => existing.key === candidate.key)))); } toString() { return `[Parameters]`; } }
JavaScript
class ReflectionClass { /** * Constructor. * * @param {string|Object} value */ constructor(value) { this._isInterface = false; this._isTrait = false; value = getClass.apply(this, [ value ]); this._methods = new Storage(); this._staticMethods = new Storage(); this._readableProperties = new Storage(); this._writableProperties = new Storage(); this._properties = new Storage(); this._constants = new Storage(); this._fields = new Storage(); this._staticFields = new Storage(); this._interfaces = []; this._traits = []; this._docblock = undefined; if (undefined !== value[Symbol.docblock]) { this._docblock = value[Symbol.docblock]; } if (undefined !== value[Symbol.reflection] && 'function' === typeof value[Symbol.reflection].isModule && value[Symbol.reflection].isModule(value)) { this._loadFromMetadata(value); } else { this._loadWithoutMetadata(value); } } /** * Checks if a class exists. * * @param {string} className */ static exists(className) { try { getClass(className); } catch (e) { if (e instanceof ReflectionException || e instanceof ClassNotFoundException) { return false; } throw e; } return true; } /** * Gets a class constructor given an object or a string * containing a FQCN. * * @param {string|Object} className */ static getClass(className) { return getClass(className); } /** * Gets a FQCN from an object, constructor or a string. * * @param {string|Object} className * * @returns {string} */ static getClassName(className) { try { return (new ReflectionClass(className)).name; } catch (e) { return 'Object'; } } /** * Construct a new object. * * @param {...*} varArgs Arguments to constructor * * @returns {*} */ newInstance(...varArgs) { return new this._constructor(...varArgs); } /** * Construct a new object without calling its constructor. * * @returns {*} */ newInstanceWithoutConstructor() { const surrogateCtor = function () { }; surrogateCtor.prototype = this._constructor.prototype; return new surrogateCtor(); } /** * Checks if this class contains a method. * * @param {string|Symbol} name * * @returns {boolean} */ hasMethod(name) { return this._methods[name] !== undefined || this._staticMethods[name] !== undefined; } /** * Gets the reflection method instance for a given method name. * * @param {string|Symbol} name * * @returns {ReflectionMethod} */ getMethod(name) { return new ReflectionMethod(this, name); } /** * Checks if class has defined property (getter/setter). * * @param {string|Symbol} name * * @returns {boolean} */ hasProperty(name) { return this._properties[name] !== undefined; } /** * Checks if class has readable property (getter). * * @param {string|Symbol} name * * @returns {boolean} */ hasReadableProperty(name) { return this._readableProperties[name] !== undefined; } /** * Gets the readable property (getter) reflection object. * * @param {string|Symbol} name * * @returns {ReflectionProperty} */ getReadableProperty(name) { return new ReflectionProperty(this, ReflectionProperty.KIND_GET, name); } /** * Checks if class has writable property (setter). * * @param {string|Symbol} name * * @returns {boolean} */ hasWritableProperty(name) { return this._writableProperties[name] !== undefined; } /** * Gets the writable property (setter) reflection object. * * @param {string|Symbol} name * * @returns {ReflectionProperty} */ getWritableProperty(name) { return new ReflectionProperty(this, ReflectionProperty.KIND_SET, name); } /** * Checks if class has defined the given class field. * * @param {string} name * * @returns {boolean} */ hasField(name) { return !! this._fields[name] || !! this._staticFields[name]; } /** * Gets the reflection field instance for a given field name. * * @param {string} name * * @returns {ReflectionField} */ getField(name) { return new ReflectionField(this, name); } /** * Gets the property descriptor. * * @param {string|Symbol} name * * @returns {*} */ getPropertyDescriptor(name) { if (undefined === this._properties[name]) { throw new ReflectionException('Property "' + name + '\' does not exist.'); } return this._properties[name]; } /** * Returns the ReflectionClass object for the parent class. * * @returns {ReflectionClass} */ getParentClass() { let parent = this._constructor; let r; while ((parent = Object.getPrototypeOf(parent))) { if (parent === Object || parent === Object.prototype) { return undefined; } try { r = new ReflectionClass(parent); } catch (e) { continue; } if (parent === r.getConstructor()[Symbol.for('_jymfony_mixin')]) { continue; } break; } try { return r; } catch (e) { return undefined; } } /** * Gets the class constructor. * * @returns {Function} */ getConstructor() { return this._constructor; } /** * Checks whether this class is a subclass of a given subclass. * * @param {Function|string} superClass * * @returns {boolean} */ isSubclassOf(superClass) { if ('string' === typeof superClass) { superClass = ReflectionClass._recursiveGet(global, superClass.split('.')); } return this._constructor.prototype instanceof superClass; } /** * Checks whether this class is an instance of the given class. * * @param {Function|string} superClass * * @returns {boolean} */ isInstanceOf(superClass) { if ('string' === typeof superClass) { superClass = ReflectionClass._recursiveGet(global, superClass.split('.')); } return this._constructor === superClass || this._constructor === new ReflectionClass(superClass).getConstructor() || this._constructor.prototype instanceof superClass; } /** * Is this class an interface? * * @returns {boolean} */ get isInterface() { return this._isInterface; } /** * Is this class a trait? * * @returns {boolean} */ get isTrait() { return this._isTrait; } /** * The fully qualified name of the reflected class. * * @returns {string|undefined} */ get name() { return this._className; } /** * The class short name (without namespace). * * @returns {string} */ get shortName() { return this._namespace ? this._className.substr(this.namespaceName.length + 1) : this._className; } /** * The Namespace object containing this class. * * @returns {null|Jymfony.Component.Autoloader.Namespace} */ get namespace() { return this._namespace || null; } /** * The namespace name. * * @returns {null|string} */ get namespaceName() { if (! this._namespace) { return null; } return this._namespace.name; } /** * Filename declaring this class. * * @returns {string} */ get filename() { return this._filename; } /** * Module object exporting this class. * * @returns {NodeJS.Module} */ get module() { return this._module; } /** * Get all methods names. * * @returns {string[]} */ get methods() { return [ ...Object.keys(this._methods), ...Object.keys(this._staticMethods) ]; } /** * Gets the docblock for this class. * * @returns {string} */ get docblock() { return this._docblock.class; } /** * Gets the fields names. * * @returns {Array} */ get fields() { return Object.keys(this._fields); } /** * Get properties name defined by setters/getters. * Other properties are added dynamically and are not * enumerable in the prototype. * * @returns {Array} */ get properties() { return Object.keys(this._properties); } /** * Get constants. * * @returns {Object.<string, *>} */ get constants() { return Object.assign({}, this._constants); } /** * Get interfaces reflection classes. * * @returns {ReflectionClass[]} */ get interfaces() { return [ ...this._interfaces ]; } /** * Get traits reflection classes. * * @returns {ReflectionClass[]} */ get traits() { return [ ...this._traits ]; } /** * Gets the class metadata. * * @returns {[Function, *][]} */ get metadata() { return MetadataStorage.getMetadata(this._constructor, null); } /** * @param {Object} value * * @private */ _loadFromMetadata(value) { const metadata = value[Symbol.reflection]; this._className = metadata.fqcn; this._namespace = metadata.namespace; if (TheBigReflectionDataCache.data[this._className]) { this._loadFromCache(); return; } this._filename = metadata.filename; this._module = metadata.module; this._constructor = this._isInterface || this._isTrait ? value : metadata.constructor; if (metadata.fields) { this._fields = metadata.fields; } const parent = this.getParentClass(); if (parent && parent.name) { const parentFields = parent._fields; for (const name of Object.keys(parentFields)) { if ('#' !== name[0] && ! (name in this._fields)) { this._fields[name] = parentFields[name]; } } } if (metadata.staticFields) { this._staticFields = metadata.staticFields; } this._loadProperties(); this._loadStatics(); if (undefined === TheBigReflectionDataCache.data[this._className]) { TheBigReflectionDataCache.data[this._className] = { filename: this._filename, module: this._module, constructor: this._constructor, methods: this._methods, staticMethods: this._staticMethods, constants: this._constants, properties: { all: this._properties, readable: Object.keys(this._readableProperties), writable: Object.keys(this._writableProperties), }, interfaces: this._interfaces, traits: this._traits, fields: this._fields, staticFields: this._staticFields, }; } } /** * @private */ _loadFromCache() { const data = TheBigReflectionDataCache.data[this._className]; const propFunc = function (storage, data) { for (const v of data) { storage[v] = true; } }; this._filename = data.filename; this._module = data.module; this._constructor = data.constructor; this._methods = data.methods; this._staticMethods = data.staticMethods; this._constants = data.constants; this._properties = data.properties.all; propFunc(this._readableProperties, data.properties.readable); propFunc(this._writableProperties, data.properties.writable); this._interfaces = data.interfaces; this._traits = data.traits; this._fields = data.fields; this._staticFields = data.staticFields; } /** * @private */ _loadWithoutMetadata(value) { this._className = value.name; this._module = ReflectionClass._searchModule(value); this._filename = this._module ? this._module.filename : undefined; this._constructor = value; this._namespace = undefined; this._loadProperties(); this._loadStatics(); } /** * @private */ _loadProperties() { const loadFromPrototype = (proto) => { if (undefined === proto || null === proto) { return; } const properties = [ ...Object.getOwnPropertyNames(proto), ...Object.getOwnPropertySymbols(proto) ]; for (const name of properties) { if ('constructor' === name || 'arguments' === name || 'caller' === name) { continue; } let descriptor; try { descriptor = Object.getOwnPropertyDescriptor(proto, name); } catch (e) { // Non-configurable property. continue; } if ('function' === typeof descriptor.value) { if ('__construct' === name) { continue; } this._methods[name] = { ...descriptor, ownClass: proto.constructor }; } else { if ('function' === typeof descriptor.get) { this._properties[name] = { ...descriptor, ownClass: proto.constructor }; this._readableProperties[name] = true; } if ('function' === typeof descriptor.set) { this._properties[name] = { ...descriptor, ownClass: proto.constructor }; this._writableProperties[name] = true; } } } }; let parent = this._constructor; const chain = [ this._constructor.prototype ]; if (! this._isInterface) { chain.push(Object.getPrototypeOf(this._constructor)); } while ((parent = Object.getPrototypeOf(parent))) { if (parent.prototype) { chain.unshift(parent.prototype); } } for (const p of chain) { loadFromPrototype(p); } if (this._isInterface || this._isTrait) { return; } for (const IF of global.mixins.getInterfaces(this._constructor)) { const reflectionInterface = new ReflectionClass(IF); this._interfaces.push(reflectionInterface); } for (const TR of global.mixins.getTraits(this._constructor)) { const reflectionTrait = new ReflectionClass(TR); this._traits.push(reflectionTrait); } } /** * @private */ _loadStatics() { const FunctionProps = [ ...Object.getOwnPropertyNames(Function.prototype), ...Object.getOwnPropertySymbols(Function.prototype) ]; let parent = this._constructor; const chain = [ this._constructor ]; while ((parent = Object.getPrototypeOf(parent))) { if (parent.prototype) { chain.unshift(parent.prototype.constructor); } } const consts = {}; for (parent of chain) { const names = [ ...Object.getOwnPropertyNames(parent), ...Object.getOwnPropertySymbols(parent) ] .filter(P => { if ('prototype' === P || Symbol.for('_jymfony_mixin') === P) { return false; } if ('arguments' === P || 'caller' === P) { // 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context. return false; } let descriptor; try { descriptor = Object.getOwnPropertyDescriptor(parent, P); } catch (e) { // Non-configurable property. return false; } if ('function' === typeof descriptor.value) { this._staticMethods[P] = { ...descriptor, ownClass: parent }; return false; } return -1 === FunctionProps.indexOf(P); }); for (const name of names) { if (Symbol.reflection === name) { continue; } if (! consts.hasOwnProperty(name) && Object.prototype.hasOwnProperty.call(parent, name)) { const descriptor = Object.getOwnPropertyDescriptor(parent, name); if (descriptor.hasOwnProperty('value')) { consts[name] = descriptor.value; } } } } this._constants = consts; } /** * @returns {Function} * * @private */ static _recursiveGet(start, parts) { let part; // Save autoload debug flag. const debug = __jymfony.autoload.debug; __jymfony.autoload.debug = false; try { const original = parts.join('.'); parts = [ ...parts ].reverse(); while ((part = parts.pop())) { if (undefined === start) { throw new ReflectionException('Requesting non-existent class ' + original); } start = start[part]; } return start; } finally { // Restore debug flag. __jymfony.autoload.debug = debug; } } /** * @private */ static _searchModule(value) { for (const moduleName of Object.keys(require.cache)) { const mod = require.cache[moduleName]; if (mod.exports === value) { return mod; } } return undefined; } }
JavaScript
class Http { /** * Create a new HTTP client. * @param {string} baseUrl The base URL to route all requests to. Omit trailing '/' */ constructor(baseUrl) { this.baseUrl = baseUrl; } /** * Make an HTTP GET request * @param {string} url The path of the request. * @param {{name: string, value: string}} param A query string parameter */ async get(url, param) { return this._makeRequest('GET', `${this.baseUrl}${url}?${param.name}=${encodeURIComponent(param.value)}`); } /** * Make an HTTP POST request. * @param {string} url The path of request. * @param {{}} body The JSON body content. */ async post(url, body) { return this._makeRequest('POST', `${this.baseUrl}${url}`, body); } async _makeRequest(method, url, body = null) { return new Promise(function(resolve, reject) { let xhr = new XMLHttpRequest(); xhr; xhr.open(method, url); xhr.onload = function() { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject({ status: this.status, statusText: xhr.statusText }); } }; xhr.onerror = function() { reject({ status: this.status, statusText: xhr.statusText }); }; if (body != null) { xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(body)); } else { xhr.send(); } }); } }
JavaScript
class HistoryViewer extends Component { constructor(props) { super(props); this.handleSetPage = this.handleSetPage.bind(this); this.handleNextPage = this.handleNextPage.bind(this); this.handlePrevPage = this.handlePrevPage.bind(this); } /** * Manually handle state changes in the page number, because Griddle doesn't support Redux. * See: https://github.com/GriddleGriddle/Griddle/issues/626 * * @param {object} prevProps */ componentDidUpdate(prevProps) { const { page: prevPage } = prevProps; const { page: currentPage, actions: { versions } } = this.props; if (prevPage !== currentPage && typeof versions.goToPage === 'function') { versions.goToPage(currentPage); } } /** * Reset the selected version when unmounting HistoryViewer to prevent data leaking * between instances */ componentWillUnmount() { const { onSelect } = this.props; if (typeof onSelect === 'function') { onSelect(0); } } /** * Returns the result of the GraphQL version history query * * @returns {Array} */ getVersions() { const { versions } = this.props; const edges = (versions && versions.Versions && versions.Versions.edges) ? versions.Versions.edges : []; return edges.map((version) => version.node); } /** * Get the latest (highest) version number from the list available. If we are not on page * zero then it's always false, because there are higher versions that we aren't aware of * in this context. * * @returns {object} */ getLatestVersion() { const { page } = this.props; // Page numbers are not zero based as they come from GriddlePage numbers if (page > 1) { return false; } return this.getVersions() .reduce((prev, current) => { if (prev.Version > current.Version) { return prev; } return current; }); } /** * Handles setting the pagination page number * * @param {number} page */ handleSetPage(page) { const { onSetPage } = this.props; if (typeof onSetPage === 'function') { // Note: data from Griddle is zero-indexed onSetPage(page + 1); } } /** * Handler for incrementing the set page */ handleNextPage() { const { page } = this.props; // Note: data for Griddle needs to be zero-indexed, so don't add 1 to this this.handleSetPage(page); } /** * Handler for decrementing the set page */ handlePrevPage() { const { page } = this.props; // Note: data for Griddle needs to be zero-indexed const currentPage = page - 1; if (currentPage < 1) { this.handleSetPage(currentPage); return; } this.handleSetPage(currentPage - 1); } /** * Renders the detail form for a selected version * * @returns {HistoryViewerVersionDetail} */ renderVersionDetail() { const { currentVersion, isPreviewable, recordId, recordClass, schemaUrl, VersionDetailComponent, } = this.props; // Insert variables into the schema URL via regex replacements const schemaReplacements = { ':id': recordId, ':class': recordClass, ':version': currentVersion, }; // eslint-disable-next-line no-shadow const version = this.getVersions().find(version => version.Version === currentVersion); const latestVersion = this.getLatestVersion(); const props = { isLatestVersion: latestVersion && latestVersion.Version === version.Version, isPreviewable, recordId, schemaUrl: schemaUrl.replace(/:id|:class|:version/g, (match) => schemaReplacements[match]), version, }; return ( <div className="history-viewer fill-height"> <VersionDetailComponent {...props} /> </div> ); } /** * Renders the react component for pagination. * Currently borrows the pagination from Griddle, to keep styling consistent * between the two views. * * See: ThumbnailView.js * * @returns {XML|null} */ renderPagination() { const { limit, page, versions } = this.props; if (!versions) { return null; } const totalVersions = versions.Versions ? versions.Versions.pageInfo.totalCount : 0; if (totalVersions <= limit) { return null; } const props = { setPage: this.handleSetPage, maxPage: Math.ceil(totalVersions / limit), next: this.handleNextPage, nextText: i18n._t('HistoryViewer.NEXT', 'Next'), previous: this.handlePrevPage, previousText: i18n._t('HistoryViewer.PREVIOUS', 'Previous'), // Note: zero indexed currentPage: page - 1, useGriddleStyles: false, }; return ( <div className="griddle-footer"> <Griddle.GridPagination {...props} /> </div> ); } /** * Renders a list of versions * * @returns {HistoryViewerVersionList} */ renderVersionList() { const { isPreviewable, ListComponent, onSelect } = this.props; return ( <div className="history-viewer fill-height"> <div className={isPreviewable ? 'panel panel--padded panel--scrollable' : ''}> <ListComponent onSelect={onSelect} versions={this.getVersions()} /> <div className="history-viewer__pagination"> {this.renderPagination()} </div> </div> </div> ); } render() { const { loading, currentVersion } = this.props; if (loading) { return <Loading />; } if (currentVersion) { return this.renderVersionDetail(); } return this.renderVersionList(); } }
JavaScript
class PathFactory { constructor(settings, data) { // Store settings and data this._settings = settings = { ...settings }; this._data = data = { ...data }; // Prepare the handlers const handlers = settings.handlers || defaultHandlers; for (const key in handlers) handlers[key] = toHandler(handlers[key]); for (const key of Object.getOwnPropertySymbols(handlers)) handlers[key] = toHandler(handlers[key]); // Prepare the resolvers const resolvers = (settings.resolvers || [ new LanguageResolver(), ]).map(toResolver); if (settings.context) { resolvers.push(new JSONLDResolver(settings.context)); settings.parsedContext = new ContextParser().parse(settings.context) .then(({ contextRaw }) => contextRaw); } else { settings.context = settings.parsedContext = {}; } // Instantiate PathProxy that will create the paths this._pathProxy = new PathProxy({ handlers, resolvers }); // Remove PathProxy settings from the settings object delete settings.handlers; delete settings.resolvers; } /** * Creates a path with the given (optional) settings and data. */ create(settings = {}, data) { // The settings parameter is optional if (!data) [data, settings] = [settings, null]; // Apply defaults on settings and data return this._pathProxy.createPath( Object.assign(Object.create(null), this._settings, settings), Object.assign(Object.create(null), this._data, data)); } }
JavaScript
class ServiceHealth extends models['EntityHealth'] { /** * Create a ServiceHealth. * @member {string} [name] The name of the service whose health information * is described by this object. * @member {array} [partitionHealthStates] The list of partition health * states associated with the service. */ constructor() { super(); } /** * Defines the metadata of ServiceHealth * * @returns {object} metadata of ServiceHealth * */ mapper() { return { required: false, serializedName: 'ServiceHealth', type: { name: 'Composite', className: 'ServiceHealth', modelProperties: { aggregatedHealthState: { required: false, serializedName: 'AggregatedHealthState', type: { name: 'String' } }, healthEvents: { required: false, serializedName: 'HealthEvents', type: { name: 'Sequence', element: { required: false, serializedName: 'HealthEventElementType', type: { name: 'Composite', className: 'HealthEvent' } } } }, unhealthyEvaluations: { required: false, serializedName: 'UnhealthyEvaluations', type: { name: 'Sequence', element: { required: false, serializedName: 'HealthEvaluationWrapperElementType', type: { name: 'Composite', className: 'HealthEvaluationWrapper' } } } }, healthStatistics: { required: false, serializedName: 'HealthStatistics', type: { name: 'Composite', className: 'HealthStatistics' } }, name: { required: false, serializedName: 'Name', type: { name: 'String' } }, partitionHealthStates: { required: false, serializedName: 'PartitionHealthStates', type: { name: 'Sequence', element: { required: false, serializedName: 'PartitionHealthStateElementType', type: { name: 'Composite', className: 'PartitionHealthState' } } } } } } }; } }
JavaScript
class NavigationLarge extends React.Component { constructor(props) { // Make our props accessible through this.props super(props); // Base styles to change transition state for // collapsing menu hero. this.state = { scrollClass: 'top', }; // Bind base functions to change transition state for // collapsing menu hero. this.handleScroll = this.handleScroll.bind(this); } // Make sure we are listening for scroll once mounted. componentDidMount() { window.addEventListener('scroll', this.handleScroll); } // Remove listener when not mounted. componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } // Base functions to change transition state for // navigation on scroll handleScroll(event) { if (window.scrollY === 0 && this.state.scrollClass === 'scroll') { this.setState({ scrollClass: 'top' }); } else if (window.scrollY !== 0 && this.state.scrollClass !== 'scroll') { this.setState({ scrollClass: 'scroll' }); } } render() { const Location = this.props.Location; const Routes = this.props.Routes; return ( <NavigationStyle> <NavigationStyle.Top className={'nav-top ' + this.state.scrollClass}> <NavigationStyle.Top.BrandingBlock> <HamburgerOverlayToggle> <figure /> <figure /> <figure /> </HamburgerOverlayToggle> <Link to="/"> <Brandmark /> </Link> </NavigationStyle.Top.BrandingBlock> <NavigationStyle.Top.LinkListBlock> <NavigationStyle.Top.TopLinkListWrapper location={Location} routes={Routes} > <LinkList /> </NavigationStyle.Top.TopLinkListWrapper> </NavigationStyle.Top.LinkListBlock> <NavigationStyle.Top.CommunicationBlock> <Icon Name="intercom" /> <Btn Label="View Our Menu" Destination="/menu" BgColor={Theme.Color.Primary} TextColor={Theme.Color.White} IconClass="plus" IconFas IconPosition="left" /> </NavigationStyle.Top.CommunicationBlock> </NavigationStyle.Top> <NavigationStyle.Bottom location={Location} routes={Routes} className="nav-bottom" > <NavigationStyle.Bottom.LinkListWrapper location={Location} routes={Routes} > <LinkList ActiveclassName="active" /> </NavigationStyle.Bottom.LinkListWrapper> </NavigationStyle.Bottom> </NavigationStyle> ); } }
JavaScript
class BroadBrushHelper { constructor () { // Direction vector of the last mouse move this.lastVec = null; // End point of the last mouse move this.lastPoint = null; // The path of the brush stroke we are building this.finalPath = null; // Number of points of finalPath that have already been processed this.smoothed = 0; // Number of steps to wait before performing another amortized smooth this.smoothingThreshold = 20; // Mouse moves since mouse down this.steps = 0; // End caps round out corners and are not merged into the path until the end. this.endCaps = []; } onBroadMouseDown (event, tool, options) { this.steps = 0; this.smoothed = 0; this.lastVec = null; tool.minDistance = Math.min( 5, Math.max(2 / paper.view.zoom, options.brushSize / 2) ); tool.maxDistance = options.brushSize; if (event.event.button > 0) return; // only first mouse button this.finalPath = new paper.Path.Circle({ center: event.point, radius: options.brushSize / 2 }); styleBlob(this.finalPath, options); this.lastPoint = event.point; } onBroadMouseDrag (event, tool, options) { this.steps++; const step = event.delta.normalize(options.brushSize / 2); // Add an end cap if the mouse has changed direction very quickly if (this.lastVec) { const angle = this.lastVec.getDirectedAngle(step); if (Math.abs(angle) > 126) { // This will cause us to skip simplifying this sharp angle. Running simplify on // sharp angles causes the stroke to blob outwards. this.simplify(1); this.smoothed++; // If the angle is large, the broad brush tends to leave behind a flat edge. // This code makes a shape to fill in that flat edge with a rounded cap. const circ = new paper.Path.Circle( this.lastPoint, options.brushSize / 2 ); circ.fillColor = options.fillColor; const rect = new paper.Path.Rectangle( this.lastPoint.subtract( new paper.Point(-options.brushSize / 2, 0) ), this.lastPoint.subtract( new paper.Point( options.brushSize / 2, this.lastVec.length ) ) ); rect.fillColor = options.fillColor; rect.rotate(this.lastVec.angle - 90, this.lastPoint); const rect2 = new paper.Path.Rectangle( event.point.subtract( new paper.Point(-options.brushSize / 2, 0) ), event.point.subtract( new paper.Point( options.brushSize / 2, event.delta.length ) ) ); rect2.fillColor = options.fillColor; rect2.rotate(step.angle - 90, event.point); this.endCaps.push(this.union(circ, this.union(rect, rect2))); } } step.angle += 90; // Move the first point out away from the drag so that the end of the path is rounded if (this.steps === 1) { // Replace circle with path this.finalPath.remove(); this.finalPath = new paper.Path(); const handleVec = event.delta.normalize(options.brushSize / 2); this.finalPath.add( new paper.Segment( this.lastPoint.subtract(handleVec), handleVec.rotate(-90), handleVec.rotate(90) ) ); styleBlob(this.finalPath, options); this.finalPath.insert( 0, new paper.Segment(this.lastPoint.subtract(step)) ); this.finalPath.add(new paper.Segment(this.lastPoint.add(step))); } // Update angle of the last brush step's points to match the average angle of the last mouse vector and this // mouse vector (aka the vertex normal). if (this.lastVec) { const lastNormal = this.lastVec .normalize(options.brushSize / 2) .rotate(90); const averageNormal = new paper.Point( lastNormal.x + step.x, lastNormal.y + step.y ).normalize(options.brushSize / 2); this.finalPath.segments[0].point = this.lastPoint.subtract(averageNormal); this.finalPath.segments[this.finalPath.segments.length - 1].point = this.lastPoint.add(averageNormal); } this.finalPath.add(event.point.add(step)); this.finalPath.insert(0, event.point.subtract(step)); if ( this.finalPath.segments.length > this.smoothed + this.smoothingThreshold * 2 ) { this.simplify(1); } this.lastVec = event.delta; this.lastPoint = event.point; } /** * Simplify the path so that it looks almost the same while trying to have a reasonable number of handles. * Without this, there would be 2 handles for every mouse move, which would make the path produced basically * uneditable. This version of simplify keeps track of how much of the path has already been simplified to * avoid repeating work. * @param {number} threshold The simplify algorithm must try to stay within this distance of the actual line. * The algorithm will be faster and able to remove more points the higher this number is. * Note that 1 is about the lowest this algorithm can do (the result is about the same when 1 is * passed in as when 0 is passed in) */ simplify (threshold) { // Length of the current path const length = this.finalPath.segments.length; // Number of new points added to front and end of path since last simplify const newPoints = Math.floor((length - this.smoothed) / 2) + 1; // Where to cut. Don't go past the rounded start of the line (so there's always a tempPathMid) const firstCutoff = Math.min(newPoints + 1, Math.floor(length / 2)); const lastCutoff = Math.max( length - 1 - newPoints, Math.floor(length / 2) + 1 ); if (firstCutoff <= 1 || lastCutoff >= length - 1) { // Entire path is simplified already return; } // Cut the path into 3 segments: the 2 ends where the new points are, and the middle, which will be // staying the same const tempPath1 = new paper.Path( this.finalPath.segments.slice(1, firstCutoff) ); const tempPathMid = new paper.Path( this.finalPath.segments.slice(firstCutoff, lastCutoff) ); const tempPath2 = new paper.Path( this.finalPath.segments.slice(lastCutoff, length - 1) ); // Run simplify on the new ends. We need to graft the old handles back onto the newly // simplified paths, since simplify removes the in handle from the start of the path, and // the out handle from the end of the path it's simplifying. const oldPath1End = tempPath1.segments[tempPath1.segments.length - 1]; const oldPath2End = tempPath2.segments[0]; tempPath1.simplify(threshold); tempPath2.simplify(threshold); const newPath1End = tempPath1.segments[tempPath1.segments.length - 1]; const newPath2End = tempPath2.segments[0]; newPath1End.handleOut = oldPath1End.handleOut; newPath2End.handleIn = oldPath2End.handleIn; // Delete the old contents of finalPath and replace it with the newly simplified segments, concatenated this.finalPath.removeSegments(1, this.finalPath.segments.length - 1); this.finalPath.insertSegments( 1, tempPath1.segments .concat(tempPathMid.segments) .concat(tempPath2.segments) ); // Remove temp paths tempPath1.remove(); tempPath2.remove(); tempPathMid.remove(); // Update how many points have been smoothed so far so that we don't redo work when // simplify is called next time. this.smoothed = Math.max(2, this.finalPath.segments.length); } /** * Like paper.Path.unite, but it removes the original 2 paths * @param {paper.Path} path1 to merge * @param {paper.Path} path2 to merge * @return {paper.Path} merged path. Original paths 1 and 2 will be removed from the view. */ union (path1, path2) { const temp = path1.unite(path2); path1.remove(); path2.remove(); return temp; } onBroadMouseUp (event, tool, options) { // If there was only a single click, draw a circle. if (this.steps === 0) { this.endCaps.length = 0; return this.finalPath; } let delta = this.lastVec; // If the mouse up is at the same point as the mouse drag event then we need // the second to last point to get the right direction vector for the end cap if (!event.point.equals(this.lastPoint)) { // The given event.delta is the difference between the mouse down coords and the mouse up coords, // but we want the difference between the last mouse drag coords and the mouse up coords. delta = event.point.subtract(this.lastPoint); const step = delta.normalize(options.brushSize / 2); step.angle += 90; const top = event.point.add(step); const bottom = event.point.subtract(step); this.finalPath.add(top); this.finalPath.insert(0, bottom); } // Simplify before adding end cap so cap doesn't get warped this.simplify(1); const handleVec = delta.normalize(options.brushSize / 2); this.finalPath.add( new paper.Segment( event.point.add(handleVec), handleVec.rotate(90), handleVec.rotate(-90) ) ); this.finalPath.closePath(); // Resolve self-crossings const newPath = this.finalPath .resolveCrossings() .reorient(true /* nonZero */, true /* clockwise */) .reduce({simplify: true}); if (newPath !== this.finalPath) { newPath.copyAttributes(this.finalPath); newPath.fillColor = this.finalPath.fillColor; this.finalPath.remove(); this.finalPath = newPath; } // Try to merge end caps for (const cap of this.endCaps) { const temp = this.union(this.finalPath, cap); if ( temp.area >= this.finalPath.area && !( temp instanceof paper.CompoundPath && !(this.finalPath instanceof paper.CompoundPath) ) ) { this.finalPath = temp; } else { // If the union of the two shapes is smaller than the original shape, // or it caused the path to become a compound path, // then there must have been a glitch with paperjs's unite function. // In this case, skip merging that segment. It's not great, but it's // better than losing the whole path for instance. (Unfortunately, this // happens reasonably often to scribbles, and this code doesn't catch // all of the failures.) this.finalPath.insertAbove(temp); temp.remove(); log.warn('Skipping a merge.'); } } this.endCaps.length = 0; return this.finalPath; } }
JavaScript
class Graph { constructor() { this.numberOfNode = 0; this.adjacentList = {}; } addVertex(node) { if (!this.adjacentList[node]) { this.adjacentList[node] = []; this.numberOfNode++; } } addEdge(node1, node2) { if (!this.adjacentList[node1] || !this.adjacentList[node2]) { return false; } this.adjacentList[node1].push(node2); this.adjacentList[node2].push(node1); } // Not a part of API, just to pretty print the adjacent list. showConnections() { const allNodes = Object.keys(this.adjacentList); for (let node of allNodes) { let nodeConnections = this.adjacentList[node]; let connections = ''; let vertex; for (vertex of nodeConnections) { connections += vertex + ' '; } console.log(node + '--> ' + connections); } } }
JavaScript
class Device { constructor(identifier, ipV4Address, basicAuthentication = undefined, id = crypto.randomBytes(10).toString('hex')) { this._identifier = Device.validateIdentifier(identifier); this._ipV4Address = Device.validateIpV4Address(ipV4Address); this._basicAuthentication = Device.validateBasicAuthentication(basicAuthentication); this._id = id; } static validateIdentifier(identifier) { if (!identifier) { throw new ValidationError('The identifier is mandatory and cannot be empty'); } else if (typeof identifier !== 'string') { throw new TypeError('The identifier is not of type string'); } return identifier; } static validateIpV4Address(ipV4Address) { if (!(ipV4Address instanceof IpV4Address)) { throw new TypeError('The ipV4Address is not of type IpV4Address'); } return ipV4Address; } static validateBasicAuthentication(basicAuthentication) { if (!basicAuthentication) { return basicAuthentication; } if (!(basicAuthentication instanceof BasicAuthentication)) { throw new TypeError('The basicAuthentication is not of type BasicAuthentication'); } return basicAuthentication; } static async of(ip, userId, password) { const ipV4Address = IpV4Address.of(ip); return ShellyService.searchForShellyOnIpAddress(ip).then((shelly) => { const { identifier, isAuthenticationRequired } = shelly; if (isAuthenticationRequired) { const basicAuthentication = BasicAuthentication.of(userId, password); return new Device(identifier, ipV4Address, basicAuthentication); } return new Device(identifier, ipV4Address); }).then(async (device) => { if (device.hasAuthentication) { // verify authentication by performing an authenticated status request await StatusService.getStatus(device); } return device; }).catch(() => { throw new NotFoundError(`Device with ip '${ip}' could not be found`); }); } /** * Returns the id. * * @returns {string} The device's unique id, e.g. '12345678' * @since 1.0.0 */ get id() { return this._id; } /** * Returns the model identifier. * * @returns {string} The device's model identifier, e.g. 'SHSW-1' * @since 1.0.0 */ get identifier() { return this._identifier; } /** * Returns the device's IP v4 address. * * @returns {IpV4Address} The device's IP v4 address * @since 1.0.0 */ get ipV4Address() { return this._ipV4Address; } set ipV4Address(ipV4Address) { this._ipV4Address = Device.validateIpV4Address(ipV4Address); } /** * Returns the device's basic authentication. * * @returns {BasicAuthentication | undefined} The device's basic authentication, if provided * @since 1.0.0 */ get basicAuthentication() { return this._basicAuthentication; } set basicAuthentication(basicAuthentication) { this._basicAuthentication = Device.validateBasicAuthentication(basicAuthentication); } /** * Returns if the device requires basic authentication. * * @returns {boolean} If basic authentication is required * @since 1.0.0 */ get hasAuthentication() { return this.basicAuthentication instanceof BasicAuthentication; } toString() { return `${this.id} ${this.identifier} ${this.ipV4Address} ${this.hasAuthentication ? '🔐' : '🔓'}`; } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn("Component was already destroyed"); // eslint-disable-line no-console }; } $capture_state() {} $inject_state() {} }
JavaScript
class GraphQLError extends Error { /** * An array of `{ line, column }` locations within the source GraphQL document * which correspond to this error. * * Errors during validation often contain multiple locations, for example to * point out two things with the same name. Errors during execution include a * single location, the field which produced the error. * * Enumerable, and appears in the result of JSON.stringify(). */ /** * An array describing the JSON-path into the execution response which * corresponds to this error. Only included for errors during execution. * * Enumerable, and appears in the result of JSON.stringify(). */ /** * An array of GraphQL AST Nodes corresponding to this error. */ /** * The source GraphQL document for the first location of this error. * * Note that if this Error represents more than one node, the source may not * represent nodes after the first node. */ /** * An array of character offsets within the source GraphQL document * which correspond to this error. */ /** * The original error thrown from a field resolver during execution. */ /** * Extension fields to add to the formatted error. */ constructor( message, nodes, source, positions, path, originalError, extensions ) { var _this$nodes, _nodeLocations$, _ref; super(message); this.name = "GraphQLError"; this.path = path !== null && path !== void 0 ? path : undefined; this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. this.nodes = undefinedIfEmpty( Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined ); const nodeLocations = undefinedIfEmpty( (_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null) ); // Compute locations in the source for the given nodes/positions. this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source; this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start); this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start)); const originalExtensions = isObjectLike( originalError === null || originalError === void 0 ? void 0 : originalError.extensions ) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : undefined; this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : Object.create(null); // Only properties prescribed by the spec should be enumerable. // Keep the rest as non-enumerable. Object.defineProperties(this, { message: { writable: true, enumerable: true, }, name: { enumerable: false, }, nodes: { enumerable: false, }, source: { enumerable: false, }, positions: { enumerable: false, }, originalError: { enumerable: false, }, }); // Include (non-enumerable) stack trace. // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') if ( originalError !== null && originalError !== void 0 && originalError.stack ) { Object.defineProperty(this, "stack", { value: originalError.stack, writable: true, configurable: true, }); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, GraphQLError); } else { Object.defineProperty(this, "stack", { value: Error().stack, writable: true, configurable: true, }); } } get [Symbol.toStringTag]() { return "GraphQLError"; } toString() { let output = this.message; if (this.nodes) { for (const node of this.nodes) { if (node.loc) { output += "\n\n" + printLocation(node.loc); } } } else if (this.source && this.locations) { for (const location of this.locations) { output += "\n\n" + printSourceLocation(this.source, location); } } return output; } toJSON() { const formattedError = { message: this.message, }; if (this.locations != null) { formattedError.locations = this.locations; } if (this.path != null) { formattedError.path = this.path; } if (this.extensions != null && Object.keys(this.extensions).length > 0) { formattedError.extensions = this.extensions; } return formattedError; } }
JavaScript
class Location { /** * The character offset at which this Node begins. */ /** * The character offset at which this Node ends. */ /** * The Token at which this Node begins. */ /** * The Token at which this Node ends. */ /** * The Source document the AST represents. */ constructor(startToken, endToken, source) { this.start = startToken.start; this.end = endToken.end; this.startToken = startToken; this.endToken = endToken; this.source = source; } get [Symbol.toStringTag]() { return "Location"; } toJSON() { return { start: this.start, end: this.end, }; } }
JavaScript
class Token { /** * The kind of Token. */ /** * The character offset at which this Node begins. */ /** * The character offset at which this Node ends. */ /** * The 1-indexed line number on which this Token appears. */ /** * The 1-indexed column number at which this Token begins. */ /** * For non-punctuation tokens, represents the interpreted value of the token. * * Note: is undefined for punctuation tokens, but typed as string for * convenience in the parser. */ /** * Tokens exist as nodes in a double-linked-list amongst all tokens * including ignored tokens. <SOF> is always the first node and <EOF> * the last. */ constructor(kind, start, end, line, column, value) { this.kind = kind; this.start = start; this.end = end; this.line = line; this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.value = value; this.prev = null; this.next = null; } get [Symbol.toStringTag]() { return "Token"; } toJSON() { return { kind: this.kind, value: this.value, line: this.line, column: this.column, }; } }