language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class App extends Component {
render() {
return (
<AppLayout>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route path="/donate" component={DonatePage} />
<Route path="/range" component={StyleRangePage} />
<Route path="/styles" component={CompareStylesPage} />
<Route path="/questions/:category/:topic" component={QuestionPage} />
<Route path="/copyright" component={CopyrightPage} />
<Route path="/about" component={AboutPage} />
<Route component={NotFoundPage} />
</Switch>
</AppLayout>
);
}
} |
JavaScript | class HiddenWord extends Puzzle{
constructor(word,words,hints,answers){
super('HiddenWord');
this.output=word;
this.word=word;
this.words=words;
this.hints=hints;
this.answers=answers;
this.hiddenWord=this.generateHiddenWord(word,words);
}
generateHiddenWord(word,words){
let matrix = [];
for (let i=0;i<words.length;i++){
matrix.push(words[i].indexOf(word[i]));
}
return matrix;
}
} |
JavaScript | @registerDynamicValueClass
class UrlPathParamDynValue {
static identifier = 'com.blockchainofthings.PawExtensions.UrlPathParamDynValue';
static title = 'URL Path Parameter';
static inputs = [
DynamicValueInput('paramName', 'Parameter Name', "String"),
DynamicValueInput('paramValue', 'Value', "String")
];
evaluate(context) {
return encodeURIComponent(this.paramValue);
}
title(context) {
return 'Param';
}
text(context) {
return this.paramName;
}
} |
JavaScript | class List extends Array {
/**
* @param {*} array - array like object
*/
constructor(array = null) {
super();
if (array != null) {
for (let i = 0; i < array.length; i++) this.push(array[i]);
}
}
/**
* Constructor from a single item.
* Ex. const list = List.fromSingle('a');
* @param {*} item
*/
static fromSingle(item) {
return new List().add(item);
}
/** Returns the first element in the list. If empty, return null */
get first() { return this[0]; }
/** True if the list has not elements */
get isEmpty() { return this.length < 1; }
/** True if the list contains elements */
get isNotEmpty() { return this.length > 0; }
/** Returns the last element in the list. If empty, return null */
get last() { return this[this.length - 1]; }
/** True if the list has only one element */
get single() { return this.length === 1; }
/**
* push an item at the end of the list. Could be null.
* options = {unique: true}
* @param {*} item
* @param {Object} options
*/
add(item, options = null) {
if (options && options.unique) {
if (!this.contains(item)) this.push(item);
} else {
this.push(item);
}
return this;
}
/**
* All all the items at the end of the list.
* options = {unique: true}
* @param {*} items
* @param {Object} options
*/
addAll(items, options = null) {
if (items == null) return this;
if (options == null) return new List(this.concat(items));
for (let i = 0; i < items.length; i++) {
this.add(items[i], options);
}
return this;
}
/**
* Returns a list new copy
*/
clone() {
return this.slice();
}
/**
* True if item is in the list
* @param {*} item
* @return {Boolean}
*/
contains(item) {
return this.indexOf(item) > -1;
}
/**
* True if item is the only element in the list
* @param {*} item
*/
containsOnly(item) {
return (this.length === 1) &&
this.indexOf(item) > -1;
}
/**
* Inserts item in the index position
*/
insert(index, item) {
this.splice(index, 0, item);
return this;
}
/**
* Merge two list, sorted by:
* (moveif(left, rigth) => left > right) descendent
* (moveif(left, rigth) => left < right) ascendent
* @param {List} left
* @param {List} right
* @param {Function} moveif
* @return {List}
*/
_mergeStableSort(left, right, moveif) {
const result = new List();
while (left.isNotEmpty && right.isNotEmpty) {
if (moveif(left.first, right.first)) {
result.add(right.removeFirst());
} else {
result.add(left.removeFirst());
}
}
return result.addAll(left).addAll(right);
}
/**
* Removes the first occurrend of item in the list
* @param {*} item
*/
remove(item) {
if (this.isEmpty) return this;
const i = this.indexOf(item);
if (i > -1) this.splice(i, 1);
return this;
}
/**
* Removes the item in the index position
* @param {Number} index
*/
removeAt(index) {
if (index < 0 || index > this.length - 1) return this;
this.splice(index, 1);
return this;
}
/**
* Removes first item in the list and return it;
* @return {*} item removed
*/
removeFirst() {
return this.shift();
}
/**
* Returns a stable sorted list (keep original order at same sorted level. see a and c).
* (a, 3) (b, 1) (c, 3) (d, 2) => (b, 1) (d, 2) (a, 3) (c, 3)
* Array sort is not stable:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
* @param {Function} moveif compare(left, right) => left < right or left > rigth (true/false)
* @return {List}
*/
stableSort(moveif) {
const len = this.length;
if (len < 2) return this;
const pivot = Math.ceil(len / 2);
const left = this.sublist(0, pivot).stableSort(moveif);
const right = this.sublist(pivot).stableSort(moveif);
return this._mergeStableSort(left, right, moveif);
}
/**
* Returns a list from start to end (exclusive). If end is ommited the length is used
* @param {Number} start
* @param {Number} end
* @return {List}
*/
sublist(start, end = null) {
return (end != null) ? new List(this.slice(start, end)) : new List(this.slice(start));
}
/**
* Remove spaces left and right for string elements.
* If one element is not string throws an error.
*/
trim() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].trim();
}
return this;
}
} |
JavaScript | class PostgresClient {
/**
* Create Postgres client
* @param {Postgres} service Postgres service instance
* @param {object} client Connected PG client
* @param {function} done Client termination function
*/
constructor(service, client, done) {
this.client = client;
this.maxTransactionRetries = 59;
this.minTransactionDelay = 100;
this.maxTransactionDelay = 1000;
this._done = done;
this._postgres = service;
this._transactionLevel = 0;
}
/**
* Client termination
*/
done() {
if (!this.client)
return;
debug('Disconnecting...');
let res = this._done();
this.client = null;
this._done = null;
return res;
}
/**
* Run Postgres query<br>
* Date/Moment params are converted to strings in UTC timezone.
* @param {string} sql SQL query string
* @param {Array} [params] Query parameters
* @return {Promise} Resolves to query result
*/
async query(sql, params = []) {
let parsedSql = sql.trim().replace(/\s+/g, ' ');
let parsedParams = [];
for (let param of params) {
if (param instanceof Date)
param = moment(param);
if (moment.isMoment(param))
parsedParams.push(param.tz('UTC').format(this._postgres.constructor.datetimeFormat)); // DB uses UTC
else
parsedParams.push(param);
}
let debugSql = parsedSql;
for (let i = parsedParams.length - 1; i >= 0; i--) {
let param = parsedParams[i];
switch (typeof param) {
case 'string':
if (!isFinite(param))
param = "'" + param.replace("'", "\\'") + "'";
break;
case 'object':
if (param === null)
param = 'null';
else
param = JSON.stringify(param);
break;
case 'boolean':
param = param ? 'true' : 'false';
break;
}
debugSql = debugSql.replace(new RegExp('\\$' + (i + 1), 'g'), param);
}
debug(debugSql);
if (!this.client)
throw Error('Query on terminated client');
return new Promise((resolve, reject) => {
try {
this.client.query(
parsedSql, parsedParams,
(error, result) => {
if (error) {
let sqlState = (typeof error.sqlState === 'undefined' ? error.code : error.sqlState);
return reject(
new NError(
error,
{ sqlState: sqlState, query: parsedSql, params: parsedParams },
'Query failed: ' + sqlState
)
);
}
resolve(result);
}
);
} catch (error) {
reject(new NError(error, 'PostgresClient.query()'));
}
});
}
/**
* Run a transaction
* @param {object} [params]
* @param {string} [params.name] Transaction name for debugging
* @param {string} [params.isolation='serializable'] Isolation level
* @param {PostgresTransaction} cb The transaction
* @return {Promise} Resolves to transaction result
*/
async transaction() {
let params = { isolation: 'serializable' };
let cb;
if (arguments.length >= 2) {
if (arguments[0].name)
params.name = arguments[0].name;
if (arguments[0].isolation)
params.isolation = arguments[0].isolation;
cb = arguments[1];
} else if (arguments.length === 1) {
cb = arguments[0];
}
if (!this.client) {
return Promise.reject(new Error(
'Transaction ' +
(params.name ? params.name + ' ' : '') +
'on terminated client'
));
}
debug(`Transaction ${params.name}`);
class RollbackError extends Error {
}
function rollback(savepoint) {
return result => {
let error = new RollbackError(
'Uncatched transaction rollback' +
(params.name ? ` in ${params.name}` : '')
);
error.savepoint = savepoint;
error.result = result;
throw error;
};
}
if (++this._transactionLevel !== 1) {
let savepoint = 'arpen_' + this._postgres._util.getRandomString(16, { lower: true, digits: true });
let savepointCreated = false;
try {
await this.query('SAVEPOINT ' + savepoint);
savepointCreated = true;
let result = cb(rollback(savepoint));
if (result === null || typeof result !== 'object' || typeof result.then !== 'function') {
throw new Error(
'Transaction ' +
(params.name ? params.name + ' ' : '') +
'function must return a Promise'
);
}
let value = await result;
this._transactionLevel--;
return value;
} catch (error) {
this._transactionLevel--;
if (error instanceof RollbackError && error.savepoint === savepoint) {
if (savepointCreated)
await this.query('ROLLBACK TO ' + savepoint);
return error.result;
}
throw error;
}
}
let value;
try {
value = await new Promise(async (resolve, reject) => {
let numTries = 0;
let tryAgain = async () => {
let transactionStarted = false;
try {
await this.query('BEGIN TRANSACTION ISOLATION LEVEL ' + params.isolation.toUpperCase());
transactionStarted = true;
let result = cb(rollback(null));
if (result === null || typeof result !== 'object' || typeof result.then !== 'function') {
throw new Error(
'Transaction ' +
(params.name ? params.name + ' ' : '') +
'function must return a Promise'
);
}
let value = await result;
await this.query('COMMIT TRANSACTION');
resolve(value);
} catch (error) {
if (transactionStarted)
await this.query('ROLLBACK TRANSACTION');
if (error instanceof RollbackError)
return resolve(error.result);
if (error.info && error.info.sqlState === '40001') { // SERIALIZATION FAILURE
if (++numTries > this.maxTransactionRetries) {
return reject(
new NError(
error,
'Maximum transaction retries reached' +
(params.name ? ` in ${params.name}` : '')
)
);
}
this._postgres._logger.warn(
'Postgres transaction serialization failure' +
(params.name ? ` in ${params.name}` : '')
);
let delay = this._postgres._util.getRandomInt(
this.minTransactionDelay,
this.maxTransactionDelay
);
return setTimeout(async () => { await tryAgain(); }, delay);
}
reject(error);
}
};
await tryAgain();
});
} catch (error) {
this._transactionLevel--;
throw error;
}
this._transactionLevel--;
return value;
}
} |
JavaScript | class Plugin {
/**
* Initializes the plugin.
*/
initialize() {
throw new Error('Method not implemented!');
}
} |
JavaScript | class App extends Component {
/**
* @function render
* @description The funtion that generates the game on a web page
* @returns a div container that contains the web game
*/
render() {
return (
<div className="App">
<header className="App-header">
<Game/>
</header>
</div>
);
}
} |
JavaScript | class Route {
/****************************************************************************\
* Class Properties
\****************************************************************************/
defaultOptions = {
methods: ['get'],
}
path = null
/****************************************************************************\
* Public Methods
\****************************************************************************/
/**
* Constructs a new Route.
*
* @param {object} options
* @param {string[]} [options.methods]
*/
constructor (options = {}) {
this.options = {
...this.defaultOptions,
...options,
}
}
/**
* Method to be executed when the route is hit.
*
* @abstract
* @param {object} context
*/
handler (context) { // eslint-disable-line no-unused-vars
throw new Error('Must be implemented by route.')
}
/**
* Validate this route before attaching to a Router.
*/
validate () {
if (typeof this.path === 'string') {
throw new Error('path is required')
}
}
/****************************************************************************\
* Getters
\****************************************************************************/
/**
* Returns a list of methods that are allowed for this route.
* @returns {string[]}
*/
get methods () {
return this.options.methods
}
} |
JavaScript | class TorrentList {
/**
* @param {?Object} data The data to patch into this class
*/
constructor(data) {
if (data) this._patch(data);
}
/**
* Patch data into this class
* @param {Object} data The data to patch
* @private
*/
_patch(data) {
Object.entries(data).forEach(([res, torrent]) => {
torrent.resolution = res;
this[res] = new _Torrent2.default(torrent);
});
}
/**
* Gets the highest resolution in this TorrentList
* @type {Torrent}
*/
get maxRes() {
return this['1080p'] || this['720p'] || this['480p'] || this['0'];
}
} |
JavaScript | class Base extends EventEmitter {
constructor(opts) {
super();
this.isValid(opts);
this.opts = opts;
this.clientId = opts.clientId || `kafka-observable-${shortid.generate()}`;
this.brokers = Base.formatBrokers(opts.brokers);
this.log = bunyan.createLogger({
name: this.clientId,
level: process.env.LOG_LEVEL
});
}
/**
* Convert to array or throw if parameter is not string or array
* @param {String|Array} brokers single or multiple brokers URL
* @return {Array.<*>}
*/
static formatBrokers(brokers) {
const className = brokers.constructor.name;
if (className !== 'Array' && className !== 'String') {
throw new TypeError('invalid brokers parameter');
}
return [].concat(brokers);
}
/**
* Validate options. Throws if invalid.
* @param {Object} opts user defined options
*/
isValid(opts) {
if (!opts.brokers) {
throw new Error('missing vipaddress or brokers parameter');
}
}
/**
* To be overridden by consumer and producer defaults
* @return {Object} default client options
*/
defaults() {
return {
connectionString: this.brokers.join(','),
logger: {logFunction: this.logging.bind(this)}
};
}
/**
* @return {Object} client options
*/
clientOptions() {
return Object.assign({}, this.defaults(), this.opts);
}
/**
* Emits error event if listener error is found.
* EventEmitter throws if an error event is emitted without listeners
* @see https://nodejs.org/api/events.html#events_error_events
* @param {Object} err error object
*/
handleError(err) {
this.log.error(err);
if (this.listenerCount('error') > 0) {
this.emit('error', err);
}
return Promise.reject(err);
}
/**
* Pipes logs through Bunyan and fire events
* @param {String} level log level
* @param {Array} args
*/
logging(level, ...args) {
this.log[level.toLowerCase()](...args);
this.monitoring(level, ...args);
}
/**
* Parses through the logs to emit meaningful events
* @param {String} level log level
* @param {Array} args
*/
monitoring(level, ...args) {
if (level === bunyan.ERROR) {
this.handleError(args[3]);
}
}
} |
JavaScript | class Money {
/**
* Create a new Money object with the initial value.
* @param {number} value - The value to put on money
* @param {number} [locale=en] - The locale for this money
* @param {number} [currency=USD] - The currency to use in currency formatting.
* @param {number} [currencyFractionals=2] - The currency fractionals to use in currency formatting
*/
constructor(value, {
locale = DEFAULT_LOCALE, currency = DEFAULT_CURRENCY, normalized = false, ...options
} = {}) {
this.currencyFractionals = getValue(options.currencyFractionals, DEFAULT_CURRENCY_FRACTIONALS)
isValidCurrencyFractionals(this.currencyFractionals)
this.DEFAULT_INTL_OPTIONS = {
minimumFractionDigits: this.currencyFractionals,
maximumFractionDigits: this.currencyFractionals,
}
this.value = normalized ? value : normalize(this.currencyFractionals, value)
this.locale = locale
this.currency = currency
}
/**
* Create a new Money object with the initial value.
* @param {number} value - A value to put on money
* @param {number} [locale=en] - The locale for this money
* @param {number} [currency=USD] - The currency to use in currency formatting.
* @param {number} [currencyFractionals=2] - The currency fractionals to use in currency formatting
* @return {Money} The money with value
*/
static init = (value = 0, { ...options } = {}) => new Money(value, options)
/**
* Create a new Money object from String value
* @param {string} string - A value to put on money
* @param {number} [locale=en] - The locale for this money
* @param {number} [currency=USD] - The currency to use in currency formatting.
* @return {Money} The money with value
*/
static fromString = (string = '0', { ...options } = {}) => new Money(string, options)
/**
* Adds a value to money
* @param {number} value - A value to put on money
* @return {Money} The money with new value
*/
add = value => handleMoney(sum.bind(this, value), this)
/**
* Subtract a value to money
* @param {number} value - A value to remove from money
* @return {Money} The money with new value
*/
subtract = value => handleMoney(subtract.bind(this, value), this)
/**
* Multiply your money by value
* @param {number} value - A value to multiply
* @return {Money} The money with new value
*/
multiplyBy = value => handleMoney(multiply.bind(this, value), this)
/**
* Divide your money by value
* @param {number} value - A value to divide
* @return {Money} The money with new value
*/
divideBy = value => handleMoney(divide.bind(this, value), this)
/**
* Get current value
* @return {number} The value on Money
*/
getValue = () => denormalize(this.currencyFractionals, this.value)
/**
* Get money locale
* @return {string}
*/
getLocale = () => this.locale
/**
* Return a formatted currency of Money
* @param {number} [currencyDisplay=symbol] - How to display the currency in currency formatting.
* @return {string} currency number of money
*/
toCurrency = (currencyDisplay = DEFAULT_CURRENCY_DISPLAY) => {
const options = {
...this.DEFAULT_INTL_OPTIONS,
style: 'currency',
currency: this.currency,
currencyDisplay,
}
const intl = new Intl.NumberFormat(this.locale, options)
return intl.format(denormalize(this.currencyFractionals, this.value))
}
/**
* Formatted value of Money
* @return {string} formatted number of money
*/
toString = () => {
const intl = new Intl.NumberFormat(this.locale, this.DEFAULT_INTL_OPTIONS)
return intl.format(denormalize(this.currencyFractionals, this.value))
}
} |
JavaScript | class AbstractCloud {
constructor(name, options) {
this.environment = name;
this.maxRetries = constants.MAX_RETRIES;
this.retryInterval = constants.RETRY_INTERVAL;
const logger = options && options.logger ? options.logger : Logger;
if (logger) {
this.logger = logger;
}
}
/**
* Initialize the Cloud Provider
*
* @param {Object} options - function options
* @param {Object} [options.addressTags] - tags to filter addresses on
* @param {Boolean} [options.addressTagsRequired] - denote if address tags are required for all objects
* (such as GCP forwarding rules)
* @param {Object} [options.proxySettings] - proxy settings { protocol: '', 'host': '', port: '' }
* @param {Object} [options.routeGroupDefinitions] - group definitions to filter routes on
* @param {Object} [options.routeAddressRanges] - addresses to filter on [{ 'range': '192.0.2.0/24' }]
* with next hop address discovery configuration:
* { 'type': 'address': 'items': [], tag: null}
* @param {Object} [options.storageTags] - storage tags to filter on { 'key': 'value' }
* @param {Object} [options.storageName] - storage scoping name
* @param {Object} [options.subnets] - subnets
* @param {Object} [options.trustedCertBundle] - custom certificate bundle for cloud API calls
*/
init(options) {
options = options || {};
this.addressTags = options.addressTags || {};
this.addressTagsRequired = options.addressTagsRequired || false;
this.proxySettings = options.proxySettings || null;
this.routeGroupDefinitions = options.routeGroupDefinitions || {};
this.storageTags = options.storageTags || {};
this.storageName = options.storageName || '';
this.subnets = options.subnets || {};
this.trustedCertBundle = options.trustedCertBundle || '';
}
downloadDataFromStorage() {
throw new Error('Method must be implemented in child class!');
}
getAssociatedAddressAndRouteInfo() {
throw new Error('Method must be implemented in child class!');
}
updateAddresses() {
throw new Error('Method must be implemented in child class!');
}
discoverAddresses() {
throw new Error('Method must be implemented in child class!');
}
discoverAddressOperationsUsingDefinitions() {
throw new Error('Method must be implemented in child class!');
}
uploadDataToStorage() {
throw new Error('Method must be implemented in child class!');
}
/**
* Update routes
*
* @param {Object} options - function options
* @param {Object} [options.localAddresses] - object containing 1+ local (self) addresses [ '192.0.2.1' ]
* @param {Boolean} [options.discoverOnly] - only perform discovery operation
* @param {Object} [options.updateOperations] - skip discovery and perform 'these' update operations
*
* @returns {Promise}
*/
updateRoutes(options) {
options = options || {};
const localAddresses = options.localAddresses || [];
const discoverOnly = options.discoverOnly || false;
const updateOperations = options.updateOperations;
this.logger.silly('updateRoutes: ', options);
if (discoverOnly === true) {
return this._discoverRouteOperations(localAddresses)
.catch(err => Promise.reject(err));
}
if (updateOperations) {
return this._updateRoutes(updateOperations.operations)
.catch(err => Promise.reject(err));
}
// default - discover and update
return this._discoverRouteOperations(localAddresses)
.then(operations => this._updateRoutes(operations.operations))
.catch(err => Promise.reject(err));
}
_checkForNicOperations() {
throw new Error('Method must be implemented in child class!');
}
/**
* Discover next hop address - support 'none' (static) and routeTag discovery types
*
* @param {Object} localAddresses - local addresses
* @param {Object} routeTableTags - route table tags
* @param {Object} discoveryOptions - discovery options
* @param {String} [discoveryOptions.type] - type of discovery: address|routeTag
* @param {Array} [discoveryOptions.items] - items, used for some discovery types
* @param {String} [discoveryOptions.tag] - tag, used for some discovery types
*
* @returns {String} - next hop address
*/
_discoverNextHopAddress(localAddresses, routeTableTags, discoveryOptions) {
let potentialAddresses = [];
switch (discoveryOptions.type) {
case 'static':
potentialAddresses = discoveryOptions.items;
break;
case 'routeTag':
routeTableTags = this._normalizeTags(routeTableTags);
if (!routeTableTags[discoveryOptions.tag]) {
this.logger.warning(`expected tag: ${discoveryOptions.tag} does not exist on route table`);
}
// tag value may be '1.1.1.1,2.2.2.2' or ['1.1.1.1', '2.2.2.2']
if (Array.isArray(routeTableTags[discoveryOptions.tag])) {
potentialAddresses = routeTableTags[discoveryOptions.tag];
} else {
potentialAddresses = routeTableTags[discoveryOptions.tag].split(',').map(i => i.trim());
}
break;
default:
throw new Error(`Invalid discovery type was provided: ${discoveryOptions.type}`);
}
const nextHopAddressToUse = potentialAddresses.filter(item => localAddresses.indexOf(item) !== -1)[0];
if (!nextHopAddressToUse) {
this.logger.warning(`Next hop address to use is empty: ${localAddresses} ${potentialAddresses}`);
}
this.logger.silly(`Next hop address: ${nextHopAddressToUse}`);
return nextHopAddressToUse;
}
/**
* Discover route operations
*
* @param {Object} localAddresses - local addresses
*
* @returns {Object} - { operations: [] }
*/
_discoverRouteOperations(localAddresses) {
return this._getRouteTables()
.then(routeTables => Promise.all(this.routeGroupDefinitions.map(
routeGroup => this._discoverRouteOperationsPerGroup(
localAddresses,
routeGroup,
routeTables
)
)))
.then((groupOperations) => {
const operations = [];
groupOperations.forEach((groupOperation) => {
groupOperation.forEach((operation) => {
operations.push(operation);
});
});
return Promise.resolve({ operations });
})
.catch(err => Promise.reject(err));
}
/**
* Filter route tables
*
* @param {Object} routeTables - route tables
* @param {Object} options - function options
* @param {Object} [options.tags] - object containing 1+ tags to filter on { 'key': 'value' }
* @param {Object} [options.name] - route name to filter on
*
* @returns {object} routeTables - filtered route tables
*/
_filterRouteTables(routeTables, options) {
options = options || {};
if (options.tags && Object.keys(options.tags)) {
return routeTables.filter((item) => {
let matchedTags = 0;
Object.keys(options.tags).forEach((key) => {
const itemTags = this._normalizeTags(item.Tags || item.tags || item.parsedTags);
if (itemTags && Object.keys(itemTags).indexOf(key) !== -1
&& itemTags[key] === options.tags[key]) {
matchedTags += 1;
}
});
return Object.keys(options.tags).length === matchedTags;
});
}
if (options.name) {
return routeTables.filter(item => (item.name || item.RouteTableId) === options.name);
}
return [];
}
/**
* Format proxy URL
*
* @param {Object} settings - proxy settings
*
* @returns {String} URL (valid proxy URL)
*/
_formatProxyUrl(settings) {
if (!settings.host) throw new Error('Host must be provided to format proxy URL');
if (!settings.port) throw new Error('Port must be provided to format proxy URL');
const protocol = settings.protocol || 'https';
const auth = settings.username && settings.password
? `${settings.username}:${settings.password}@` : '';
return `${protocol}://${auth}${settings.host}:${settings.port}`;
}
/**
* Returns route address range and next hop addresses config info given the route's
* destination cidr
*
* Note: If one of the route address entries contains 'all', it should be considered a match
*
* @param cidr - Cidr to match against routeAddressRanges.routeAddresses
* @param routeAddressRanges - route address ranges to match against
*
* @return {Object|null}
*/
_matchRouteToAddressRange(cidr, routeAddressRanges) {
// check for special 'all' case
if (routeAddressRanges[0].routeAddresses.indexOf('all') !== -1) {
return routeAddressRanges[0];
}
// simply compare this cidr to the route address ranges array and look for a match
const matchingRouteAddressRange = routeAddressRanges.filter(
routeAddressRange => routeAddressRange.routeAddresses.indexOf(cidr) !== -1
);
return matchingRouteAddressRange.length ? matchingRouteAddressRange[0] : null;
}
/**
* Normalize tags into a known object structure
*
* Known unique object structures
* - { 'key1': 'value1' }
* - [{ 'Key': 'key1', 'Value': 'value1' }]
*
* @param {Object|Array} tags - cloud resource tags
*
* @returns {Object} - tags: { 'key1': 'value1' }
*/
_normalizeTags(tags) {
let ret = {};
if (Array.isArray(tags)) {
ret = tags.reduce((acc, cur) => {
acc[cur.Key] = cur.Value;
return acc;
}, {});
} else {
ret = tags;
}
return ret;
}
/**
* Retrier function
*
* Note: Wrapper for utils.retrier with sane defaults, such as setting
* logger and 'thisArg'
*
* @param {Object} func - Function to try
* @param {Array} args - Arguments to pass to function
* @param {Object} [options] - Function options
* @param {Integer} [options.maxRetries] - Number of times to retry on failure
* @param {Integer} [options.retryInterval] - Milliseconds between retries
* @param {Object} [options.thisArg] - 'this' arg to use
* @param {Object} [options.logger] - logger to use
*
* @returns {Promise} A promise which will be resolved once function resolves
*/
_retrier(func, args, options) {
options = options || {};
return utils.retrier(func, args, {
maxRetries: options.maxRetries || this.maxRetries,
retryInterval: options.retryInterval || this.retryInterval,
thisArg: options.thisArg || this,
logger: options.logger || this.logger
})
.catch(err => Promise.reject(err));
}
/**
* Generate the configuration operations required to reassociate the addresses
*
* @param {Object} localAddresses - local addresses
* @param {Object} failoverAddresses - failover addresses
* @param {Object} parsedNics - parsed NICs information
*
* @returns {Promise} - A Promise that is resolved with the operations, or rejected if an error occurs
*/
_generateAddressOperations(localAddresses, failoverAddresses, parsedNics) {
const operations = {
disassociate: [],
associate: []
};
this.logger.debug('parsedNics', parsedNics);
if (!parsedNics.mine || !parsedNics.theirs) {
this.logger.error('Could not determine network interfaces.');
} else {
// go through 'their' nics and come up with disassociate/associate actions required
// to move addresses to 'my' nics, if any are required
for (let s = parsedNics.mine.length - 1; s >= 0; s -= 1) {
for (let h = parsedNics.theirs.length - 1; h >= 0; h -= 1) {
const theirNic = parsedNics.theirs[h].nic;
const myNic = parsedNics.mine[s].nic;
theirNic.tags = theirNic.tags ? theirNic.tags : this._normalizeTags(theirNic.TagSet);
myNic.tags = myNic.tags ? myNic.tags : this._normalizeTags(myNic.TagSet);
if (theirNic.tags[constants.NIC_TAG] === undefined || myNic.tags[constants.NIC_TAG] === undefined) {
this.logger.warning(`${constants.NIC_TAG} tag values do not match or doesn't exist for a interface`);
} else if (theirNic.tags[constants.NIC_TAG] && myNic.tags[constants.NIC_TAG]
&& theirNic.tags[constants.NIC_TAG] === myNic.tags[constants.NIC_TAG]) {
const nicOperations = this._checkForNicOperations(myNic, theirNic, failoverAddresses);
if (nicOperations.disassociate && nicOperations.associate) {
operations.disassociate.push(nicOperations.disassociate);
operations.associate.push(nicOperations.associate);
}
}
}
}
this.logger.debug('Generated Address Operations', operations);
}
return Promise.resolve(operations);
}
} |
JavaScript | class Controller {
// ..and an (optional) custom class constructor. If one is
// not supplied, a default constructor is used instead:
// constructor() { }
constructor() {
this.name = 'Controller';
};
getControllerName() {
return this.name;
};
} |
JavaScript | class App extends React.Component {
click(url, alt) {
console.log(
"Switching To Service " + alt + " At The URL " + url
);
ipc.send("open-url", url);
}
render() {
return React.createElement(
"div",
{
className: "services"
},
services.map((service, index) => {
return React.createElement(
"a",
{
className: "service",
key: index,
onClick: () => { this.click(service.url, service.name) },
href: "#"
},
React.createElement("img", {
src: service.logo,
alt: service.name,
style: {
width: service.width,
height: service.height,
padding: service.padding
}
}),
React.createElement("h3", null, service.name)
);
})
);
}
} |
JavaScript | class CommandRepository {
/**
* Class dependencies: <code>['app', 'terminal', 'yargs']</code>.
*
* @type {Array<string>}
*/
static get dependencies() {
return ['app', 'terminal', 'yargs'];
}
/**
* @inheritdoc
* @private
*/
init() {
(0, _privateRegistry.default)(this).set('commands', []);
if (this.app.isBound('gate')) {
(0, _privateRegistry.default)(this).set('gate', this.app.make('gate'));
}
}
/**
* Get all commands.
* Can return either an array of commands or a dictionary associating groups of commands based on names.
*
* @param {boolean} [withPolicies] - Use gate service to filter valid commands by policies.
* @param {boolean} [grouped] - Request grouped command result instead of a single array.
* @returns {Array<Command>|object<string,Array<Command>>} The commands or the grouped commands.
*/
all(withPolicies = true, grouped = false) {
const gate = (0, _privateRegistry.default)(this).get('gate');
const commands = (0, _privateRegistry.default)(this).get('commands').map(command => {
return this.makeCommand(command);
}).filter(({
policies = []
}) => {
return !withPolicies || policies.every(scope => {
return !gate || gate.can(scope);
});
}).sort(({
name: a
}, {
name: b
}) => {
return a.localeCompare(b);
});
if (!grouped) {
return commands;
}
const groups = {};
commands.forEach(command => {
const {
name
} = command;
if (name !== '*') {
let prefix = name.split(':').shift();
prefix = prefix === name ? '' : prefix;
if (!groups[prefix]) {
groups[prefix] = [];
}
groups[prefix].push(command);
}
});
return groups;
}
/**
* Get command by name.
*
* @param {string} name - The command name.
* @returns {console.Command|null} The command instance, or null if not found.
*/
get(name) {
return (0, _privateRegistry.default)(this).get('commands').find(command => {
let instance = command instanceof _Command.default ? command : command.prototype;
while (instance !== _Command.default.prototype) {
if (instance.name === name) {
return this.makeCommand(command);
}
instance = Object.getPrototypeOf(instance);
}
return null;
}) || null;
}
/**
* Check if command is registered.
*
* @param {string} name - The command name.
* @returns {boolean} Indicates if the command exists.
*/
has(name) {
return Boolean(this.get(name));
}
/**
* Add given command in the command list.
*
* @param {Function|console.Command} command - The command class or instance.
* @returns {console.repositories.CommandRepository} The current command repository instance.
*/
add(command) {
if (!command.abstract) {
(0, _privateRegistry.default)(this).get('commands').push(command);
}
return this;
}
/**
* Make a command instance.
*
* @param {Command|Function} command - A command class.
* @returns {Command} The command class instance.
*/
makeCommand(command) {
const {
app,
terminal,
yargs
} = this;
return app.make(command, {
app,
terminal,
yargs
});
}
} |
JavaScript | class Collection1 extends Core.Model.MongooseModel {
/**
* Collection constructor
*/
constructor (collectionName) {
// We must call super() in child class to have access to 'this' in a constructor
super(collectionName);
console.log("New Model: %s", this.collectionName);
}
/**
* Initialize collection
*/
init () {
console.log("Initializing model: %s", this.collectionName);
// Init schema definition
var schemaDefinition = {
"token": String,
"password": String,
"email": String,
"isAdmin" : Boolean,
"createdAt" : {
type: Date,
"default": Date.now
},
"modifiedAt" : {
type: Date,
"default": Date.now
},
"isVerified" : Boolean,
"firstName": String,
"lastName": String,
notifications: []
};
// Creating schema
this.createSchema(schemaDefinition);
}
} |
JavaScript | class ElasticsearchHttpConnector extends HttpConnector {
constructor(host, config) {
super(host, config);
}
/**
* Adapted from HttpConnector.request, but returns the request stream itself, instead of the response.
*
* @param {Object} params - ElasticSearch request parameters. See the following URL for more info:
* https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-conventions.html
* @param {Function} cb
* @param {Error} cb.err
* @param {ReadableStream} cb.stream
*/
requestStream(params, cb) {
// Build request parameters
let reqParams = this.makeReqParams(params);
// general clean-up procedure to run after the request
// completes, has an error, or is aborted.
let cleanUp = _.once((err, incoming) => {
if ((err instanceof Error) === false) {
err = undefined;
}
this.log.trace(params.method, reqParams, params.body, '[streamed response]', incoming.status);
if (err) {
cb(err);
} else {
cb(err, incoming);
}
});
let request = this.hand.request(reqParams, (_incoming) => {
let incoming = zstreams(_incoming);
// Automatically handle unzipping incoming stream
let encoding = (_incoming.headers['content-encoding'] || '').toLowerCase();
if (encoding === 'gzip' || encoding === 'deflate') {
incoming = incoming.pipe(zlib.createUnzip());
}
// Wrap IncomingMessage functinoality into the zstream
_incoming.on('close', () => incoming.emit('close'));
incoming.httpVersion = _incoming.httpVersion;
incoming.headers = _incoming.headers;
incoming.rawHeaders = _incoming.rawHeaders;
incoming.trailers = _incoming.trailers;
incoming.rawTrailers = _incoming.trailers;
incoming.setTimeout = _incoming.setTimeout.bind(_incoming);
incoming.method = _incoming.method;
incoming.url = _incoming.url;
incoming.statusCode = _incoming.statusCode;
incoming.statusMessage = _incoming.statusMessage;
incoming.socket = _incoming.socket;
cleanUp(undefined, incoming);
});
request.on('error', cleanUp);
request.setNoDelay(true);
request.setSocketKeepAlive(true);
if (params.body) {
request.setHeader('Content-Length', Buffer.byteLength(params.body, 'utf8'));
request.end(params.body);
} else {
request.end();
}
return () => {
request.abort();
};
}
} |
JavaScript | class ButtonGroupButton extends Button {
'__ember-bootstrap_subclass' = true;
/**
* @property groupValue
* @private
*/
/**
* @property buttonGroupType
* @type string
* @private
*/
/**
* @property active
* @type boolean
* @readonly
* @private
*/
get active() {
let { value, groupValue } = this.args;
if (this.args.buttonGroupType === 'radio') {
return value === groupValue;
} else {
if (isArray(groupValue)) {
return groupValue.indexOf(value) !== -1;
}
}
return false;
}
} |
JavaScript | class PortProvider {
/**
* Begin listening to port requests from other frames.
*
* @param {string} hypothesisAppsOrigin - the origin of the hypothesis apps
* is use to send the notebook and sidebar ports to only the frames that
* match the origin.
*/
constructor(hypothesisAppsOrigin) {
this._hypothesisAppsOrigin = '*';
this._emitter = new TinyEmitter();
/**
* IDs of port requests that have been handled.
*
* This is used to avoid responding to the same request multiple times.
* Guest frames in particular may send duplicate requests (see comments in
* PortFinder).
*
* @type {Set<string>}
*/
this._handledRequests = new Set();
// Create the `sidebar-host` channel immediately, while other channels are
// created on demand
this._sidebarHostChannel = new MessageChannel();
this._listeners = new ListenerCollection();
/** @type {Array<Partial<Message> & {allowedOrigin: string}>} */
this._allowedMessages = [
{
allowedOrigin: '*',
frame1: 'guest',
frame2: 'host',
type: 'request',
},
{
allowedOrigin: '*',
frame1: 'guest',
frame2: 'sidebar',
type: 'request',
},
{
allowedOrigin: this._hypothesisAppsOrigin,
frame1: 'sidebar',
frame2: 'host',
type: 'request',
},
{
allowedOrigin: this._hypothesisAppsOrigin,
frame1: 'notebook',
frame2: 'sidebar',
type: 'request',
},
];
this._listen();
}
_listen() {
const errorContext = 'Handling port request';
const sentErrors = /** @type {Set<string>} */ (new Set());
/** @param {string} message */
const reportError = message => {
if (sentErrors.has(message)) {
// PortFinder will send requests repeatedly until it gets a response or
// a timeout is reached.
//
// Only send errors once to avoid spamming Sentry.
return;
}
sentErrors.add(message);
sendError(new Error(message), errorContext);
};
/** @param {MessageEvent} event */
const handleRequest = event => {
const { data, origin, source } = event;
if (!isMessage(data) || data.type !== 'request') {
// If this does not look like a message intended for us, ignore it.
return;
}
const { frame1, frame2, requestId } = data;
const channel = /** @type {Channel} */ (`${frame1}-${frame2}`);
if (!isSourceWindow(source)) {
reportError(
`Ignored port request for channel ${channel} from non-Window source`
);
return;
}
const match = this._allowedMessages.find(
({ allowedOrigin, ...allowedMessage }) =>
this._messageMatches({
allowedMessage,
allowedOrigin,
data,
origin,
})
);
if (match === undefined) {
reportError(
`Ignored invalid port request for channel ${channel} from ${origin}`
);
return;
}
if (this._handledRequests.has(requestId)) {
return;
}
this._handledRequests.add(requestId);
// Create the channel for these two frames to communicate and send the
// corresponding ports to them.
const messageChannel =
channel === 'sidebar-host'
? this._sidebarHostChannel
: new MessageChannel();
const message = { frame1, frame2, type: 'offer', requestId };
source.postMessage(message, '*', [messageChannel.port1]);
if (frame2 === 'sidebar') {
this._sidebarHostChannel.port2.postMessage(message, [
messageChannel.port2,
]);
} else if (frame2 === 'host') {
this._emitter.emit('frameConnected', frame1, messageChannel.port2);
}
};
this._listeners.add(
window,
'message',
captureErrors(handleRequest, errorContext)
);
}
/**
* @param {object} options
* @param {Partial<Message>} options.allowedMessage - the `data` must match this
* `Message`.
* @param {string} options.allowedOrigin - the `origin` must match this
* value. If `allowedOrigin` is '*', the origin is ignored.
* @param {unknown} options.data - the data to be compared with `allowedMessage`.
* @param {string} options.origin - the origin to be compared with
* `allowedOrigin`.
*/
_messageMatches({ allowedMessage, allowedOrigin, data, origin }) {
if (allowedOrigin !== '*' && origin !== allowedOrigin) {
return false;
}
return isMessageEqual(data, allowedMessage);
}
/**
* @param {'frameConnected'} eventName
* @param {(source: 'guest'|'sidebar', port: MessagePort) => void} handler - this handler
* fires when a frame connects to the host frame
*/
on(eventName, handler) {
this._emitter.on(eventName, handler);
}
destroy() {
this._listeners.removeAll();
}
} |
JavaScript | class Collection {
/**
* @param {Object} options
* @param {List} options.primary_key - list of property names
*/
constructor (options) {
options = options || {};
this._primary_key = options.primary_key || [];
this._records = [];
this._populators = {};
}
get records () { return this._records; }
get primary_key() { return this._primary_key; }
/**
* Declare a partial function to another collection.
*
* @param {Collection} that - other collection
* @param {KeyMap} keymap - maps properties of that to properties of this
* @param {string} refprop - name of property in this
*
* this.populate(rec) sets rec.refprop to the matching record in that.
*
* @return this
*/
references (that, keymap, refprop) {
this._populators[refprop] = function (rec) {
let query = _.mapValues(keymap, k => rec[k]);
return _.find(that.records, query) || null;
};
return this;
}
/**
* Assign refprops
*/
populate (rec) {
_.forEach(this._populators, (fn, refprop) => rec[refprop] = fn(rec));
return rec;
}
/**
* Add a record to the collection.
*/
add (record) {
this._records.push(record);
}
/**
* Look up a record by primary key.
* @return record, null if not found.
*/
findByKey (...args) {
assert(args.length === this._primary_key.length, 'wrong#args');
var selector = _.fromPairs(_.zip(this._primary_key, args))
, ans = this.chain().find(selector).value();
return ans || null;
}
/**
* Start a lodash chain.
*/
chain () {
return _.chain(this._records);
}
} |
JavaScript | class StartSubjectModel {
/**
*
* @param {Object} opts
* @param {Object} opts.kafkaProducer Optional. kafka producer instance to use. If not provided one will be create.
* @param {String} opts.groupId groupId to use in message key. defaults to 'start-subject-model'. used in message source
* @param {Boolean} opts.log log when event messages are sent
*/
constructor(opts={}) {
this.opts = opts;
this.groupId = opts.groupId || 'start-subject-model';
if( opts.kafkaProducer ) {
this.kafkaProducer = kafkaProducer;
} else {
this.kafkaProducer = new kafka.Producer({
'metadata.broker.list': config.kafka.host+':'+config.kafka.port
});
}
}
async connect() {
await this.kafkaProducer.connect();
}
async send(file, data) {
let subject = 'file://'+path.join('/', file);
let baseDir = path.parse(path.join(config.fs.nfsRoot, file)).dir;
await fs.mkdirp(baseDir);
await fs.writeFile(path.join(config.fs.nfsRoot, file), data);
let value = {
id : uuid.v4(),
time : new Date().toISOString(),
type : 'new.subject',
source : 'http://'+this.groupId+'.'+config.server.url.hostname,
datacontenttype : 'application/json',
subject
}
if( this.opts.log === true ) {
logger.info(this.groupId+' sending subject ready to kafka: ', subject)
}
await this.kafkaProducer.produce({
topic : config.kafka.topics.subjectReady,
value
});
}
} |
JavaScript | class Character {
constructor(context, sprites, position) {
this.context = context;
this.width = 32;
this.height = 32;
this.sprites = sprites;
this.position = position;
this.img = new Image();
this.img.onload = () => {
this.draw();
};
this.img.src = this.sprites[0];
}
draw() {
this.context.drawImage(this.img, this.position.x, this.position.y);
}
} |
JavaScript | class ThreeWrap {
constructor(el, beforeInitFn) {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 75, el.width/el.height, 0.1, 1000 );
this.renderer = new THREE.WebGLRenderer({
canvas: el,
alpha: true
});
this.renderer.setSize(el.width, el.height );
// this.gui = new dat.GUI();
this.guied = [];
beforeInitFn.call(this);
this.init({scene: this.scene, camera: this.camera, addToScene: this.addToScene.bind(this)});
this.guied.forEach(x => {
this.gui.addFolder(x.gui.folderName);
Object.keys(x.gui.params)
.forEach(key => {
let meta = x.gui.meta[key] || []
this.gui.add(x.gui.params, key, ...meta)
})
})
this.camera.position.z = 5;
this.animate = this.animate.bind(this);
this.animate();
}
onResize() {
}
addToScene(obj) {
if(obj.hasGui) {
this.guied.push(obj)
}
this.scene.add(obj);
}
init({scene}) {
}
onEnterFrame({camera}){
}
animate() {
requestAnimationFrame( this.animate );
this.guied.forEach(x => {
x.updateWithGuiValues()
});
this.onEnterFrame({
scene: this.scene,
camera: this.camera
})
this.renderer.render( this.scene, this.camera );
};
} |
JavaScript | class Term {
/**
*
* @param {string} name name of the Term ('tall', 'low', 'yong', 'old', 'fast', 'slow', etc...)
* @param {string} mfType type of membership functions. See mfTypes.
* @param {Array.<number>} mfParams parameters of the membership function. Here is some defaults.
*/
constructor (name, mfType = 'triangle', mfParams = getDefaultParams(mfType)) {
this.name = name;
if (!mfTypes[mfType]) mfType = 'triangle';
this.mfType = mfType;
this.mf = mfTypes[mfType];
this.mfParams = mfParams;
}
/**
* Returns membership function value at x
* @param {number} x
* @returns {number}
*/
valueAt (x) {
let args = this.mfParams.slice();
args.splice(0, 0, x); // insert to args value of x as first param
return this.mf.apply(this, args);
};
} |
JavaScript | class GetAndSet {
getAndSet = null; // error at "getAndSet"
public get haveGetAndSet() { // this should not be an error
return this.getAndSet;
}
// this shouldn't be an error
public set haveGetAndSet(value) { // error at "value"
this.getAndSet = value;
}
} |
JavaScript | class StackableCard {
constructor(megabas, id) {
this._megabas = megabas;
this._id = id.toString();
this._stackLevel = id;
this._baseObjName = "stackableCard:" + id;
this._inputPorts = new Array(8);
this._dacOutputPorts = new Array(8);
}
/**
* Returns the input ports
*/
get inputPorts() {
return this._inputPorts;
}
/**
* Returns the analog output ports
*/
get dacOutputPorts() {
return this._dacOutputPorts;
}
/**
* Returns base address of this card in the I2C bus
*/
get hwBaseAddress() {
return megabasConstants_1.MegabasConstants.HW_ADD + this._stackLevel;
}
/**
* Returns the name of the device object in ioBroker
*/
get objectName() {
return this._baseObjName;
}
/**
* Initializes the states in the ioBroker object model
*/
async InitializeIoBrokerObjects() {
await this._megabas.setObjectNotExistsAsync(this._baseObjName, {
type: "device",
common: {
name: "Stackable card level " + this._id,
},
native: {},
});
for (let i = 0; i < 8; i++) {
const port = new inputPort_1.InputPort(this._megabas, this, i);
port.InitializeInputPort();
this._inputPorts[i] = port;
}
for (let i = 0; i < 4; i++) {
const port = new dacOutputPort_1.DacOutputPort(this._megabas, this, i);
port.InitializeOutputPort();
this._dacOutputPorts[i] = port;
}
}
/**
* Subscribes the necessary properties for updates from ioBroker
*/
SubscribeStates() {
this._inputPorts.forEach((port) => {
port.SubscribeStates();
});
this._dacOutputPorts.forEach((port) => {
port.SubscribeStates();
});
}
/**
* Reads the current status from the Megabas
* @param i2cBus The I2C bus to read the the data from
*/
UpdateI2c(i2cBus) {
this._megabas.log.silly("Reading i2c status");
const dryContactStatus = i2cBus.readByteSync(this.hwBaseAddress, megabasConstants_1.MegabasConstants.DRY_CONTACT_VAL_ADD);
let mask = 1;
let contactClosed = false;
for (let i = 0; i < 8; i++) {
mask = 1 << i;
contactClosed = (dryContactStatus & mask) > 0;
this._megabas.log.silly(`${this._baseObjName} contact ${i}: ${contactClosed}`);
this._inputPorts[i].UpdateValue(contactClosed, i2cBus);
}
}
} |
JavaScript | class BasePaginationControlsGroup extends BaseControlsGroup{
/**
* there can be only 1 pagination options object;
* in case of multiple -> get the latest
* @return {object|null} pagination options
*/
getPaginationOptions(){
if(this.controls.length > 0){
return this.controls[this.controls.length - 1].getPaginationOptions();
}
return null;
}
/**
* update controls according to the pagination options calculated using PaginationAction class;
* @param {PaginationAction} paginationOptions
*/
setPaginationOptions(paginationOptions){}
/**
* add control to the group
* @param {BaseControl} control
* @return {BasePaginationControl|null}
*/
addControl(control){
if(control.name !== this.name || control.group !== this.group){
return null;
}
const basePaginationControl = new BasePaginationControl(control.element);
this.controls.push(basePaginationControl);
return basePaginationControl;
}
} |
JavaScript | class Post extends Component {
static propTypes = {
showModal: PropTypes.func.isRequired,
user: PropTypes.string.isRequired,
csrf: PropTypes.string,
post: PropTypes.shape(PropTypes.object.isRequired),
handleUpvote: PropTypes.func.isRequired,
upvotePayload: PropTypes.shape(PropTypes.object.isRequired),
isCommenting: PropTypes.bool.isRequired,
commentedId: PropTypes.number,
commentPayload: PropTypes.shape(PropTypes.object.isRequired),
getContent: PropTypes.func.isRequired,
replies: PropTypes.arrayOf(PropTypes.object.isRequired),
match: PropTypes.shape(PropTypes.object.isRequired),
isAuth: PropTypes.bool.isRequired,
groups: PropTypes.arrayOf(PropTypes.object.isRequired),
modalOpenAddPost: PropTypes.bool.isRequired,
postExists: PropTypes.bool.isRequired,
addPostLoading: PropTypes.bool.isRequired,
handleModalClickAddPost: PropTypes.func.isRequired,
onModalCloseAddPost: PropTypes.func.isRequired,
handleGroupSelect: PropTypes.func.isRequired,
isFetchingDetails: PropTypes.bool.isRequired,
isUpdating: PropTypes.bool,
draft: PropTypes.shape(PropTypes.object.isRequired),
isDeleting: PropTypes.bool,
redirect: PropTypes.string,
resteemedPayload: PropTypes.shape(PropTypes.object.isRequired),
clearPostDetails: PropTypes.func,
clearComments: PropTypes.func,
clearNewComments: PropTypes.func,
showEditPost: PropTypes.func,
sendDeletePost: PropTypes.func,
handleResteem: PropTypes.func,
sendComment: PropTypes.func.isRequired,
allFollowing: PropTypes.func,
followingList: PropTypes.arrayOf(PropTypes.string),
};
static defaultProps = {
post: {},
groups: [],
upvotePayload: {},
commentPayload: {},
commentedId: 0,
match: {},
csrf: '',
replies: [],
isUpdating: false,
draft: {},
isDeleting: false,
redirect: '',
resteemedPayload: {},
followingList: [],
clearPostDetails: () => {},
clearComments: () => {},
clearNewComments: () => {},
showEditPost: () => {},
handleResteem: () => {},
sendDeletePost: () => {},
allFollowing: () => {},
}
constructor(props) {
super(props);
this.existPost = "Post already in group.";
this.redirect = '';
}
/**
* Extract the author and permlink from the route address and call the
* redux function to get the content of the post.
*/
componentDidMount() {
const {
getContent,
allFollowing,
match: {
params: {
author,
permlink
}
}
} = this.props;
getContent(author, permlink);
allFollowing();
}
/**
* This is needed to pull new data from a post after an update is done.
* Rather than simpy update the title, body and tags alone from the draft
* update, the time elapsed could contain new comments or upvotes that
* are usefult o see after an update, and one might expect to see.
*/
componentDidUpdate(prevProps) {
const {
getContent,
draft,
redirect,
clearPostDetails,
match: {
params: {
author,
permlink
}
}
} = this.props;
this.redirect = '';
//if no draft present, get content data from Redux
if (!hasLength(draft) && draft !== prevProps.draft) {
getContent(author, permlink);
}
//if redirect requested, clear previous post data in Redux
if (redirect && redirect !== prevProps.redirect) {
this.redirect = redirect;
clearPostDetails();
}
}
componentWillUnmount() {
const { clearPostDetails, clearComments, clearNewComments } = this.props;
clearPostDetails();
clearComments();
clearNewComments();
}
render() {
const {
user,
csrf,
isAuth,
match,
groups,
modalOpenAddPost,
postExists,
addPostLoading,
showModal,
handleModalClickAddPost,
onModalCloseAddPost,
handleGroupSelect,
post,
isFetchingDetails,
getContent,
handleUpvote,
upvotePayload,
replies,
isCommenting,
commentedId,
commentPayload,
isUpdating,
isDeleting,
resteemedPayload,
showEditPost,
sendDeletePost,
handleResteem,
sendComment,
followingList,
} = this.props;
let addErrorPost = '';
if (postExists) addErrorPost = <ErrorLabel position='left' text={this.existPost} />;
return (
this.redirect
? <Redirect to={this.redirect} />
: (
<ErrorBoundary>
<React.Fragment>
<ModalGroup
modalOpen={modalOpenAddPost}
onModalClose={onModalCloseAddPost}
handleModalClick={handleModalClickAddPost}
handleGroupSelect={handleGroupSelect}
groups={groups}
addErrorPost={addErrorPost}
addPostLoading={addPostLoading}
/>
{
!isFetchingDetails && !hasLength(post)
? <div>That post does not exist.</div>
: !isFetchingDetails && hasLength(post)
? (
<PostDetails
match={match}
showModal={showModal}
user={user}
csrf={csrf}
isAuth={isAuth}
getContent={getContent}
post={post}
handleUpvote={handleUpvote}
upvotePayload={upvotePayload}
replies={replies}
isCommenting={isCommenting}
commentedId={commentedId}
isFetching={isFetchingDetails}
commentPayload={commentPayload}
isUpdating={isUpdating}
isDeleting={isDeleting}
resteemedPayload={resteemedPayload}
showEditPost={showEditPost}
sendDeletePost={sendDeletePost}
handleResteem={handleResteem}
sendComment={sendComment}
followingList={followingList}
/>
)
: <Loading />
}
</React.Fragment>
</ErrorBoundary>
)
)
}
} |
JavaScript | class Mesh {
/**
* A point whose position is the average of all the vertices in the mesh.
* @type {vec4}
*/
get centroid() {
let sumPts = _.reduce(this.vertices, (memo, v) => {
memo[0] += v.xyz[0];
memo[1] += v.xyz[1];
memo[2] += v.xyz[2];
return memo;
}, [0,0,0]);
let centroid = vec3.scale([], sumPts, 1/this.vertices.length);
centroid[3] = 1;
return centroid;
}
/**
* The mesh's face culling mode. This can be any of the following:
* GL_FRONT: cull front faces for each triangle.
* GL_BACK: cull back faces for each triangle.
* GL_FRONT_AND_BACK: cull both faces for each triangle.
* @type {GLenum}
*/
get cullMode() {
return this._cullMode;
}
set cullMode(mode) {
this._cullMode = mode || GL_BACK;
}
/**
* The mesh's drawing mode. This defines how the indices should be ordered
* to draw each primitive. This can be any of the following:
* GL_POINTS: Each vertex is drawn as a point.
* GL_LINES: Every 2 vertices are drawn as a line segment.
* GL_LINE_STRIP: A line is drawn from each vertex to the next vertex.
* GL_LINE_LOOP: A line is drawn from each vertex to the next, plus a line
* connecting the last vertex to the first.
* GL_TRIANGLES: Every 3 vertices are drawn as a triangle.
* @type {GLenum}
*/
get drawMode() {
return this._drawMode;
}
set drawMode(mode) {
this._drawMode = mode || GL_TRIANGLES;
}
/**
* The winding direction used to determine the front face of each triangle
* in this mesh. This can be either of the following:
* GL_CW: The face where the vertices are in clockwise order is the front.
* GL_CCW: The face where the vertices are in counter-clockwise order is
* the front.
* @type {GLenum}
*/
get frontFace() {
return this._frontFace;
}
set frontFace(mode) {
this._frontFace = mode || GL_CCW;
}
/**
* The vertex indices specifying the order to draw the mesh's primitives.
* @type {uint[]}
*/
get indices() {
return this._indices;
}
set indices(v) {
this._indices = v;
}
/**
* The vertices defining the mesh.
* @type {KraGL.geo.Vertex[]}
*/
get vertices() {
return this._vertices;
}
set vertices(v) {
this._vertices = v;
}
/**
* @param {object} opts
* @param {GLenum} [opts.cullMode=GL_FRONT_AND_BACK]
* The face culling mode used for the mesh.
* @param {GLenum} [opts.drawMode=GL_TRIANGLES]
* The drawing mode used for the mesh.
* @param {GLenum} [opts.frontFace=GL_CCW]
* The winding direction used to determine the front of each triangle.
* @param {boolean} [opts.generateTangents=false]
* Whether to generate tangent vectors for each vertex for normal
* mapping.
* @param {uint[]} opts.indices
* The list of indices specifying the order to draw the vertices as
* more complex primitives defined by drawMode.
* @param {class} [opts.vertexClass=KraGL.geo.Vertex]
* The class used to construct the vertices.
* If given, this must be a child class of KraGL.geo.Vertex.
* @param {object} opts.vertices
* A list of options for constructing the mesh's vertices.
*/
constructor(opts) {
let VertClass = opts.vertexClass || Vertex;
this.vertices = [];
_.each(opts.vertices, vertOpts => {
let vertex = new VertClass(vertOpts);
this.vertices.push(vertex);
});
this.indices = opts.indices;
this.drawMode = opts.drawMode;
this.cullMode = opts.cullMode;
this.frontFace = opts.frontFace;
// A map of ShaderProgram names to Vertex Buffer Objects (VBOs).
this._vbos = {};
// Generate the tangent vectors if enabled.
if(opts.generateTangents)
this._generateTangents();
}
/**
* Unloads any GL resources associated with this mesh.
* @param {WebGLRenderingContext} gl
*/
clean(gl) {
_.each(this._vbos, vbo => {
vbo.clean(gl);
});
this._vbos = {};
}
/**
* Creates a cloned copy of this mesh.
* @return {KraGL.geo.Mesh}
*/
clone() {
return this.transform(mat4.identity([]));
}
/**
* Generates the tangent vector for each each vertex in the
* mesh, based on relative texture coordinates.
* Algorithm stolen from
* https://learnopengl.com/Advanced-Lighting/Normal-Mapping.
*/
_generateTangents() {
if(this.drawMode === GL_TRIANGLES) {
let numTriangles = Math.floor(this.indices.length/3);
_.each(numTriangles, triIndex => {
let i1 = this.indices[triIndex * 3];
let i2 = this.indices[triIndex * 3 + 1];
let i3 = this.indices[triIndex * 3 + 2];
let v1 = this.vertices[i1];
let v2 = this.vertices[i2];
let v3 = this.vertices[i3];
let edge1 = vec3.sub([], v2.xyz, v1.xyz);
let edge2 = vec3.sub([], v3.xyz, v1.xyz);
let deltaUV1 = vec2.sub([], v2.uv, v1.uv);
let deltaUV2 = vec2.sub([], v3.uv, v1.uv);
// Keep in mind that in the GL matrices used here are in
// row-major order. That is - the coordinates XY correspond to
// row and column, respectively.
let matUV = [ deltaUV1, deltaUV2 ];
let matEdges = [
[edge1[0], edge2[0]],
[edge1[1], edge2[1]],
[edge1[2], edge2[2]]
];
let matUVInv = Matrices.inverse(matUV);
let [tangent, bitangent] = Matrices.transpose(
Matrices.mul(matUVInv, matEdges)
);
v1.t = tangent;
v2.t = tangent;
v3.t = tangent;
// Technically, we can just compute the bitangent from the cross
// product of the normal and tangent vectors.
v1.b = bitangent;
v2.b = bitangent;
v3.b = bitangent;
});
}
else
throw new GeometryError('');
}
/**
* Renders the mesh using the VBO associated with the currently bound
* ShaderProgram.
* @param {KraGL.app.Application} app
* The application the mesh is being rendered in.
*/
render(app) {
let shaderName = app.shaderLib.curName;
let shader = app.shaderLib.curProgram;
let gl = app.gl;
// Set up GL state.
gl.cullFace(this.cullMode);
gl.frontFace(this.frontFace);
// Create the VBO data for the model if it doesn't already exist for
// the current shader.
if(!this._vbos[shaderName])
this._vbos[shaderName] = new VBO(shader, this);
// Render the mesh's VBO for the current shader.
let vbo = this._vbos[shaderName];
vbo.render(gl, this.drawMode);
}
/**
* Produces a mesh resulting from an affine transformation applied to this
* mesh.
* @param {mat4} m
* The matrix for the affine transformation.
* @return {KraGL.geo.Mesh}
*/
transform(m) {
return new Mesh({
cullMode: this.cullMode,
drawMode: this.drawMode,
frontFace: this.frontFace,
indices: _.clone(this.indices),
vertices: _.map(this.vertices, v => {
return v.transform(m);
})
});
}
} |
JavaScript | class ConsoleLogger extends BaseLogger {
/**
*
* @param {Object} data
*/
log(data) {
this._prepareLog('cyan', 'log', data)
}
/**
*
* @param {Object} data
*/
info(data) {
this._prepareLog('reset', 'info', data)
}
/**
*
* @param {Object} data
*/
warn(data) {
this._prepareLog('yellow', 'warn', data)
}
/**
*
* @param {Object} data
*/
error(data) {
this._prepareLog('red', 'error', data)
}
/**
*
* @param {string} color
* @param {string} prefix
* @param {Object} data
* @private
*/
_prepareLog(color, prefix, data) {
Object.keys(data).forEach(key => {
if (data[key] instanceof Error) {
data[key] = data[key].stack || data[key]
}
})
console.log(`${COLOR_CODES[color]}[${prefix}] ${COLOR_CODES.reset}`)
Object.keys(data).forEach(key => console.log(key, data[key]))
console.log('\n')
}
} |
JavaScript | class SearchBar extends Component {
// STATE constructor. OOP style
// is only relevant for individual component instances.
constructor(props) {
super(props);
this.state = { term: '' }; //creates a state, only place for this syntax
// to change it, it is this.setState({})
}
render() {
return (
<div className="search-bar">
<input
// makes input a controlled component
value = {this.state.term}
// value only changes when the state changes
onChange={event => this.onInputChange(event.target.value)} />
</div>
)
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term); //triggers the callback
}
} |
JavaScript | class ChannelStatListFormatter extends BaseFormatter {
/**
* Constructor for channel stat list formatter.
*
* @param {object} params
* @param {array} params.channelIds
* @param {object} params.channelStatsMap
*
* @augments BaseFormatter
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.channelIds = params.channelIds;
oThis.channelStatsMap = params.channelStatsMap;
}
/**
* Validate the input objects.
*
* @returns {result}
* @private
*/
_validate() {
const oThis = this;
if (!CommonValidators.validateArray(oThis.channelIds)) {
return responseHelper.error({
internal_error_identifier: 'l_f_s_cs_l_1',
api_error_identifier: 'entity_formatting_failed',
debug_options: { array: oThis.channelIds }
});
}
if (!CommonValidators.validateObject(oThis.channelStatsMap)) {
return responseHelper.error({
internal_error_identifier: 'l_f_s_cs_l_2',
api_error_identifier: 'entity_formatting_failed',
debug_options: { object: oThis.channelStatsMap }
});
}
return responseHelper.successWithData({});
}
/**
* Format the input object.
*
* @returns {result}
* @private
*/
_format() {
const oThis = this;
const finalResponse = [];
for (let index = 0; index < oThis.channelIds.length; index++) {
const channelId = oThis.channelIds[index],
channelStat = oThis.channelStatsMap[channelId];
const formattedChannel = new ChannelStatSingleFormatter({ channel: channelStat }).perform();
if (formattedChannel.isFailure()) {
return formattedChannel;
}
finalResponse.push(formattedChannel.data);
}
return responseHelper.successWithData(finalResponse);
}
} |
JavaScript | class Dog extends Animal {
speak() {
// calling parent classes' super method which returns a string
// "my name is <object-name>"
let superString = super.speak();
return `woof woof ${superString}`;
}
} |
JavaScript | class Cat extends Animal {
speak() {
// calling parent classes' super method which returns a string
// "my name is <object-name>"
let superString = super.speak();
return `meow meow ${superString}`;
}
} |
JavaScript | class Context {
constructor () {
this.ctx = {};
}
set = item => {
this.ctx = Object.assign ({}, this.ctx, item);
};
get = key => {
return key ? this.ctx[key] : this.ctx;
};
} |
JavaScript | class PassthroughLoader {
constructor(modelArtifacts) {
this.modelArtifacts = modelArtifacts;
}
async load() {
return this.modelArtifacts;
}
} |
JavaScript | class MixClient extends MixConnector{
/**
* Connect to a network via:
* - web3 object supplied as param
* - Explicit URI supplied as param
* - Explicit URI stored in localstorage.
* - Metamask (https://metamask.io/)
*
* Explicit URI overrides Metamask
*
* @constructor
* @param {String}[nodeURI = null] nodeURI
* @param {Object}[web3 = null] web3
*
* @throws{Error} if connection is not made
*
*/
constructor(nodeURI = null, web3Object = null) {
super();
try{
this.blockchainConnect(nodeURI, web3Object);
}catch(err){
console.error(err);
return;
}
// Instantiate libraries
this._systemStats = new MixSystemStats(this.web3);
this._mixSearch = new MixSearch(this.web3);
}
/**
* Determine which blockchain the client is connected to by matching the hash
* of block 192001 from the connected blockchain to known blockchains
*
* @returns {Promise}
*/
getBlockchainName(){
const IDENTIFYING_BLOCK = 1920001,
blockchainHashes = {
'0x7644ba8795e260e7c4ad9f7e72aa1d0856f914f1a4847fb903aa504da29f9d22' : 'Mix',
'0x87b2bc3f12e3ded808c6d4b9b528381fa2a7e95ff2368ba93191a9495daa7f50' : 'Ethereum',
'0xab7668dfd3bedcf9da505d69306e8fd12ad78116429cf8880a9942c6f0605b60' : 'Ethereum Classic'
};
return new Promise(
(resolve, reject)=>{
// The Ethereum hard fork was at block 1920000. Therefore the block at 1920001 will have a different hash
// depending on whether it is from the Ethereum or Ethereum classic blockchain.
this.getBlock(IDENTIFYING_BLOCK).then(
(block)=>{
if(!block) return this.getBlock(1);
resolve(blockchainHashes[block.hash]);
}
).then(
(firstBlock)=>{
if(!firstBlock || !blockchainHashes[firstBlock.hash]){
return resolve('Unknown blockchain');
}
resolve(blockchainHashes[firstBlock.hash]);
}
);
}
);
}
/**
* Watch the network for new blocks
*
* @param {function} callback
* @param {function} errorCallback
* @returns {Object} filter
*/
watchNetwork(callback, errorCallback){
const filter = this.web3.eth.filter('latest');
filter.watch(function(error, result){
if(error){
return errorCallback(error);
}
callback(result);
});
return filter;
}
/**
* Take a hash, address or block number and search for:
* - An account balance
* - A transaction
* - A block
*
* @param query
* @returns {Promise}
*
*/
doSearch(query){
const promises = [
this._mixSearch.getBlock(query),
this._mixSearch.getBalance(query),
this._mixSearch.getTransaction(query)
];
return new Promise(
(resolve, reject)=>{
Promise.all(promises).then(
(results)=>{
resolve(
{
block : results[0],
account : results[1],
transaction : results[2]
}
)
}
).catch(
(error)=>{
reject(error);
}
)
}
)
}
/**
* Numerous asynchronous calls to various APIs to retrieve system stats based on the last ten blocks
* of the blockchain. getLatestBlocks will initially make an asynchronous call to retrieve each
* individual block (I'm not aware of any other way of doing that with the web3 api). You can avoid that
* if you supply an existing list of latestBlocks via the param.
*
* @param {Array} [latestBlocks = null] - a prepopulated list of blocks
* @returns {Promise}
*
*/
getSystemStats(latestBlocks = null) {
// Must get system state before everything else.
return new Promise(
(resolve, reject)=>{
let stats = {};
this._systemStats.getState().then(
(state)=>{
stats.state = state;
let promises = [
this._systemStats.getPeerCount(),
this._systemStats.getGasPrice()
];
if(!latestBlocks){
promises.push(this._systemStats.getLatestBlocks());
}
Promise.all(promises).then(
(results)=>{
stats.peerCount = results[0];
stats.gasPrice = results[1];
stats.latestBlocks = latestBlocks || results[2];
stats.difficulty = this._systemStats.getAverageDifficulty(stats.latestBlocks);
stats.blockTimes = this._systemStats.getBlockTimes(stats.latestBlocks);
stats.hashRate = this._systemStats.getHashRate();
resolve(stats);
}
).catch(
(error)=>{
console.error(error.message);
reject(error);
}
);
}
);
}
)
}
/**
* Add a new block to the latestBlocks list and update the system stats
*
* @param {Array} latestBlocks - a list of Ethereum blocks
* @returns {Promise}
*/
updateBlocks(latestBlocks){
this._systemStats.setLatestBlocks(latestBlocks);
// Returns promise
return this.getSystemStats(latestBlocks);
}
/**
* Returns the last ten blocks of the blockchain
*
* @returns {Promise}
*/
getBlocks(){
return new Promise(
(resolve, reject)=>{
this._systemStats.getState().then(
()=>{
this._systemStats.getLatestBlocks().then(
(latestBlocks)=>{
resolve(latestBlocks);
}
)
}
)
}
);
}
/**
* Return an Ethereum block based on block hash or number
*
* @param {String} hashOrNumber
* @returns {Promise}
*/
getBlock(hashOrNumber){
// Returns promise
return this._mixSearch.getBlock(hashOrNumber);
}
/**
* Retrieve a transaction by transaction hash
*
* @param {String} transactionHash
* @returns {Promise}
*/
getTransaction(transactionHash){
// Returns promise
return this._mixSearch.getTransaction(transactionHash);
}
/**
* Retrieve the balance for an account at accountHash
*
* @param {String} accountHash
* @returns {Promise}
*/
getAccountBalance(accountHash){
// Returns promise
return this._mixSearch.getBalance(accountHash);
}
} |
JavaScript | class MappingsApiProvider extends BaseProvider {
/**
* Returns a Promise with a list of mappings from a jskos-server.
*/
_getMappings({ from, to, direction, mode, identifier, options }) {
let params = {}
if (from) {
params.from = from.uri
}
if (to) {
params.to = to.uri
}
if (direction) {
params.direction = direction
}
if (mode) {
params.mode = mode
}
if (identifier) {
params.identifier = identifier
}
options = Object.assign({}, { params }, options)
return this.get(this.registry.mappings, options).then(mappings => {
mappings = mappings || []
// Filter exact duplicates from result
let newMappings = []
for (let mapping of mappings) {
if (!newMappings.find(m => _.isEqual(m, mapping))) {
newMappings.push(mapping)
}
}
return newMappings
}).then(mappings => {
for (let mapping of mappings) {
// Add mapping type if not available
mapping.type = mapping.type || [jskos.defaultMappingType.uri]
// Add JSKOS mapping identifiers
mapping = jskos.addMappingIdentifiers(mapping)
// Add fromScheme and toScheme if missing
if (!mapping.fromScheme) {
mapping.fromScheme = _.get(mapping, "from.memberSet[0].inScheme[0]")
}
if (!mapping.toScheme) {
mapping.toScheme = _.get(mapping, "to.memberSet[0].inScheme[0]")
}
}
return mappings
})
}
/**
* Saves a mapping with http post or http put. Returns a Promise with the saved mapping.
*
* @param {*} mapping
* @param {*} original
*/
_saveMapping(mapping, original) {
mapping = jskos.minifyMapping(mapping)
mapping = jskos.addMappingIdentifiers(mapping)
let uri = _.get(original, "uri")
if (uri) {
// If there is a URI, use PUT to update the mapping.
return this.put(uri, mapping)
} else {
// Otherwise, use POST to save the mapping.
return this.post(this.registry.mappings, mapping)
}
}
/**
* Removes a mapping with http delete. Returns a Promise with a boolean whether removal was successful.
*/
_removeMapping(mapping) {
let uri = _.get(mapping, "uri")
if (uri) {
return this.delete(uri).then(result => result === undefined ? false : true)
} else {
return Promise.resolve(false)
}
}
/**
* Adds a new annotation with http POST.
*/
_addAnnotation(annotation) {
return this.post(this.registry.annotations, annotation)
}
/**
* Edits an annotation. If patch is given, http PATCH will be used, otherwise PUT.
*/
_editAnnotation(annotation, patch) {
let uri = _.get(annotation, "id")
if (uri) {
if (patch) {
return this.patch(uri, patch)
} else {
return this.put(uri, annotation)
}
} else {
return Promise.resolve(null)
}
}
/**
* Removes an annotation with http DELETE. Returns a Promise with a boolean whether removal was successful.
*/
_removeAnnotation(annotation) {
let uri = _.get(annotation, "id")
if (uri) {
return this.delete(uri).then(result => result === undefined ? false : true)
} else {
return Promise.resolve(false)
}
}
} |
JavaScript | class LightningAccordion extends LightningElement {
privateIsSectionLessInLastRender = true;
_allowMultipleSectionsOpen = false;
connected = false;
constructor() {
super();
this.privateAccordionManager = createAccordionManager();
this.privateAccordionManager.attachOpenSectionObserver(() => {
const openSections = this.activeSectionName;
// there is nothing but to dispatch the sectiontoggle here.
if (this.connected) {
this.dispatchEvent(
new CustomEvent('sectiontoggle', {
detail: {
openSections,
},
})
);
}
});
}
connectedCallback() {
this.connected = true;
this.setAttribute('role', 'list');
this.classList.add('slds-accordion');
this.addEventListener(
'privateaccordionsectionregister',
this.handleSectionRegister.bind(this)
);
}
disconnectedCallback() {
this.connected = false;
}
/**
* Displays tooltip text when the mouse moves over the element.
*
* @type {string}
*/
@api
get title() {
return this.getAttribute('title');
}
set title(value) {
this.setAttribute('title', value);
}
/**
* Expands the specified accordion sections. Pass in a string for a single section or a list of section names. Section names are case-sensitive.
* To support multiple expanded sections, include allow-multiple-sections-open in your markup.
* By default, only the first section in the accordion is expanded.
* @type {array|string}
*/
@api
get activeSectionName() {
const openSections = this.privateAccordionManager.openSectionsNames;
if (!this.allowMultipleSectionsOpen) {
return openSections.length ? openSections[0] : undefined;
}
return openSections;
}
set activeSectionName(value) {
this._activeSectionName = value;
if (!this.privateIsSectionLessInLastRender) {
this.privateAccordionManager.openSectionByName(value);
}
}
/**
* If present, the accordion allows multiple open sections.
* Otherwise, opening a section closes another that's currently open.
*
* @type {boolean}
* @default false
*/
@api
get allowMultipleSectionsOpen() {
return this._allowMultipleSectionsOpen;
}
set allowMultipleSectionsOpen(value) {
this._allowMultipleSectionsOpen = value;
this.privateAccordionManager.collapsible = value;
}
renderedCallback() {
if (this.privateIsSectionLessInLastRender) {
let hasOpenSection = false;
// open sectionName or first section.
if (this._activeSectionName) {
hasOpenSection = this.privateAccordionManager.openSectionByName(
this._activeSectionName
);
}
if (!(this._allowMultipleSectionsOpen || hasOpenSection)) {
this.privateAccordionManager.openFirstSection();
}
}
this.privateIsSectionLessInLastRender =
this.privateAccordionManager.sections.length === 0;
}
get openedSection() {
return this.privateAccordionManager.openedSection;
}
handleSectionRegister(event) {
event.stopPropagation();
event.preventDefault();
const { detail } = event;
const accordionSection = {
id: detail.targetId,
name: detail.targetName,
ref: event.target,
open: detail.openSection,
isOpen: detail.isOpen,
close: detail.closeSection,
focus: detail.focusSection,
ackParentAccordion: detail.ackParentAccordion,
};
this.privateAccordionManager.registerSection(accordionSection);
}
} |
JavaScript | class Session extends Connectable {
static BUFFER_SIZE = 2048;
/**
* @param {AudioContext} context This argument is in order to use the interfaces of Web Audio API.
* @param {number} bufferSize This argument is buffer size for `ScriptProcessorNode`.
* @param {number} numberOfInputs This argument is the number of inputs for `ScriptProcessorNode`.
* @param {number} numberOfOutputs This argument the number of outputs for `ScriptProcessorNode`.
* @param {Analyser} analyser This argument is the instance of `Analyser`.
*/
constructor(context, bufferSize, numberOfInputs, numberOfOutputs, analyser) {
super();
this.isActive = false;
this.context = context;
this.analyser = analyser; // the instance of `Analyser`
// HACK: Fix buffer size on different environments
this.sender = context.createScriptProcessor(Session.BUFFER_SIZE, numberOfInputs, numberOfOutputs);
this.receiver = context.createScriptProcessor(Session.BUFFER_SIZE, numberOfInputs, numberOfOutputs);
this.websocket = null; // for the instance of `WebSocket`
this.paused = true; // for preventing from the duplicate `onaudioprocess` event (`start` method)
}
/**
* This method creates the instance of `WebSocket` and registers event handlers.
* @param {boolean} tls This argument is in order to select protocol (either `wss` or `ws`).
* @param {string} host This argument is server's hostname.
* @param {number} port This argument is port number for connection.
* @param {string} path This argument is file that is executed in server side.
* @param {function} openCallback This argument is invoked as `onopen` event handler in the instance of `WebSocket`.
* @param {function} closeCallback This argument is invoked as `onclose` event handler in the instance of `WebSocket`.
* @param {function} errorCallback This argument is invoked as `onerror` event handler in the instance of `WebSocket`.
* @return {Session} This is returned for method chain.
*/
setup(tls, host, port, path, openCallback, closeCallback, errorCallback) {
/*
if (!navigator.onLine) {
// Clear
this.isActive = false;
this.paused = true;
this.connect();
this.websocket = null;
throw new Error('Now Offline.');
}
*/
// The argument is associative array ?
if (Object.prototype.toString.call(arguments[0]) === '[object Object]') {
const properties = arguments[0];
if ('tls' in properties) {
tls = properties.tls;
}
if ('host' in properties) {
host = properties.host;
}
if ('port' in properties) {
port = properties.port;
}
if ('path' in properties) {
path = properties.path;
}
if ('open' in properties) {
openCallback = properties.open;
}
if ('close' in properties) {
closeCallback = properties.close;
}
if ('error' in properties) {
errorCallback = properties.error;
}
}
const scheme = tls ? 'wss://' : 'ws://';
if (path.charAt(0) !== '/') {
path = `/${path}`;
}
const p = parseInt(port, 10);
if (isNaN(p) || (p < 0) || (p > 65535)) {
return this;
}
this.websocket = new WebSocket(`${scheme}${host}:${p}${path}`);
this.websocket.binaryType = 'arraybuffer';
this.websocket.onopen = event => {
if (Object.prototype.toString.call(openCallback) === '[object Function]') {
openCallback(event);
}
};
this.websocket.onclose = event => {
this.isActive = false;
this.paused = true;
this.connect();
if (Object.prototype.toString.call(closeCallback) === '[object Function]') {
closeCallback(event);
}
};
this.websocket.onerror = event => {
this.isActive = false;
this.paused = true;
this.connect();
if (Object.prototype.toString.call(errorCallback) === '[object Function]') {
errorCallback(event);
}
};
this.websocket.onmessage = event => {
if (!this.isActive) {
this.analyser.stop('time');
this.analyser.stop('fft');
return;
}
if (event.data instanceof ArrayBuffer) {
const total = event.data.byteLength / Float32Array.BYTES_PER_ELEMENT;
const length = Math.floor(total / 2);
const offset = length * Float32Array.BYTES_PER_ELEMENT;
const bufferLs = new Float32Array(event.data, 0, length); // Get Left channel data
const bufferRs = new Float32Array(event.data, offset, length); // Get Right channel data
// Start drawing sound wave
this.analyser.start('time');
this.analyser.start('fft');
this.receiver.onaudioprocess = event => {
const outputLs = event.outputBuffer.getChannelData(0);
const outputRs = event.outputBuffer.getChannelData(1);
if (bufferLs instanceof Float32Array) { outputLs.set(bufferLs); }
if (bufferRs instanceof Float32Array) { outputRs.set(bufferRs); }
// bufferLs = null;
// bufferRs = null;
if (!this.isActive || (this.websocket === null)) {
this.analyser.stop('time');
this.analyser.stop('fft');
}
};
}
};
return this;
}
/**
* This method connects nodes according to state.
* @return {Session} This is returned for method chain.
*/
connect() {
// Clear connection
this.receiver.disconnect(0);
this.sender.disconnect(0);
this.receiver.onaudioprocess = null;
this.sender.onaudioprocess = null;
if (this.isActive) {
// ScriptProcessorNode (Input) -> Analyser
this.receiver.connect(this.analyser.input);
// ScriptProcessorNode (Input) -> AudioDestinationNode (Output)
this.receiver.connect(this.context.destination);
} else {
this.paused = true;
}
return this;
}
/**
* This method sends sound data to server.
* @return {Session} This is returned for method chain.
*/
start() {
if (this.isActive && this.isConnected() && this.paused) {
this.paused = false;
const bufferSize = this.sender.bufferSize;
this.sender.onaudioprocess = event => {
if (this.isActive && this.isConnected()) {
const inputLs = event.inputBuffer.getChannelData(0);
const inputRs = event.inputBuffer.getChannelData(1);
const buffer = new Float32Array(2 * bufferSize);
const offset = parseInt((buffer.length / 2), 10);
for (let i = 0; i < bufferSize; i++) {
buffer[i] = inputLs[i];
buffer[offset + i] = inputRs[i];
}
if (this.websocket.bufferedAmount === 0) {
this.websocket.send(buffer);
}
}
};
}
return this;
}
/**
* This method closes connection to server and destroys the instance of `WebSocket`.
* @return {Session} This is returned for method chain.
*/
close() {
if (this.websocket instanceof WebSocket) {
this.isActive = false;
this.paused = true;
this.connect();
this.websocket.close();
this.websocket = null;
}
return this;
}
/**
* This method determines whether there is the connection to server.
* @return {boolean} If the connection to server exists, this value is `true`. Otherwise, this value is `false`.
*/
isConnected() {
return (this.websocket instanceof WebSocket) && (this.websocket.readyState === WebSocket.OPEN);
}
/**
* This method toggles active state or inactive state.
* @param {boolean|string} state If this argument is boolean, state is changed the designated.
* If this argument is 'toggle', state is changed automatically.
* If this argument is omitted, this method is getter.
* @param {function} stateCallback This argument is invoked when `bufferedAmount` equals to 0.
* @param {function} waitCallback This argument is invoked until `bufferedAmount` equals to 0.
* @return {Session} This is returned for method chain.
*/
state(state, stateCallback, waitCallback) {
if (state === undefined) {
return this.isActive;
}
if (Object.prototype.toString.call(waitCallback) === '[object Function]') {
waitCallback();
}
const intervalid = window.setInterval(() => {
if ((this.websocket instanceof WebSocket) && (this.websocket.bufferedAmount !== 0)) {
return;
}
if (String(state).toLowerCase() === 'toggle') {
this.isActive = !this.isActive;
} else {
this.isActive = Boolean(state);
}
this.connect();
if (Object.prototype.toString.call(stateCallback) === '[object Function]') {
stateCallback();
}
window.clearInterval(intervalid);
}, 10);
return this;
}
/**
* This method gets the instance of `WebSocket`.
* @return {WebSocket}
*/
get() {
return this.websocket;
}
/** @override */
get INPUT() {
return this.sender;
}
/** @override */
get OUTPUT() {
return this.sender;
}
/** @override */
toString() {
return '[SoundModule Session]';
}
} |
JavaScript | class AbstractService {
/**
* @param {Object} options
* @param {Joi} optionsSchema
*/
constructor(options = {}, optionsSchema = {}) {
this.options = Validator.options(options, optionsSchema);
this.logger = {
log: () => {}
};
}
/**
* Set service logger
*
* @param {Object} logger
* @param {Function} logger.log Log function
*/
setLogger(logger) {
this.logger = Validator.api(logger, {
log: Joi.func()
}, 'logger');
}
/**
* Async validates params using Joi schema provided.
*
* @param {Object} params
* @param {Joi} schema
* @param {boolean} [strict=true] false - allows unknown parameters
* @returns {Promise}
*/
validateParamsAsync(params, schema, strict = true) {
return Validator.paramsAsync(params, schema, strict);
}
/**
* Alias of {@link AbstractService#validateParamsAsync}
*/
paramsAsync(params, schema, strict = true) {
return this.validateParamsAsync(params, schema, strict);
}
/**
* Validates params using Joi schema provided.
*
* @param {Object} params
* @param {Joi} schema
* @param {boolean} [strict=true] false - allows unknown parameters
* @returns {*}
*/
validateParams(params, schema, strict = true) {
return Validator.params(params, schema, strict);
}
/**
* Alias of {@link AbstractService#validateParams}
*/
params(params, schema, strict = true) {
return this.validateParams(params, schema, strict);
}
} |
JavaScript | class DefaultTheme {
constructor() {
this.$el = document.createElement('div');
}
createControls() {
// TODO (hub33k): wrap all controls within this div
const $controls = document.createElement('div');
$controls.classList.add('controls');
this.$el.appendChild($controls);
return this;
}
createProgress() {
const $progress = document.createElement('div');
const $progressBar = document.createElement('div');
$progress.classList.add('progress', 'bg-white', 'mb-2');
$progressBar.classList.add('progress-bar', 'bg-success');
$progressBar.style.width = '0%';
$progress.appendChild($progressBar);
this.$el.appendChild($progress);
return this;
}
addButton(name, label, callback) {
const $button = document.createElement('button');
$button.classList.add('btn', 'btn-outline-primary', 'mr-2', name);
$button.textContent = label;
$button.addEventListener('click', callback);
this.$el.appendChild($button);
return this;
}
render(target) {
target.append(this.$el);
return this.$el;
}
} |
JavaScript | class HmrOptionBuilder {
/**
* @param {?} __0
*/
constructor({ deferTime, autoClearLogs }) {
this.deferTime = deferTime || 100;
this.autoClearLogs = autoClearLogs === undefined ? true : autoClearLogs;
}
/**
* @return {?}
*/
clearLogs() {
if (this.autoClearLogs) {
console.clear();
}
}
} |
JavaScript | class TwoFA extends React.Component {
static propTypes = {
/** @ignore */
password: PropTypes.object.isRequired,
/** @ignore */
is2FAEnabled: PropTypes.bool.isRequired,
/** @ignore */
set2FAStatus: PropTypes.func.isRequired,
/** @ignore */
generateAlert: PropTypes.func.isRequired,
/** @ignore */
t: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
key: authenticator.generateKey(),
code: '',
passwordConfirm: false,
};
}
/**
* Update 2fa code value and trigger authentication once necessary length is reached
* @param {string} value - Code value
*/
setCode = (value) => {
const { is2FAEnabled } = this.props;
this.setState({ code: value }, () => {
if (value.length !== 6) {
return;
} else if (is2FAEnabled) {
this.disableTwoFA();
} else {
this.verifyCode();
}
});
};
verifyCode(e) {
const { key, code } = this.state;
const { generateAlert, t } = this.props;
if (e) {
e.preventDefault();
}
const validCode = authenticator.verifyToken(key, code);
if (validCode) {
this.setState({
passwordConfirm: true,
});
} else {
generateAlert('error', t('twoFA:wrongCode'), t('twoFA:wrongCodeExplanation'));
this.setState({
code: '',
});
}
}
enableTwoFA(password) {
const { key } = this.state;
const { generateAlert, set2FAStatus, t } = this.props;
try {
setTwoFA(password, key);
set2FAStatus(true);
this.setState({
key: '',
code: '',
passwordConfirm: false,
});
generateAlert('success', t('twoFA:twoFAEnabled'), t('twoFA:twoFAEnabledExplanation'));
} catch (err) {
generateAlert(
'error',
t('changePassword:incorrectPassword'),
t('changePassword:incorrectPasswordExplanation'),
);
return;
}
}
disableTwoFA = async () => {
const { code } = this.state;
const { password, generateAlert, set2FAStatus, t } = this.props;
try {
const key = await authorize(password);
const validCode = authenticator.verifyToken(key, code);
if (!validCode) {
generateAlert('error', t('twoFA:wrongCode'), t('twoFA:wrongCodeExplanation'));
this.setState({
passwordConfirm: false,
code: '',
});
return;
}
setTwoFA(password, null);
set2FAStatus(false);
this.setState({
key: authenticator.generateKey(),
code: '',
passwordConfirm: false,
});
generateAlert('success', t('twoFA:twoFADisabled'), t('twoFA:twoFADisabledExplanation'));
} catch (err) {
generateAlert(
'error',
t('changePassword:incorrectPassword'),
t('changePassword:incorrectPasswordExplanation'),
);
return;
}
};
disableTwoFAview() {
const { code } = this.state;
const { t } = this.props;
return (
<form
className={css.twoFa}
onSubmit={(e) => {
e.preventDefault();
this.disableTwoFA();
}}
>
<h3>{t('twoFA:enterCode')}</h3>
<Text value={code} label={t('twoFA:code')} onChange={this.setCode} />
<fieldset>
<Button type="submit" variant="primary">
{t('disable')}
</Button>
</fieldset>
</form>
);
}
enableTwoFAview() {
const { key, code } = this.state;
const { t } = this.props;
if (!key) {
return null;
}
const qr = new QRCode(-1, 1);
qr.addData(authenticator.generateTotpUri(key, 'Trinity desktop wallet'));
qr.make();
const cells = qr.modules;
return (
<form className={css.twoFa} onSubmit={(e) => this.verifyCode(e)}>
<h3>1. {t('twoFA:addKey')}</h3>
<svg width="160" height="160" viewBox={`0 0 ${cells.length} ${cells.length}`}>
{cells.map((row, rowIndex) => {
return row.map((cell, cellIndex) => (
<rect
height={1}
key={cellIndex}
style={{ fill: cell ? '#000000' : 'none' }}
width={1}
x={cellIndex}
y={rowIndex}
/>
));
})}
</svg>
<small>
{t('twoFA:key')}:{' '}
<Clipboard text={key} title={t('twoFA:keyCopied')} success={t('twoFA:keyCopiedExplanation')}>
<strong>{key}</strong>
</Clipboard>
</small>
<hr />
<h3>2. {t('twoFA:enterCode')}</h3>
<Text value={code} onChange={this.setCode} />
<fieldset>
<Button type="submit" disabled={code.length < 6} variant="primary">
{t('apply')}
</Button>
</fieldset>
</form>
);
}
render() {
const { passwordConfirm } = this.state;
const { is2FAEnabled, t } = this.props;
return (
<React.Fragment>
{is2FAEnabled ? this.disableTwoFAview() : this.enableTwoFAview()}
<Password
isOpen={passwordConfirm}
onSuccess={(password) => this.enableTwoFA(password)}
onClose={() => this.setState({ passwordConfirm: false })}
content={{
title: t('enterPassword'),
confirm: is2FAEnabled ? t('disable') : t('enable'),
}}
/>
</React.Fragment>
);
}
} |
JavaScript | class AnimationBee extends LitElement {
constructor() {
super()
this.properties = FIXTURE_PROPERTIES
this.properties.sort()
}
static get properties() {
return {
name: { type: String },
duration: { type: Number },
id: { type: String },
keyframes: { type: Object }
}
}
removeAnimation(e) {
const { animationId } = e.target
store.dispatch(removeAnimationFromEverywhere(animationId))
}
handleKeyframeSubmit(e) {
// Prevent sending data to server
e.preventDefault()
// Get data out of the form
const data = new FormData(e.target)
const step = data.get('step')
const property = data.get('property')
const value = data.get('value')
store.dispatch(addKeyframe(this.id, step, property, value))
}
handleAnimationSubmit(e) {
// Prevent sending data to server
e.preventDefault()
// Get data out of the form
const data = new FormData(e.target)
const name = data.get('name')
const duration = parseInt(data.get('duration'), 10)
const { id } = this
store.dispatch(setAnimation({
id,
name,
duration
}))
}
render() {
const { id, properties, keyframes, name, duration } = this
return html`
<style>
.name {
display: inline-block;
width: 100%;
margin: 0;
padding: .35em .15em;
border: 0;
background: rgba(0, 0, 0, 1);
color: #fff;
}
</style>
<div>
<form @submit="${e => this.handleAnimationSubmit(e)}">
<input class="name" name="name" type="text" value="${name}" />
<input class="name" name="duration" type="number" min="0" value="${duration}" />
<button type="submit">Save</button>
</form>
<button @click="${e => this.removeAnimation(e)}" .animationId="${id}">Remove</button>
<br><br>
<form @submit="${e => this.handleKeyframeSubmit(e)}">
<input name="step" type="number" min="0" max="1" step="any" required placeholder="Step"/>
<select name="property" required>
<option value="" disabled selected>Property</option>
${repeat(properties, property => html`
<option value="${property}">${property}</option>
`)}
</select>
<input name="value" type="text" required placeholder="Value"/>
<button type="submit">Add keyframe</button>
</form>
<br>
<keyframe-grid .keyframes="${keyframes}"></keyframe-grid>
</div>
`
}
} |
JavaScript | class TextViewerView extends ViewerView {
/**
* Constructor
*/
constructor () {
super()
this._text = ''
this._disabled = false
this._$textarea = null
}
/**
* Returns text.
* @return {string}
*/
getText () {
return this._text
}
/**
* Sets text.
* @param {string} text
* @return {ViewerView} Fluent interface
*/
setText (text) {
if (this._text !== text) {
this._text = text
if (this._$textarea !== null) {
this._$textarea.value = text
this.layoutTextarea()
}
}
return this
}
/**
* Returns wether input is disabled.
* @return {boolean}
*/
isDisabled () {
return this._disabled
}
/**
* Sets wether input is disabled.
* @param {boolean} disabled
* @return {TextViewerView} Fluent interface
*/
setDisabled (disabled) {
this._disabled = disabled
if (this._$textarea !== null) {
if (disabled) {
this._$textarea.disabled = 'disabled'
} else {
this._$textarea.removeAttribute('disabled')
}
}
return this
}
/**
* Renders view.
* @protected
* @return {HTMLElement}
*/
render () {
const $root = super.render()
$root.classList.add('viewer-text')
return $root
}
/**
* Renders content.
* @protected
* @return {BrickView} Fluent interface
*/
renderContent () {
this._$textarea = View.createElement('textarea', {
className: 'viewer-text__textarea',
ariaLabel: 'Content',
spellcheck: false,
value: this._text,
onInput: this.textareaValueDidChange.bind(this),
onFocus: evt => this.focus(),
onBlur: evt => this.blur()
})
if (this.isDisabled()) {
this._$textarea.disabled = 'disabled'
}
const $content = super.renderContent()
$content.appendChild(this._$textarea)
return $content
}
/**
* Triggered when textarea value changed.
* @protected
* @param {Event} evt
*/
textareaValueDidChange (evt) {
if (this.isDisabled()) {
evt.preventDefault()
return false
}
const text = this._$textarea.value
if (this._text !== text) {
this._text = text
// notify model about text change
this.getModel().viewTextDidChange(this, this._text)
this.layoutTextarea()
}
}
/**
* Layouts view and its subviews.
* @return {View}
*/
layout () {
this.layoutTextarea()
return super.layout()
}
/**
* Calculates height nessesary to view the text without scrollbars.
* @protected
* @return {TextViewerView} Fluent interface
*/
layoutTextarea () {
this._$textarea.style.height = ''
this._$textarea.style.height = `${this._$textarea.scrollHeight}px`
return this
}
/**
* Updates view on model change.
* @return {View} Fluent interface
*/
update () {
// Update status
const error = this.getModel().getError()
if (error !== null) {
return this.updateStatus(
'error',
'Binary content can\'t be interpreted as text. ' +
'Try switching to the bytes view. ' +
error.message
)
} else {
return this.updateStatus(null)
}
}
} |
JavaScript | class ContactInfoModal extends Component {
state = {
relation: "relation_oneself",
};
/**
* ok事件
*/
onModalOk = () => {
const {onOk} = this.props;
if (onOk) {
this.props.form.validateFields((err, values) => {
if (!err) {
onOk(values);
}
});
}
};
/**
* 关系变动
* @param value
*/
onRelationChange = (value) => {
this.setState({
relation: value,
})
};
render() {
const {getFieldDecorator} = this.props.form;
const {name} = this.props.dataSource;
return <Modal
title="联系人"
destroyOnClose={true}
visible={this.props.visible}
onOk={this.onModalOk}
onCancel={this.props.onCancel}
>
<Form {...formItemLayout}>
<Form.Item label="关系">
{getFieldDecorator('relation', {
initialValue: "relation_oneself",
rules: [
{
required: true,
message: '关系不能为空'
}
]
})(<Select onChange={this.onRelationChange} style={{width: '70%'}}>
{getRelationTypeDataOptions()}
</Select>)}
</Form.Item>
<Form.Item label="联系人名称">
{getFieldDecorator('relationName', {
initialValue: this.state.relation === "relation_oneself" ? name : "",
rules: [
{
required: true,
message: '联系人名称不能为空'
}
]
})(<Input style={{width: '70%'}}/>)}
</Form.Item>
<Form.Item label="通讯方式">
{getFieldDecorator('contactType', {
initialValue: "contact_wechat",
rules: [
{
required: true,
message: '通讯方式不能为空'
}
]
})(<Radio.Group style={{width: '70%'}}>
{getContactTypeDataRadio()}
</Radio.Group>)}
</Form.Item>
<Form.Item label="通讯号码">
{getFieldDecorator('number', {
initialValue: null,
rules: [
{
required: true,
message: '通讯号码不能为空'
}
]
})(<Input style={{width: '70%'}}/>)}
</Form.Item>
<Form.Item label="描述">
{getFieldDecorator('description', {
initialValue: null,
})(<TextArea rows={4} style={{width: '70%'}}/>)}
</Form.Item>
</Form>
</Modal>;
}
} |
JavaScript | class MyUnitCubeQuad extends CGFobject {
constructor(scene, texture) {
super(scene);
this.quadPol = new MyQuad(scene);
this.cubeMat = new CGFappearance(this.scene);
this.cubeMat.setAmbient(0.5, 0.5, 0.5, 1.0);
this.cubeMat.setDiffuse(1, 1, 1, 1.0);
this.cubeMat.setSpecular(0.7, 0.7, 0.7, 1.0);
this.cubeMat.setShininess(10.0);
this.texture = texture;
this.cubeMat.setTexture(this.texture);
}
updateBuffers() {
}
display() {
this.cubeMat.apply();
//FRONT
this.scene.pushMatrix();
this.scene.translate(0,0,0.5);
this.quadPol.display();
this.scene.popMatrix();
//BACK
this.scene.pushMatrix();
this.scene.translate(0,0,-0.5);
this.scene.scale(-1,1,1);
this.quadPol.display();
this.scene.popMatrix();
//RIGHT
this.scene.pushMatrix();
this.scene.translate(0.5,0,0);
this.scene.rotate(Math.PI/2, 0,1,0);
this.quadPol.display();
this.scene.popMatrix();
//LEFT
this.scene.pushMatrix();
this.scene.translate(-0.5,0,0);
this.scene.rotate(-Math.PI/2, 0,1,0);
this.quadPol.display();
this.scene.popMatrix();
//TOP
this.scene.pushMatrix();
this.scene.translate(0,0.5,0);
this.scene.rotate(-Math.PI/2, 1,0,0);
this.quadPol.display();
this.scene.popMatrix();
//BOTTOM
this.scene.pushMatrix();
this.scene.translate(0,-0.5,0);
this.scene.rotate(Math.PI/2, 1,0,0);
this.quadPol.display();
this.scene.popMatrix();
}
} |
JavaScript | class Person {
/**
*
* @param {String} name - The name of the person.
*/
constructor(name){
if (!name) { throw new Error("Person must have a name!"); }
this.name = name
}
} |
JavaScript | class PropTypeBridge extends Bridge {
constructor() {
super('PropTypes');
}
export(model, options = {}, depth = 512) {
return PropTypes.oneOfType([
PropTypes.instanceOf(model),
PropTypes.shape(Object.assign({},
{ uuid: PropTypes.string },
model.schema.toBasic((value, type) => {
const checker = this.getTypeChecker(model, value, type, options, depth);
if (!type.options.required) return checker;
return checker.isRequired;
}),
))
]);
};
getTypeChecker(model, value, type, options, depth) {
switch (value) {
case Boolean: return PropTypes.bool;
case Number: return PropTypes.number;
case String: return PropTypes.string;
case BigInt: return PropTypes.instanceOf(BigInt);
case Date: return PropTypes.instanceOf(Date);
case Object:
if (Array.isArray(value)) return PropTypes.arrayOf(value[0]);
return this.export(type.generator, options, depth - 1);
default: return PropTypes.any;
}
};
} |
JavaScript | class ListenerHandler {
/**
* The event listener manager, which triggers event listeners via the Astron client. Saves all listeners to a discord.js collection.
* @param {AstronClient} client The Astron client
* @param {import("discord-astron").ListenerHandlerOptions} options The options for the listener handler
*/
constructor(client, options) {
/**
* The Astron client.
* @type {AstronClient}
*/
this.client = client;
/**
* The directory of event listeners.
* @type {string}
*/
this.directory = options.directory;
/**
* Fetches all event listener files via the directory and saves them a discord.js collection, then executes them.
* @async
* @param {any[]} [args] The event listener parameters
* @type {Promise<void>}
*/
this.load = async () => {
for (const events of readdirSync(this.directory)) {
const event = require(`${this.directory}/${events}`);
this.client.on(`${new event().name.toString().toLowerCase()}`, new event().exec.bind(null, this.client));
};
console.log(`${client.util.time()} | [ Event Handler ] Loaded ${readdirSync(this.directory).length} event(s)`);
};
};
} |
JavaScript | class Session {
constructor() {
this.allSessions = [];
}
// get the list of sessions
syncSessionList() {
// wrapping storage.sync callback function into promise
return new Promise(resolve => {
// get sessions list from storage
chrome.storage.local.get(config.sessionsStorage.list, storage => {
this.allSessions = storage.sessions ? storage.sessions : [];
resolve();
});
});
}
get getAll() {
// allSessions is read only
return [...this.allSessions];
}
// save tabs in chrome local storage
saveSession(tabs, name) {
// building set data
const setData = {};
// detect if session with such name is already exists
let sessionIndex = this.allSessions.indexOf(name);
let updated = (sessionIndex !== -1);
// remove existing session from list and
if(updated) {
// add number to session name if no noOverwriteMode is active for current mode
if(menu.getModeSetting("noOverwriteMode")) {
let i = 1;
const originalName = name;
name = name+` (${i})`;
// add number while session exists
while(this.allSessions.indexOf(name) !== -1) {
name = originalName+` (${++i})`;
}
} else {
this.allSessions.splice(sessionIndex, 1);
}
}
// add session name at the start
setData.sessions = [name, ...this.allSessions];
// to provide dynamic session name
// session_(config.sessionsStorage.prefix) prefix added to avoid extension configs overwriting
setData[config.sessionsStorage.prefix+name] = {
tabs: tabs.map(t => {
return {
index: t.index,
url: t.url,
active: t.active,
pinned: t.pinned
}
})
};
// wrapping storage.local.set callback function into promise
return new Promise(resolve => {
// save new session and update sessions list
chrome.storage.local.set(setData, () => {
// push session name to list after success, if new session added
this.allSessions.unshift(name);
// close selected tabs if config exists
if (menu.getModeSetting("closeTabsOnCreate")) {
tab.closeSelectedTabs(tab.getTabsIds(tabs)).then(() => resolve(updated));
} else {
resolve(updated);
}
});
});
}
// open saved session
openSession(name) {
// wrapping storage.local.get callback function into promise
return new Promise(resolve => {
// getting session from chrome local storage
chrome.storage.local.get(config.sessionsStorage.prefix+name, storage => {
// sort pinned and not pinned tabs
const pinnedTabs = [], initTabUrls = [];
storage[config.sessionsStorage.prefix+name].tabs.forEach(t => {
if(t.pinned) pinnedTabs.push(t);
else initTabUrls.push(t.url);
});
// create new window with initTabs
chrome.windows.create({url: initTabUrls, state: "maximized"}, newWindow => {
if(!pinnedTabs.length) return resolve();
const pinnedTabPromises = [];
// open pinned tabs if there exists
// chrome API doesn't provide new window creation with pinned tabs inside
pinnedTabs.forEach(t => {
// push pinned tab creation wrapped promise
pinnedTabPromises.push(new Promise(res => {
chrome.tabs.create({...t, windowId: newWindow.id}, () => res());
}));
});
// resolve function when all pinned tabs opened
Promise.all(pinnedTabPromises).then(() => resolve());
});
});
});
}
removeSession(name) {
// remove session from sessions list
let sessionIndex = this.allSessions.indexOf(name);
if(sessionIndex !== -1) this.allSessions.splice(sessionIndex, 1);
// update session list and delete session actions wrapped in promise
return Promise.all([
chrome.storage.local.set({sessions:this.allSessions}, () => Promise.resolve()),
chrome.storage.local.remove(config.sessionsStorage.prefix+name, () => Promise.resolve())
]);
}
clearSessions() {
const keysToRemove = this.allSessions.map(name => config.sessionsStorage.prefix+name);
keysToRemove.unshift(config.sessionsStorage.list);
this.allSessions = [];
DOM.setSessionList([]);
return new Promise(resolve => chrome.storage.local.remove(keysToRemove, () => resolve()));
}
} |
JavaScript | class SyncTransform extends AFrameComponent
{
get dependencies(){ return ['sync']; }
init()
{
this.sync = this.el.components.sync;
if(this.sync.isConnected)
start();
else
this.el.addEventListener('connected', this.start.bind(this));
}
start()
{
let sync = this.sync, component = this;
let positionRef = sync.dataRef.child('position');
let rotationRef = sync.dataRef.child('rotation');
let scaleRef = sync.dataRef.child('scale');
component.updateRate = 100;
let stoppedAnimations = [];
//pause all animations on ownership loss
component.el.addEventListener('ownershiplost', () => {
Array.from(component.el.children).forEach(child => {
let tagName = child.tagName.toLowerCase();
if (tagName === "a-animation") {
stoppedAnimations.push(child);
child.stop();
}
});
});
component.el.addEventListener('ownershipgained', () => {
stoppedAnimations.forEach(a => a.start());
stoppedAnimations = [];
});
function onTransform(snapshot, componentName) {
if (sync.isMine) return;
let value = snapshot.val();
if (!value) return;
component.el.setAttribute(componentName, value);
}
positionRef.on('value', snapshot => onTransform(snapshot, 'position'));
rotationRef.on('value', snapshot => onTransform(snapshot, 'rotation'));
scaleRef.on('value', snapshot => onTransform(snapshot, 'scale'));
let sendPosition = throttle(function(value){
positionRef.set(value);
}, component.updateRate);
let sendRotation = throttle(function(value){
rotationRef.set(value);
}, component.updateRate);
let sendScale = throttle(function(value){
scaleRef.set(value);
}, component.updateRate);
function onComponentChanged(event)
{
if (!sync.isMine) return;
let name = event.detail.name;
let newData = event.detail.newData;
if (name === 'position') {
sendPosition(newData);
} else if (name === 'rotation') {
sendRotation(newData);
} else if (name === 'scale') {
sendScale(newData);
}
}
component.el.addEventListener('componentchanged', onComponentChanged);
}
} |
JavaScript | class ServiceServerDispatcher {
constructor(
target = self,
receiverEventPreprocessor,
clientReceiverEventPreprocessor,
clientSenderEventPreprocessor,
) {
this.type = WorkerType.SERVICE_WORKER_SERVER;
this.target = target;
this.clientFactory = (port) => {
if (!port) {
return null;
}
return new ServiceClientDispatcher(
port,
clientReceiverEventPreprocessor,
clientSenderEventPreprocessor,
);
};
this.receiver = createEventDispatcher(receiverEventPreprocessor);
dispatchWorkerErrorEvent(target, this.receiver);
target.addEventListener(NativeEventType.MESSAGE, (event) => this._postMessageListener(event),
);
}
addEventListener = (...args) => this.receiver.addEventListener(...args);
hasEventListener = (...args) => this.receiver.hasEventListener(...args);
removeEventListener = (...args) => this.receiver.removeEventListener(...args);
removeAllEventListeners = (...args) => this.receiver.removeAllEventListeners(...args);
/**
* @private
*/
_postMessageListener(nativeEvent) {
const {
data: rawMessage,
ports: [client],
} = nativeEvent;
if (!rawMessage) {
return;
}
const {
event: { type: eventType, data: eventData },
} = parseMessagePortEvent(rawMessage);
const event = new WorkerEvent(
eventType,
eventData,
nativeEvent,
this.clientFactory(client),
);
this.receiver.dispatchEvent(event);
}
} |
JavaScript | class AidSprite extends AnimationSprite {
static IMAGE = [
[' ', '+', ' '],
['+', '+', '+'],
[' ', '+', ' '],
];
static PALETTE = {
' ': '',
'+': '#AA5555',
};
#canvasHeight = 0;
#canvasWidth = 0
#helicopter = null;
#dropX = 0;
#scale = 1;
#velocity = 0;
#taken = false;
constructor({
canvasHeight,
canvasWidth,
helicopter,
scale,
velocity,
birthDate,
dropX,
}) {
super(birthDate);
this.#canvasHeight = canvasHeight;
this.#canvasWidth = canvasWidth;
this.#helicopter = helicopter;
this.#scale = scale;
this.#velocity = velocity;
this.#dropX = dropX;
}
height(time) {
return this.scale(time) * AidSprite.IMAGE.length;
}
image() {
return AidSprite.IMAGE;
}
isLanded(time) {
return this.offsetY(time) >= this.#canvasHeight - this.height(time) - 1;
}
landingTime() {
const dropTime = this.dropTime();
const dropHeight = this.#canvasHeight
- this.#helicopter.offsetY(dropTime)
- this.#helicopter.height(dropTime) / 2
- this.height(this.birthDate);
return new Date(Number(dropTime) + (1E3 * dropHeight) / this.#velocity);
}
needDestroy() {
return this.#taken;
}
offsetX() {
return this.#dropX;
}
dropTime() {
return this.#helicopter.timeFromOffsetX(
this.offsetX()
+ this.#helicopter.width(this.#helicopter.birthDate)
- this.width(this.birthDate),
);
}
offsetY(time) {
const dropTime = this.dropTime();
if (time < this.dropTime()) {
return 0;
}
if (time < this.landingTime()) {
return this.#helicopter.offsetY(dropTime)
+ this.#helicopter.height(dropTime) / 2
+ this.#velocity * (time - dropTime) * 1E-3;
}
return this.#canvasHeight - this.height(time);
}
palette(color) {
return AidSprite.PALETTE[color];
}
scale() {
return this.#scale;
}
take() {
this.#taken = true;
}
visible(time) {
return time - this.dropTime() >= 0;
}
width(time) {
return this.scale(time) * AidSprite.IMAGE.length;
}
} |
JavaScript | class ArgumentType {
constructor(client, name) {
this.client = client;
this.name = name;
}
/**
* Validate a string for parsing
*/
validate(arg, str, msg) {
if (arg.validate) return arg.validate(str, msg);
}
/**
* Parse a string into the necessary type
* Behavior is undefined on an invalid string
*/
// eslint-disable-next-line no-unused-vars
parse(str, msg) {
throw new Error(`missing parse function for ${this.name}`);
}
} |
JavaScript | class Debris extends MovingObject {
constructor(config) {
super(config);
}
} |
JavaScript | class TextBox extends Control {
/**
* @param {Object} options
* @param {String} [options.placeholder] Text that is shown inside the textbox when it is empty
* @param {Boolean} [options.multiline] Makes textbox one-lined or multilined
*/
constructor ({ placeholder = "", multiline = false }) {
super()
this.placeholder = placeholder
this.multiline = multiline
this.setOutline({ all: 1, color: Colors.lightGray, style: OutlineStyle.solid, radius: 7 })
.setPadding({ all: 7 })
.setFont(Fonts.inherit)
.setBackground({ color: Colors.white })
.setForeground({ color: Colors.black })
.applyCSS({ resize: "none", outline: "none" })
.setAttributes({ placeholder: this.placeholder })
}
/**
* A method to set the text white space showing style
* @param {Symbol} style Item of the WhiteSpaceStyle enum
*/
setWhiteSpaceStyle(style) {
if (WhiteSpaceStyle.contains(style)) {
this.styles.whiteSpace = whiteSpaceStyleToCssValue(style)
}
return this
}
getBody () {
var result = super.getBody()
result.tag = (this.multiline ? "textarea" : "input")
return result
}
} |
JavaScript | class Action {
constructor(displayName, actionPathname, handler) {
this.displayName = displayName;
this.uri = `action://${actionPathname.split('/').map(encodeURIComponent).join('/')}`;
this.handler = handler;
}
static get list() {
return buttonActions;
}
static runURI(uri) {
buttonActions.find(action => action.uri === uri).handler();
}
} |
JavaScript | class Charts {
constructor() {
// Initialization of the page plugins
if (typeof Chart === 'undefined') {
console.log('Chart is undefined!');
return;
}
this._lineChart = null;
this._areaChart = null;
this._scatterChart = null;
this._radarChart = null;
this._polarChart = null;
this._pieChart = null;
this._doughnutChart = null;
this._barChart = null;
this._horizontalBarChart = null;
this._bubbleChart = null;
this._roundedBarChart = null;
this._horizontalRoundedBarChart = null;
this._streamingLineChart = null;
this._streamingBarChart = null;
this._customTooltipDoughnut = null;
this._customTooltipBar = null;
this._customLegendBar = null;
this._customLegendDoughnut = null;
this._smallDoughnutChart1 = null;
this._smallDoughnutChart2 = null;
this._smallDoughnutChart3 = null;
this._smallDoughnutChart4 = null;
this._smallDoughnutChart5 = null;
this._smallDoughnutChart6 = null;
this._smallLineChart1 = null;
this._smallLineChart2 = null;
this._smallLineChart3 = null;
this._smallLineChart4 = null;
// Standard charts
this._initLineChart();
this._initAreaChart();
this._initScatterChart();
this._initRadarChart();
this._initPolarChart();
this._initPieChart();
this._initDoughnutChart();
this._initBarChart();
this._initHorizontalBarChart();
this._initBubbleChart();
// Requires chartjs-plugin-rounded-bar.min.js
this._initRoundedBarChart();
this._initHorizontalRoundedBarChart();
// Streaming charts
this._initStreamingLineChart();
this._initStreamingBarChart();
// Customizations
this._initCustomTooltipDoughnut();
this._initCustomTooltipBar();
this._initCustomLegendBar();
this._initCustomLegendDoughnut();
// Small charts
this._initSmallDoughnutCharts();
this._initSmallLineCharts();
this._initEvents();
}
_initEvents() {
// Listening for color change events to update charts
document.documentElement.addEventListener(Globals.colorAttributeChange, (event) => {
this._lineChart && this._lineChart.destroy();
this._initLineChart();
this._areaChart && this._areaChart.destroy();
this._initAreaChart();
this._scatterChart && this._scatterChart.destroy();
this._initScatterChart();
this._radarChart && this._radarChart.destroy();
this._initRadarChart();
this._polarChart && this._polarChart.destroy();
this._initPolarChart();
this._pieChart && this._pieChart.destroy();
this._initPieChart();
this._doughnutChart && this._doughnutChart.destroy();
this._initDoughnutChart();
this._barChart && this._barChart.destroy();
this._initBarChart();
this._horizontalBarChart && this._horizontalBarChart.destroy();
this._initHorizontalBarChart();
this._bubbleChart && this._bubbleChart.destroy();
this._initBubbleChart();
this._roundedBarChart && this._roundedBarChart.destroy();
this._initRoundedBarChart();
this._horizontalRoundedBarChart && this._horizontalRoundedBarChart.destroy();
this._initHorizontalRoundedBarChart();
this._streamingLineChart && this._streamingLineChart.destroy();
this._initStreamingLineChart();
this._streamingBarChart && this._streamingBarChart.destroy();
this._initStreamingBarChart();
this._customTooltipDoughnut && this._customTooltipDoughnut.destroy();
this._initCustomTooltipDoughnut();
this._customTooltipBar && this._customTooltipBar.destroy();
this._initCustomTooltipBar();
this._customLegendBar && this._customLegendBar.destroy();
this._initCustomLegendBar();
this._customLegendDoughnut && this._customLegendDoughnut.destroy();
this._initCustomLegendDoughnut();
this._smallDoughnutChart1 && this._smallDoughnutChart1.destroy();
this._smallDoughnutChart2 && this._smallDoughnutChart2.destroy();
this._smallDoughnutChart3 && this._smallDoughnutChart3.destroy();
this._smallDoughnutChart4 && this._smallDoughnutChart4.destroy();
this._smallDoughnutChart5 && this._smallDoughnutChart5.destroy();
this._smallDoughnutChart6 && this._smallDoughnutChart6.destroy();
this._initSmallDoughnutCharts();
this._smallLineChart1 && this._smallLineChart1.destroy();
this._smallLineChart2 && this._smallLineChart2.destroy();
this._smallLineChart3 && this._smallLineChart3.destroy();
this._smallLineChart4 && this._smallLineChart4.destroy();
this._initSmallLineCharts();
});
}
// Standard line chart
_initLineChart() {
if (document.getElementById('lineChart')) {
const lineChart = document.getElementById('lineChart').getContext('2d');
this._lineChart = new Chart(lineChart, {
type: 'line',
options: {
plugins: {
crosshair: ChartsExtend.Crosshair(),
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {display: true, lineWidth: 1, color: Globals.separatorLight, drawBorder: false},
ticks: {beginAtZero: true, stepSize: 5, min: 50, max: 70, padding: 20, fontColor: Globals.alternate},
},
],
xAxes: [{gridLines: {display: false}, ticks: {fontColor: Globals.alternate}}],
},
legend: {display: false},
tooltips: ChartsExtend.ChartTooltipForCrosshair(),
},
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: '',
data: [60, 54, 68, 60, 63, 60, 65],
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.primary,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 3,
pointBorderWidth: 3,
pointHoverRadius: 4,
fill: false,
},
],
},
});
}
}
// Standard area chart
_initAreaChart() {
if (document.getElementById('areaChart')) {
const areaChart = document.getElementById('areaChart').getContext('2d');
this._areaChart = new Chart(areaChart, {
type: 'line',
options: {
plugins: {
crosshair: ChartsExtend.Crosshair(),
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {display: true, lineWidth: 1, color: Globals.separatorLight, drawBorder: false},
ticks: {beginAtZero: true, stepSize: 5, min: 50, max: 70, padding: 20, fontColor: Globals.alternate},
},
],
xAxes: [
{
gridLines: {display: false},
ticks: {fontColor: Globals.alternate},
},
],
},
legend: {display: false},
tooltips: ChartsExtend.ChartTooltipForCrosshair(),
},
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: '',
data: [60, 54, 68, 60, 63, 60, 65],
borderColor: Globals.primary,
pointBackgroundColor: Globals.foreground,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.primary,
pointHoverBorderColor: Globals.foreground,
pointRadius: 4,
pointBorderWidth: 2,
pointHoverRadius: 5,
fill: true,
borderWidth: 2,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
},
],
},
});
}
}
// Standard scatter chart
_initScatterChart() {
if (document.getElementById('scatterChart')) {
const scatterChart = document.getElementById('scatterChart').getContext('2d');
this._scatterChart = new Chart(scatterChart, {
type: 'scatter',
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {display: true, lineWidth: 1, color: Globals.separatorLight, drawBorder: false},
ticks: {beginAtZero: true, stepSize: 20, min: -80, max: 80, padding: 20, fontColor: Globals.alternate},
},
],
xAxes: [
{
gridLines: {display: true, lineWidth: 1, color: Globals.separatorLight},
ticks: {fontColor: Globals.alternate},
},
],
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
datasets: [
{
borderWidth: 2,
label: 'Breads',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [
{x: 62, y: -78},
{x: -0, y: 74},
{x: -67, y: 45},
{x: -26, y: -43},
{x: -15, y: -30},
{x: 65, y: -68},
{x: -28, y: -61},
],
},
{
borderWidth: 2,
label: 'Patty',
borderColor: Globals.tertiary,
backgroundColor: 'rgba(' + Globals.tertiaryrgb + ',0.1)',
data: [
{x: 79, y: 62},
{x: 62, y: 0},
{x: -76, y: -81},
{x: -51, y: 41},
{x: -9, y: 9},
{x: 72, y: -37},
{x: 62, y: -26},
],
},
],
},
});
}
}
// Standard radar chart
_initRadarChart() {
if (document.getElementById('radarChart')) {
const radarChart = document.getElementById('radarChart').getContext('2d');
this._radarChart = new Chart(radarChart, {
type: 'radar',
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scale: {
ticks: {display: false},
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
datasets: [
{
label: 'Stock',
borderWidth: 2,
pointBackgroundColor: Globals.primary,
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [80, 90, 70],
},
{
label: 'Order',
borderWidth: 2,
pointBackgroundColor: Globals.secondary,
borderColor: Globals.secondary,
backgroundColor: 'rgba(' + Globals.secondaryrgb + ',0.1)',
data: [68, 80, 95],
},
],
labels: ['Breads', 'Patty', 'Pastry'],
},
});
}
}
// Standard polar chart
_initPolarChart() {
if (document.getElementById('polarChart')) {
const polarChart = document.getElementById('polarChart').getContext('2d');
this._polarChart = new Chart(polarChart, {
type: 'polarArea',
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scale: {
ticks: {
display: false,
},
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
datasets: [
{
label: 'Stock',
borderWidth: 2,
pointBackgroundColor: Globals.primary,
borderColor: [Globals.primary, Globals.secondary, Globals.tertiary],
backgroundColor: ['rgba(' + Globals.primaryrgb + ',0.1)', 'rgba(' + Globals.secondaryrgb + ',0.1)', 'rgba(' + Globals.tertiaryrgb + ',0.1)'],
data: [80, 90, 70],
},
],
labels: ['Breads', 'Patty', 'Pastry'],
},
});
}
}
// Standard pie chart
_initPieChart() {
if (document.getElementById('pieChart')) {
const pieChart = document.getElementById('pieChart');
this._pieChart = new Chart(pieChart, {
type: 'pie',
data: {
labels: ['Breads', 'Pastry', 'Patty'],
datasets: [
{
label: '',
borderColor: [Globals.primary, Globals.secondary, Globals.tertiary],
backgroundColor: ['rgba(' + Globals.primaryrgb + ',0.1)', 'rgba(' + Globals.secondaryrgb + ',0.1)', 'rgba(' + Globals.tertiaryrgb + ',0.1)'],
borderWidth: 2,
data: [15, 25, 20],
},
],
},
draw: function () {},
options: {
plugins: {
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
layout: {
padding: {
bottom: 20,
},
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
});
}
}
// Standard doughnut chart
_initDoughnutChart() {
if (document.getElementById('doughnutChart')) {
const doughnutChart = document.getElementById('doughnutChart');
this._doughnutChart = new Chart(doughnutChart, {
plugins: [ChartsExtend.CenterTextPlugin()],
type: 'doughnut',
data: {
labels: ['Breads', 'Pastry', 'Patty'],
datasets: [
{
label: '',
borderColor: [Globals.tertiary, Globals.secondary, Globals.primary],
backgroundColor: ['rgba(' + Globals.tertiaryrgb + ',0.1)', 'rgba(' + Globals.secondaryrgb + ',0.1)', 'rgba(' + Globals.primaryrgb + ',0.1)'],
borderWidth: 2,
data: [15, 25, 20],
},
],
},
draw: function () {},
options: {
plugins: {
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 80,
title: {
display: false,
},
layout: {
padding: {
bottom: 20,
},
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
});
}
}
// Standard bar chart
_initBarChart() {
if (document.getElementById('barChart')) {
const barChart = document.getElementById('barChart').getContext('2d');
this._barChart = new Chart(barChart, {
type: 'bar',
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 100,
min: 300,
max: 800,
padding: 20,
fontColor: Globals.alternate,
},
},
],
xAxes: [
{
gridLines: {display: false},
},
],
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Breads',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [456, 479, 424, 569],
borderWidth: 2,
},
{
label: 'Patty',
borderColor: Globals.secondary,
backgroundColor: 'rgba(' + Globals.secondaryrgb + ',0.1)',
data: [364, 504, 605, 400],
borderWidth: 2,
},
],
},
});
}
}
// Standard horizontal bar chart
_initHorizontalBarChart() {
if (document.getElementById('horizontalBarChart')) {
const barChart = document.getElementById('horizontalBarChart').getContext('2d');
this._horizontalBarChart = new Chart(barChart, {
type: 'horizontalBar',
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 100,
min: 300,
max: 800,
padding: 20,
},
},
],
xAxes: [
{
gridLines: {display: false},
},
],
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Breads',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [456, 479, 324, 569],
borderWidth: 2,
},
],
},
});
}
}
// Standard bubble chart
_initBubbleChart() {
if (document.getElementById('bubbleChart')) {
this._bubbleChart = new Chart(document.getElementById('bubbleChart'), {
type: 'bubble',
data: {
labels: '',
datasets: [
{
borderWidth: 2,
label: ['Patty'],
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
borderColor: Globals.primary,
data: [
{
x: 240,
y: 15,
r: 15,
},
],
},
{
borderWidth: 2,
label: ['Bread'],
backgroundColor: 'rgba(' + Globals.quaternaryrgb + ',0.1)',
borderColor: Globals.quaternary,
data: [
{
x: 140,
y: 8,
r: 10,
},
],
},
{
borderWidth: 2,
label: ['Pastry'],
backgroundColor: 'rgba(' + Globals.tertiaryrgb + ',0.1)',
borderColor: Globals.tertiary,
data: [
{
x: 190,
y: 68,
r: 20,
},
],
},
],
},
options: {
plugins: {
crosshair: false,
datalabels: {display: false},
},
title: {
display: true,
text: 'Consumption',
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: 'Fat',
},
ticks: {beginAtZero: true, stepSize: 20, min: 0, max: 100, padding: 20},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: 'Calories',
},
ticks: {stepSize: 20, min: 100, max: 300, padding: 20},
},
],
},
tooltips: ChartsExtend.ChartTooltip(),
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
},
});
}
}
// Rounded bar chart
_initRoundedBarChart() {
if (document.getElementById('roundedBarChart')) {
const barChart = document.getElementById('roundedBarChart').getContext('2d');
this._roundedBarChart = new Chart(barChart, {
type: 'bar',
options: {
cornerRadius: parseInt(Globals.borderRadiusMd),
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 100,
min: 300,
max: 800,
padding: 20,
},
},
],
xAxes: [
{
gridLines: {display: false},
},
],
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Breads',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [456, 479, 424, 569],
borderWidth: 2,
},
{
label: 'Patty',
borderColor: Globals.secondary,
backgroundColor: 'rgba(' + Globals.secondaryrgb + ',0.1)',
data: [364, 504, 605, 400],
borderWidth: 2,
},
],
},
});
}
}
// Rounded horizontal bar chart
_initHorizontalRoundedBarChart() {
if (document.getElementById('horizontalRoundedBarChart')) {
const barChart = document.getElementById('horizontalRoundedBarChart').getContext('2d');
this._horizontalRoundedBarChart = new Chart(barChart, {
type: 'horizontalBar',
options: {
cornerRadius: parseInt(Globals.borderRadiusMd),
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 100,
min: 300,
max: 800,
padding: 20,
},
},
],
xAxes: [
{
gridLines: {display: false},
},
],
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Breads',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [456, 479, 324, 569],
borderWidth: 2,
},
],
},
});
}
}
// Streaming line chart that updates the data via this._onRefresh
_initStreamingLineChart() {
if (document.getElementById('streamingLineChart')) {
const streamingLineChart = document.getElementById('streamingLineChart').getContext('2d');
this._streamingLineChart = new Chart(streamingLineChart, {
type: 'line',
options: {
plugins: {
crosshair: ChartsExtend.Crosshair(),
datalabels: {display: false},
streaming: {
frameRate: 30,
},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
gridLines: {display: true, lineWidth: 1, color: Globals.separatorLight, drawBorder: false},
ticks: {beginAtZero: true, padding: 20, fontColor: Globals.alternate, min: 0, max: 100, stepSize: 25},
},
],
xAxes: [
{
gridLines: {display: false},
ticks: {display: false},
type: 'realtime',
realtime: {
duration: 20000,
refresh: 1000,
delay: 3000,
onRefresh: this._onRefresh,
},
},
],
},
legend: {display: false},
tooltips: ChartsExtend.ChartTooltipForCrosshair(),
},
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: '',
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.primary,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 2,
pointBorderWidth: 2,
pointHoverRadius: 3,
fill: false,
},
],
},
});
}
}
// Streaming bar chart that updates the data via this._onRefresh
_initStreamingBarChart() {
if (document.getElementById('streamingBarChart')) {
const streamingBarChart = document.getElementById('streamingBarChart').getContext('2d');
this._streamingBarChart = new Chart(streamingBarChart, {
type: 'bar',
data: {
labels: [],
datasets: [
{
label: 'Breads',
data: [],
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
borderWidth: 2,
},
],
},
options: {
cornerRadius: parseInt(Globals.borderRadiusMd),
plugins: {
crosshair: ChartsExtend.Crosshair(),
datalabels: {display: false},
streaming: {
frameRate: 30,
},
},
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
scales: {
xAxes: [
{
ticks: {display: false},
type: 'realtime',
realtime: {
duration: 20000,
refresh: 1000,
delay: 3000,
onRefresh: this._onRefresh,
},
gridLines: {display: false},
},
],
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 25,
min: 0,
max: 100,
padding: 20,
},
},
],
},
tooltips: ChartsExtend.ChartTooltip(),
legend: {
display: false,
},
},
});
}
}
// Streaming chart data update method
_onRefresh(chart) {
chart.config.data.datasets.forEach(function (dataset) {
dataset.data.push({
x: moment(),
y: Math.round(Math.random() * 50) + 25,
});
});
}
// Custom vertical tooltip doughnut chart
_initCustomTooltipDoughnut() {
if (document.getElementById('verticalTooltipChart')) {
var ctx = document.getElementById('verticalTooltipChart').getContext('2d');
this._customTooltipDoughnut = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: '',
data: [450, 475, 625],
backgroundColor: ['rgba(' + Globals.primaryrgb + ',0.1)', 'rgba(' + Globals.secondaryrgb + ',0.1)', 'rgba(' + Globals.quaternaryrgb + ',0.1)'],
borderColor: [Globals.primary, Globals.secondary, Globals.quaternary],
},
],
labels: ['Burger', 'Cakes', 'Pastry'],
icons: ['burger', 'cupcake', 'loaf'],
},
options: {
plugins: {
datalabels: {display: false},
},
cutoutPercentage: 70,
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
layout: {
padding: {
bottom: 20,
},
},
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
tooltips: {
enabled: false,
custom: function (tooltip) {
var tooltipEl = this._chart.canvas.parentElement.querySelector('.custom-tooltip');
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
if (tooltip.body) {
var chart = this;
var index = tooltip.dataPoints[0].index;
var icon = tooltipEl.querySelector('.icon');
icon.style = 'color: ' + tooltip.labelColors[0].borderColor;
icon.setAttribute('data-cs-icon', chart._data.icons[index]);
csicons.replace();
var iconContainer = tooltipEl.querySelector('.icon-container');
iconContainer.style = 'border-color: ' + tooltip.labelColors[0].borderColor + '!important';
tooltipEl.querySelector('.text').innerHTML = chart._data.labels[index].toLocaleUpperCase();
tooltipEl.querySelector('.value').innerHTML = chart._data.datasets[0].data[index];
}
var positionY = this._chart.canvas.offsetTop;
var positionX = this._chart.canvas.offsetLeft;
tooltipEl.style.opacity = 1;
tooltipEl.style.left = positionX + tooltip.caretX + 'px';
tooltipEl.style.top = positionY + tooltip.caretY + 'px';
},
},
},
});
}
}
// Custom horizontal tooltip bar chart
_initCustomTooltipBar() {
if (document.getElementById('horizontalTooltipChart')) {
var ctx = document.getElementById('horizontalTooltipChart').getContext('2d');
this._customTooltipBar = new Chart(ctx, {
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Burger',
icon: 'burger',
borderColor: Globals.primary,
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
data: [456, 479, 424, 569],
borderWidth: 2,
},
{
label: 'Patty',
icon: 'loaf',
borderColor: Globals.secondary,
backgroundColor: 'rgba(' + Globals.secondaryrgb + ',0.1)',
data: [364, 504, 605, 400],
borderWidth: 2,
},
],
},
options: {
cornerRadius: parseInt(Globals.borderRadiusMd),
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
labels: ChartsExtend.LegendLabels(),
},
scales: {
yAxes: [
{
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 100,
min: 300,
max: 800,
padding: 20,
},
},
],
xAxes: [
{
gridLines: {display: false},
},
],
},
tooltips: {
enabled: false,
custom: function (tooltip) {
var tooltipEl = this._chart.canvas.parentElement.querySelector('.custom-tooltip');
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
if (tooltip.body) {
var chart = this;
var index = tooltip.dataPoints[0].index;
var datasetIndex = tooltip.dataPoints[0].datasetIndex;
var icon = tooltipEl.querySelector('.icon');
var iconContainer = tooltipEl.querySelector('.icon-container');
iconContainer.style = 'border-color: ' + tooltip.labelColors[0].borderColor + '!important';
icon.style = 'color: ' + tooltip.labelColors[0].borderColor + ';';
icon.setAttribute('data-cs-icon', chart._data.datasets[datasetIndex].icon);
csicons.replace();
tooltipEl.querySelector('.text').innerHTML = chart._data.datasets[datasetIndex].label.toLocaleUpperCase();
tooltipEl.querySelector('.value').innerHTML = chart._data.datasets[datasetIndex].data[index];
}
var positionY = this._chart.canvas.offsetTop;
var positionX = this._chart.canvas.offsetLeft;
tooltipEl.style.opacity = 1;
tooltipEl.style.left = positionX + tooltip.dataPoints[0].x - 75 + 'px';
tooltipEl.style.top = positionY + tooltip.caretY + 'px';
},
},
},
});
}
}
// Custom legend bar chart
_initCustomLegendBar() {
if (document.getElementById('customLegendBarChart')) {
const ctx = document.getElementById('customLegendBarChart').getContext('2d');
this._customLegendBar = new Chart(ctx, {
type: 'bar',
options: {
cornerRadius: parseInt(Globals.borderRadiusMd),
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [
{
stacked: true,
gridLines: {
display: true,
lineWidth: 1,
color: Globals.separatorLight,
drawBorder: false,
},
ticks: {
beginAtZero: true,
stepSize: 200,
min: 0,
max: 800,
padding: 20,
},
},
],
xAxes: [
{
stacked: true,
gridLines: {display: false},
barPercentage: 0.5,
},
],
},
legend: false,
legendCallback: function (chart) {
const legendContainer = chart.canvas.parentElement.parentElement.querySelector('.custom-legend-container');
legendContainer.innerHTML = '';
const legendItem = chart.canvas.parentElement.parentElement.querySelector('.custom-legend-item');
for (let i = 0; i < chart.data.datasets.length; i++) {
var itemClone = legendItem.content.cloneNode(true);
var total = chart.data.datasets[i].data.reduce(function (total, num) {
return total + num;
});
itemClone.querySelector('.text').innerHTML = chart.data.datasets[i].label.toLocaleUpperCase();
itemClone.querySelector('.value').innerHTML = total;
itemClone.querySelector('.value').style = 'color: ' + chart.data.datasets[i].borderColor + '!important';
itemClone.querySelector('.icon-container').style = 'border-color: ' + chart.data.datasets[i].borderColor + '!important';
itemClone.querySelector('.icon').style = 'color: ' + chart.data.datasets[i].borderColor + '!important';
itemClone.querySelector('.icon').setAttribute('data-cs-icon', chart.data.icons[i]);
itemClone.querySelector('a').addEventListener('click', (event) => {
event.preventDefault();
const hidden = chart.getDatasetMeta(i).hidden;
chart.getDatasetMeta(i).hidden = !hidden;
if (event.currentTarget.classList.contains('opacity-50')) {
event.currentTarget.classList.remove('opacity-50');
} else {
event.currentTarget.classList.add('opacity-50');
}
chart.update();
});
legendContainer.appendChild(itemClone);
}
csicons.replace();
},
tooltips: {
enabled: false,
custom: function (tooltip) {
var tooltipEl = this._chart.canvas.parentElement.querySelector('.custom-tooltip');
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
if (tooltip.body) {
var chart = this;
var index = tooltip.dataPoints[0].index;
var datasetIndex = tooltip.dataPoints[0].datasetIndex;
var icon = tooltipEl.querySelector('.icon');
var iconContainer = tooltipEl.querySelector('.icon-container');
iconContainer.style = 'border-color: ' + tooltip.labelColors[0].borderColor + '!important';
icon.style = 'color: ' + tooltip.labelColors[0].borderColor + ';';
icon.setAttribute('data-cs-icon', chart._data.icons[datasetIndex]);
csicons.replace();
tooltipEl.querySelector('.text').innerHTML = chart._data.datasets[datasetIndex].label.toLocaleUpperCase();
tooltipEl.querySelector('.value').innerHTML = chart._data.datasets[datasetIndex].data[index];
tooltipEl.querySelector('.value').style = 'color: ' + tooltip.labelColors[0].borderColor + ';';
}
var positionY = this._chart.canvas.offsetTop;
var positionX = this._chart.canvas.offsetLeft;
tooltipEl.style.opacity = 1;
tooltipEl.style.left = positionX + tooltip.dataPoints[0].x - 75 + 'px';
tooltipEl.style.top = positionY + tooltip.caretY + 'px';
},
},
},
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: 'Breads',
backgroundColor: 'rgba(' + Globals.primaryrgb + ',0.1)',
borderColor: Globals.primary,
borderWidth: 2,
data: [213, 434, 315, 367, 289, 354, 242],
},
{
label: 'Cakes',
backgroundColor: 'rgba(' + Globals.secondaryrgb + ',0.1)',
borderColor: Globals.secondary,
borderWidth: 2,
data: [143, 234, 156, 207, 191, 214, 95],
},
],
icons: ['loaf', 'cupcake'],
},
});
this._customLegendBar.generateLegend();
}
}
// Custom legend doughnut chart
_initCustomLegendDoughnut() {
if (document.getElementById('customLegendDoughnutChart')) {
const ctx = document.getElementById('customLegendDoughnutChart').getContext('2d');
this._customLegendDoughnut = new Chart(ctx, {
type: 'doughnut',
options: {
cutoutPercentage: 70,
plugins: {
crosshair: false,
datalabels: {display: false},
},
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
layout: {
padding: {
bottom: 20,
},
},
legend: false,
legendCallback: function (chart) {
const legendContainer = chart.canvas.parentElement.parentElement.querySelector('.custom-legend-container');
legendContainer.innerHTML = '';
const legendItem = chart.canvas.parentElement.parentElement.querySelector('.custom-legend-item');
for (let i = 0; i < chart.data.datasets[0].data.length; i++) {
var itemClone = legendItem.content.cloneNode(true);
itemClone.querySelector('.text').innerHTML = chart.data.labels[i].toLocaleUpperCase();
itemClone.querySelector('.value').innerHTML = chart.data.datasets[0].data[i];
itemClone.querySelector('.value').style = 'color: ' + chart.data.datasets[0].borderColor[i] + '!important';
itemClone.querySelector('.icon-container').style = 'border-color: ' + chart.data.datasets[0].borderColor[i] + '!important';
itemClone.querySelector('.icon').style = 'color: ' + chart.data.datasets[0].borderColor[i] + '!important';
itemClone.querySelector('.icon').setAttribute('data-cs-icon', chart.data.icons[i]);
itemClone.querySelector('a').addEventListener('click', (event) => {
event.preventDefault();
const hidden = chart.getDatasetMeta(0).data[i].hidden;
chart.getDatasetMeta(0).data[i].hidden = !hidden;
if (event.currentTarget.classList.contains('opacity-50')) {
event.currentTarget.classList.remove('opacity-50');
} else {
event.currentTarget.classList.add('opacity-50');
}
chart.update();
});
legendContainer.appendChild(itemClone);
}
csicons.replace();
},
tooltips: ChartsExtend.ChartTooltip(),
},
data: {
datasets: [
{
label: '',
data: [450, 475, 625],
backgroundColor: ['rgba(' + Globals.primaryrgb + ',0.1)', 'rgba(' + Globals.secondaryrgb + ',0.1)', 'rgba(' + Globals.quaternaryrgb + ',0.1)'],
borderColor: [Globals.primary, Globals.secondary, Globals.quaternary],
},
],
labels: ['Burger', 'Cakes', 'Pastry'],
icons: ['burger', 'cupcake', 'loaf'],
},
});
this._customLegendDoughnut.generateLegend();
}
}
// Small doughnut charts
_initSmallDoughnutCharts() {
if (document.getElementById('smallDoughnutChart1')) {
this._smallDoughnutChart1 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart1', [14, 0], 'PURCHASING');
}
if (document.getElementById('smallDoughnutChart2')) {
this._smallDoughnutChart2 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart2', [12, 6], 'PRODUCTION');
}
if (document.getElementById('smallDoughnutChart3')) {
this._smallDoughnutChart3 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart3', [22, 8], 'PACKAGING');
}
if (document.getElementById('smallDoughnutChart4')) {
this._smallDoughnutChart4 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart4', [1, 5], 'DELIVERY');
}
if (document.getElementById('smallDoughnutChart5')) {
this._smallDoughnutChart5 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart5', [4, 6], 'EDUCATION');
}
if (document.getElementById('smallDoughnutChart6')) {
this._smallDoughnutChart6 = ChartsExtend.SmallDoughnutChart('smallDoughnutChart6', [3, 8], 'PAYMENTS');
}
}
// Small line charts
_initSmallLineCharts() {
this._smallLineChart1 = ChartsExtend.SmallLineChart('smallLineChart1', {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
datasets: [
{
label: 'BTC / USD',
data: [9415.1, 9430.3, 9436.8, 9471.5, 9467.2],
icons: ['chevron-bottom', 'chevron-top', 'chevron-top', 'chevron-top', 'chevron-bottom'],
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.foreground,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 2,
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointHoverRadius: 5,
fill: false,
},
],
});
this._smallLineChart2 = ChartsExtend.SmallLineChart('smallLineChart2', {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
datasets: [
{
label: 'ETH / USD',
data: [325.3, 310.4, 338.2, 347.1, 348.0],
icons: ['chevron-top', 'chevron-bottom', 'chevron-top', 'chevron-top', 'chevron-top'],
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.foreground,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 2,
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointHoverRadius: 5,
fill: false,
},
],
});
this._smallLineChart3 = ChartsExtend.SmallLineChart('smallLineChart3', {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
datasets: [
{
label: 'LTC / USD',
data: [43.3, 42.8, 45.3, 45.3, 41.4],
icons: ['chevron-top', 'chevron-bottom', 'chevron-top', 'circle', 'chevron-top'],
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.foreground,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 2,
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointHoverRadius: 5,
fill: false,
},
],
});
this._smallLineChart4 = ChartsExtend.SmallLineChart('smallLineChart4', {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
datasets: [
{
label: 'XRP / USD',
data: [0.25, 0.253, 0.268, 0.243, 0.243],
icons: ['chevron-top', 'chevron-top', 'chevron-top', 'chevron-bottom', 'circle'],
borderColor: Globals.primary,
pointBackgroundColor: Globals.primary,
pointBorderColor: Globals.primary,
pointHoverBackgroundColor: Globals.foreground,
pointHoverBorderColor: Globals.primary,
borderWidth: 2,
pointRadius: 2,
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointHoverRadius: 5,
fill: false,
},
],
});
}
} |
JavaScript | class Repository {
// Returns the absolute path to the repository's directory.
get directory() { return path.resolve('../playground'); }
// Executes |command| asynchronously on the directory of the repository. Both the command and the
// output of the command will be written to the log file.
executeCommand(log, command) {
return new Promise((resolve, reject) => {
log('$ ' + command + '\n');
const options = {
cwd: this.directory,
timeout: 30000
};
console.log('$ ' + command);
child_process.exec(command, options, (error, stdout, stderr) => {
log(stdout); console.log(stdout);
log(stderr); console.log(stderr);
if (error)
log(error); console.log(error);
if (error)
reject(new Error('Unable to execute command: ' + command));
else
resolve();
});
});
}
// Resets the current state of the repository, then updates it to |base|. Since this touches the
// filesystem it happens asynchronously. We first fetch all latest information for the repository,
// reset to a neutral state, then remove all files (including untracked files and changes to the
// .gitignore file), check out the appropriate branch and then update to the base revision.
updateTo(log, base) {
const commands = [
'git fetch -a',
'git reset --hard',
'git clean -f -d -x',
'git checkout ' + base.branch,
'git reset --hard ' + base.sha
];
let queue = Promise.resolve();
commands.forEach(command =>
queue = queue.then(() => this.executeCommand(log, command)));
return queue;
}
// Applies the PR's diff to the repository. The |diffUrl| will be fetched from the network by the
// command we use to apply it. This method returns a promise because it happens asynchronously.
applyDiff(log, diffUrl) {
const commands = [
'wget -O - ' + diffUrl + ' | patch -p1'
];
let queue = Promise.resolve();
commands.forEach(command =>
queue = queue.then(() => this.executeCommand(log, command)));
return queue;
}
} |
JavaScript | class Git {
constructor(repo) {
this.repo = repo;
this.branch = {
create: branch.create(repo),
remove: branch.remove(repo),
checkOut: branch.checkOut(repo),
checkOutCommit: branch.checkOutCommit(repo),
checkOutMasterBranch: branch.checkOutMasterBranch(repo),
isDetachedHead: branch.isDetachedHead(repo),
getBranchList: branch.getBranchList(repo)
};
}
addAndCommit = async commitMsg => {
return await addAndCommit(this.repo, commitMsg);
};
get branch() {
return this._branch;
}
set branch(obj) {
return (this._branch = obj);
}
createInitialCommit = async () => {
return await createInitialCommit(this.repo);
};
getCurrentBranch = async () => {
return await getCurrentBranch(this.repo);
};
getLatestCommitTime = async branch => {
return getLatestCommitTime(this.repo, branch);
};
reset = async (branchName, commitHash) => {
return await reset(this.repo, branchName, commitHash);
};
} |
JavaScript | class ClusterHealth extends models['EntityHealth'] {
/**
* Create a ClusterHealth.
* @member {array} [nodeHealthStates] Cluster node health states as found in
* the health store.
* @member {array} [applicationHealthStates] Cluster application health
* states as found in the health store.
*/
constructor() {
super();
}
/**
* Defines the metadata of ClusterHealth
*
* @returns {object} metadata of ClusterHealth
*
*/
mapper() {
return {
required: false,
serializedName: 'ClusterHealth',
type: {
name: 'Composite',
className: 'ClusterHealth',
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'
}
},
nodeHealthStates: {
required: false,
serializedName: 'NodeHealthStates',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'NodeHealthStateElementType',
type: {
name: 'Composite',
className: 'NodeHealthState'
}
}
}
},
applicationHealthStates: {
required: false,
serializedName: 'ApplicationHealthStates',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ApplicationHealthStateElementType',
type: {
name: 'Composite',
className: 'ApplicationHealthState'
}
}
}
}
}
}
};
}
} |
JavaScript | class ConceptLoader {
static get SystemDefaultMappings() {
let defaultMappings = ["dom"];
if(Datastore.getDatastoreType("cauldron") != null) {
defaultMappings.push("cauldron");
}
return this.hasOwnProperty('_SystemDefaultMappings') ? this._SystemDefaultMappings : defaultMappings;
}
static set SystemDefaultMappings(mappings) {
this._SystemDefaultMappings = mappings;
}
static parseSpec(json) {
let parsedSpec = {
"concepts":[],
"dataStores": []
}
function getConceptFromName(name) {
return parsedSpec.concepts.find((concept)=>{
return concept.name === name;
});
}
//Start parse group
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Parsing: ", json);
}
//Start datastore group
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Parsing dataStores...");
}
const dataStores = {
"dom": {
"type": "dom",
"options": {default: true}
},
"memory": {
"type": "memory",
"options": {default: true}
},
"localStorage": {
"type": "localStorage",
"options": {default: true}
}
};
if(Datastore.getDatastoreType("cauldron") != null) {
dataStores.cauldron = {
"type": "cauldron",
"options": {default: true}
};
}
if(ConceptLoader.DEBUG) {
console.log("Default dataStores:", Object.assign({},dataStores));
}
if(json.dataStores != null) {
Object.keys(json.dataStores).forEach((dataStoreKey)=>{
let dataStoreConfig = json.dataStores[dataStoreKey];
dataStores[dataStoreKey] = dataStoreConfig;
});
}
for(let dataStoreKey of Object.keys(dataStores)) {
const dataStoreConfig = dataStores[dataStoreKey];
if(ConceptLoader.DEBUG) {
console.log("Creating dataStore instance:", dataStoreKey, dataStoreConfig);
}
let dataStoreClass = Datastore.getDatastoreType(dataStoreConfig.type);
let dataStoreInstance = new dataStoreClass(dataStoreKey, dataStoreConfig.options);
parsedSpec.dataStores.push(dataStoreInstance);
}
//End datastore group
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(json.concepts != null) {
// Go through every concept in this JSON
Object.keys(json.concepts).forEach((conceptName) => {
let conceptJson = json.concepts[conceptName];
if (ConceptLoader.DEBUG) {
console.groupCollapsed("Concept:", conceptName);
}
let concept = new Concept(conceptName);
//VarvEngine.registerConceptFromType(conceptName, concept);
let structure = conceptJson.structure || conceptJson.schema;
// Find the properties of this Concept
if (structure != null) {
Object.keys(structure).forEach((propertyName) => {
let propertyJson = structure[propertyName];
let property = new Property(propertyName, propertyJson);
if (ConceptLoader.DEBUG) {
console.log("Property:", property);
}
concept.addProperty(property);
});
}
// Find the mappings
concept.properties.forEach((property) => {
//Dont map derived properties
if(property.isDerived()) {
return;
}
let propertyName = property.name;
let propertyMappings = ConceptLoader.getMappingsForProperty(conceptJson, propertyName);
if (ConceptLoader.DEBUG) {
console.log("Mapping:", propertyName, propertyMappings);
}
concept.mapProperty(property, propertyMappings);
});
// Find the actions
if (conceptJson.actions != null) {
Object.keys(conceptJson.actions).forEach((actionName) => {
let actionSetup = conceptJson.actions[actionName];
if (Array.isArray(actionSetup)) {
//This is a behaviour action, with only then part
let behaviour = new Behaviour(actionName, [], actionSetup, concept, actionName);
if (ConceptLoader.DEBUG) {
console.log("Behaviour:", behaviour);
}
concept.addBehaviour(behaviour);
} else {
//This is a behaviour action, with either then or when or both...
let behaviour = new Behaviour(actionName, actionSetup.when, actionSetup.then, concept, actionName);
if (ConceptLoader.DEBUG) {
console.log("Behaviour:", behaviour);
}
concept.addBehaviour(behaviour);
}
});
}
if(conceptJson.extensions != null) {
if(json.extensions == null) {
json.extensions = [];
}
let sugarExtensions = [];
if (ConceptLoader.DEBUG) {
console.log("Sugar extensions...");
}
Object.keys(conceptJson.extensions).forEach((extensionType) => {
let extensionSetup = conceptJson.extensions[extensionType];
if(!Array.isArray(extensionSetup)) {
extensionSetup = [extensionSetup];
}
switch(extensionType) {
case "inject": {
if (ConceptLoader.DEBUG) {
console.log("Inject:", extensionSetup);
}
let extension = {
"concept": concept.name,
"inject": extensionSetup
}
sugarExtensions.unshift(extension);
break;
}
case "pick": {
if (ConceptLoader.DEBUG) {
console.log("Pick:", extensionSetup);
}
extensionSetup.forEach((extensionSetupElm)=>{
let extension = {
"concept": extensionSetupElm.concept,
"into": concept.name,
"pick": {}
}
if(extensionSetupElm.schema != null) {
extension.pick.schema = extensionSetupElm.schema;
}
if(extensionSetupElm.actions != null) {
extension.pick.actions = extensionSetupElm.actions;
}
sugarExtensions.unshift(extension);
});
break;
}
case "omit": {
if (ConceptLoader.DEBUG) {
console.log("Omit:", extensionSetup);
}
extensionSetup.forEach((extensionSetupElm)=>{
let extension = {
"concept": concept.name,
"omit": {}
}
if(extensionSetupElm.schema != null) {
extension.omit.schema = extensionSetupElm.schema;
}
if(extensionSetupElm.actions != null) {
extension.omit.actions = extensionSetupElm.actions;
}
sugarExtensions.unshift(extension);
});
break;
}
default:
console.log("Unknown extension type:", extensionType, extensionSetup);
}
});
sugarExtensions.forEach((extension)=>{
json.extensions.unshift(extension);
})
}
if (ConceptLoader.DEBUG) {
console.groupEnd();
}
parsedSpec.concepts.push(concept);
});
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Extensions");
}
// Now modify the environment with the concept extensions (join, inject ...) in order of definition
if (json.extensions){
json.extensions.forEach((extension)=>{
try {
if (extension.inject != null) {
// Join two or more concepts together into a new concept
if (!extension.concept) throw new Error("Inject extension without target 'concept' name: " + JSON.stringify(extension));
let target = getConceptFromName(extension.concept);
if (!target) throw new Error("Inject extension with target 'concept' set to '" + extension.concept + "' that does not exist: " + JSON.stringify(extension));
if (ConceptLoader.DEBUG) {
console.log("Injecting into " + extension.concept + ":");
}
if (!Array.isArray(extension.inject)) extension.inject = [extension.inject];
for (let joinee of extension.inject) {
let otherConcept = getConceptFromName(joinee);
if (!otherConcept) throw new Error("Inject extension with unknown concept '" + joinee + "' in 'inject' list: " + JSON.stringify(extension));
target.join(otherConcept);
}
} else if (extension.join != null) {
// Join two or more concepts together into a new concept
if (!extension.as) throw new Error("Join extension without 'as' target concept name: " + JSON.stringify(extension));
let potentialClash = getConceptFromName(extension.as);
if (potentialClash) throw new Error("Join extension with 'as' target concept name '" + extension.as + "' that already exists: " + JSON.stringify(extension));
let concept = new Concept(extension.as);
parsedSpec.concepts.push(concept);
if (ConceptLoader.DEBUG) {
console.groupCollapsed("Joining into " + extension.as + ":");
}
for (let joinee of extension.join) {
let otherConcept = getConceptFromName(joinee);
if (!otherConcept) throw new Error("Join extension with unknown concept '" + joinee + "' in 'join' list: " + JSON.stringify(extension));
if (ConceptLoader.DEBUG) {
console.log(otherConcept.name);
}
concept.join(otherConcept);
}
if (ConceptLoader.DEBUG) {
console.groupEnd();
}
} else if (extension.omit != null) {
if(!extension.concept) throw new Error("Omit extension without 'concept' option: "+JSON.stringify(extension));
let concept = getConceptFromName(extension.concept);
if(concept != null) {
if (ConceptLoader.DEBUG) {
console.log("Omitting from " + extension.concept + ":", extension.omit);
}
concept.omit(extension.omit);
}
} else if (extension.pick != null) {
if(!extension.concept) throw new Error("Pick extension without 'concept' option: "+JSON.stringify(extension));
if(!extension.as && !extension.into) throw new Error("Pick extension without 'as' or 'into' option: "+JSON.stringify(extension));
let toConcept = null;
let fromConcept = getConceptFromName(extension.concept);
if(fromConcept == null) {
throw new Error("Pick extension with unknown concept '"+extension.concept+"': "+JSON.stringify(extension));
}
if(extension.as != null) {
if(getConceptFromName(extension.as) != null) {
throw new Error("Pick extension option 'as' another concept with that name already exists: "+JSON.stringify(extension));
}
toConcept = new Concept(extension.as);
parsedSpec.concepts.push(toConcept);
} else if(extension.into != null) {
toConcept = getConceptFromName(extension.into);
}
if (ConceptLoader.DEBUG) {
console.log("Picking from " + extension.concept + " as "+extension.as+":", extension.pick);
}
if(extension.pick.schema != null) {
if(!Array.isArray(extension.pick.schema)) {
extension.pick.schema = [extension.pick.schema];
}
extension.pick.schema.forEach((propertyName)=>{
let property = fromConcept.getProperty(propertyName);
toConcept.addProperty(property.cloneFresh(toConcept), true);
let mappings = fromConcept.mappings.get(propertyName);
toConcept.mapProperty(toConcept.getProperty(propertyName), mappings);
});
}
if(extension.pick.actions != null) {
if (!Array.isArray(extension.pick.actions)) {
extension.pick.actions = [extension.pick.actions];
}
extension.pick.actions.forEach((behaviourName)=>{
let behaviour = fromConcept.getBehaviour(behaviourName);
toConcept.addBehaviour(behaviour.cloneFresh(toConcept), true);
});
}
} else {
throw new Error("Unsupported extension: " + JSON.stringify(extension));
}
} catch(e) {
console.warn(e);
}
});
}
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
//End Parse group
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
return parsedSpec;
}
/**
*
* @param {object} json
* @returns {Promise<any[]>}
*/
static async loadSpec(spec) {
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Loading: ", spec);
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Mapping concepts...");
}
spec.concepts.forEach((concept)=>{
if(ConceptLoader.DEBUG) {
console.log(concept);
}
VarvEngine.registerConceptFromType(concept.name, concept);
});
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Loading dataStores...");
}
for(let dataStore of spec.dataStores) {
if(ConceptLoader.DEBUG) {
console.log("Initializing datastore:", dataStore);
}
await dataStore.init();
Datastore.datastores.set(dataStore.name, dataStore);
}
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Enabling mappings");
}
spec.concepts.forEach((concept)=>{
concept.enableMappings(ConceptLoader.DEBUG);
});
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Loading backing store...");
}
// Run all datastore load methods
for(let datastore of Array.from(Datastore.datastores.values())) {
await Trigger.runWithoutTriggers(async ()=>{
await datastore.loadBackingStore();
});
}
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(ConceptLoader.DEBUG) {
console.groupCollapsed("Finishing concepts");
}
spec.concepts.forEach((concept)=>{
concept.finishSetup(ConceptLoader.DEBUG);
});
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
if(ConceptLoader.DEBUG) {
console.groupEnd();
}
return spec.concepts;
}
static getMappingsForProperty(conceptJson, propertyName){
// System-level default
let propertyMappings = ConceptLoader.SystemDefaultMappings;
// If concept has defaultMappings, use those
if(conceptJson.defaultMappings != null) {
if(!Array.isArray(conceptJson.defaultMappings)) {
console.warn("concept defaultMappings must be an array");
} else {
propertyMappings = conceptJson.defaultMappings;
}
}
// If property has mappings use those
if (conceptJson.mappings && conceptJson.mappings[propertyName]) {
propertyMappings = conceptJson.mappings[propertyName];
}
return propertyMappings;
}
static parseTrigger(triggerName, triggerJson) {
let triggerType = Object.keys(triggerJson)[0];
let triggerOptions = triggerJson[triggerType];
try {
return Trigger.getTrigger(triggerType, triggerName, triggerOptions);
} catch (e) {
console.warn(e);
}
return null;
}
static parseAction(actionName, actionSetup, concept) {
let chain = new ActionChain(actionName, {}, concept);
actionSetup.forEach((actionPart) => {
if(typeof actionPart === "string") {
if(Action.hasPrimitiveAction(actionPart)) {
chain.addAction(Action.getPrimitiveAction(actionPart, {}, concept));
} else {
let lookupAction = new LookupActionAction("", {
"lookupActionName": actionPart
}, concept);
chain.addAction(lookupAction);
}
} else {
let keys = Object.keys(actionPart);
if(keys.length > 1) {
console.warn("You have an action with more than one key as action name: ", actionPart);
}
let actionName = keys[0];
let actionOptions = actionPart[actionName];
let action = null;
try {
// Check for primitive action
action = Action.getPrimitiveAction(actionName, actionOptions, concept);
} catch(e) {
// No primitive action, reference with arguments?
action = new LookupActionAction("", {
"lookupActionName": actionName,
"lookupActionArguments": actionOptions
}, concept);
}
chain.addAction(action);
}
});
return chain;
}
} |
JavaScript | class TargetNestedElements extends core_1.Question {
/**
* @desc
*
* @param {Question<ElementFinder> | ElementFinder} parent
* @param {Question<ElementArrayFinder> | ElementArrayFinder} children
*/
constructor(parent, children) {
super(`${children.toString()} of ${parent}`);
this.parent = parent;
this.children = children;
this.list = new core_1.List(new lists_1.ElementArrayFinderListAdapter(this));
}
/**
* @desc
* Retrieves a group of {@link WebElement}s located by `locator`,
* resolved in the context of a `parent` {@link WebElement}.
*
* @param {Question<ElementFinder> | ElementFinder} parent
* @returns {TargetNestedElements}
*
* @see {@link Target}
*/
of(parent) {
return new TargetNestedElements(parent, this);
}
/**
* @desc
* Returns the number of {@link ElementFinder}s matched by the `locator`
*
* @returns {@serenity-js/core/lib/screenplay~Question<Promise<number>>}
*
* @see {@link @serenity-js/core/lib/screenplay/questions~List}
*/
count() {
return this.list.count();
}
/**
* @desc
* Returns the first of {@link ElementFinder}s matched by the `locator`
*
* @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>}
*
* @see {@link @serenity-js/core/lib/screenplay/questions~List}
*/
first() {
return this.list.first();
}
/**
* @desc
* Returns the last of {@link ElementFinder}s matched by the `locator`
*
* @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>}
*
* @see {@link @serenity-js/core/lib/screenplay/questions~List}
*/
last() {
return this.list.last();
}
/**
* @desc
* Returns an {@link ElementFinder} at `index` for `locator`
*
* @param {number} index
*
* @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>}
*
* @see {@link @serenity-js/core/lib/screenplay/questions~List}
*/
get(index) {
return this.list.get(index);
}
/**
* @desc
* Filters the list of {@link ElementFinder}s matched by `locator` to those that meet the additional {@link @serenity-js/core/lib/screenplay/questions~Expectation}s.
*
* @param {@serenity-js/core/lib/screenplay/questions~MetaQuestion<ElementFinder, Promise<Answer_Type> | Answer_Type>} question
* @param {@serenity-js/core/lib/screenplay/questions~Expectation<any, Answer_type>} expectation
*
* @returns {@serenity-js/core/lib/screenplay/questions~List<ElementArrayFinderListAdapter, ElementFinder, ElementArrayFinder>}
*
* @see {@link @serenity-js/core/lib/screenplay/questions~List}
*/
where(question, expectation) {
return this.list.where(question, expectation);
}
/**
* @desc
* Makes the provided {@link @serenity-js/core/lib/screenplay/actor~Actor}
* answer this {@link @serenity-js/core/lib/screenplay~Question}.
*
* @param {AnswersQuestions & UsesAbilities} actor
* @returns {Promise<void>}
*
* @see {@link @serenity-js/core/lib/screenplay/actor~Actor}
* @see {@link @serenity-js/core/lib/screenplay/actor~AnswersQuestions}
* @see {@link @serenity-js/core/lib/screenplay/actor~UsesAbilities}
*/
answeredBy(actor) {
return (0, withAnswerOf_1.withAnswerOf)(actor, this.parent, parent => (0, withAnswerOf_1.withAnswerOf)(actor, this.children, children => (0, override_1.override)(parent.all(children.locator()), 'toString', TargetNestedElements.prototype.toString.bind(this))));
}
} |
JavaScript | class Points extends Object3D {
constructor(geometry = new BufferGeometry(), material = new PointsMaterial({color: Math.random() * 0xffffff})) {
super();
this.type = 'Points';
this.geometry = geometry;
this.material = material;
this.isPoints= true;
}
raycast(raycaster, intersects) {
let inverseMatrix = new Matrix4();
let ray = new Ray();
let sphere = new Sphere();
let that = this;
return (function raycast() {
let object = that;
let geometry = that.geometry;
let matrixWorld = that.matrixWorld;
let threshold = raycaster.params.Points.threshold;
// Checking boundingSphere distance to ray
if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
sphere.copy(geometry.boundingSphere);
sphere.applyMatrix4(matrixWorld);
sphere.radius += threshold;
if (raycaster.ray.intersectsSphere(sphere) === false) return;
//
inverseMatrix.getInverse(matrixWorld);
ray.copy(raycaster.ray).applyMatrix4(inverseMatrix);
let localThreshold = threshold / ((that.scale.x + that.scale.y + that.scale.z) / 3);
let localThresholdSq = localThreshold * localThreshold;
let position = new Vector3();
let intersectPoint = new Vector3();
function testPoint(point, index) {
let rayPointDistanceSq = ray.distanceSqToPoint(point);
if (rayPointDistanceSq < localThresholdSq) {
ray.closestPointToPoint(point, intersectPoint);
intersectPoint.applyMatrix4(matrixWorld);
let distance = raycaster.ray.origin.distanceTo(intersectPoint);
if (distance < raycaster.near || distance > raycaster.far) return;
intersects.push({
distance: distance,
distanceToRay: Math.sqrt(rayPointDistanceSq),
point: intersectPoint.clone(),
index: index,
face: null,
object: object
});
}
}
if (geometry.isBufferGeometry) {
let index = geometry.index;
let attributes = geometry.attributes;
let positions = attributes.position.array;
if (index !== null) {
let indices = index.array;
for (let i = 0, il = indices.length; i < il; i++) {
let a = indices[i];
position.fromArray(positions, a * 3);
testPoint(position, a);
}
} else {
for (let i = 0, l = positions.length / 3; i < l; i++) {
position.fromArray(positions, i * 3);
testPoint(position, i);
}
}
} else {
let vertices = geometry.vertices;
for (let i = 0, l = vertices.length; i < l; i++) {
testPoint(vertices[i], i);
}
}
})();
}
clone() {
return new this.constructor(this.geometry, this.material).copy(this);
}
} |
JavaScript | class activityButton {
constructor (ImgA, xA, yA, width, height) {
this.xA = xA;//position on x.axis
this.yA = yA;//position on y.axis
this.ImgA = ImgA;//picture to be displayed
this.width = width;//width of picture
this.height = height;//height of picture
}
icons () {
image(this.ImgA, this.xA, this.yA, this.width, this.height);
}
} |
JavaScript | class Dictionary {
constructor() {
this.items = {};
}
set(key, value) {
// This adds a new item to the dictionary
this.items[key] = value;
}
delete(key) {
// This removes the value from the dictionary using the key
if (this.has(key)) {
delete this.items[key];
return true;
}
return false;
}
has(key) {
// This returns true if the key exists in the dictionary and false otherwise
return key in this.items;
}
get(key) {
// This returns a specific value searched by the key
return this.has(key) ? this.items[key] : undefined;
}
clear() {
// This removes all the items from the dictionary
this.items = {};
}
size() {
// This returns how many elements the dictionary contains.
return Object.keys(this.items).length;
}
keys() {
// This returns all the keys the dictionary contains as an array
return Object.keys(this.items);
}
values() {
// This returns all the values the dictionary contains as an array
const values = [];
const keys = Object.keys(this.items);
for (let i = 0; i < keys.length; i += 1) {
if (this.has(keys[i])) {
values.push(this.items[keys[i]]);
}
}
return values;
}
} |
JavaScript | class LionField extends FormControlMixin(
InteractionStateMixin(FocusMixin(FormatMixin(ValidateMixin(SlotMixin(LitElement))))),
) {
/**
* @param {import('@lion/core').PropertyValues } changedProperties
*/
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
/** @type {any} */
this._initialModelValue = this.modelValue;
}
connectedCallback() {
super.connectedCallback();
this._onChange = this._onChange.bind(this);
this._inputNode.addEventListener('change', this._onChange);
this.classList.add('form-field'); // eslint-disable-line
}
disconnectedCallback() {
super.disconnectedCallback();
this._inputNode.removeEventListener('change', this._onChange);
}
resetInteractionState() {
super.resetInteractionState();
this.submitted = false;
}
/**
* Resets modelValue to initial value.
* Interaction states are cleared
*/
reset() {
this.modelValue = this._initialModelValue;
this.resetInteractionState();
}
/**
* Clears modelValue.
* Interaction states are not cleared (use resetInteractionState for this)
*/
clear() {
// TODO: [v1] set to undefined
this.modelValue = '';
}
/**
* Dispatches custom bubble event
* @protected
*/
_onChange() {
/** @protectedEvent user-input-changed */
this.dispatchEvent(new Event('user-input-changed', { bubbles: true }));
}
/**
* @configure InteractionStateMixin, ValidateMixin
*/
get _feedbackConditionMeta() {
return { ...super._feedbackConditionMeta, focused: this.focused };
}
/**
* @configure FocusMixin
*/
get _focusableNode() {
return this._inputNode;
}
} |
JavaScript | class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
/**
* Adds a Point to the location of this Point and returns a new Point.
*
* @param {Point} point
* @returns {Point}
*/
add(point) {
return new Point(this.x + point.x, this.y + point.y);
}
/**
* Subtracts a Point from the location of this Point and returns a new Point.
*
* @param {Point} point
* @returns {Point}
*/
sub(point) {
return new Point(this.x - point.x, this.y - point.y);
}
} |
JavaScript | class Size {
constructor(width, height) {
this.width = width;
this.height = height;
}
} |
JavaScript | class Rect {
constructor(x, y, width, height) {
this.left = x;
this.top = y;
this.right = x + width;
this.bottom = y + height;
this.width = width;
this.height = height;
}
static fromPositions({ left, top, right, bottom }) {
return new Rect(left, top, right - left, bottom - top);
}
getPosition() {
return new Point(this.left, this.top);
}
getSize() {
return new Size(this.width, this.height);
}
/**
* Adds a point to the location of this Rect and returns a new Rect.
*
* @param {Point} point
* @returns {Rect}
*/
add(point) {
return new Rect(
this.left + point.x,
this.top + point.y,
this.width,
this.height
);
}
/**
* Subtracts a point from the location of this Rect and returns a new Rect.
*
* @param {Point} point
* @returns {Rect}
*/
sub(point) {
return new Rect(
this.left - point.x,
this.top - point.y,
this.width,
this.height
);
}
} |
JavaScript | class AffiliationSelector extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
const {affiliationSelector, userInfo} = this.props;
const {authenticated} = userInfo;
if (authenticated && !affiliationSelector.selected)
// Init selector lists only if container doesn't contain any selected state!
this.props.initAffiliationSelector(authenticated.role, affiliationSelector);
// Adjust lists, make sure that corresponding lists are not empty!
if (affiliationSelector.selected) {
const {org, fac, dep} = affiliationSelector.selected;
if (org && fac && dep) {
this.props.setExistingOrganisationsForSelector('All');
this.props.setExistingFacultiesForSelector(org.value.toString());
this.props.setExistingDepartmentsForSelector(fac.value.toString());
} else if (fac && dep) {
this.props.setExistingFacultiesForSelector('All');
this.props.setExistingDepartmentsForSelector(fac.value.toString());
} else {
this.props.setExistingDepartmentsForSelector('All');
}
}
}
handleSubmit(formData) {
const {affiliation} = formData;
let aff = new Affiliation(
affiliation.orgId,
affiliation.facId,
affiliation.depId);
// Invoke a function to have job done!
this.props.afterAffiliationSelected(aff);
}
handleOwnDepartment() {
// Invoke a function to have a job done!
this.props.afterOwnDepartmentSelected()
}
render() {
const {authenticated} = this.props.userInfo;
if (authenticated && !authenticated.isAtLeastFacAdmin) return <ProtectedResource/>;
const {userInfo, affiliationSelector} = this.props;
const {isLoading, error, selected} = affiliationSelector;
return (
<div>
<div className="row">
<div className="col-12">
<div className="card bg-transparent">
{
isLoading &&
<div className="text-secondary text-center mb-n3">Loading...</div>
}
{
error &&
<div className="pl-1 pr-1 mt-2 mb-n3">
<Error message="Operation failed!" close={() => this.props.clearLoadingFailure()}/>
</div>
}
<div className="ratos-form-card card-body">
<AffiliationSelectorForm
initialValues={selected ?
{
affiliation: {
orgId: selected.org ? selected.org.value : null,
facId: selected.fac ? selected.fac.value : null,
depId: selected.dep ? selected.dep.value : null,
}
}
: null
}
userInfo={userInfo}
affiliationSelector={affiliationSelector}
getAllFacultiesForSelectorByOrganisationId={this.props.getAllFacultiesForSelectorByOrganisationId}
getAllDepartmentsForSelectorByFacultyId={this.props.getAllDepartmentsForSelectorByFacultyId}
clearAllOnOrganisationReset={this.props.clearAllOnOrganisationReset}
clearAllOnFacultyReset={this.props.clearAllOnFacultyReset}
onSubmit={formData => this.handleSubmit(formData)}
/>
</div>
<button type="button" value="Own" className="btn btn-sm btn-info p-2"
onClick={() => this.handleOwnDepartment()}>
<div className="align-middle">Select my department <FaStepForward/></div>
</button>
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class TenantAdministration extends TwyrBaseFeature {
// #region Constructor
constructor(parent, loader) {
super(parent, loader);
}
// #endregion
// #region Protected methods - need to be overriden by derived classes
/**
* @async
* @function
* @override
* @instance
* @memberof TenantAdministration
* @name getDashboardDisplayDetails
*
* @param {Object} ctxt - Koa context.
*
* @returns {Object} Dashboard display stuff for this Feature.
*
* @summary Everyone logged-in gets access.
*/
async getDashboardDisplayDetails(ctxt) {
try {
const rbacChecker = this._rbac('tenant-administration-read');
await rbacChecker(ctxt);
const defaultDisplay = await super.getDashboardDisplayDetails(ctxt);
defaultDisplay['attributes']['description'] = `Edit Account Settings`;
defaultDisplay['attributes']['icon_type'] = 'mdi';
defaultDisplay['attributes']['icon_path'] = 'account-settings';
return defaultDisplay;
}
catch(err) {
return null;
}
}
// #endregion
// #region Properties
/**
* @override
*/
get basePath() {
return __dirname;
}
// #endregion
} |
JavaScript | class ObjectDataTableAdapter {
/**
* @param {?} data
* @return {?}
*/
static generateSchema(data) {
/** @type {?} */
const schema = [];
if (data && data.length) {
/** @type {?} */
const rowToExaminate = data[0];
if (typeof rowToExaminate === 'object') {
for (const key in rowToExaminate) {
if (rowToExaminate.hasOwnProperty(key)) {
schema.push({
type: 'text',
key: key,
title: key,
sortable: false
});
}
}
}
}
return schema;
}
/**
* @param {?=} data
* @param {?=} schema
*/
constructor(data = [], schema = []) {
this._rows = [];
this._columns = [];
if (data && data.length > 0) {
this._rows = data.map((/**
* @param {?} item
* @return {?}
*/
(item) => {
return new ObjectDataRow(item);
}));
}
if (schema && schema.length > 0) {
this._columns = schema.map((/**
* @param {?} item
* @return {?}
*/
(item) => {
return new ObjectDataColumn(item);
}));
// Sort by first sortable or just first column
/** @type {?} */
const sortable = this._columns.filter((/**
* @param {?} column
* @return {?}
*/
(column) => column.sortable));
if (sortable.length > 0) {
this.sort(sortable[0].key, 'asc');
}
}
this.rowsChanged = new Subject();
}
/**
* @return {?}
*/
getRows() {
return this._rows;
}
/**
* @param {?} rows
* @return {?}
*/
setRows(rows) {
this._rows = rows || [];
this.sort();
this.rowsChanged.next(this._rows);
}
/**
* @return {?}
*/
getColumns() {
return this._columns;
}
/**
* @param {?} columns
* @return {?}
*/
setColumns(columns) {
this._columns = columns || [];
}
/**
* @param {?} row
* @param {?} col
* @return {?}
*/
getValue(row, col) {
if (!row) {
throw new Error('Row not found');
}
if (!col) {
throw new Error('Column not found');
}
/** @type {?} */
const value = row.getValue(col.key);
if (col.type === 'icon') {
/** @type {?} */
const icon = row.getValue(col.key);
return icon;
}
return value;
}
/**
* @return {?}
*/
getSorting() {
return this._sorting;
}
/**
* @param {?} sorting
* @return {?}
*/
setSorting(sorting) {
this._sorting = sorting;
if (sorting && sorting.key) {
this._rows.sort((/**
* @param {?} a
* @param {?} b
* @return {?}
*/
(a, b) => {
/** @type {?} */
let left = a.getValue(sorting.key);
if (left) {
left = (left instanceof Date) ? left.valueOf().toString() : left.toString();
}
else {
left = '';
}
/** @type {?} */
let right = b.getValue(sorting.key);
if (right) {
right = (right instanceof Date) ? right.valueOf().toString() : right.toString();
}
else {
right = '';
}
return sorting.direction === 'asc'
? left.localeCompare(right)
: right.localeCompare(left);
}));
}
}
/**
* @param {?=} key
* @param {?=} direction
* @return {?}
*/
sort(key, direction) {
/** @type {?} */
const sorting = this._sorting || new DataSorting();
if (key) {
sorting.key = key;
sorting.direction = direction || 'asc';
}
this.setSorting(sorting);
}
} |
JavaScript | class ButtplugProvider extends Component {
static propTypes = {
/**
* Passing a `logLevel` here will enable Buttplug's console logger.
*/
logLevel: PropTypes.oneOf(['error', 'warn', 'info', 'debug', 'trace']),
/**
* This name will be passed to the ButtplugClient instance. It's arbitrary.
*/
clientName: PropTypes.string,
/**
* This name will be passed to the embedded Buttplug Server. Also arbitrary.
*/
serverName: PropTypes.string,
/**
* The rest of your app goes here, now with 110% more ButtplugDeviceContext.
*/
children: PropTypes.node,
/**
* Callback if you wish to handle Buttplug errors and rejections. Usually
* receives a String-like thing.
*/
onError: PropTypes.func,
/**
* Callback will be execute when the client connects to its own server.
* At this point, Buttplug will be truly ready, but you can also just
* wait for `context.buttplugReady` to become true.
*/
onConnect: PropTypes.func
}
constructor(props) {
super(props)
this.state = {
...defaultContext
}
this.client = null
this.addDevice = this.addDevice.bind(this)
this.removeDevice = this.removeDevice.bind(this)
}
addDevice(device) {
this.setState({
devices: [...this.state.devices, device]
})
}
removeDevice(device) {
const devices = [...this.state.devices]
this.setState({
devices: devices.filter((d) => d.Index !== device.index)
})
}
componentWillUnmount() {
this.state.devices.forEach((device) => device.disconnect())
}
componentDidMount() {
buttplugInit().then(() => {
this.client = new ButtplugClient(this.props.clientName)
this.client.addListener('deviceadded', this.addDevice)
this.client.addListener('deviceremoved', this.addDevice)
const options = new ButtplugEmbeddedConnectorOptions()
options.ServerName = this.props.serverName
this.client
.connect(options)
.then(this.props.onConnect)
.catch(this.props.onError)
this.setState({
buttplugReady: true,
client: this.client,
startScanning: this.client.startScanning
})
if (this.props.logLevel) {
activateConsoleLogger(this.props.logLevel)
}
})
}
render() {
return (
<ButtplugDeviceContext.Provider value={this.state}>
{this.props.children}
</ButtplugDeviceContext.Provider>
)
}
} |
JavaScript | class StripeClient extends HttpsClient {
/**
* Set up the http client configuration.
*/
constructor() {
super(`${config.stripe.url}/v1`, {
headers: {
Authorization: `Bearer ${config.stripe.key}`,
},
});
}
/**
* Makes a GET request to the API
* @param {string} path - Path to the resource required
* @param {object} [options={}] - Optional configuration for the GET request. See https://nodejs.org/api/http.html#http_http_request_options_callback
*/
get(path, options) {
return super.get(path, {
...options,
headers: {
'Content-Type': 'application/json',
...(options.headers || {}),
},
});
}
/**
* Makes a POST request to the API with the provided data
* @param {string} path - Full pathname to the resource
* @param {object} [data={}] - Data to be submitted to the API
* @param {object} [options={}] - Optional configuration for the GET request. See https://nodejs.org/api/http.html#http_http_request_options_callback
*/
post(path, data = {}, options = {}) {
// Stringify the payload
const stringPostData = querystring.stringify(data);
return super.post(path, stringPostData, {
...options,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(stringPostData),
...(options.headers || {}),
},
});
}
} |
JavaScript | class CloudController extends CloudControllerBase {
/**
* @param {String} endPoint [CC endpoint]
* @returns {void}
* @constructor
*/
constructor(endPoint) {
super(endPoint);
}
/**
* Get information from Cloud Controller
* {@link http://apidocs.cloudfoundry.org/214/info/get_info.html}
*
* @return {JSON} [Return all enabled services to use]
*/
getInfo () {
const url = `${this.API_URL}/v2/info`;
const options = {
method: "GET",
url: url
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
/**
* Get information about all featured flags.
* {@link http://apidocs.cloudfoundry.org/214/feature_flags/get_all_feature_flags.html}
*
* @return {JSON} [Response]
*/
getFeaturedFlags() {
const url = `${this.API_URL}/v2/config/feature_flags`;
const options = {
method: "GET",
url: url,
headers: {
Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}`
}
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
/**
* Get information about a determinated featured flag.
* {@link http://apidocs.cloudfoundry.org/214/feature_flags/get_the_diego_docker_feature_flag.html}
*
* @param {String} flag [flag]
* @return {JSON} [Response]
*/
getFeaturedFlag(flag) {
const url = `${this.API_URL}/v2/config/feature_flags/${flag}`;
const options = {
method: "GET",
url: url,
headers: {
Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}`
}
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
/**
* Enable a feature flag
* {@link http://apidocs.cloudfoundry.org/214/feature_flags/set_a_feature_flag.html }
*
* @param {String} flag [flag to make the request]
* @return {JSON} [Response]
*/
setFeaturedFlag(flag) {
const url = `${this.API_URL}/v2/config/feature_flags/${flag}`;
const options = {
method: "PUT",
url: url,
headers: {
Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}`
}
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
} |
JavaScript | class RunPage extends Component {
constructor(props) {
super(props);
this.state = {
romName: null,
romData: null,
emulatorKey: null,
slaveScreenKey: null,
running: false,
paused: false,
controlsModalOpen: false,
createRoomModalOpen: false,
loading: true,
loadedPercent: 3,
error: null,
roomsList: [],
roomId: null,
};
}
render() {
return (
<div className="RunPage">
<nav
className="navbar navbar-expand"
ref={(el) => {
this.navbar = el;
}}
>
<ul className="navbar-nav" style={{ width: "200px" }}>
<li className="navitem">
<Link to="/" className="nav-link">
‹ Back
</Link>
</li>
</ul>
<ul className="navbar-nav ml-auto mr-auto">
<li className="navitem">
<span className="navbar-text mr-3">{this.state.romName}</span>
</li>
</ul>
<ul className="navbar-nav" style={{ width: "200px" }}>
<li className="navitem">
<Button
outline
color="primary"
onClick={this.toggleCreateRoomModal}
className="mr-3"
>
Rooms
</Button>
<Button
outline
color="primary"
onClick={this.toggleControlsModal}
className="mr-3"
>
Controls
</Button>
<Button
outline
color="primary"
onClick={this.handlePauseResume}
disabled={!this.state.running}
>
{this.state.paused ? "Resume" : "Pause"}
</Button>
</li>
</ul>
</nav>
{this.state.error ? (
this.state.error
) : (
<div
className="screen-container"
ref={(el) => {
this.screenContainer = el;
}}
>
{this.state.loading ? (
<Progress
value={this.state.loadedPercent}
style={{
position: "absolute",
width: "70%",
left: "15%",
top: "48%",
}}
/>
) : this.state.romData && this.state.playerId === 1 ? (
<Emulator
romData={this.state.romData}
romName={this.state.romName}
paused={this.state.paused}
ref={(emulator) => {
this.emulator = emulator;
}}
websocket={this.state.websocket}
key={this.state.emulatorKey}
playerId={this.state.playerId}
roomId={this.state.roomId}
/>
) : this.state.playerId === 2 ? (
<SlaveScreen
romName={this.state.romName}
ref={(slaveScreen) => {
this.slaveScreen = slaveScreen;
}}
onKeyDown={(e) => {
this.state.websocket.send(
JSON.stringify({
event: "keyPressed",
data: {
direction: "down",
key: e.key,
room: {
id: this.state.roomId,
},
},
})
);
}}
onKeyUp={(e) => {
this.state.websocket.send(
JSON.stringify({
event: "keyPressed",
data: {
direction: "up",
key: e.key,
room: {
id: this.state.roomId,
},
},
})
);
}}
onKeyPress={(e) => {
console.log(e);
}}
key={this.state.slaveScreenKey}
/>
) : null}
{this.state.createRoomModalOpen && (
<RoomsListModal
isOpen={this.state.createRoomModalOpen}
toggle={this.toggleCreateRoomModal}
createRoom={this.createRoom.bind(this)}
joinRoom={this.joinRoom.bind(this)}
roomsList={this.state.roomsList}
/>
)}
{/* TODO: lift keyboard and gamepad state up */}
{this.state.controlsModalOpen && (
<ControlsModal
isOpen={this.state.controlsModalOpen}
toggle={this.toggleControlsModal}
keys={this.emulator.keyboardController.keys}
setKeys={this.emulator.keyboardController.setKeys}
promptButton={this.emulator.gamepadController.promptButton}
gamepadConfig={this.emulator.gamepadController.gamepadConfig}
setGamepadConfig={
this.emulator.gamepadController.setGamepadConfig
}
/>
)}
</div>
)}
</div>
);
}
createRoom(name) {
console.log(name);
this.state.websocket.send(
JSON.stringify({
event: "createRoom",
data: {
name,
},
})
);
}
joinRoom(id) {
console.log(id);
this.state.websocket.send(
JSON.stringify({
event: "joinRoom",
data: {
id,
},
})
);
}
onRoomsList(data) {
this.setState({
roomsList: data.rooms,
});
}
onJoinedToRoom(data) {
this.setState({
roomId: data.room.id,
playerId: data.playerId,
slaveScreenKey: `slaveScreenKeyS_${Date.now()}`,
playerId: data.playerId,
loading: false,
});
}
onConnected(data){
this.setState({
roomsList: data.rooms,
});
}
onRomLoaded(data) {
console.log(data.playerId);
this.setState((prev) => {
return {
romData: data.romData,
romName: data.romName,
emulatorKey: `${data.romName}_${Date.now()}`,
slaveScreenKey: `slaveScreenKeyS_${Date.now()}`,
playerId: data.playerId,
roomId: data.roomId,
loading: false,
};
});
}
onPlayerTwoPressKey({ direction, key }) {
console.log(key);
const keys = {
x: 0,
z: 1,
Control: 2,
Enter: 3,
ArrowUp: 4,
ArrowDown: 5,
ArrowLeft: 6,
ArrowRight: 7,
};
switch (direction) {
case "down":
this.emulator.nes.buttonDown(2, keys[key]);
break;
case "up":
this.emulator.nes.buttonUp(2, keys[key]);
break;
}
}
onSyncVideoBuffer(data) {
if (
this.state.playerId === 2 &&
this.state.websocket.readyState === WebSocket.OPEN &&
this.slaveScreen
) {
// console.log(data.buffer.length)
// var buffer = new ArrayBuffer(data.buffer);
this.slaveScreen.syncBuffer(data.buffer);
}
}
onSyncAudioBuffer(data) {
if (
this.state.playerId === 2 &&
this.state.websocket.readyState === WebSocket.OPEN &&
this.slaveScreen
) {
//console.log(data.buffer)
// var buffer = new ArrayBuffer(data.buffer);
this.slaveScreen.speakers.syncAudioBuffer(data.buffer);
}
}
componentDidMount() {
window.addEventListener("resize", this.layout);
this.layout();
const websocket = new WebSocket(config.SERVER_URL);
websocket.binaryType = "arraybuffer";
websocket.onmessage = (message) => {
if (typeof message.data === "string") {
const { event, data } = JSON.parse(message.data);
const eventListener = `on${event.charAt(0).toUpperCase() +
event.slice(1)}`;
if (typeof this[eventListener] === "function") {
this[eventListener](data);
}
}
};
this.setState({ websocket: websocket });
}
componentWillUnmount() {
window.removeEventListener("resize", this.layout);
if (this.currentRequest) {
this.currentRequest.abort();
}
if (this.state.websocket) {
this.state.websocket.onclose = function() {}; // disable onclose handler first
this.state.websocket.close();
}
}
load = () => {
if (this.props.match.params.slug) {
const slug = this.props.match.params.slug;
const isLocalROM = /^local-/.test(slug);
const romHash = slug.split("-")[1];
const romInfo = isLocalROM
? RomLibrary.getRomInfoByHash(romHash)
: config.ROMS[slug];
if (!romInfo) {
this.setState({ error: `No such ROM: ${slug}` });
return;
}
if (isLocalROM) {
this.setState({ romName: romInfo.name });
const localROMData = localStorage.getItem("blob-" + romHash);
this.handleLoaded(localROMData);
} else {
this.setState({ romName: romInfo.description });
this.currentRequest = loadBinary(
romInfo.url,
(err, data) => {
if (err) {
this.setState({ error: `Error loading ROM: ${err.message}` });
} else {
this.handleLoaded(data);
}
},
this.handleProgress
);
}
} else if (this.props.location.state && this.props.location.state.file) {
let reader = new FileReader();
reader.readAsBinaryString(this.props.location.state.file);
reader.onload = (e) => {
this.currentRequest = null;
this.handleLoaded(reader.result);
};
} else {
this.setState({ error: "No ROM provided" });
}
};
handleProgress = (e) => {
if (e.lengthComputable) {
this.setState({ loadedPercent: (e.loaded / e.total) * 100 });
}
};
handleLoaded = (data) => {
this.setState({ running: true, loading: false, romData: data });
};
handlePauseResume = () => {
this.setState({ paused: !this.state.paused });
};
layout = () => {
let navbarHeight = parseFloat(window.getComputedStyle(this.navbar).height);
this.screenContainer.style.height = `${window.innerHeight -
navbarHeight}px`;
if (this.emulator) {
this.emulator.fitInParent();
}
if (this.slaveScreen) {
this.slaveScreen.fitInParent();
}
};
toggleControlsModal = () => {
this.setState({ controlsModalOpen: !this.state.controlsModalOpen });
};
toggleCreateRoomModal = () => {
this.setState({ createRoomModalOpen: !this.state.createRoomModalOpen });
};
} |
JavaScript | class Point{
constructor(x, y){
this.x = x,
this.y = y
}
static distance(obj1, obj2) {
return Math.sqrt(Math.pow((obj2.x - obj1.x), 2) + Math.pow((obj2.y - obj1.y), 2));
}
} |
JavaScript | class ControlFlowVerifier {
_stack = [];
_unresolvedLabels = [];
_disableVerification;
/**
* Creates and initializes a new ControlFlowVerifier.
* @param {Boolean} disableVerification Flag indicating whether control flow validation is disabled.
*/
constructor(disableVerification){
this._disableVerification = disableVerification;
}
/**
* Gets the number of items in the control flow stack.
*/
get size(){
return this._stack.length;
}
/**
* Creates a new enclosing block and pushes a label containing information about the block on to the stack.
* @param {OperandStack} The operand stack at the start of the label.
* @param {BlockType} The
* @param {LabelBuilder} label Optional unresolved label to associate with the new enclosing block.
*/
push(operandStack, blockType, label = null){
const current = this.peek();
if (label){
if (!this._disableVerification && label.isResolved){
throw new VerificationErrorError('Cannot use a label that has already been associated with another block.');
}
const labelIndex = this._unresolvedLabels.findIndex(x => x === label);
if (labelIndex === -1){
throw new VerificationError('The label was not created for this function.')
}
if (!this._disableVerification && label.block && !current.block.canReference(label.block)){
throw new VerificationError('Label has been referenced by an instruction in an enclosing block that ' +
'cannot branch to the current enclosing block.')
}
this._unresolvedLabels.splice(labelIndex, 1);
}
else {
label = new LabelBuilder();
}
const block = !current ?
new ControlFlowBlock(operandStack, BlockType.Void, null, 0, 0, 0) :
new ControlFlowBlock(operandStack, blockType, current.block, current.block.childrenCount++, current.block.depth + 1, 0);
label.resolve(block);
this._stack.push(label);
return label;
}
/**
* Pops the current label off the stack.
*/
pop(){
if (this._stack.length === 0){
throw new VerificationError('Cannot end the block, the stack is empty.');
}
this._stack.pop();
}
/**
* Peeks at the current ControlFlowBlock on the top of the stack.
*/
peek(){
return this._stack.length === 0 ? null : this._stack[this._stack.length - 1];
}
/**
* Creates a new unresolved label.
* @returns {LabelBuilder} The unresolved label.
*/
defineLabel(){
const label = new LabelBuilder();
this._unresolvedLabels.push(label);
return label;
}
/**
* Adds a reference to the specified label from the current enclosing block.
* @param {LabelBuilder} label A label referenced by a branching instruction in the current enclosing block.
*/
reference(label){
if (this._disableVerification){
return;
}
const current = this.peek();
if (label.isResolved){
if (!current || !label.block.canReference(current.block)){
throw new VerificationError('The label cannot be referenced by the current enclosing block.');
}
}
else{
if (!this._unresolvedLabels.find(x => x == label)){
throw new VerificationError('The label was not created for this function.');
}
const potentialParent = label.block.findParent(current.block);
if (!potentialParent){
throw new VerificationError('The reference to this label .');
}
label.reference(potentialParent);
}
}
/**
* Verifies there are no referenced unresolved labels. If any are found an exception is thrown.
*/
verify(){
if (this._disableVerification){
return;
}
if (this._unresolvedLabels.some(x => x.block)){
throw new VerificationError('The function contains unresolved labels.');
}
if (this._stack.length === 1){
throw new VerificationError('Function is missing closing end instruction.')
}
else if (this._stack.length !== 0){
throw new VerificationError(`Function has ${this._stack.length} control structures ` +
'that are not closed. Every block, if, and loop must have a corresponding end instruction.');
}
}
} |
JavaScript | class FoodSupplyChainNetwork {
constructor(userName, password) {
this.currentUser;
this.issuer;
this.userName = userName;
this.userPW = password;
this.connection = fabricClient;
}
/**
* Utility method to delete the mutual tls client material used
*/
_cleanUpTLSKeys()
{
let client_config = this.connection.getClientConfig();
let store_path = client_config.credentialStore.path;
let crypto_path = client_config.credentialStore.cryptoStore.path;
fsx.removeSync(crypto_path);
fsx.copySync(store_path,crypto_path);
}
/**
* Get and setup TLS mutual authentication for endpoints for this connection
*/
_setUpTLSKeys()
{
return this.connection.initCredentialStores().then(() => {
var caService = this.connection.getCertificateAuthority();
let request = {
enrollmentID: constants.OrgAdmin.Username,
enrollmentSecret: constants.OrgAdmin.Password,
profile: 'tls'
};
return caService.enroll(request)
.then((enrollment) => {
let key = enrollment.key.toBytes(); // this key will be persistenced on cvs store.
let cert = enrollment.certificate;
this.connection.setTlsClientCertAndKey(cert, key);
}).catch((err) => {
console.error('Failed to tls-enroll admin-org1: ' + err);
});
});
}
/**
* Initializes the channel object with the Membership Service Providers (MSPs). The channel's
* MSPs are critical in providing applications the ability to validate certificates and verify
* signatures in messages received from the fabric backend.
*/
_initChannelMSP()
{
var channel = this.connection.getChannel(constants.ChannelName);
return channel.initialize();
}
/**
* Init TLS material and usercontext for used by network
*/
init() {
this._cleanUpTLSKeys();
this._setUpTLSKeys()
.then(() => {
this._initChannelMSP()
.then(() => {
var isAdmin = false;
if (this.userName == constants.OrgAdmin.Username) {
isAdmin = true;
}
// Restore the state of user by the given name from key value store
// and set user context for this connection.
return this.connection.getUserContext(this.userName, true)
.then((user) => {
this.currentUser = user;
return user;
})
})
});
}
invoke(fcn, data) {
var dataAsBytes = new Buffer(JSON.stringify(data));
var tx_id = this.connection.newTransactionID();
var requestData = {
chaincodeId: constants.ChainCodeId,
fcn: fcn,
args: [dataAsBytes],
txId: tx_id
};
return this.connection.submitTransaction(requestData);
}
query(fcn, id, objectType) {
let localArgs = [];
if(id) localArgs.push(id);
if(objectType) localArgs.push(objectType);
var tx_id = this.connection.newTransactionID();
var requestData = {
chaincodeId: constants.ChainCodeId,
fcn: fcn,
args: localArgs,
txId: tx_id
};
return this.connection.query(requestData);
}
} |
JavaScript | class Composition extends Agent {
/**
*
* @param signature the signature of the composition
*
*/
constructor(signature) {
super(signature);
this.init();
}
/**
*
* Override this to modify the initialization process of a composition.
* This function is called by parent's constructor, so if you want to
* invoke `.build()` and `.wire()` after some child-class properties have been
* initialized as well, you would need to override this function. This is a typical
* scenario in case of parametric class-based compositions.
*
*/
init() {
this.build();
this.wire();
}
/**
*
* Adds a child (pin or agent) to the composition. You can provide a name. If not,
* the child will be named numerically based on the length of the children already added:
*
* ```typescript
* build() {
* this.add('myState', state());
* this.add(expr((x, y) => x * y));
* }
*
* wire() {
* this.agent('myState'); // --> this is the defined state
* this.agent(1); // --> this is the defined expr
* }
* ```
*
* @param nameOrChild
* @param child
*
*/
add(nameOrChild, child) {
if (!this._children)
this._children = {};
if (!child)
return this.add(`${Object.keys(this._children).length}`, nameOrChild);
let _name = nameOrChild;
this._children[_name] = child;
if (isBindable(child))
this.toBind(child);
return child;
}
/**
*
* @param name
* @returns the child with given name.
* @throws an error if no child with given name is defined.
*
*/
child(name) {
if (typeof name !== 'string')
return this.child(name.toString());
if (this._children && name in this._children)
return this._children[name];
throw new ChildNotDefined(name);
}
/**
*
* @param name
* @returns the pin child with given name.
* @throws an error if no child with given name is defined or if it is not a pin.
*
*/
pin(name) {
let _child = this.child(name);
if (_child instanceof Agent)
throw new ChildIsNotPin(name.toString());
return _child;
}
/**
*
* @param name
* @returns the child agent with given name.
* @throws an error if no child with given name is defined or if it is not an agent.
*
*/
agent(name) {
let _child = this.child(name);
if (!(_child instanceof Agent))
throw new ChildIsNotAgent(name.toString());
return _child;
}
/**
*
* Registers a `Bindable` that will be bound when `.bind()` is called on this composition.
*
* @param bindable
*
*/
toBind(bindable) {
if (!this._bindables)
this._bindables = [];
this._bindables.push(bindable);
return this;
}
/**
*
* Binds all registered `Bindable`s, including bindable children like
* [states](https://connective.dev/docs/state) and
* [sinks](https://connective.dev/docs/sink).
*
*/
bind() {
if (this._bindables)
this._bindables.forEach(bindable => bindable.bind());
return this;
}
/**
*
* @note `.clear()` on `Composition` also clears all registered children.
*
*/
clear() {
if (this._children) {
Object.values(this._children).forEach(child => child.clear());
this._children = undefined;
}
if (this._bindables)
this._bindables = undefined;
return super.clear();
}
} |
JavaScript | class Matcher {
static registry = []
static register(matcher) {
Matcher.registry.push(matcher)
return matcher
}
static for(settings) {
for (const matcher of Matcher.registry) {
if (matcher.canHandle(settings)) return new matcher(settings)
}
throw new Error('No matchers for available settings')
}
static createPattern(settings) {
return settings.matchEntireLine ? `^${settings.pattern}$` : `${settings.pattern}`
}
static createFlags(settings) {
return settings.ignoreCase ? 'ig' : 'g'
}
static createRegExp(settings) {
return new RegExp(Matcher.createPattern(settings), Matcher.createFlags(settings))
}
} |
JavaScript | class DefaultFunctionCollection extends FunctionCollection_1.FunctionCollection {
/**
* Constructs this list and fills it with the standard functions.
*/
constructor() {
super();
this.add(new DelegatedFunction_1.DelegatedFunction("Ticks", this.ticksFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("TimeSpan", this.timeSpanFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Now", this.nowFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Date", this.dateFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("DayOfWeek", this.dayOfWeekFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Min", this.minFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Max", this.maxFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Sum", this.sumFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("If", this.ifFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Choose", this.chooseFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("E", this.eFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Pi", this.piFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Rnd", this.rndFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Random", this.rndFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Abs", this.absFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Acos", this.acosFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Asin", this.asinFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Atan", this.atanFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Exp", this.expFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Log", this.logFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Ln", this.logFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Log10", this.log10FunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Ceil", this.ceilFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Ceiling", this.ceilFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Floor", this.floorFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Round", this.roundFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Trunc", this.truncFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Truncate", this.truncFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Cos", this.cosFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Sin", this.sinFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Tan", this.tanFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Sqr", this.sqrtFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Sqrt", this.sqrtFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Empty", this.emptyFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Null", this.nullFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Contains", this.containsFunctionCalculator, this));
this.add(new DelegatedFunction_1.DelegatedFunction("Array", this.arrayFunctionCalculator, this));
}
/**
* Checks if params contains the correct number of function parameters (must be stored on the top of the params).
* @param params A list of function parameters.
* @param expectedParamCount The expected number of function parameters.
*/
checkParamCount(params, expectedParamCount) {
let paramCount = params.length;
if (expectedParamCount != paramCount) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected " + expectedParamCount
+ " parameters but was found " + paramCount);
}
}
/**
* Gets function parameter by it's index.
* @param params A list of function parameters.
* @param paramIndex Index for the function parameter (0 for the first parameter).
* @returns Function parameter value.
*/
getParameter(params, paramIndex) {
return params[paramIndex];
}
ticksFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return Variant_1.Variant.fromLong(new Date().getTime());
});
}
timeSpanFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount != 1 && paramCount != 3 && paramCount != 4 && paramCount != 5) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected 1, 3, 4 or 5 parameters");
}
let result = new Variant_1.Variant();
if (paramCount == 1) {
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Long);
result.asTimeSpan = value.asLong;
}
else if (paramCount > 2) {
let value1 = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Long);
let value2 = variantOperations.convert(this.getParameter(params, 1), VariantType_1.VariantType.Long);
let value3 = variantOperations.convert(this.getParameter(params, 2), VariantType_1.VariantType.Long);
let value4 = paramCount > 3 ? variantOperations.convert(this.getParameter(params, 3), VariantType_1.VariantType.Long) : Variant_1.Variant.fromLong(0);
let value5 = paramCount > 4 ? variantOperations.convert(this.getParameter(params, 4), VariantType_1.VariantType.Long) : Variant_1.Variant.fromLong(0);
result.asTimeSpan = (((value1.asLong * 24 + value2.asLong) * 60 + value3.asLong) * 60 + value4.asLong) * 1000 + value5.asLong;
}
return result;
});
}
nowFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return Variant_1.Variant.fromDateTime(new Date());
});
}
dateFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount < 1 || paramCount > 7) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected from 1 to 7 parameters");
}
if (paramCount == 1) {
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Long);
return Variant_1.Variant.fromDateTime(new Date(value.asLong));
}
let value1 = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Integer);
let value2 = paramCount > 1 ? variantOperations.convert(this.getParameter(params, 1), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(1);
let value3 = paramCount > 2 ? variantOperations.convert(this.getParameter(params, 2), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(1);
let value4 = paramCount > 3 ? variantOperations.convert(this.getParameter(params, 3), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(0);
let value5 = paramCount > 4 ? variantOperations.convert(this.getParameter(params, 4), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(0);
let value6 = paramCount > 5 ? variantOperations.convert(this.getParameter(params, 5), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(0);
let value7 = paramCount > 6 ? variantOperations.convert(this.getParameter(params, 6), VariantType_1.VariantType.Integer) : Variant_1.Variant.fromInteger(0);
let date = new Date(value1.asInteger, value2.asInteger - 1, value3.asInteger, value4.asInteger, value5.asInteger, value6.asInteger, value7.asInteger);
return Variant_1.Variant.fromDateTime(date);
});
}
dayOfWeekFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.DateTime);
let date = value.asDateTime;
return Variant_1.Variant.fromInteger(date.getDay());
});
}
minFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount < 2) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected at least 2 parameters");
}
let result = this.getParameter(params, 0);
for (let i = 1; i < paramCount; i++) {
let value = this.getParameter(params, i);
if (variantOperations.more(result, value).asBoolean) {
result = value;
}
}
return result;
});
}
maxFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount < 2) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected at least 2 parameters");
}
let result = this.getParameter(params, 0);
for (let i = 1; i < paramCount; i++) {
let value = this.getParameter(params, i);
if (variantOperations.less(result, value).asBoolean) {
result = value;
}
}
return result;
});
}
sumFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount < 2) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected at least 2 parameters");
}
let result = this.getParameter(params, 0);
for (let i = 1; i < paramCount; i++) {
let value = this.getParameter(params, i);
result = variantOperations.add(result, value);
}
return result;
});
}
ifFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 3);
let value1 = this.getParameter(params, 0);
let value2 = this.getParameter(params, 1);
let value3 = this.getParameter(params, 2);
let condition = variantOperations.convert(value1, VariantType_1.VariantType.Boolean);
return condition.asBoolean ? value2 : value3;
});
}
chooseFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
let paramCount = params.length;
if (paramCount < 3) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected at least 3 parameters");
}
let value1 = this.getParameter(params, 0);
let condition = variantOperations.convert(value1, VariantType_1.VariantType.Integer);
let paramIndex = condition.asInteger;
if (paramCount < paramIndex + 1) {
throw new ExpressionException_1.ExpressionException(null, "WRONG_PARAM_COUNT", "Expected at least " + (paramIndex + 1) + " parameters");
}
return this.getParameter(params, paramIndex);
});
}
eFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return new Variant_1.Variant(Math.E);
});
}
piFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return new Variant_1.Variant(Math.PI);
});
}
rndFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return new Variant_1.Variant(Math.random());
});
}
absFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = this.getParameter(params, 0);
let result = new Variant_1.Variant();
switch (value.type) {
case VariantType_1.VariantType.Integer:
result.asInteger = Math.abs(value.asInteger);
break;
case VariantType_1.VariantType.Long:
result.asLong = Math.abs(value.asLong);
break;
case VariantType_1.VariantType.Float:
result.asFloat = Math.abs(value.asFloat);
break;
case VariantType_1.VariantType.Double:
result.asDouble = Math.abs(value.asDouble);
break;
default:
value = variantOperations.convert(value, VariantType_1.VariantType.Double);
result.asDouble = Math.abs(value.asDouble);
break;
}
return result;
});
}
acosFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.acos(value.asDouble));
});
}
asinFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.asin(value.asDouble));
});
}
atanFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.atan(value.asDouble));
});
}
expFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.exp(value.asDouble));
});
}
logFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.log(value.asDouble));
});
}
log10FunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.log10(value.asDouble));
});
}
ceilFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.ceil(value.asDouble));
});
}
floorFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.floor(value.asDouble));
});
}
roundFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.round(value.asDouble));
});
}
truncFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return Variant_1.Variant.fromInteger(Math.trunc(value.asDouble));
});
}
cosFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.cos(value.asDouble));
});
}
sinFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.sin(value.asDouble));
});
}
tanFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.tan(value.asDouble));
});
}
sqrtFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.Double);
return new Variant_1.Variant(Math.sqrt(value.asDouble));
});
}
emptyFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 1);
let value = this.getParameter(params, 0);
return new Variant_1.Variant(value.isEmpty());
});
}
nullFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 0);
return new Variant_1.Variant();
});
}
containsFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
this.checkParamCount(params, 2);
let containerstr = variantOperations.convert(this.getParameter(params, 0), VariantType_1.VariantType.String);
let substring = variantOperations.convert(this.getParameter(params, 1), VariantType_1.VariantType.String);
if (containerstr.isEmpty() || containerstr.isNull()) {
return Variant_1.Variant.fromBoolean(false);
}
return Variant_1.Variant.fromBoolean(containerstr.asString.indexOf(substring.asString) >= 0);
});
}
arrayFunctionCalculator(params, variantOperations) {
return __awaiter(this, void 0, void 0, function* () {
return Variant_1.Variant.fromArray(params);
});
}
} |
JavaScript | class ImageBackground extends React.Component {
render() {
const {children, style, imageStyle, imageRef, ...props} = this.props;
return (
<View style={style}>
<Image
{...props}
style={[
{
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
},
imageStyle,
]}
ref={imageRef}
/>
{children}
</View>
);
}
} |
JavaScript | class Parsable {
constructor(name) {
this.name = name;
}
parse(txt) {
let i = -1;
while((i = txt.indexOf("${", i + 1)) >= 0) {
let x = txt.substring(i + 2, txt.indexOf("}", i + 2));
txt = txt.replace("\$\{" + x + "\}", eval(x));
}
return txt;
}
} |
JavaScript | class HTML {
constructor() {
}
static elem(e, txt, attrs) {
let r = "<" + e;
if(attrs) for(let a in attrs) { r += " " + a + "=\"" + attrs[a] + "\""; }
r += ">" + txt + "</" + e + ">";
return r;
}
static p(txt, attrs) {
return HTML.elem("p", txt, attrs);
}
static li(txt, attrs) {
return HTML.elem("li", txt, attrs);
}
static ul(txt, attrs) {
return HTML.elem("ul", txt, attrs);
}
static figure(txt, attrs) {
return HTML.elem("figure", txt, attrs);
}
static img(attrs) {
return HTML.elem("img", "", attrs);
}
static span(txt, attrs) {
return HTML.elem("span", txt, attrs);
}
static div(txt, attrs) {
return HTML.elem("div", txt, attrs);
}
static hidden(e) {
e.style.visibility = "hidden";
}
static enable(e) {
e.classList.remove("disabled");
}
static disable(e) {
e.classList.add("disabled");
}
static clickable(e, n) {
e.classList.add("clickable");
}
static visible(e) {
e.style.visibility = "visible";
}
static toggle(e) {
if(e.style.visibility == "hidden") HTML.visible(e); else HTML.hidden(e);
return e.style.visibility;
}
} |
JavaScript | class SBrickExtended extends SBrick {
// CONSTRUCTOR
/**
* Create a new instance of the SBrickExtended class (and accordingly also WebBluetooth)
* @param {string} sbrick_name - The name of the sbrick
*/
constructor( sbrick_name ) {
super( sbrick_name);
// vars for sensor timeouts
this.sensorTimer = null;
this.sensorTimeoutIsCancelled = false;
this.sensors = [];// will contain object for each sensor port with timer: {lastValue, lastState, timer, keepAlive}
};
// PUBLIC FUNCTIONS
/**
* update a set of lights
* @param {object} data - New settings for this port {portId, power (0-100), direction}
* @returns {promise returning object} - { Returned object: portId, direction, power (0-255!), mode}
*/
setLights(data) {
data.power = Math.round(this.MAX * data.power/100);
return this.drive(data);
};
/**
* update a drive motor
* @param {object} data - New settings for this port {portId, power (0-100), direction}
* @returns {promise returning object} - { Returned object: portId, direction, power (0-255!), mode}
*/
setDrive(data) {
data.power = this.drivePercentageToPower(data.power);
return this.drive(data);
};
/**
* update a servo motor
* @param {object} data - New settings for this port {portId, angle (0-90), direction}
* @returns {promise returning object} - { Returned object: portId, direction, power (0-255!), mode}
*/
setServo(data) {
data.power = this.servoAngleToPower(data.angle);
return this.drive(data);
};
/**
* start stream of sensor measurements and send a sensorstart.sbrick event
* @param {number} portId - The id of the port to read sensor data from
* @returns {promise returning undefined} - The promise returned by sbrick.getSensor, but somehow that promise's data isn't returned
*/
startSensor(portId) {
const sensorObj = this._getSensorObj(portId);
sensorObj.keepAlive = true;
const data = {portId},
event = new CustomEvent('sensorstart.sbrick', {detail: data});
document.body.dispatchEvent(event);
return this._getNextSensorData(portId);
}
/**
* stop stream of sensor measurements and send a sensorstop.sbrick event
* @returns {undefined}
*/
stopSensor(portId) {
// sensorData timeout is only set when the promise resolves
// but in the time the promise is pending, there is no timeout to cancel
// so let's manipulate a property that has to be checked before calling a new setTimeout
const sensorObj = this._getSensorObj(portId);
sensorObj.keepAlive = false;
const data = {portId};
const event = new CustomEvent('sensorstop.sbrick', {detail: data});
document.body.dispatchEvent(event);
};
/**
* translate servo's angle to corresponding power-value
* @param {number} angle - The angle of the servo motor
* @returns {number} The corresponding power value (0-255)
*/
servoAngleToPower(angle) {
// servo motor only supports 7 angles per 90 degrees, i.e. increments of 13 degrees
angle = parseInt(angle, 10);
const idx = Math.round(angle/13);
let power = powerAngles[idx].power;
return power;
};
/**
* translate servo's power to corresponding angle-value
* @param {number} power - The current power (0-255) of the servo motor
* @returns {number} The corresponding angle value
*/
servoPowerToAngle(power) {
let angle = 0;
power = parseInt(power, 10);
for (let i=0, len=powerAngles.length; i<len; i++) {
const obj = powerAngles[i];
if (power === obj.power) {
angle = obj.angle;
break;
}
}
return angle;
};
/**
* drive motor does not seem to work below certain power threshold value
* translate the requested percentage to the actual working power range
* @param {number} powerPerc - The requested power as percentage
* @returns {number} - A value within the acutal power range
*/
drivePercentageToPower(powerPerc) {
let power = 0;
if (powerPerc !== 0) {
// define the power range within which the drive does work
const powerRange = MAX - MIN_VALUE_BELOW_WHICH_MOTOR_DOES_NOT_WORK;
power = Math.round(powerRange * powerPerc/100 + MIN_VALUE_BELOW_WHICH_MOTOR_DOES_NOT_WORK);
}
return power;
};
/**
* drive motor does not seem to work below certain power threshold value
* translate the actual power in the percentage within the actual working power range
* @returns {number} - The percentage within the actual power range
*/
drivePowerToPercentage(power) {
// define the power range within which the drive does work
let powerPerc = 0;
if (power !== 0) {
const powerRange = MAX - MIN_VALUE_BELOW_WHICH_MOTOR_DOES_NOT_WORK,
relativePower = power - MIN_VALUE_BELOW_WHICH_MOTOR_DOES_NOT_WORK;
powerPerc = Math.round(100 * relativePower / powerRange);
}
return powerPerc;
};
/**
* get the type of sensor (tilt, motion) by channel value
* @param {number} ch0Value - The value of the sensor's channel 0
* @returns {string} - The type: unknown (default) | tilt | motion
*/
getSensorType(ch0Value) {
return _rangeValueToType(ch0Value, sensorTypes);
};
/**
* determine the state for a sensor value, depending on the kind of sensor
* @returns {string} state: unknown (default) or [close | midrange | clear] (motion) or [flat | left | right | up | down] (tilt)
*/
getSensorState(value, sensorType) {
let state = 'unknown';
if (sensorType === 'motion') {
state = _rangeValueToType(value, motionStates);
} else if (sensorType === 'tilt') {
state = _rangeValueToType(value, tiltStates);
}
return state;
};
// PRIVATE FUNCTIONS
/**
* get a new reading of sensor data; send event and set timeout to call this function again
* @param {number} portId - The id of the port to read sensor data from
* @param {string} sensorSeries - not implemented yet - in the future it will manage different sensor series (wedo (default), EV3, NXT, ...)
* @returns {undefined}
*/
_getNextSensorData(portId, sensorSeries = 'wedo') {
let sensorObj = this._getSensorObj(portId);
return this.getSensor(portId, sensorSeries)
.then((sensorData) => {
// sensorData looks like this: { type, voltage, ch0_raw, ch1_raw, value }
const state = this.getSensorState(sensorData.value, sensorData.type),
{value, type} = sensorData;
// add state to sensorData obj
sensorData.state = state;
// send event if the raw value of the sensor has changed
if (value !== sensorObj.lastValue) {
sensorObj.lastValue = value;
const changeValueEvent = new CustomEvent('sensorvaluechange.sbrick', {detail: sensorData});
document.body.dispatchEvent(changeValueEvent);
}
// send event if the state of the sensor has changed
if (state !== sensorObj.lastState) {
sensorObj.lastState = state;
const event = new CustomEvent('sensorchange.sbrick', {detail: sensorData});
document.body.dispatchEvent(event);
}
// other functions may want to cancel the sensorData timeout, but they can't use clearTimeout
// because that might be called when the promise is pending (when there is no current timeout),
// and new timeout would be set in the then-clause when the promise resolves.
// so they can set the keepAlive property and we'll check that before setting a new timeout
if (sensorObj.keepAlive) {
clearTimeout(sensorObj.timer);
sensorObj.timer = setTimeout(() => {
this._getNextSensorData(portId);
}, 200);
}
});
}
/**
* get a ports object with sensor properties (lastValue etc)
* @param {number} portId - The id of the port we want to read the sensor from
* @returns {object} - object with sensor properties ({lastValue, lastState, timer, keepAlive})
*/
_getSensorObj(portId) {
let sensorObj = this.sensors[portId];
if (typeof sensorObj === 'undefined') {
sensorObj = {
lastValue: null,
lastState: null,
timer: null,
keepAlive: true
};
this.sensors[portId] = sensorObj;
}
return sensorObj;
};
} |
JavaScript | class DeviceError extends _verror.VError {
constructor(...args) {
super(...args);
Error.captureStackTrace(this, this.constructor);
}
} |
JavaScript | class DeviceCredentialsManager {
/**
* @param {object} options The client options.
* @param {string} options.baseUrl The URL of the API.
* @param {object} [options.headers] Headers to be included in all requests.
* @param {object} [options.retry] Retry Policy Config
*/
constructor(options) {
if (options === null || typeof options !== 'object') {
throw new ArgumentError('Must provide manager options');
}
if (options.baseUrl === null || options.baseUrl === undefined) {
throw new ArgumentError('Must provide a base URL for the API');
}
if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) {
throw new ArgumentError('The provided base URL is invalid');
}
/**
* Options object for the RestClient instance.
*
* @type {object}
*/
const clientOptions = {
errorFormatter: { message: 'message', name: 'error' },
headers: options.headers,
query: { repeatParams: false },
};
/**
* Provides an abstraction layer for consuming the
* {@link https://docs.authok.cn/api/v1#!/Device_Credentials
* Authok DeviceCredentialsManagers endpoint}.
*
* @type {external:RestClient}
*/
const authokRestClient = new AuthokRestClient(
`${options.baseUrl}/device-credentials/:id`,
clientOptions,
options.tokenProvider
);
this.resource = new RetryRestClient(authokRestClient, options.retry);
}
/**
* Create an Authok credential.
*
* @example
* management.deviceCredentials.create(data, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Credential created.
* });
* @param {object} data The device credential data object.
* @param {Function} [cb] Callback function.
* @returns {Promise|undefined}
*/
createPublicKey(...args) {
return this.resource.create(...args);
}
/**
* Get all Authok credentials.
*
* @example
* var params = {user_id: "USER_ID"};
*
* management.deviceCredentials.getAll(params, function (err, credentials) {
* console.log(credentials.length);
* });
* @param {object} params Credential parameters.
* @param {Function} [cb] Callback function.
* @returns {Promise|undefined}
*/
getAll(...args) {
return this.resource.getAll(...args);
}
/**
* Delete an Authok device credential.
*
* @example
* var params = { id: CREDENTIAL_ID };
*
* management.deviceCredentials.delete(params, function (err) {
* if (err) {
* // Handle error.
* }
*
* // Credential deleted.
* });
* @param {object} params Credential parameters.
* @param {string} params.id Device credential ID.
* @param {Function} [cb] Callback function.
* @returns {Promise|undefined}
*/
delete(...args) {
return this.resource.delete(...args);
}
} |
JavaScript | class Square {
constructor(row, col) {
this.row = row;
this.col = col;
this.covered = true;
this.mine = false;
this.flag = false;
this.number0ImgDir = "img/number0.svg";
this.number1ImgDir = "img/number1.svg";
this.number2ImgDir = "img/number2.svg";
this.number3ImgDir = "img/number3.svg";
this.number4ImgDir = "img/number4.svg";
this.number5ImgDir = "img/number5.svg";
this.number6ImgDir = "img/number6.svg";
this.number7ImgDir = "img/number7.svg";
this.number8ImgDir = "img/number8.svg";
this.squareImgDir = "img/square.svg";
this.mineImgDir = "img/mine.svg";
this.flagImgDir = "img/flag.svg";
this.wrongFlagImgDir = "img/wrongFlag.svg";
}
static get getSize() {
return 24; // 24 pixels
}
get isCovered() {
return this.covered;
}
get isFlagged() {
return this.flag;
}
get isMine() {
return this.mine;
}
set setCovered(covered) {
this.covered = covered;
}
set setFlagged(flag) {
this.flag = flag;
}
set setMine(mine) {
this.mine = mine;
}
/**
* @param num
* parameter map
* 0 ~ 8: number 0 ~ 8
* 9 : covered square
* 10 : mine
* 11 : flag
* 12 : wrong flag
*/
draw(num) {
let squareElement = document.querySelector("#square" + this.row + "-" + this.col);
switch(num) {
case(0) :
squareElement.src = this.number0ImgDir;
break;
case(1) :
squareElement.src = this.number1ImgDir
break;
case(2) :
squareElement.src = this.number2ImgDir;
break;
case(3) :
squareElement.src = this.number3ImgDir;
break;
case(4) :
squareElement.src = this.number4ImgDir;
break;
case(5) :
squareElement.src = this.number5ImgDir;
break;
case(6) :
squareElement.src = this.number6ImgDir;
break;
case(7) :
squareElement.src = this.number7ImgDir;
break;
case(8) :
squareElement.src = this.number8ImgDir;
break;
case(9) :
squareElement.src = this.squareImgDir;
break;
case(10) :
squareElement.src = this.mineImgDir;
break;
case(11) :
squareElement.src = this.flagImgDir;
break;
case(12) :
squareElement.src = this.wrongFlagImgDir;
break;
}
}
} |
JavaScript | class BgJobEnqueue extends RabbitMqEnqueueBase {
/**
* Get rabbitMq provider.
*
* @returns {string}
*/
getRmqProvider() {
return rabbitMqProvider.getInstance(configStrategyConstants.bgJobRabbitmq, machineKindConstants.appServerKind);
}
get jobProcessorFactory() {
return require(rootPrefix + '/lib/jobs/bg/factory');
}
} |
JavaScript | class ErrorBoundary2 extends React.Component {
componentDidCatch() {
// Don't do anything
}
render() {
return this.props.children;
}
} |
JavaScript | class SDKConst {
static get ERRORS() {
return {
TIMED_OUT: "TIMED_OUT"
};
}
static get UPDATECONFIG() {
return {
UPDATECONFIG: "realTime" // and you can choose realTime but may cause some message lost if your bot is offline
};
}
static get UPDATELIMIT() {
return {
UPDATELIMIT: 10 // if you use polling update you can limit your update that you received
};
}
static get GrayLogConfig() {
return {
GrayLogConfig: {
graylogPort: 12201,
graylogHostname: '192.1.1.1',
connection: 'wan',
maxChunkSizeWan: 1420,
maxChunkSizeLan: 8154
}
};
}
} |
JavaScript | class SettingsActivity {
/** @private */ static _instance;
/**
* Creates and initializes the activity.
* To implement the Singleton pattern, it should never be called directly. Use {@link SettingsActivity.getInstance}
* to get the Singleton instance of the class.
*
* @constructor
*/
constructor() {
// Cache the screen
this._screen = $("#page--settings");
// Name of the currently opened setting
this._openedSetting = null;
// Initialize the settings user interface
this.initSettingsUi();
// Initialize the "account" setting user interface
this.initAccountUi();
}
/**
* Returns the current SettingsActivity instance if any, otherwise creates it.
*
* @returns {SettingsActivity} The activity instance.
*/
static getInstance() {
if (!SettingsActivity._instance)
SettingsActivity._instance = new SettingsActivity();
return SettingsActivity._instance;
}
/** Opens the activity. */
open() {
// Push the activity into the stack
utils.pushStackActivity(this);
// Set the expert checkbox based on the current mode
$("#expert-cbx").prop("checked", App.isExpertMode);
// Show the screen
this._screen.show();
}
/** Closes the activity. */
close() {
// Pop the activity from the stack
utils.popStackActivity();
// Hide the screen
this._screen.scrollTop(0).hide();
// et the currently opened setting to null
this._openedSetting = null;
}
/** Defines the behaviour of the back button for this activity */
onBackPressed() {
// If a setting is open
if (this._openedSetting) {
// Close the setting
this.closeSetting(this._openedSetting);
// Return
return;
}
// Close the activity
this.close();
}
/** Initializes the user interface of the main screen of the activity. */
initSettingsUi() {
// When the user clicks on the "close" button, close the activity
$("#settings-close").click(() => this.close());
// Fired when the user clicks on the account setting
$("#settings-account-wrapper").click(() => {
// If the user is a guest
if (app.isGuest) {
// Alert the user
utils.createAlert(
"",
i18next.t("dialogs.profileGuest"),
i18next.t("dialogs.btnNo"),
null,
i18next.t("dialogs.btnYes"),
() => {
// Log out
this.logout();
// Set is guest flag to false
app.isGuest = false;
}
);
// Return
return;
}
// If there is no connection
if (!navigator.onLine) {
// Alert the user
utils.createAlert("", i18next.t("dialogs.profileOffline"), i18next.t("dialogs.btnOk"));
// Return
return;
}
// Show the page
$("#page--account-settings").show();
// Set the opened setting name
this._openedSetting = "account";
});
// Fired when the user clicks on the expert checkbox
$("#expert-cbx").click(() => {
// Change the mode
localStorage.setItem("mode", (!App.isExpertMode).toString());
});
// Fired when the user clicks on the language setting
$("#settings-language-wrapper").click(() => {
let targetLng;
console.log(`Current language: ${App.appLanguage}`);
if (App.appLanguage === "en") {
targetLng = "it"
} else {
targetLng = "en"
}
i18next.changeLanguage(targetLng, err => {
if (err) {
console.error("Error changing language", err);
utils.logOrToast(i18next.t("messages.changeLngError"), "long");
return;
}
$("body").localize();
localStorage.setItem("lng", targetLng);
utils.logOrToast(i18next.t("messages.lngChanged", {lng: targetLng}), "long");
});
});
// Fired when the user clicks on the help setting
// $("#settings-help-wrapper").click(() => {
//
// utils.logOrToast(i18next.t("settings.notImplemented"), "long");
//
// });
}
/** Initializes the user interface of the screen of the account setting. */
initAccountUi() {
// When the user clicks on the "close" button, close the setting
$("#account-close").click(() => this.closeSetting("account"));
// When the user clicks on the edit profile setting
$("#account-edit-profile").click(() => {
// Open the loader
utils.openLoader();
// Get the user's data
user.get(LoginActivity.getInstance().userId)
.then(data => {
// Set the values of the fields
$("#edit-profile-age").val(data.age);
utils.changeSelectorLabel("edit-profile-age", true);
$("#edit-profile-gender").val(data.gender);
utils.changeSelectorLabel("edit-profile-gender", true);
$("#edit-profile-occupation").val(data.occupation);
utils.changeSelectorLabel("edit-profile-occupation", true);
// Show the page
$("#page--edit-profile").show();
// Close the loader
utils.closeLoader();
});
// Set the opened setting name
this._openedSetting = "editProfile";
});
// When the user clicks on the change mail setting, show the page
// $("#account-change-mail").click(() => {
//
// // Show the screen
// $("#change-email").show();
//
// // Set the opened setting name
// this._openedSetting = "changeEmail";
//
// });
// When the user clicks on the change password setting, show the page
// $("#account-change-pw").click(() => {
//
// // Show the screen
// $("#change-pw").show();
//
// // Set the opened setting name
// this._openedSetting = "changePassword";
//
// });
// Fired when the user clicks on the logout setting
$("#account-logout").click(() => {
// Create a dialog to ask for user confirmation
utils.createAlert(
"",
i18next.t("settings.account.logoutConfirmation"),
i18next.t("dialogs.btnCancel"),
null,
i18next.t("dialogs.btnOk"),
() => {
// Close the screen
$("#page--account-settings").scrollTop(0).hide();
// Logout
this.logout();
}
);
});
// Initialize the change email page
// this.initChangeEmail();
// Initialize the change password page
// this.initChangePw();
// Initialize the change edit profile page
this.initEditProfile();
}
/** Initializes the change email page. */
initChangeEmail() {
// When the user click on the "close" button, close the page
$("#change-email-close").click(() => this.closeSetting("changeEmail"));
// When the user clicks on the "done" button, change the mail
$("#change-email-done").click(() => {
// Open the loader
utils.openLoader();
// Save the email provided by the user
const email = $("#new-email").val();
// If no email has been provided
if (email === "") {
// Close the loader
utils.closeLoader();
// Alert the user
utils.logOrToast(i18next.t("messages.mandatoryEmail"), "long");
// Return
return;
}
// Change the email of the user
user.putEmail(LoginActivity.getInstance().userId, email)
.then(() => {
// Close the loader
utils.closeLoader();
// Close the menu
this.closeSetting("changeEmail");
// Close the account settings page
$("#page--account-settings").scrollTop(0).hide();
// Logout
this.logout();
// Create a confirmation email dialog
utils.createAlert(i18next.t("settings.account.changeEmail.successTitle"),
i18next.t("settings.account.changeEmail.successMessage"), i18next.t("dialogs.btnOk"));
})
});
}
/** Initializes the change password page. */
initChangePw() {
// When the user click on the "close" button, close the page
$("#change-pw-close").click(() => this.closeSetting("changePassword"));
// When the user clicks on the "done" button, change the password
$("#change-pw-done").click(() => {
// Open the loader
utils.openLoader();
// Save the values of the fields
const oldPassword = $("#change-pw-old-password").val(),
newPassword = $("#change-pw-new-password").val(),
confirmPassword = $("#change-pw-confirm-password").val();
// If no old password is provided, return
if (oldPassword === "") {
utils.logOrToast(i18next.t("messages.insertOldPassword"), "long");
utils.closeLoader();
return;
}
// If the password is too weak (less than 8 characters with no number), return
if (newPassword === "" || newPassword.length < 8 || !(/\d/.test(newPassword))) {
utils.logOrToast(i18next.t("messages.weakNewPassword"), "long");
utils.closeLoader();
return;
}
// If the old password is equal to the new password, return
if (oldPassword === newPassword) {
utils.logOrToast(i18next.t("messages.samePassword"), "long");
utils.closeLoader();
return;
}
// If the fields "new password" and "confirm password" do not match, return
if (newPassword !== confirmPassword) {
utils.logOrToast(i18next.t("messages.passwordsNotMatch"), "long");
utils.closeLoader();
return;
}
// Change the password
user.putPassword(LoginActivity.getInstance().userId, oldPassword, newPassword, confirmPassword)
.then(() => {
// Close the loader
utils.closeLoader();
// Close the page
this.closeSetting("changePassword");
// Alert the user
utils.logOrToast(i18next.t("messages.changePwSuccess"), "long");
})
});
}
/** Initializes the edit profile page. */
initEditProfile() {
// When the user clicks on th "close" button, switch to the profile activity
$("#edit-profile-close").click(() => this.closeSetting("editProfile"));
// When the user clicks on the "done" button, edit the profile
$("#edit-profile-done").click(() => {
// Open the loader
utils.openLoader();
// Save the values of the fields
const age = $("#edit-profile-age").val(),
gender = $("#edit-profile-gender").val(),
occupation = $("#edit-profile-occupation").val();
// Send a request to edit the profile
user.putProfile(
LoginActivity.getInstance().userId,
JSON.stringify({ age: age, gender: gender, occupation: occupation })
)
.then(data => {
// Update the displayed data
$("#edit-profile-age").val(data.age);
utils.changeSelectorLabel("edit-profile-age", true);
$("#edit-profile-gender").val(data.gender);
utils.changeSelectorLabel("edit-profile-gender", true);
$("#edit-profile-occupation").val(data.occupation);
utils.changeSelectorLabel("edit-profile-occupation", true);
// Close the loader
utils.closeLoader();
// Close the page
this.closeSetting("editProfile");
// Alert the user
utils.logOrToast(i18next.t("messages.editProfileSuccess"), "long");
});
});
// Change the label of the selectors when their value changes
$("#edit-profile-age").change(() => utils.changeSelectorLabel("edit-profile-age", true));
$("#edit-profile-gender").change(() => utils.changeSelectorLabel("edit-profile-gender", true));
$("#edit-profile-occupation").change(() => utils.changeSelectorLabel("edit-profile-occupation", true));
}
/**
* Closes a setting.
*
* @param {string} name - The name of the setting to close.
*/
closeSetting(name) {
// Switch on the name
switch (name) {
case "account":
// Hide the screen
$("#page--account-settings").scrollTop(0).hide();
// Set the opened setting to null
this._openedSetting = null;
break;
case "editProfile":
// Hide the screen
$("#page--edit-profile").scrollTop(0).hide();
// Reset the fields
$("#edit-profile-age").val("");
utils.changeSelectorLabel("edit-profile-age", true);
$("#edit-profile-gender").val("");
utils.changeSelectorLabel("edit-profile-gender", true);
$("#edit-profile-occupation").val("");
utils.changeSelectorLabel("edit-profile-occupation", true);
// Set the opened setting to "account"
this._openedSetting = "account";
break;
case "changeEmail":
// Hide the screen
$("#change-email").scrollTop(0).hide();
// Reset the field
$("#new-email").val("");
// Set the opened setting to "account"
this._openedSetting = "account";
break;
case "changePassword":
// Hide the screen
$("#change-pw").scrollTop(0).hide();
// Reset the fields
$("#change-pw-old-password").val("");
$("#change-pw-new-password").val("");
$("#change-pw-confirm-password").val("");
// Set the opened setting to "account"
this._openedSetting = "account";
break;
}
}
/** Closes the activities and logs out form the application. */
logout() {
// Close the activity
this.close();
// Close the map activity
MapActivity.getInstance().close();
// Logout
LoginActivity.getInstance().logout();
// Open the login activity
LoginActivity.getInstance().open();
}
} |
JavaScript | class KuvaEmbed extends BaseEmbed {
/**
* @param {Genesis} bot - An instance of Genesis
* @param {Array.<Alert>} kuver - The kuva missions to be included in the embed
* @param {string} platform - platform
* @param {I18n} i18n - string template function for internationalization
*/
constructor(bot, kuver, platform, i18n) {
super();
this.thumbnail = {
url: kuvaThumb,
};
this.color = 0x742725;
this.title = i18n`[${platform.toUpperCase()}] Worldstate - Kuva`;
const grouped = groupBy(kuver, 'enemy');
this.fields = [];
Object.keys(grouped).forEach((enemy) => {
this.fields.push({
name: enemy,
value: grouped[enemy].map(kuva => i18n`${kuva.type} on ${kuva.node}`)
.join('\n'),
inline: false,
});
});
this.footer.text = 'Expires';
this.timestamp = kuver[0].expiry;
}
} |
JavaScript | class TicketFinder extends EntityFinder {
/**
* @param {InternalOpenGateAPI} Reference to the API object.
*/
constructor(ogapi) {
super(ogapi, 'ticket', 'Ticket not found', 'tickets');
}
} |
JavaScript | class LocationManagerModule extends core_1.createModule(exports.config, locationAncestor_1.default) {
/** @override */
async onPreInit() {
registry_1.Registry.addProvider(new core_1.InstanceModuleProvider(locationManager_type_1.LocationManagerType, this, () => 2));
}
/**
* Retrieves the location ancestor to be used
* @returns The obtained location ancestor
*/
async getAncestor() {
if (!this.state.locationAncestor) {
this.changeState({ locationAncestor: this.getChildLocationAncestor() });
}
return this.state.locationAncestor;
}
// Path/locations management
/**
* Retrieves a location path for the given location
* @param location The module location to get the path for
* @returns The retrieve location path
*/
async getLocationPath(location) {
// Check whether the passed location was a location or identifier
if (typeof location == "string") {
const data = this.settings.locations[location];
return data && data.path
? { nodes: [...data.path.nodes], location: data.path.location }
: { nodes: [], location: { ID: location, hints: {} } };
}
else {
const data = this.settings.locations[location.ID];
return data && data.path
? { nodes: [...data.path.nodes], location: data.path.location }
: { nodes: [], location: location };
}
}
/**
* Updates the location path in the settings
* @param locationPath The location path to be stored
*/
updateLocationPath(locationPath) {
const current = this.settings.locations[locationPath.location.ID];
this.changeSettings({
locations: {
[locationPath.location.ID]: {
path: locationPath,
modules: current ? current.modules : [],
},
},
});
}
/** @override */
async updateLocation(location) {
// Block system from saving
const allowSave = core_1.SettingsManager.preventSave();
// Retrieve the location ancestor
const locationAncestor = await this.getAncestor();
// Get the location ID and the location's current path
const currentPath = await this.getLocationPath(location);
// Create the new location path, and update the path
const newPath = await locationAncestor.createLocation(location);
this.updateLocationPath(newPath);
// Only perform the updates if the location actually changed
if (!core_1.ExtendedObject.equals(currentPath.nodes, newPath.nodes)) {
// Remove the location from the ancestor
await locationAncestor.removeLocation(currentPath);
// Reopen the modules from this location
const modules = this.getModulesAtLocation(location.ID);
const promises = modules.map(moduleReference => this.openModule(moduleReference, location.ID));
await Promise.all(promises);
}
// Allow saving again
allowSave();
}
/** @override */
async updateModuleLocation(settingsDataID, newLocationIDs, oldLocationIDs) {
// Block system from saving
const allowSave = core_1.SettingsManager.preventSave();
// Normalize the location ids
if (!newLocationIDs)
newLocationIDs = [];
if (!oldLocationIDs)
oldLocationIDs = [];
// Add the module to the new location
const addPromises = newLocationIDs.map(async (newLocationID) => {
// Only remove locations that got removed
if (oldLocationIDs.includes(newLocationID))
return;
let current = this.settings.locations[newLocationID];
await await this.changeSettings({
locations: {
[newLocationID]: {
path: current && current.path,
modules: [
// Keep everything that is not the new ID to prevent duplicates
...((current && current.modules) || []).filter(ms => !settingsDataID.equals(ms)),
// Add the new ID
settingsDataID,
],
},
},
});
});
await Promise.all(addPromises);
// Remove the module from the old location
const removePromises = oldLocationIDs.map(async (oldLocationID) => {
// Only remove locations that got removed
if (newLocationIDs.includes(oldLocationID))
return;
let current = this.settings.locations[oldLocationID];
if (current) {
await this.changeSettings({
locations: {
[oldLocationID]: {
path: current.path,
modules: current.modules.filter(ms => !settingsDataID.equals(ms)),
},
},
});
// Check if there are still modules at this location, if not, remove it
current = this.settings.locations[oldLocationID];
if (current.modules.length == 0) {
// Retrieve the location path and obtain the window
const path = await this.getLocationPath(oldLocationID);
// Remove the location from the settings
await await this.changeSettings({
locations: {
[oldLocationID]: undefined,
},
});
// Retrieve the location ancestor
const locationAncestor = await this.getAncestor();
// Remove the location
await locationAncestor.removeLocation(path);
}
}
});
await Promise.all(removePromises);
// Allow saving again
allowSave();
}
// Location editing
/**
* General approach:
* - User enables edit mode
* - User selects some locationAncestor to move by dragging (which calls setLocationsMoveData)
* - User selects a target by dropping (which calls getLocationsMoveData and updateLocationsMoveData)
* - updateMovedLocations to finalize the movement of data
*/
/** @override */
async setEditMode(edit) {
if (this.state.inEditMode == edit)
return false;
// Update the state
await super.setEditMode(edit);
// Inform ancestor
const locationAncestor = await this.getAncestor();
await locationAncestor.setEditMode(edit);
// Return that the change was successful
return true;
}
/** @override */
async setLocationsMoveData(data) {
// Make sure there is no current data, if replacing it with data
if (this.state.locationMoveData && data)
return false;
// Update own state
this.changeState({ locationMoveData: data });
// Update whether we are able to drop elements now
const locationAncestor = await this.getAncestor();
await locationAncestor.setDropMode(data != null);
// Return that the movement data was successfully set
return true;
}
/** @override */
async updateLocationsMoveData(data) {
// Make sure there is current data
if (!this.state.locationMoveData)
return false;
// Update state
this.changeState({ locationMoveData: data });
// Return that the movement data was successfully updated
return true;
}
/** @override */
async getLocationsMoveData() {
return this.state.locationMoveData;
}
/** @override */
async getLocationsAtPath(partialPath) {
return Object.values(this.settings.locations)
.filter(location =>
// Make sure all the parts of the path correspond
partialPath.reduce((res, ancestorID, index) => location.path && location.path.nodes[index] == ancestorID && res, true))
.map(location => location.path.location);
}
/** @override */
async updateMovedLocations(delay = 100) {
// Uses own locations move cata to create these new locations
const moveData = this.state.locationMoveData;
if (!moveData)
return;
// Give some time for ancestors to register their moved locations updates
await new Promise(r => setTimeout(r, delay));
// Create the locations
const promises = moveData.locations.map(location => this.updateLocation(location));
await Promise.all(promises);
// Remove the move data
await this.setLocationsMoveData(undefined);
}
// Opening/closing modules
/** @override */
async openModule(module, location) {
// Block system from saving
const allowSave = core_1.SettingsManager.preventSave();
// Retrieve the location path
const path = await this.getLocationPath(location);
// Obtain the ancestor
const locationAncestor = await this.getAncestor();
// Store the module at this path
this.changeState({
locations: {
[location]: {
modules: [
...(this.state.locations[location] || { modules: [] }).modules.filter(m => !m.equals(module)),
module,
],
},
},
});
// Open the path in the location ancestor
const obtainedPath = await locationAncestor.openModule(module, path);
// Update location path
this.updateLocationPath(obtainedPath);
// Allow saving again
allowSave();
}
/** @override */
async closeModule(module, location) {
// Retrieve the location path
const path = await this.getLocationPath(location);
// Obtain the ancestor
const locationAncestor = await this.getAncestor();
// Remove the module at this path
this.changeState({
locations: {
[location]: {
modules: (this.state.locations[location] || { modules: [] }).modules.filter(m => !m.equals(module)),
},
},
});
// Open the path in the location ancestor
await locationAncestor.closeModule(module, path);
}
/** @override */
async showModule(module, location) {
// Retrieve the location path
const path = await this.getLocationPath(location);
// Obtain the ancestor
const locationAncestor = await this.getAncestor();
// Attempt to show the module
return locationAncestor.showModule(module, path);
}
/** @override */
async isModuleOpened(module, locationID) {
return (this.state.locations[locationID].modules.find(m => m.equals(module)) != null);
}
/**
* Retrieves the modules that are opened at a given location
* @param location The ID of the location to get the opened modules of
* @returns The modules that are opened at this location in this settions
*/
getModulesAtLocation(location) {
const locData = this.state.locations[location];
return (locData && locData.modules) || [];
}
/** @override */
async getModulesAtPath(partialPath) {
// Define the modules to retrieve
const modules = [];
// Get all locations, and retriev its modules
(await this.getLocationsAtPath(partialPath)).forEach(location => {
modules.push(...this.getModulesAtLocation(location.ID));
});
// Return all modules
return modules;
}
} |
JavaScript | class CenterController {
/**
* provides validation for incoming request body for creating/editing centers
* @returns { array } an array of functions to parse request
*/
static centerValidations() {
return [
body('name')
.exists()
.trim()
.isLength({ min: 1, max: 50 })
.withMessage('name must be 1 - 50 characters'),
body('description')
.exists()
.trim()
.isLength({ min: 1, max: 1200 })
.withMessage('description must be 1 - 1200 characters'),
body('facilities')
.exists()
.trim()
.isLength({ min: 1, max: 300 })
.withMessage('facilities must be 1 - 300 characters'),
body('address')
.exists()
.trim()
.isLength({ min: 1, max: 50 })
.withMessage('address must be 1 - 50 characters'),
body('images')
.exists()
.trim()
.isLength({ min: 1, max: 500 })
.withMessage('image(s) invalid'),
sanitize('cost').toInt(),
body('cost').custom(value => Helpers.sanitizeInteger(value, 'cost')),
sanitize('capacity').toInt(),
body('capacity').custom(value =>
Helpers.sanitizeInteger(value, 'capacity')),
];
}
/**
* checks if there are any failed validations
* @param {object} req
* @param {object} parseOrStringify
* @returns {object | function} next()
*/
static jsonHandle = (req, parseOrStringify = true) => {
if (parseOrStringify) {
if (req.images) req.images = JSON.parse(req.images);
if (req.facilities) req.facilities = JSON.parse(req.facilities);
} else {
if (req.images) req.images = JSON.stringify(req.images);
if (req.facilities) req.facilities = JSON.stringify(req.facilities);
}
};
/**
* splits center facilities into an array
* @param {object} req
* @param {object} res
* @param {function} next
* @returns {function} next()
*/
static splitFacilitiesAndImages(req, res, next) {
const facilities = [];
const images = [];
req.body.facilities
.split('###:###:###')
.map(facility => facilities.push(facility.trim()));
req.body.images.split('###:###:###').map((image, index) => {
if (index <= 3) images.push(image.trim());
return null;
});
req.body.facilities = facilities;
req.body.images = images;
return next();
}
/**
* creates new ecenter
* @param {object} req
* @param {object} res
* @returns { object } center or error
*/
static addCenter(req, res) {
req.body.createdBy = req.body.updatedBy;
CenterController.jsonHandle(req.body, false);
db.center
.findOne({
where: {
[Op.and]: {
name: {
[Op.iRegexp]: `^${req.body.name}$`,
},
address: {
[Op.iRegexp]: `^${req.body.address}$`,
},
},
},
})
.then((existingCenter) => {
if (existingCenter) {
return res
.status(409)
.json(Helpers
.getResponse('center name already exists in center address'));
}
return db.center
.create(req.body)
.then((center) => {
CenterController.jsonHandle(center);
res.status(201).json(Helpers.getResponse(center, 'center', true));
})
.catch(() => {
res.status(500).json(Helpers.getResponse('Internal server error'));
});
})
.catch(() =>
res.status(500).json(Helpers.getResponse('Internal server error')));
}
/**
* modifies existing center
* @param {object} req
* @param {object} res
* @returns { object } center or error
*/
static modifyCenter(req, res) {
db.center
.findOne({
where: {
[Op.and]: {
name: req.body.name,
address: {
[Op.iRegexp]: `^${req.body.address}$`,
},
},
id: {
[Op.ne]: req.params.id,
},
},
})
.then((centerCheck) => {
if (!centerCheck) {
CenterController.jsonHandle(req.body, false);
return db.center
.update(req.body, {
where: {
id: req.params.id,
},
})
.then((rows) => {
if (rows[0] === 0) {
return res
.status(404)
.json(Helpers.getResponse('center not found'));
}
return db.center
.findOne({
where: {
id: req.params.id,
},
})
.then((updatedCenter) => {
CenterController.jsonHandle(updatedCenter);
return res.json(Helpers
.getResponse(updatedCenter, 'center', true));
});
})
.catch(() =>
res
.status(500)
.json(Helpers.getResponse('Internal server error')));
}
return res
.status(409)
.json(Helpers
.getResponse('center name already exists in center address'));
})
.catch(() =>
res.status(500).json(Helpers.getResponse('Internal server error')));
}
/**
* fetches existing centers
* @param {object} req
* @param {object} res
* @returns { object } object containing centers or fetch error message
*/
static fetchAllCenters(req, res) {
const filter = req.query.filter || '';
const facility = req.query.facility || '';
const { pagination } = req.query;
const offset = parseInt(req.query.offset, 10) || 0;
const limit = parseInt(req.query.limit, 10);
const capacity = parseInt(req.query.capacity, 10) || 1;
const where = {
capacity: {
[Op.gte]: capacity,
},
facilities: {
[Op.iRegexp]: `^.*${facility}.*$`,
},
[Op.or]: {
name: {
[Op.iRegexp]: `^.*${filter}.*$`,
},
address: {
[Op.iRegexp]: `^.*${filter}.*$`,
},
},
};
const parameters = {};
parameters.order = [['id', 'DESC']];
parameters.where = where;
parameters.offset = offset;
if (!Number.isNaN(limit)) parameters.limit = limit;
db.center.findAndCountAll(parameters).then((result) => {
const { count, rows } = result;
rows.map(center => CenterController.jsonHandle(center));
const response = Helpers.getResponse(rows, 'centers', true);
if (pagination === 'true') {
const metaData = {
pagination: Helpers.paginationMetadata(
offset,
limit,
count,
rows.length,
),
};
response.metaData = metaData;
}
return res.json(response);
});
}
/**
* fetches existing center
* @param {object} req
* @param {object} res
* @returns { object } fetched center or fetch error message
*/
static fetchCenter(req, res) {
db.center
.findOne({
where: {
id: req.params.id,
},
})
.then((center) => {
if (!center) {
return res.status(404).json(Helpers.getResponse('center not found'));
}
CenterController.jsonHandle(center);
return res.json(Helpers.getResponse(center, 'center', true));
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.