language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class BigtableTableAdminClient {
/**
* Construct an instance of BigtableTableAdminClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.servicePath] - The domain name of the
* API remote host.
*/
constructor(opts) {
this._descriptors = {};
// Ensure that options include the service address and port.
opts = Object.assign(
{
clientConfig: {},
port: this.constructor.port,
servicePath: this.constructor.servicePath,
},
opts
);
// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = this.constructor.scopes;
const gaxGrpc = new gax.GrpcClient(opts);
// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth;
// Determine the client header string.
const clientHeader = [
`gl-node/${process.version.node}`,
`grpc/${gaxGrpc.grpcVersion}`,
`gax/${gax.version}`,
`gapic/${VERSION}`,
];
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
const protos = merge(
{},
gaxGrpc.loadProto(
path.join(__dirname, '..', '..', 'protos'),
'google/bigtable/admin/v2/bigtable_table_admin.proto'
)
);
// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this._pathTemplates = {
instancePathTemplate: new gax.PathTemplate(
'projects/{project}/instances/{instance}'
),
clusterPathTemplate: new gax.PathTemplate(
'projects/{project}/instances/{instance}/clusters/{cluster}'
),
snapshotPathTemplate: new gax.PathTemplate(
'projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}'
),
tablePathTemplate: new gax.PathTemplate(
'projects/{project}/instances/{instance}/tables/{table}'
),
};
// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listTables: new gax.PageDescriptor(
'pageToken',
'nextPageToken',
'tables'
),
listSnapshots: new gax.PageDescriptor(
'pageToken',
'nextPageToken',
'snapshots'
),
};
let protoFilesRoot = new gax.GoogleProtoFilesRoot();
protoFilesRoot = protobuf.loadSync(
path.join(
__dirname,
'..',
'..',
'protos',
'google/bigtable/admin/v2/bigtable_table_admin.proto'
),
protoFilesRoot
);
// This API contains "long-running operations", which return a
// an Operation object that allows for tracking of the operation,
// rather than holding a request open.
this.operationsClient = new gax.lro({
auth: gaxGrpc.auth,
grpc: gaxGrpc.grpc,
}).operationsClient(opts);
const createTableFromSnapshotResponse = protoFilesRoot.lookup(
'google.bigtable.admin.v2.Table'
);
const createTableFromSnapshotMetadata = protoFilesRoot.lookup(
'google.bigtable.admin.v2.CreateTableFromSnapshotMetadata'
);
const snapshotTableResponse = protoFilesRoot.lookup(
'google.bigtable.admin.v2.Snapshot'
);
const snapshotTableMetadata = protoFilesRoot.lookup(
'google.bigtable.admin.v2.SnapshotTableMetadata'
);
this._descriptors.longrunning = {
createTableFromSnapshot: new gax.LongrunningDescriptor(
this.operationsClient,
createTableFromSnapshotResponse.decode.bind(
createTableFromSnapshotResponse
),
createTableFromSnapshotMetadata.decode.bind(
createTableFromSnapshotMetadata
)
),
snapshotTable: new gax.LongrunningDescriptor(
this.operationsClient,
snapshotTableResponse.decode.bind(snapshotTableResponse),
snapshotTableMetadata.decode.bind(snapshotTableMetadata)
),
};
// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
'google.bigtable.admin.v2.BigtableTableAdmin',
gapicConfig,
opts.clientConfig,
{'x-goog-api-client': clientHeader.join(' ')}
);
// Set up a dictionary of "inner API calls"; the core implementation
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this._innerApiCalls = {};
// Put together the "service stub" for
// google.bigtable.admin.v2.BigtableTableAdmin.
const bigtableTableAdminStub = gaxGrpc.createStub(
protos.google.bigtable.admin.v2.BigtableTableAdmin,
opts
);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const bigtableTableAdminStubMethods = [
'createTable',
'createTableFromSnapshot',
'listTables',
'getTable',
'deleteTable',
'modifyColumnFamilies',
'dropRowRange',
'generateConsistencyToken',
'checkConsistency',
'snapshotTable',
'getSnapshot',
'listSnapshots',
'deleteSnapshot',
];
for (const methodName of bigtableTableAdminStubMethods) {
this._innerApiCalls[methodName] = gax.createApiCall(
bigtableTableAdminStub.then(
stub =>
function() {
const args = Array.prototype.slice.call(arguments, 0);
return stub[methodName].apply(stub, args);
}
),
defaults[methodName],
this._descriptors.page[methodName] ||
this._descriptors.longrunning[methodName]
);
}
}
/**
* The DNS address for this API service.
*/
static get servicePath() {
return 'bigtableadmin.googleapis.com';
}
/**
* The port for this API service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static get scopes() {
return [
'https://www.googleapis.com/auth/bigtable.admin',
'https://www.googleapis.com/auth/bigtable.admin.cluster',
'https://www.googleapis.com/auth/bigtable.admin.instance',
'https://www.googleapis.com/auth/bigtable.admin.table',
'https://www.googleapis.com/auth/cloud-bigtable.admin',
'https://www.googleapis.com/auth/cloud-bigtable.admin.cluster',
'https://www.googleapis.com/auth/cloud-bigtable.admin.table',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-platform.read-only',
];
}
/**
* Return the project ID used by this class.
* @param {function(Error, string)} callback - the callback to
* be called with the current project Id.
*/
getProjectId(callback) {
return this.auth.getProjectId(callback);
}
// -------------------
// -- Service calls --
// -------------------
/**
* Creates a new table in the specified instance.
* The table can be created with a full set of initial column families,
* specified in the request.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the instance in which to create the table.
* Values are of the form `projects/<project>/instances/<instance>`.
* @param {string} request.tableId
* The name by which the new table should be referred to within the parent
* instance, e.g., `foobar` rather than `<parent>/tables/foobar`.
* @param {Object} request.table
* The Table to create.
*
* This object should have the same structure as [Table]{@link google.bigtable.admin.v2.Table}
* @param {Object[]} [request.initialSplits]
* The optional list of row keys that will be used to initially split the
* table into several tablets (tablets are similar to HBase regions).
* Given two split keys, `s1` and `s2`, three tablets will be created,
* spanning the key ranges: `[, s1), [s1, s2), [s2, )`.
*
* Example:
*
* * Row keys := `["a", "apple", "custom", "customer_1", "customer_2",`
* `"other", "zz"]`
* * initial_split_keys := `["apple", "customer_1", "customer_2", "other"]`
* * Key assignment:
* - Tablet 1 `[, apple) => {"a"}.`
* - Tablet 2 `[apple, customer_1) => {"apple", "custom"}.`
* - Tablet 3 `[customer_1, customer_2) => {"customer_1"}.`
* - Tablet 4 `[customer_2, other) => {"customer_2"}.`
* - Tablet 5 `[other, ) => {"other", "zz"}.`
*
* This object should have the same structure as [Split]{@link google.bigtable.admin.v2.Split}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
* var tableId = '';
* var table = {};
* var request = {
* parent: formattedParent,
* tableId: tableId,
* table: table,
* };
* client.createTable(request)
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
createTable(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
parent: request.parent,
});
return this._innerApiCalls.createTable(request, options, callback);
}
/**
* This is a private alpha release of Cloud Bigtable snapshots. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Creates a new table from the specified snapshot. The target table must
* not exist. The snapshot and the table must be in the same instance.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the instance in which to create the table.
* Values are of the form `projects/<project>/instances/<instance>`.
* @param {string} request.tableId
* The name by which the new table should be referred to within the parent
* instance, e.g., `foobar` rather than `<parent>/tables/foobar`.
* @param {string} request.sourceSnapshot
* The unique name of the snapshot from which to restore the table. The
* snapshot and the table must be in the same instance.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
* var tableId = '';
* var sourceSnapshot = '';
* var request = {
* parent: formattedParent,
* tableId: tableId,
* sourceSnapshot: sourceSnapshot,
* };
*
* // Handle the operation using the promise pattern.
* client.createTableFromSnapshot(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
* var tableId = '';
* var sourceSnapshot = '';
* var request = {
* parent: formattedParent,
* tableId: tableId,
* sourceSnapshot: sourceSnapshot,
* };
*
* // Handle the operation using the event emitter pattern.
* client.createTableFromSnapshot(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
createTableFromSnapshot(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
parent: request.parent,
});
return this._innerApiCalls.createTableFromSnapshot(
request,
options,
callback
);
}
/**
* Lists all tables served from a specified instance.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the instance for which tables should be listed.
* Values are of the form `projects/<project>/instances/<instance>`.
* @param {number} [request.view]
* The view to be applied to the returned tables' fields.
* Defaults to `NAME_ONLY` if unspecified; no others are currently supported.
*
* The number should be among the values of [View]{@link google.bigtable.admin.v2.View}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Array, ?Object, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of [Table]{@link google.bigtable.admin.v2.Table}.
*
* When autoPaginate: false is specified through options, it contains the result
* in a single response. If the response indicates the next page exists, the third
* parameter is set to be used for the next request object. The fourth parameter keeps
* the raw response object of an object representing [ListTablesResponse]{@link google.bigtable.admin.v2.ListTablesResponse}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Table]{@link google.bigtable.admin.v2.Table}.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Table]{@link google.bigtable.admin.v2.Table} in a single response.
* The second element is the next request object if the response
* indicates the next page exists, or null. The third element is
* an object representing [ListTablesResponse]{@link google.bigtable.admin.v2.ListTablesResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* // Iterate over all elements.
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
*
* client.listTables({parent: formattedParent})
* .then(responses => {
* var resources = responses[0];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i])
* }
* })
* .catch(err => {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
*
*
* var options = {autoPaginate: false};
* var callback = responses => {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows that there are more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listTables(nextRequest, options).then(callback);
* }
* }
* client.listTables({parent: formattedParent}, options)
* .then(callback)
* .catch(err => {
* console.error(err);
* });
*/
listTables(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
parent: request.parent,
});
return this._innerApiCalls.listTables(request, options, callback);
}
/**
* Equivalent to {@link listTables}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listTables} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the instance for which tables should be listed.
* Values are of the form `projects/<project>/instances/<instance>`.
* @param {number} [request.view]
* The view to be applied to the returned tables' fields.
* Defaults to `NAME_ONLY` if unspecified; no others are currently supported.
*
* The number should be among the values of [View]{@link google.bigtable.admin.v2.View}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @returns {Stream}
* An object stream which emits an object representing [Table]{@link google.bigtable.admin.v2.Table} on 'data' event.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
* client.listTablesStream({parent: formattedParent})
* .on('data', element => {
* // doThingsWith(element)
* }).on('error', err => {
* console.log(err);
* });
*/
listTablesStream(request, options) {
options = options || {};
return this._descriptors.page.listTables.createStream(
this._innerApiCalls.listTables,
request,
options
);
}
/**
* Gets metadata information about the specified table.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the requested table.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {number} [request.view]
* The view to be applied to the returned table's fields.
* Defaults to `SCHEMA_VIEW` if unspecified.
*
* The number should be among the values of [View]{@link google.bigtable.admin.v2.View}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* client.getTable({name: formattedName})
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
getTable(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.getTable(request, options, callback);
}
/**
* Permanently deletes a specified table and all of its data.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the table to be deleted.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)} [callback]
* The function which will be called with the result of the API call.
* @returns {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* client.deleteTable({name: formattedName}).catch(err => {
* console.error(err);
* });
*/
deleteTable(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.deleteTable(request, options, callback);
}
/**
* Performs a series of column family modifications on the specified table.
* Either all or none of the modifications will occur before this method
* returns, but data requests received prior to that point may see a table
* where only some modifications have taken effect.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the table whose families should be modified.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {Object[]} request.modifications
* Modifications to be atomically applied to the specified table's families.
* Entries are applied in order, meaning that earlier modifications can be
* masked by later ones (in the case of repeated updates to the same family,
* for example).
*
* This object should have the same structure as [Modification]{@link google.bigtable.admin.v2.Modification}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Table]{@link google.bigtable.admin.v2.Table}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* var modifications = [];
* var request = {
* name: formattedName,
* modifications: modifications,
* };
* client.modifyColumnFamilies(request)
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
modifyColumnFamilies(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.modifyColumnFamilies(request, options, callback);
}
/**
* Permanently drop/delete a row range from a specified table. The request can
* specify whether to delete all rows in a table, or only those that match a
* particular prefix.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the table on which to drop a range of rows.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {string} [request.rowKeyPrefix]
* Delete all rows that start with this row key prefix. Prefix cannot be
* zero length.
* @param {boolean} [request.deleteAllDataFromTable]
* Delete all rows in the table. Setting this to false is a no-op.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)} [callback]
* The function which will be called with the result of the API call.
* @returns {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* client.dropRowRange({name: formattedName}).catch(err => {
* console.error(err);
* });
*/
dropRowRange(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.dropRowRange(request, options, callback);
}
/**
* This is a private alpha release of Cloud Bigtable replication. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Generates a consistency token for a Table, which can be used in
* CheckConsistency to check whether mutations to the table that finished
* before this call started have been replicated. The tokens will be available
* for 90 days.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the Table for which to create a consistency token.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [GenerateConsistencyTokenResponse]{@link google.bigtable.admin.v2.GenerateConsistencyTokenResponse}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [GenerateConsistencyTokenResponse]{@link google.bigtable.admin.v2.GenerateConsistencyTokenResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* client.generateConsistencyToken({name: formattedName})
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
generateConsistencyToken(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.generateConsistencyToken(
request,
options,
callback
);
}
/**
* This is a private alpha release of Cloud Bigtable replication. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Checks replication consistency based on a consistency token, that is, if
* replication has caught up based on the conditions specified in the token
* and the check request.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the Table for which to check replication consistency.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {string} request.consistencyToken
* The token created using GenerateConsistencyToken for the Table.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [CheckConsistencyResponse]{@link google.bigtable.admin.v2.CheckConsistencyResponse}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [CheckConsistencyResponse]{@link google.bigtable.admin.v2.CheckConsistencyResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* var consistencyToken = '';
* var request = {
* name: formattedName,
* consistencyToken: consistencyToken,
* };
* client.checkConsistency(request)
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
checkConsistency(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.checkConsistency(request, options, callback);
}
/**
* This is a private alpha release of Cloud Bigtable snapshots. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Creates a new snapshot in the specified cluster from the specified
* source table. The cluster and the table must be in the same instance.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the table to have the snapshot taken.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* @param {string} request.cluster
* The name of the cluster where the snapshot will be created in.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>`.
* @param {string} request.snapshotId
* The ID by which the new snapshot should be referred to within the parent
* cluster, e.g., `mysnapshot` of the form: `[_a-zA-Z0-9][-_.a-zA-Z0-9]*`
* rather than
* `projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/mysnapshot`.
* @param {string} request.description
* Description of the snapshot.
* @param {Object} [request.ttl]
* The amount of time that the new snapshot can stay active after it is
* created. Once 'ttl' expires, the snapshot will get deleted. The maximum
* amount of time a snapshot can stay active is 7 days. If 'ttl' is not
* specified, the default value of 24 hours will be used.
*
* This object should have the same structure as [Duration]{@link google.protobuf.Duration}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* var cluster = '';
* var snapshotId = '';
* var description = '';
* var request = {
* name: formattedName,
* cluster: cluster,
* snapshotId: snapshotId,
* description: description,
* };
*
* // Handle the operation using the promise pattern.
* client.snapshotTable(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedName = client.tablePath('[PROJECT]', '[INSTANCE]', '[TABLE]');
* var cluster = '';
* var snapshotId = '';
* var description = '';
* var request = {
* name: formattedName,
* cluster: cluster,
* snapshotId: snapshotId,
* description: description,
* };
*
* // Handle the operation using the event emitter pattern.
* client.snapshotTable(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
snapshotTable(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.snapshotTable(request, options, callback);
}
/**
* This is a private alpha release of Cloud Bigtable snapshots. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Gets metadata information about the specified snapshot.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the requested snapshot.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [Snapshot]{@link google.bigtable.admin.v2.Snapshot}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Snapshot]{@link google.bigtable.admin.v2.Snapshot}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.snapshotPath('[PROJECT]', '[INSTANCE]', '[CLUSTER]', '[SNAPSHOT]');
* client.getSnapshot({name: formattedName})
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
getSnapshot(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.getSnapshot(request, options, callback);
}
/**
* This is a private alpha release of Cloud Bigtable snapshots. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Lists all snapshots associated with the specified cluster.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the cluster for which snapshots should be listed.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>`.
* Use `<cluster> = '-'` to list snapshots for all clusters in an instance,
* e.g., `projects/<project>/instances/<instance>/clusters/-`.
* @param {number} [request.pageSize]
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Array, ?Object, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of [Snapshot]{@link google.bigtable.admin.v2.Snapshot}.
*
* When autoPaginate: false is specified through options, it contains the result
* in a single response. If the response indicates the next page exists, the third
* parameter is set to be used for the next request object. The fourth parameter keeps
* the raw response object of an object representing [ListSnapshotsResponse]{@link google.bigtable.admin.v2.ListSnapshotsResponse}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Snapshot]{@link google.bigtable.admin.v2.Snapshot}.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Snapshot]{@link google.bigtable.admin.v2.Snapshot} in a single response.
* The second element is the next request object if the response
* indicates the next page exists, or null. The third element is
* an object representing [ListSnapshotsResponse]{@link google.bigtable.admin.v2.ListSnapshotsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* // Iterate over all elements.
* var formattedParent = client.clusterPath('[PROJECT]', '[INSTANCE]', '[CLUSTER]');
*
* client.listSnapshots({parent: formattedParent})
* .then(responses => {
* var resources = responses[0];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i])
* }
* })
* .catch(err => {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var formattedParent = client.clusterPath('[PROJECT]', '[INSTANCE]', '[CLUSTER]');
*
*
* var options = {autoPaginate: false};
* var callback = responses => {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows that there are more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listSnapshots(nextRequest, options).then(callback);
* }
* }
* client.listSnapshots({parent: formattedParent}, options)
* .then(callback)
* .catch(err => {
* console.error(err);
* });
*/
listSnapshots(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
parent: request.parent,
});
return this._innerApiCalls.listSnapshots(request, options, callback);
}
/**
* Equivalent to {@link listSnapshots}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listSnapshots} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* The unique name of the cluster for which snapshots should be listed.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>`.
* Use `<cluster> = '-'` to list snapshots for all clusters in an instance,
* e.g., `projects/<project>/instances/<instance>/clusters/-`.
* @param {number} [request.pageSize]
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @returns {Stream}
* An object stream which emits an object representing [Snapshot]{@link google.bigtable.admin.v2.Snapshot} on 'data' event.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.clusterPath('[PROJECT]', '[INSTANCE]', '[CLUSTER]');
* client.listSnapshotsStream({parent: formattedParent})
* .on('data', element => {
* // doThingsWith(element)
* }).on('error', err => {
* console.log(err);
* });
*/
listSnapshotsStream(request, options) {
options = options || {};
return this._descriptors.page.listSnapshots.createStream(
this._innerApiCalls.listSnapshots,
request,
options
);
}
/**
* This is a private alpha release of Cloud Bigtable snapshots. This feature
* is not currently available to most Cloud Bigtable customers. This feature
* might be changed in backward-incompatible ways and is not recommended for
* production use. It is not subject to any SLA or deprecation policy.
*
* Permanently deletes the specified snapshot.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The unique name of the snapshot to be deleted.
* Values are of the form
* `projects/<project>/instances/<instance>/clusters/<cluster>/snapshots/<snapshot>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)} [callback]
* The function which will be called with the result of the API call.
* @returns {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const admin = require('admin.v2');
*
* var client = new admin.v2.BigtableTableAdminClient({
* // optional auth parameters.
* });
*
* var formattedName = client.snapshotPath('[PROJECT]', '[INSTANCE]', '[CLUSTER]', '[SNAPSHOT]');
* client.deleteSnapshot({name: formattedName}).catch(err => {
* console.error(err);
* });
*/
deleteSnapshot(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers[
'x-goog-request-params'
] = gax.routingHeader.fromParams({
name: request.name,
});
return this._innerApiCalls.deleteSnapshot(request, options, callback);
}
// --------------------
// -- Path templates --
// --------------------
/**
* Return a fully-qualified instance resource name string.
*
* @param {String} project
* @param {String} instance
* @returns {String}
*/
instancePath(project, instance) {
return this._pathTemplates.instancePathTemplate.render({
project: project,
instance: instance,
});
}
/**
* Return a fully-qualified cluster resource name string.
*
* @param {String} project
* @param {String} instance
* @param {String} cluster
* @returns {String}
*/
clusterPath(project, instance, cluster) {
return this._pathTemplates.clusterPathTemplate.render({
project: project,
instance: instance,
cluster: cluster,
});
}
/**
* Return a fully-qualified snapshot resource name string.
*
* @param {String} project
* @param {String} instance
* @param {String} cluster
* @param {String} snapshot
* @returns {String}
*/
snapshotPath(project, instance, cluster, snapshot) {
return this._pathTemplates.snapshotPathTemplate.render({
project: project,
instance: instance,
cluster: cluster,
snapshot: snapshot,
});
}
/**
* Return a fully-qualified table resource name string.
*
* @param {String} project
* @param {String} instance
* @param {String} table
* @returns {String}
*/
tablePath(project, instance, table) {
return this._pathTemplates.tablePathTemplate.render({
project: project,
instance: instance,
table: table,
});
}
/**
* Parse the instanceName from a instance resource.
*
* @param {String} instanceName
* A fully-qualified path representing a instance resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromInstanceName(instanceName) {
return this._pathTemplates.instancePathTemplate.match(instanceName).project;
}
/**
* Parse the instanceName from a instance resource.
*
* @param {String} instanceName
* A fully-qualified path representing a instance resources.
* @returns {String} - A string representing the instance.
*/
matchInstanceFromInstanceName(instanceName) {
return this._pathTemplates.instancePathTemplate.match(instanceName)
.instance;
}
/**
* Parse the clusterName from a cluster resource.
*
* @param {String} clusterName
* A fully-qualified path representing a cluster resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromClusterName(clusterName) {
return this._pathTemplates.clusterPathTemplate.match(clusterName).project;
}
/**
* Parse the clusterName from a cluster resource.
*
* @param {String} clusterName
* A fully-qualified path representing a cluster resources.
* @returns {String} - A string representing the instance.
*/
matchInstanceFromClusterName(clusterName) {
return this._pathTemplates.clusterPathTemplate.match(clusterName).instance;
}
/**
* Parse the clusterName from a cluster resource.
*
* @param {String} clusterName
* A fully-qualified path representing a cluster resources.
* @returns {String} - A string representing the cluster.
*/
matchClusterFromClusterName(clusterName) {
return this._pathTemplates.clusterPathTemplate.match(clusterName).cluster;
}
/**
* Parse the snapshotName from a snapshot resource.
*
* @param {String} snapshotName
* A fully-qualified path representing a snapshot resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromSnapshotName(snapshotName) {
return this._pathTemplates.snapshotPathTemplate.match(snapshotName).project;
}
/**
* Parse the snapshotName from a snapshot resource.
*
* @param {String} snapshotName
* A fully-qualified path representing a snapshot resources.
* @returns {String} - A string representing the instance.
*/
matchInstanceFromSnapshotName(snapshotName) {
return this._pathTemplates.snapshotPathTemplate.match(snapshotName)
.instance;
}
/**
* Parse the snapshotName from a snapshot resource.
*
* @param {String} snapshotName
* A fully-qualified path representing a snapshot resources.
* @returns {String} - A string representing the cluster.
*/
matchClusterFromSnapshotName(snapshotName) {
return this._pathTemplates.snapshotPathTemplate.match(snapshotName).cluster;
}
/**
* Parse the snapshotName from a snapshot resource.
*
* @param {String} snapshotName
* A fully-qualified path representing a snapshot resources.
* @returns {String} - A string representing the snapshot.
*/
matchSnapshotFromSnapshotName(snapshotName) {
return this._pathTemplates.snapshotPathTemplate.match(snapshotName)
.snapshot;
}
/**
* Parse the tableName from a table resource.
*
* @param {String} tableName
* A fully-qualified path representing a table resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromTableName(tableName) {
return this._pathTemplates.tablePathTemplate.match(tableName).project;
}
/**
* Parse the tableName from a table resource.
*
* @param {String} tableName
* A fully-qualified path representing a table resources.
* @returns {String} - A string representing the instance.
*/
matchInstanceFromTableName(tableName) {
return this._pathTemplates.tablePathTemplate.match(tableName).instance;
}
/**
* Parse the tableName from a table resource.
*
* @param {String} tableName
* A fully-qualified path representing a table resources.
* @returns {String} - A string representing the table.
*/
matchTableFromTableName(tableName) {
return this._pathTemplates.tablePathTemplate.match(tableName).table;
}
} |
JavaScript | class Market extends Component {
// React Method (Life cycle hook)
componentDidMount() {
this.refresher();
googleanalytics.SendScreen('Market');
window.addEventListener('contextmenu', this.setupcontextmenu, false);
}
// React Method (Life cycle hook)
componentWillUnmount() {
window.removeEventListener('contextmenu', this.setupcontextmenu);
}
// Class Methods
/**
* Sets up the page's context menu
*
* @param {*} e
* @memberof Market
*/
setupcontextmenu(e) {
e.preventDefault();
const contextmenu = new ContextMenuBuilder().defaultContext;
//build default
let defaultcontextmenu = remote.Menu.buildFromTemplate(contextmenu);
defaultcontextmenu.popup(remote.getCurrentWindow());
}
/**
* Refreshes the data from the markets
*
* @memberof Market
*/
refresher() {
let any = this;
this.props.binanceDepthLoader();
this.props.bittrexDepthLoader();
this.props.cryptopiaDepthLoader();
this.props.binanceCandlestickLoader(any);
this.props.bittrexCandlestickLoader(any);
this.props.cryptopiaCandlestickLoader(any);
this.props.binance24hrInfo();
this.props.bittrex24hrInfo();
this.props.cryptopia24hrInfo();
}
/**
* Formats the buy data and returns it
*
* @memberof Market
*/
formatBuyData = array => {
const { locale } = this.props.settings;
let newQuantity = 0;
let prevQuantity = 0;
let finnishedArray = array
.map(e => {
newQuantity = prevQuantity + e.Volume;
prevQuantity = newQuantity;
if (e.Price < array[0].Price * 0.05) {
return {
x: 0,
y: newQuantity,
};
} else {
return {
x: e.Price,
y: newQuantity,
label: `${translate('Market.Price', locale)}: ${
e.Price
} \n ${translate('Market.Volume', locale)}: ${newQuantity}`,
};
}
})
.filter(e => e.x > 0);
return finnishedArray;
};
/**
* Formats the sell data and returns it
*
* @param {*} array
* @returns
* @memberof Market
*/
formatSellData(array) {
let newQuantity = 0;
let prevQuantity = 0;
let finnishedArray = array
.sort((a, b) => b.Rate - a.Rate)
.map(e => {
newQuantity = prevQuantity + e.Volume;
prevQuantity = newQuantity;
if (e.Price < array[0].Price * 0.05) {
return {
x: 0,
y: newQuantity,
};
} else {
return {
x: e.Price,
y: newQuantity,
label: `${translate('Market.Price', locale)}: ${
e.Price
} \n ${translate('Market.Volume', locale)}: ${newQuantity}`,
};
}
})
.filter(e => e.x > 0);
return finnishedArray;
}
/**
* Formats the Exchange Data
*
* @param {*} exchange
* @returns
* @memberof Market
*/
formatChartData(exchange) {
const dataSetArray = [];
switch (exchange) {
case 'binanceBuy':
return this.formatBuyData(this.props.binance.buy);
break;
case 'binanceSell':
return this.formatBuyData(this.props.binance.sell);
break;
case 'bittrexBuy':
return this.formatBuyData(this.props.bittrex.buy);
break;
case 'bittrexSell':
return this.formatBuyData(this.props.bittrex.sell);
break;
case 'cryptopiaBuy':
return this.formatBuyData(this.props.cryptopia.buy);
break;
case 'cryptopiaSell':
return this.formatBuyData(this.props.cryptopia.sell);
break;
default:
return [];
break;
}
}
/**
* Returns a Div of various market data from the Exchange Name
*
* @param {*} exchangeName
* @returns
* @memberof Market
*/
oneDayinfo(exchangeName) {
return (
<div style={{ display: 'table-row' }}>
<div style={{ display: 'table-cell', verticalAlign: 'middle' }}>
<b>
<Text id="overview.24hrChange" />
</b>
</div>
<div style={{ display: 'table-cell', paddingLeft: '1.5em' }}>
{exchangeName === 'cryptopia' ? (
<div>
<b>Percent change:</b> {this.props[exchangeName].info24hr.change}
{' %'}
</div>
) : (
<div>
<b>
<Text id="Market.PriceChange" />
</b>{' '}
{this.props[exchangeName].info24hr.change}
{' BTC'}
</div>
)}
<div>
<b>
{' '}
<Text id="Market.High" />:{' '}
</b>{' '}
{this.props[exchangeName].info24hr.high}
{' BTC '}
<b>
{' '}
<Text id="Market.Low" />:{' '}
</b>{' '}
{this.props[exchangeName].info24hr.low}
{' BTC '}
<b>
{' '}
<Text id="Market.Volume" />:{' '}
</b>{' '}
{this.props[exchangeName].info24hr.volume}
{' NXS '}
</div>
</div>
</div>
);
}
/**
* Refreshes the market data and shows a notification
*
* @memberof Market
*/
refreshMarket() {
this.refresher();
UIController.showNotification(<Text id="Market.Refreshing" />, 'success');
}
// Mandatory React method
/**
* React Render
*
* @returns
* @memberof Market
*/
render() {
return (
<Panel
controls={
<Tooltip.Trigger tooltip={<Text id="Market.Refreash" />}>
<Button square skin="primary" onClick={() => this.refreshMarket()}>
<Icon icon={syncingIcon} />
</Button>
</Tooltip.Trigger>
}
icon={chartIcon}
title={<Text id="Market.Information" />}
>
{/* <a className="refresh" onClick={() => this.refresher()}>
<Text id="Market.Refreash" />
</a> */}
{/* <div className="alertbox">{this.arbitageAlert()}</div> */}
{this.props.loaded && this.props.binance.buy[0] && (
<div className="exchangeUnitContainer">
<img className="exchangeLogo" src={binanceLogo} />
{this.oneDayinfo('binance')}
<div className="marketInfoContainer">
<MarketDepth
locale={this.props.settings.locale}
chartData={this.formatChartData('binanceBuy')}
chartSellData={this.formatChartData('binanceSell')}
/>
{this.props.binance.candlesticks[0] !== undefined ? (
<Candlestick
locale={this.props.settings.locale}
data={this.props.binance.candlesticks}
/>
) : null}
</div>
</div>
)}
{this.props.loaded && this.props.bittrex.buy[0] && (
<div className="exchangeUnitContainer">
<img className="exchangeLogo" src={bittrexLogo} />
{this.oneDayinfo('bittrex')}
<div className="marketInfoContainer">
<br />
<MarketDepth
locale={this.props.settings.locale}
chartData={this.formatChartData('bittrexBuy')}
chartSellData={this.formatChartData('bittrexSell')}
/>
{this.props.bittrex.candlesticks[0] !== undefined ? (
<Candlestick
locale={this.props.settings.locale}
data={this.props.bittrex.candlesticks}
/>
) : null}
</div>
</div>
)}
{this.props.loaded && this.props.cryptopia.buy[0] && (
<div className="exchangeUnitContainer">
<img className="exchangeLogo" src={cryptopiaLogo} />
{this.oneDayinfo('cryptopia')}
<div className="marketInfoContainer">
<MarketDepth
locale={this.props.settings.locale}
chartData={this.formatChartData('cryptopiaBuy')}
chartSellData={this.formatChartData('cryptopiaSell')}
/>
{this.props.cryptopia.candlesticks[0] !== undefined ? (
<Candlestick
data={this.props.cryptopia.candlesticks}
locale={this.props.settings.locale}
/>
) : null}
</div>
</div>
)}
</Panel>
);
}
} |
JavaScript | class Node {
constructor(value) {
this.value = value;
this.next = null;
}
} |
JavaScript | class BioIcons extends PolymerElement {
static get template() {
return html`
<iron-iconset-svg name="bio" size="24">
<svg>
<defs>
<g id="arrow-forward">
<path
d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"
/>
</g>
<g id="description">
<path
d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"
/>
</g>
<g id="launch">
<path
d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"
/>
</g>
</defs>
</svg>
</iron-iconset-svg>
`;
}
/**
* Instance of the element is created/upgraded. Use: initializing state,
* set up event listeners, create shadow dom.
* @constructor
*/
constructor() {
super();
}
/**
* Use for one-time configuration of your component after local
* DOM is initialized.
*/
ready() {
super.ready();
}
} |
JavaScript | class Countdown extends Component {
constructor(props) {
super(props);
this.state = {
days: 0,
hours: 0,
min: 0,
sec: 0,
}
}
componentDidMount() {
// update every second
this.interval = setInterval(() => {
const date = this.calculateCountdown(this.props.date);
date ? this.setState(date) : this.stop();
}, 1000);
}
componentWillUnmount() {
this.stop();
}
calculateCountdown(endDate) {
let diff = (Date.parse(new Date(endDate)) - Date.parse(new Date())) / 1000;
// clear countdown when date is reached
if (diff <= 0) return false;
const timeLeft = {
years: 0,
days: 0,
hours: 0,
min: 0,
sec: 0
};
// calculate time difference between now and expected date
if (diff >= (365.25 * 86400)) { // 365.25 * 24 * 60 * 60
timeLeft.years = Math.floor(diff / (365.25 * 86400));
diff -= timeLeft.years * 365.25 * 86400;
}
if (diff >= 86400) { // 24 * 60 * 60
timeLeft.days = Math.floor(diff / 86400);
diff -= timeLeft.days * 86400;
}
if (diff >= 3600) { // 60 * 60
timeLeft.hours = Math.floor(diff / 3600);
diff -= timeLeft.hours * 3600;
}
if (diff >= 60) {
timeLeft.min = Math.floor(diff / 60);
diff -= timeLeft.min * 60;
}
timeLeft.sec = diff;
return timeLeft;
}
stop() {
clearInterval(this.interval);
}
addLeadingZeros(value) {
value = String(value);
while (value.length < 2) {
value = '0' + value;
}
return value;
}
render() {
const countDown = this.state;
return (
<div className="Countdown">
<b>Next Draw:</b>
<span className="Countdown-col">
<span className="Countdown-col-element">
{countDown.hours}
{countDown.hours > 1 && <span> hours </span>}
{countDown.hours === 1 && <span> hour </span>}
{countDown.hours === 0 && <span> hours </span>}
</span>
</span>
<span className="Countdown-col">
<span className="Countdown-col-element">
{countDown.min}
{countDown.min > 1 && <span> Minutes </span>}
{countDown.min === 1 && <span> Minute </span>}
{countDown.min === 0 && <span> Minutes </span>}
</span>
</span>
<span className="Countdown-col">
<span className="Countdown-col-element">
{countDown.sec}
{countDown.sec > 1 && <span> Seconds </span>}
{countDown.sec === 1 && <span> Second </span>}
{countDown.sec === 0 && <span> Seconds </span>}
</span>
</span>
</div>
);
}
} |
JavaScript | class DepthCalculator {
calculateDepth(arr, isFirstStart) {
if (!isFirstStart) {
this.max = 0;
this.count = 1;
}
for (let item of arr) {
if (Array.isArray(item)) {
this.count++;
this.calculateDepth(item, true);
}
}
if (this.count > this.max) this.max = this.count;
this.count--;
return this.max;
}
} |
JavaScript | class Ellipsoid {
/**
* @param {number} equatorialSize - Equatorial ellipsoid size.
* @param {number} polarSize - Polar ellipsoid size.
*/
constructor(equatorialSize, polarSize) {
this._a = equatorialSize;
this._b = polarSize;
this._flattening = (equatorialSize - polarSize) / equatorialSize;
this._f = 1 / this._flattening;
this._a2 = equatorialSize * equatorialSize;
this._b2 = polarSize * polarSize;
var qa2b2 = Math.sqrt(this._a2 - this._b2);
this._e = qa2b2 / equatorialSize;
this._e2 = this._e * this._e;
this._e22 = this._e2 * this._e2;
this._k = qa2b2 / polarSize;
this._k2 = this._k * this._k;
this._radii = new Vec3(equatorialSize, polarSize, equatorialSize);
this._radii2 = new Vec3(this._a2, this._b2, this._a2);
this._invRadii = new Vec3(1.0 / equatorialSize, 1.0 / polarSize, 1.0 / equatorialSize);
this._invRadii2 = new Vec3(1.0 / this._a2, 1.0 / this._b2, 1.0 / this._a2);
}
static getRelativeBearing(a, b) {
let a_y = Math.cos(a),
a_x = Math.sin(a),
b_y = Math.cos(b),
b_x = Math.sin(b);
let c = a_y * b_x - b_y * a_x,
d = a_x * b_x + a_y * b_y;
if (c > 0.0) {
return Math.acos(d);
}
return -Math.acos(d);
}
/**
* Returns the midpoint between two points on the great circle.
* @param {LonLat} lonLat1 - Longitude/latitude of first point.
* @param {LonLat} lonLat2 - Longitude/latitude of second point.
* @return {LonLat} Midpoint between points.
*/
static getMiddlePointOnGreatCircle(lonLat1, lonLat2) {
var f1 = lonLat1.lat * math.RADIANS,
l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS;
var dl = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var Bx = Math.cos(f2) * Math.cos(dl);
var By = Math.cos(f2) * Math.sin(dl);
var x = Math.sqrt((Math.cos(f1) + Bx) * (Math.cos(f1) + Bx) + By * By);
var y = Math.sin(f1) + Math.sin(f2);
var f3 = Math.atan2(y, x);
var l3 = l1 + Math.atan2(By, Math.cos(f1) + Bx);
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
/**
* Returns the point at given fraction between two points on the great circle.
* @param {LonLat} lonLat1 - Longitude/Latitude of source point.
* @param {LonLat} lonLat2 - Longitude/Latitude of destination point.
* @param {number} fraction - Fraction between the two points (0 = source point, 1 = destination point).
* @returns {LonLat} Intermediate point between points.
*/
static getIntermediatePointOnGreatCircle(lonLat1, lonLat2, fraction) {
var f1 = lonLat1.lat * math.RADIANS,
l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS,
l2 = lonLat2.lon * math.RADIANS;
var sinf1 = Math.sin(f1),
cosf1 = Math.cos(f1),
sinl1 = Math.sin(l1),
cosl1 = Math.cos(l1);
var sinf2 = Math.sin(f2),
cosf2 = Math.cos(f2),
sinl2 = Math.sin(l2),
cosl2 = Math.cos(l2);
var df = f2 - f1,
dl = l2 - l1;
var a =
Math.sin(df / 2) * Math.sin(df / 2) +
Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2);
var d = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var A = Math.sin((1 - fraction) * d) / Math.sin(d);
var B = Math.sin(fraction * d) / Math.sin(d);
var x = A * cosf1 * cosl1 + B * cosf2 * cosl2;
var y = A * cosf1 * sinl1 + B * cosf2 * sinl2;
var z = A * sinf1 + B * sinf2;
var f3 = Math.atan2(z, Math.sqrt(x * x + y * y));
var l3 = Math.atan2(y, x);
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
static getRhumbBearing(lonLat1, lonLat2) {
var dLon = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var dPhi = Math.log(
Math.tan((lonLat2.lat * math.RADIANS) / 2 + Math.PI / 4) /
Math.tan((lonLat1.lat * math.RADIANS) / 2 + Math.PI / 4)
);
if (Math.abs(dLon) > Math.PI) {
if (dLon > 0) {
dLon = (2 * Math.PI - dLon) * -1;
} else {
dLon = 2 * Math.PI + dLon;
}
}
return (Math.atan2(dLon, dPhi) * math.DEGREES + 360) % 360;
}
static getBearing(lonLat1, lonLat2) {
var f1 = lonLat1.lat * math.RADIANS,
l1 = lonLat1.lon * math.RADIANS;
var f2 = lonLat2.lat * math.RADIANS,
l2 = lonLat2.lon * math.RADIANS;
var y = Math.sin(l2 - l1) * Math.cos(f2);
var x = Math.cos(f1) * Math.sin(f2) - Math.sin(f1) * Math.cos(f2) * Math.cos(l2 - l1);
return Math.atan2(y, x) * math.DEGREES;
}
/**
* Returns the (initial) bearing from source to destination point on the great circle.
* @param {LonLat} lonLat1 - Longitude/latitude of source point.
* @param {LonLat} lonLat2 - Longitude/latitude of destination point.
* @return {number} Initial bearing in degrees from north.
*/
static getInitialBearing(lonLat1, lonLat2) {
var f1 = lonLat1.lat * math.RADIANS,
f2 = lonLat2.lat * math.RADIANS;
var dl = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var y = Math.sin(dl) * Math.cos(f2);
var x = Math.cos(f1) * Math.sin(f2) - Math.sin(f1) * Math.cos(f2) * Math.cos(dl);
var D = Math.atan2(y, x);
return (D * math.DEGREES + 360) % 360;
}
/**
* Returns the point of intersection of two paths defined by point and bearing.
* @param {LonLat} p1 - First point.
* @param {number} brng1 - Initial bearing from first point.
* @param {LonLat} p2 - Second point.
* @param {number} brng2 - Initial bearing from second point.
* @return {LonLat|null} Destination point (null if no unique intersection defined).
*/
static intersection(p1, brng1, p2, brng2) {
var f1 = p1.lat * math.RADIANS,
l1 = p1.lon * math.RADIANS;
var f2 = p2.lat * math.RADIANS,
l2 = p2.lon * math.RADIANS;
var D13 = brng1 * math.RADIANS,
D23 = brng2 * math.RADIANS;
var df = f2 - f1,
dl = l2 - l1;
var d12 =
2 *
Math.asin(
Math.sqrt(
Math.sin(df / 2) * Math.sin(df / 2) +
Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) * Math.sin(dl / 2)
)
);
if (d12 == 0) return null;
// initial/final bearings between points
var Da = Math.acos(
(Math.sin(f2) - Math.sin(f1) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f1))
);
if (isNaN(Da)) Da = 0; // protect against rounding
var Db = Math.acos(
(Math.sin(f1) - Math.sin(f2) * Math.cos(d12)) / (Math.sin(d12) * Math.cos(f2))
);
var D12 = Math.sin(l2 - l1) > 0 ? Da : 2 * Math.PI - Da;
var D21 = Math.sin(l2 - l1) > 0 ? 2 * Math.PI - Db : Db;
var a1 = ((D13 - D12 + Math.PI) % (2 * Math.PI)) - Math.PI;
var a2 = ((D21 - D23 + Math.PI) % (2 * Math.PI)) - Math.PI;
if (Math.sin(a1) == 0 && Math.sin(a2) == 0) return null; // infinite intersections
if (Math.sin(a1) * Math.sin(a2) < 0) return null; // ambiguous intersection
// a1 = Math.abs(a1);
// a2 = Math.abs(a2);
// ... Ed Williams takes abs of a1/a2, but seems to break calculation?
var a3 = Math.acos(
-Math.cos(a1) * Math.cos(a2) + Math.sin(a1) * Math.sin(a2) * Math.cos(d12)
);
var d13 = Math.atan2(
Math.sin(d12) * Math.sin(a1) * Math.sin(a2),
Math.cos(a2) + Math.cos(a1) * Math.cos(a3)
);
var f3 = Math.asin(
Math.sin(f1) * Math.cos(d13) + Math.cos(f1) * Math.sin(d13) * Math.cos(D13)
);
var dl13 = Math.atan2(
Math.sin(D13) * Math.sin(d13) * Math.cos(f1),
Math.cos(d13) - Math.sin(f1) * Math.sin(f3)
);
var l3 = l1 + dl13;
return new LonLat(((l3 * math.DEGREES + 540) % 360) - 180, f3 * math.DEGREES);
}
/**
* Returns final bearing arriving at destination destination point from lonLat1 point; the final bearing
* will differ from the initial bearing by varying degrees according to distance and latitude.
* @param {LonLat} lonLat1 - Longitude/latitude of source point.
* @param {LonLat} lonLat2 - Longitude/latitude of destination point.
* @return {number} Final bearing in degrees from north.
*/
static getFinalBearing(lonLat1, lonLat2) {
// get initial bearing from destination lonLat2 to lonLat1 & reverse it by adding 180°
return (Ellipsoid.getInitialBearing(lonLat2, lonLat1) + 180) % 360;
}
/**
* Gets ellipsoid equatorial size.
* @public
* @returns {number} -
*/
getEquatorialSize() {
return this._a;
}
/**
* Gets ellipsoid polar size.
* @public
* @returns {number} -
*/
getPolarSize() {
return this._b;
}
/**
* Gets cartesian ECEF from Wgs84 geodetic coordiantes.
* @public
* @param {LonLat} lonlat - Degrees geodetic coordiantes.
* @returns {Vec3} -
*/
lonLatToCartesian(lonlat) {
var latrad = math.RADIANS * lonlat.lat,
lonrad = math.RADIANS * lonlat.lon;
var slt = Math.sin(latrad);
var N = this._a / Math.sqrt(1.0 - this._e2 * slt * slt);
var nc = (N + lonlat.height) * Math.cos(latrad);
return new Vec3(
nc * Math.sin(lonrad),
(N * (1.0 - this._e2) + lonlat.height) * slt,
nc * Math.cos(lonrad)
);
}
/**
* Gets cartesian ECEF from Wgs84 geodetic coordiantes.
* @public
* @param {LonLat} lonlat - Degrees geodetic coordiantes.
* @param {Vec3} res - Output result.
* @returns {Vec3} -
*/
lonLatToCartesianRes(lonlat, res) {
var latrad = math.RADIANS * lonlat.lat,
lonrad = math.RADIANS * lonlat.lon;
var slt = Math.sin(latrad);
var N = this._a / Math.sqrt(1.0 - this._e2 * slt * slt);
var nc = (N + lonlat.height) * Math.cos(latrad);
res.x = nc * Math.sin(lonrad);
res.y = (N * (1.0 - this._e2) + lonlat.height) * slt;
res.z = nc * Math.cos(lonrad);
return res;
}
/**
* Gets cartesian ECEF from Wgs84 geodetic coordiantes.
* @public
* @param {Number} lon - Longitude.
* @param {Number} lat - Latitude.
* @param {Number} height - Height.
* @returns {Vec3} -
*/
geodeticToCartesian(lon, lat, height = 0) {
var latrad = math.RADIANS * lat,
lonrad = math.RADIANS * lon;
var slt = Math.sin(latrad);
var N = this._a / Math.sqrt(1 - this._e2 * slt * slt);
var nc = (N + height) * Math.cos(latrad);
return new Vec3(
nc * Math.sin(lonrad),
(N * (1 - this._e2) + height) * slt,
nc * Math.cos(lonrad)
);
}
/**
* Gets Wgs84 geodetic coordiantes from cartesian ECEF.
* @public
* @param {Vec3} cartesian - Cartesian coordinates.
* @returns {LonLat} -
*/
cartesianToLonLat(cartesian) {
var x = cartesian.z,
y = cartesian.x,
z = cartesian.y;
var ecc2 = this._e2;
var ecc22 = this._e22;
var r2 = x * x + y * y;
var r = Math.sqrt(r2);
var z2 = z * z;
var f = 54.0 * this._b2 * z2;
var g = r2 + (1.0 - ecc2) * z2 + ecc2 * (this._a2 - this._b2);
var g2 = g * g;
var c = (ecc22 * f * r2) / (g2 * g);
var s = Math.pow(1.0 + c + Math.sqrt(c * (c + 2.0)), 0.33333333333333333);
var p = f / (3.0 * Math.pow(1.0 + s + 1.0 / s, 2.0) * g2);
var q = Math.sqrt(1.0 + 2.0 * ecc22 * p);
var recc2r0 =
r -
ecc2 *
(-(p * ecc2 * r) / 1 +
q +
Math.sqrt(
0.5 * this._a2 * (1.0 + 1.0 / q) -
(p * (1.0 - ecc2) * z2) / (q * (1.0 + q)) -
0.5 * p * r2
));
var recc2r02 = recc2r0 * recc2r0;
var v = Math.sqrt(recc2r02 + (1.0 - ecc2) * z2);
var z0 = (this._b2 * z) / (this._a * v);
var lat = Math.atan((z + this._k2 * z0) / r) * math.DEGREES;
var lon = Math.atan2(y, x) * math.DEGREES;
return new LonLat(
lon,
lat,
cartesian.length() - this.geodeticToCartesian(lon, lat).length()
);
}
/**
* Gets ellipsoid surface normal.
* @public
* @param {Vec3} coord - Spatial coordiantes.
* @return {Vec3} -
*/
getSurfaceNormal3v(coord) {
var r2 = this._invRadii2;
var nx = coord.x * r2.x,
ny = coord.y * r2.y,
nz = coord.z * r2.z;
var l = 1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz);
return new Vec3(nx * l, ny * l, nz * l);
}
/**
*
* @param {LonLat} lonLat1
* @param {number} [bearing]
* @param {number} [distance]
* @return {LonLat} -
*/
getBearingDestination(lonLat1, bearing = 0.0, distance = 0) {
bearing = bearing * math.RADIANS;
var nlon = ((lonLat1.lon + 540) % 360) - 180;
var f1 = lonLat1.lat * math.RADIANS,
l1 = nlon * math.RADIANS;
var dR = distance / this._a;
var f2 = Math.asin(
Math.sin(f1) * Math.cos(dR) + Math.cos(f1) * Math.sin(dR) * Math.cos(bearing)
);
return new LonLat(
(l1 +
Math.atan2(
Math.sin(bearing) * Math.sin(dR) * Math.cos(f1),
Math.cos(dR) - Math.sin(f1) * Math.sin(f2)
)) *
math.DEGREES,
f2 * math.DEGREES
);
}
/**
* Returns the distance from one point to another(using haversine formula) on the great circle.
* @param {LonLat} lonLat1 - Longitude/latitude of source point.
* @param {LonLat} lonLat2 - Longitude/latitude of destination point.
* @return {number} Distance between points.
*/
getGreatCircleDistance(lonLat1, lonLat2) {
var dLat = (lonLat2.lat - lonLat1.lat) * math.RADIANS;
var dLon = (lonLat2.lon - lonLat1.lon) * math.RADIANS;
var a =
Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
Math.sin(dLon / 2.0) *
Math.sin(dLon / 2) *
Math.cos(lonLat1.lat * math.RADIANS) *
Math.cos(lonLat2.lat * math.RADIANS);
return this._a * 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
}
/**
* Calculates the destination point given start point lat / lon, bearing(deg) and distance (m).
*
* Taken from http://movable-type.co.uk/scripts/latlong-vincenty-direct.html and optimized / cleaned up by Mathias Bynens <http://mathiasbynens.be/>
* Based on the Vincenty direct formula by T. Vincenty, “Direct and Inverse Solutions of Geodesics on the Ellipsoid with application of nested equations”, Survey Review, vol XXII no 176, 1975 <http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf>
*/
getGreatCircleDestination(lonLat, brng, dist) {
var lon1 = lonLat.lon,
lat1 = lonLat.lat;
var a = this._a,
b = this._b,
f = 1.0 / this._f,
s = dist,
alpha1 = brng * math.RADIANS,
sinAlpha1 = Math.sin(alpha1),
cosAlpha1 = Math.cos(alpha1),
tanU1 = (1 - f) * Math.tan(lat1 * math.RADIANS),
cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1),
sinU1 = tanU1 * cosU1,
sigma1 = Math.atan2(tanU1, cosAlpha1),
sinAlpha = cosU1 * sinAlpha1,
cosSqAlpha = 1 - sinAlpha * sinAlpha,
uSq = (cosSqAlpha * (a * a - b * b)) / (b * b),
A = 1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))),
B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))),
sigma = s / (b * A),
sigmaP = 2 * Math.PI;
while (Math.abs(sigma - sigmaP) > 1e-12) {
var cos2SigmaM = Math.cos(2 * sigma1 + sigma),
sinSigma = Math.sin(sigma),
cosSigma = Math.cos(sigma),
deltaSigma =
B *
sinSigma *
(cos2SigmaM +
(B / 4) *
(cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
(B / 6) *
cos2SigmaM *
(-3 + 4 * sinSigma * sinSigma) *
(-3 + 4 * cos2SigmaM * cos2SigmaM)));
sigmaP = sigma;
sigma = s / (b * A) + deltaSigma;
}
var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1,
lat2 = Math.atan2(
sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
(1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)
),
lambda = Math.atan2(
sinSigma * sinAlpha1,
cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1
),
C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)),
L =
lambda -
(1 - C) *
f *
sinAlpha *
(sigma +
C *
sinSigma *
(cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))),
revAz = Math.atan2(sinAlpha, -tmp); // final bearing
return new LonLat(lon1 + L * math.DEGREES, lat2 * math.DEGREES);
}
/**
* Returns ray vector hit ellipsoid coordinates.
* If the ray doesn't hit ellipsoid returns null.
* @public
* @param {Vec3} origin - Ray origin point.
* @param {Vec3} direction - Ray direction.
* @returns {Vec3} -
*/
hitRay(origin, direction) {
var q = this._invRadii.mul(origin);
var w = this._invRadii.mul(direction);
var q2 = q.dot(q);
var qw = q.dot(w);
var difference, w2, product, discriminant, temp;
if (q2 > 1.0) {
// Outside ellipsoid.
if (qw >= 0.0) {
// Looking outward or tangent (0 intersections).
return null;
}
// qw < 0.0.
var qw2 = qw * qw;
difference = q2 - 1.0; // Positively valued.
w2 = w.dot(w);
product = w2 * difference;
let eps = Math.abs(qw2 - product);
if (eps > math.EPSILON15 && qw2 < product) {
// Imaginary roots (0 intersections).
return null;
} else if (qw2 > product) {
// Distinct roots (2 intersections).
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
var root0 = temp / w2;
var root1 = difference / temp;
if (root0 < root1) {
return origin.add(direction.scaleTo(root0));
}
return origin.add(direction.scaleTo(root1));
} else {
// qw2 == product. Repeated roots (2 intersections).
var root = Math.sqrt(difference / w2);
return origin.add(direction.scaleTo(root));
}
} else if (q2 < 1.0) {
// Inside ellipsoid (2 intersections).
difference = q2 - 1.0; // Negatively valued.
w2 = w.dot(w);
product = w2 * difference; // Negatively valued.
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant); // Positively valued.
return origin.add(direction.scaleTo(temp / w2));
} else {
// q2 == 1.0. On ellipsoid.
if (qw < 0.0) {
// Looking inward.
w2 = w.dot(w);
return origin.add(direction.scaleTo(-qw / w2));
}
// qw >= 0.0. Looking outward or tangent.
return null;
}
}
} |
JavaScript | class TarballImageAsset extends core_2.Construct {
/**
* @stability stable
*/
constructor(scope, id, props) {
super(scope, id);
jsiiDeprecationWarnings._aws_cdk_aws_ecr_assets_TarballImageAssetProps(props);
if (!fs.existsSync(props.tarballFile)) {
throw new Error(`Cannot find file at ${props.tarballFile}`);
}
const stagedTarball = new core_1.AssetStaging(this, 'Staging', { sourcePath: props.tarballFile });
this.sourceHash = stagedTarball.assetHash;
this.assetHash = stagedTarball.assetHash;
const stage = core_1.Stage.of(this);
const relativePathInOutDir = stage ? path.relative(stage.assetOutdir, stagedTarball.absoluteStagedPath) : stagedTarball.absoluteStagedPath;
const stack = core_1.Stack.of(this);
const location = stack.synthesizer.addDockerImageAsset({
sourceHash: stagedTarball.assetHash,
executable: [
'sh',
'-c',
`docker load -i ${relativePathInOutDir} | sed "s/Loaded image: //g"`,
],
});
this.repository = ecr.Repository.fromRepositoryName(this, 'Repository', location.repositoryName);
this.imageUri = location.imageUri;
}
} |
JavaScript | class TodoList extends LitElement {
static get styles() {
return css`
:host {
display: block;
border: solid 1px gray;
padding: 16px;
max-width: 800px;
}
`;
}
static get properties() {
return {
todos: {type: Array},
/**
* The name to say "Hello" to.
*/
name: {type: String},
/**
* The number of times the button has been clicked.
*/
count: {type: Number},
};
}
constructor() {
super();
this.name = 'World';
this.count = 0;
this.todos = [];
}
render() {
return html`
<h1>Hello, ${this.name}!</h1>
<button @click=${this._onClick} part="button">
Click Count: ${this.count}
</button>
<button @click=${this._onAddTodo} part="button">
Add todo
</button>
<!-- <slot></slot> -->
<ul>
<!-- use a map function to repeat a template -->
${this.todos.map(todo => html`
<li>${todo.description}</li>
`)}
</ul>
`;
}
_onClick() {
this.count++;
}
_onAddTodo() {
this.todos.push({description: "Wash car"});
this.requestUpdate();
}
} |
JavaScript | class Scratch3LooksBlocks {
constructor (runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
this._onTargetChanged = this._onTargetChanged.bind(this);
this._onResetBubbles = this._onResetBubbles.bind(this);
this._onTargetWillExit = this._onTargetWillExit.bind(this);
this._updateBubble = this._updateBubble.bind(this);
// Reset all bubbles on start/stop
this.runtime.on('PROJECT_STOP_ALL', this._onResetBubbles);
this.runtime.on('targetWasRemoved', this._onTargetWillExit);
// Enable other blocks to use bubbles like ask/answer
this.runtime.on('SAY', this._updateBubble);
}
/**
* The default bubble state, to be used when a target has no existing bubble state.
* @type {BubbleState}
*/
static get DEFAULT_BUBBLE_STATE () {
return {
drawableId: null,
onSpriteRight: true,
skinId: null,
text: '',
type: 'say',
usageId: null
};
}
/**
* The key to load & store a target's bubble-related state.
* @type {string}
*/
static get STATE_KEY () {
return 'Scratch.looks';
}
/**
* Limit for say bubble string.
* @const {string}
*/
static get SAY_BUBBLE_LIMIT () {
return 330;
}
/**
* @param {Target} target - collect bubble state for this target. Probably, but not necessarily, a RenderedTarget.
* @returns {BubbleState} the mutable bubble state associated with that target. This will be created if necessary.
* @private
*/
_getBubbleState (target) {
let bubbleState = target.getCustomState(Scratch3LooksBlocks.STATE_KEY);
if (!bubbleState) {
bubbleState = Clone.simple(Scratch3LooksBlocks.DEFAULT_BUBBLE_STATE);
target.setCustomState(Scratch3LooksBlocks.STATE_KEY, bubbleState);
}
return bubbleState;
}
/**
* Handle a target which has moved.
* @param {RenderedTarget} target - the target which has moved.
* @private
*/
_onTargetChanged (target) {
const bubbleState = this._getBubbleState(target);
if (bubbleState.drawableId) {
this._positionBubble(target);
}
}
/**
* Handle a target which is exiting.
* @param {RenderedTarget} target - the target.
* @private
*/
_onTargetWillExit (target) {
const bubbleState = this._getBubbleState(target);
if (bubbleState.drawableId && bubbleState.skinId) {
this.runtime.renderer.destroyDrawable(bubbleState.drawableId, StageLayering.SPRITE_LAYER);
this.runtime.renderer.destroySkin(bubbleState.skinId);
bubbleState.drawableId = null;
bubbleState.skinId = null;
this.runtime.requestRedraw();
}
target.removeListener(RenderedTarget.EVENT_TARGET_VISUAL_CHANGE, this._onTargetChanged);
}
/**
* Handle project start/stop by clearing all visible bubbles.
* @private
*/
_onResetBubbles () {
for (let n = 0; n < this.runtime.targets.length; n++) {
const bubbleState = this._getBubbleState(this.runtime.targets[n]);
bubbleState.text = '';
this._onTargetWillExit(this.runtime.targets[n]);
}
clearTimeout(this._bubbleTimeout);
}
/**
* Position the bubble of a target. If it doesn't fit on the specified side, flip and rerender.
* @param {!Target} target Target whose bubble needs positioning.
* @private
*/
_positionBubble (target) {
if (!target.visible) return;
const bubbleState = this._getBubbleState(target);
const [bubbleWidth, bubbleHeight] = this.runtime.renderer.getCurrentSkinSize(bubbleState.drawableId);
let targetBounds;
try {
targetBounds = target.getBoundsForBubble();
} catch (error_) {
// Bounds calculation could fail (e.g. on empty costumes), in that case
// use the x/y position of the target.
targetBounds = {
left: target.x,
right: target.x,
top: target.y,
bottom: target.y
};
}
const stageSize = this.runtime.renderer.getNativeSize();
const stageBounds = {
left: -stageSize[0] / 2,
right: stageSize[0] / 2,
top: stageSize[1] / 2,
bottom: -stageSize[1] / 2
};
if (bubbleState.onSpriteRight && bubbleWidth + targetBounds.right > stageBounds.right &&
(targetBounds.left - bubbleWidth > stageBounds.left)) { // Only flip if it would fit
bubbleState.onSpriteRight = false;
this._renderBubble(target);
} else if (!bubbleState.onSpriteRight && targetBounds.left - bubbleWidth < stageBounds.left &&
(bubbleWidth + targetBounds.right < stageBounds.right)) { // Only flip if it would fit
bubbleState.onSpriteRight = true;
this._renderBubble(target);
} else {
this.runtime.renderer.updateDrawableProperties(bubbleState.drawableId, {
position: [
bubbleState.onSpriteRight ? (
Math.max(
stageBounds.left, // Bubble should not extend past left edge of stage
Math.min(stageBounds.right - bubbleWidth, targetBounds.right)
)
) : (
Math.min(
stageBounds.right - bubbleWidth, // Bubble should not extend past right edge of stage
Math.max(stageBounds.left, targetBounds.left - bubbleWidth)
)
),
// Bubble should not extend past the top of the stage
Math.min(stageBounds.top, targetBounds.bottom + bubbleHeight)
]
});
this.runtime.requestRedraw();
}
}
/**
* Create a visible bubble for a target. If a bubble exists for the target,
* just set it to visible and update the type/text. Otherwise create a new
* bubble and update the relevant custom state.
* @param {!Target} target Target who needs a bubble.
* @return {undefined} Early return if text is empty string.
* @private
*/
_renderBubble (target) {
if (!this.runtime.renderer) return;
const bubbleState = this._getBubbleState(target);
const {type, text, onSpriteRight} = bubbleState;
// Remove the bubble if target is not visible, or text is being set to blank.
if (!target.visible || text === '') {
this._onTargetWillExit(target);
return;
}
if (bubbleState.skinId) {
this.runtime.renderer.updateTextSkin(bubbleState.skinId, type, text, onSpriteRight, [0, 0]);
} else {
target.addListener(RenderedTarget.EVENT_TARGET_VISUAL_CHANGE, this._onTargetChanged);
bubbleState.drawableId = this.runtime.renderer.createDrawable(StageLayering.SPRITE_LAYER);
bubbleState.skinId = this.runtime.renderer.createTextSkin(type, text, bubbleState.onSpriteRight, [0, 0]);
this.runtime.renderer.updateDrawableProperties(bubbleState.drawableId, {
skinId: bubbleState.skinId
});
}
this._positionBubble(target);
}
/**
* The entry point for say/think blocks. Clears existing bubble if the text is empty.
* Set the bubble custom state and then call _renderBubble.
* @param {!Target} target Target that say/think blocks are being called on.
* @param {!string} type Either "say" or "think"
* @param {!string} text The text for the bubble, empty string clears the bubble.
* @private
*/
_updateBubble (target, type, text) {
const bubbleState = this._getBubbleState(target);
bubbleState.type = type;
bubbleState.text = text;
bubbleState.usageId = uid();
this._renderBubble(target);
}
/**
* Retrieve the block primitives implemented by this package.
* @return {object.<string, Function>} Mapping of opcode to Function.
*/
getPrimitives () {
return {
looks_say: this.say,
looks_sayforsecs: this.sayforsecs,
looks_think: this.think,
looks_thinkforsecs: this.thinkforsecs,
looks_show: this.show,
looks_hide: this.hide,
looks_hideallsprites: () => {}, // legacy no-op block
looks_switchcostumeto: this.switchCostume,
looks_switchbackdropto: this.switchBackdrop,
looks_switchbackdroptoandwait: this.switchBackdropAndWait,
looks_nextcostume: this.nextCostume,
looks_nextbackdrop: this.nextBackdrop,
looks_changeeffectby: this.changeEffect,
looks_seteffectto: this.setEffect,
looks_cleargraphiceffects: this.clearEffects,
looks_changesizeby: this.changeSize,
looks_setsizeto: this.setSize,
looks_changestretchby: () => {}, // legacy no-op blocks
looks_setstretchto: () => {},
looks_gotofrontback: this.goToFrontBack,
looks_goforwardbackwardlayers: this.goForwardBackwardLayers,
looks_size: this.getSize,
looks_costumenumbername: this.getCostumeNumberName,
looks_backdropnumbername: this.getBackdropNumberName
};
}
getMonitored () {
return {
looks_size: {
isSpriteSpecific: true,
getId: targetId => `${targetId}_size`
},
looks_costumenumbername: {
isSpriteSpecific: true,
getId: targetId => `${targetId}_costumenumbername`
},
looks_backdropnumbername: {
getId: () => 'backdropnumbername'
}
};
}
say (args, util) {
// @TODO in 2.0 calling say/think resets the right/left bias of the bubble
let message = args.MESSAGE;
if (typeof message === 'number') {
message = parseFloat(message.toFixed(2));
}
message = String(message).substr(0, Scratch3LooksBlocks.SAY_BUBBLE_LIMIT);
this.runtime.emit('SAY', util.target, 'say', message);
}
sayforsecs (args, util) {
this.say(args, util);
const target = util.target;
const usageId = this._getBubbleState(target).usageId;
return new Promise(resolve => {
this._bubbleTimeout = setTimeout(() => {
this._bubbleTimeout = null;
// Clear say bubble if it hasn't been changed and proceed.
if (this._getBubbleState(target).usageId === usageId) {
this._updateBubble(target, 'say', '');
}
resolve();
}, 1000 * args.SECS);
});
}
think (args, util) {
this._updateBubble(util.target, 'think', String(args.MESSAGE).substr(0, Scratch3LooksBlocks.SAY_BUBBLE_LIMIT));
}
thinkforsecs (args, util) {
this.think(args, util);
const target = util.target;
const usageId = this._getBubbleState(target).usageId;
return new Promise(resolve => {
this._bubbleTimeout = setTimeout(() => {
this._bubbleTimeout = null;
// Clear think bubble if it hasn't been changed and proceed.
if (this._getBubbleState(target).usageId === usageId) {
this._updateBubble(target, 'think', '');
}
resolve();
}, 1000 * args.SECS);
});
}
show (args, util) {
util.target.setVisible(true);
this._renderBubble(util.target);
}
hide (args, util) {
util.target.setVisible(false);
this._renderBubble(util.target);
}
/**
* Utility function to set the costume or backdrop of a target.
* Matches the behavior of Scratch 2.0 for different types of arguments.
* @param {!Target} target Target to set costume/backdrop to.
* @param {Any} requestedCostume Costume requested, e.g., 0, 'name', etc.
* @param {boolean=} optZeroIndex Set to zero-index the requestedCostume.
* @return {Array.<!Thread>} Any threads started by this switch.
*/
_setCostumeOrBackdrop (target,
requestedCostume, optZeroIndex) {
if (typeof requestedCostume === 'number') {
target.setCostume(optZeroIndex ?
requestedCostume : requestedCostume - 1);
} else {
const costumeIndex = target.getCostumeIndexByName(requestedCostume);
if (costumeIndex > -1) {
target.setCostume(costumeIndex);
} else if (requestedCostume === 'previous costume' ||
requestedCostume === 'previous backdrop') {
target.setCostume(target.currentCostume - 1);
} else if (requestedCostume === 'next costume' ||
requestedCostume === 'next backdrop') {
target.setCostume(target.currentCostume + 1);
} else if (requestedCostume === 'random backdrop') {
const numCostumes = target.getCostumes().length;
if (numCostumes > 1) {
let selectedIndex = Math.floor(Math.random() * (numCostumes - 1));
if (selectedIndex === target.currentCostume) selectedIndex += 1;
target.setCostume(selectedIndex);
}
} else {
const forcedNumber = Number(requestedCostume);
if (!isNaN(forcedNumber)) {
target.setCostume(optZeroIndex ?
forcedNumber : forcedNumber - 1);
}
}
}
if (target === this.runtime.getTargetForStage()) {
// Target is the stage - start hats.
const newName = target.getCostumes()[target.currentCostume].name;
return this.runtime.startHats('event_whenbackdropswitchesto', {
BACKDROP: newName
});
}
return [];
}
switchCostume (args, util) {
this._setCostumeOrBackdrop(util.target, args.COSTUME);
}
nextCostume (args, util) {
this._setCostumeOrBackdrop(
util.target, util.target.currentCostume + 1, true
);
}
switchBackdrop (args) {
this._setCostumeOrBackdrop(this.runtime.getTargetForStage(), args.BACKDROP);
}
switchBackdropAndWait (args, util) {
// Have we run before, starting threads?
if (!util.stackFrame.startedThreads) {
// No - switch the backdrop.
util.stackFrame.startedThreads = (
this._setCostumeOrBackdrop(
this.runtime.getTargetForStage(),
args.BACKDROP
)
);
if (util.stackFrame.startedThreads.length === 0) {
// Nothing was started.
return;
}
}
// We've run before; check if the wait is still going on.
const instance = this;
// Scratch 2 considers threads to be waiting if they are still in
// runtime.threads. Threads that have run all their blocks, or are
// marked done but still in runtime.threads are still considered to
// be waiting.
const waiting = util.stackFrame.startedThreads
.some(thread => instance.runtime.threads.indexOf(thread) !== -1);
if (waiting) {
// If all threads are waiting for the next tick or later yield
// for a tick as well. Otherwise yield until the next loop of
// the threads.
if (
util.stackFrame.startedThreads
.every(thread => instance.runtime.isWaitingThread(thread))
) {
util.yieldTick();
} else {
util.yield();
}
}
}
nextBackdrop () {
const stage = this.runtime.getTargetForStage();
this._setCostumeOrBackdrop(
stage, stage.currentCostume + 1, true
);
}
changeEffect (args, util) {
const effect = Cast.toString(args.EFFECT).toLowerCase();
const change = Cast.toNumber(args.CHANGE);
if (!util.target.effects.hasOwnProperty(effect)) return;
const newValue = change + util.target.effects[effect];
util.target.setEffect(effect, newValue);
}
setEffect (args, util) {
const effect = Cast.toString(args.EFFECT).toLowerCase();
const value = Cast.toNumber(args.VALUE);
util.target.setEffect(effect, value);
}
clearEffects (args, util) {
util.target.clearEffects();
}
changeSize (args, util) {
const change = Cast.toNumber(args.CHANGE);
util.target.setSize(util.target.size + change);
}
setSize (args, util) {
const size = Cast.toNumber(args.SIZE);
util.target.setSize(size);
}
goToFrontBack (args, util) {
if (!util.target.isStage) {
if (args.FRONT_BACK === 'front') {
util.target.goToFront();
} else {
util.target.goToBack();
}
}
}
goForwardBackwardLayers (args, util) {
if (!util.target.isStage) {
if (args.FORWARD_BACKWARD === 'forward') {
util.target.goForwardLayers(Cast.toNumber(args.NUM));
} else {
util.target.goBackwardLayers(Cast.toNumber(args.NUM));
}
}
}
getSize (args, util) {
return Math.round(util.target.size);
}
getBackdropNumberName (args) {
const stage = this.runtime.getTargetForStage();
if (args.NUMBER_NAME === 'number') {
return stage.currentCostume + 1;
}
// Else return name
return stage.getCostumes()[stage.currentCostume].name;
}
getCostumeNumberName (args, util) {
if (args.NUMBER_NAME === 'number') {
return util.target.currentCostume + 1;
}
// Else return name
return util.target.getCostumes()[util.target.currentCostume].name;
}
} |
JavaScript | class ManagePanel {
/**
* @constructor
*/
constructor() {
this.manageTabs = [
Datasets,
Jobs,
Basemaps,
Translations,
TransAssist,
ReviewBookmarks,
ReviewBookmarkNotes
];
this.isOpen = false;
}
/**
* Render base panel and all of its components
*/
render() {
this.container = d3.select( 'body' )
.insert( 'div', '#id-container' )
.attr( 'id', 'manage-panel' )
.classed( 'hidden', true );
this.panelSidebar = this.container
.append( 'div' )
.attr( 'id', 'manage-sidebar-menu' )
.classed( 'wrapper fill-light keyline-right', true );
this.panelSidebar
.append( 'h3' )
.classed( 'manage-header pad1y strong center', true )
.append( 'label' )
.text( 'Manage Panel' );
return this;
}
renderTabs() {
if ( Hoot.users.isAdvanced() ) {
this.manageTabs.push( TaskingManagerPanel );
}
if ( Hoot.users.isAdmin() ) {
this.manageTabs.push( AdminPanel );
}
// Render all tabs
return Promise.all( _map( this.manageTabs, Tab => new Tab( this ).render() ) )
.then( modules => {
this.datasets = modules[ 0 ];
this.jobs = modules[ 1 ];
this.basemaps = modules[ 2 ];
this.translations = modules[ 3 ];
this.transAssist = modules[ 4 ];
this.reviewBookmarks = modules[ 5 ];
this.bookmarkNotes = modules[ 6 ];
this.tabs = modules;
} );
}
} |
JavaScript | class SyncKeyValueProvider extends SynchronousProvider {
static isAvailable() { return true; }
constructor(options) {
super();
this.store = options.store;
// INVARIANT: Ensure that the root exists.
this.makeRootDirectory();
}
getName() { return this.store.name(); }
isReadOnly() { return false; }
supportsSymlinks() { return false; }
supportsProps() { return false; }
supportsSynch() { return true; }
/**
* Delete all contents stored in the file system.
*/
empty() {
this.store.clear();
// INVARIANT: Root always exists.
this.makeRootDirectory();
}
renameSync(oldPath, newPath) {
const tx = this.store.beginTransaction('readwrite'), oldParent = paths.dirname(oldPath), oldName = paths.basename(oldPath), newParent = paths.dirname(newPath), newName = paths.basename(newPath),
// Remove oldPath from parent's directory listing.
oldDirNode = this.findINode(tx, oldParent), oldDirList = this.getDirListing(tx, oldParent, oldDirNode);
if (!oldDirList[oldName]) {
throw FileError.ENOENT(oldPath);
}
const nodeId = oldDirList[oldName];
delete oldDirList[oldName];
// Invariant: Can't move a folder inside itself.
// This funny little hack ensures that the check passes only if oldPath
// is a subpath of newParent. We append '/' to avoid matching folders that
// are a substring of the bottom-most folder in the path.
if ((newParent + '/').indexOf(oldPath + '/') === 0) {
throw new FileError(ErrorCodes.EBUSY, oldParent);
}
// Add newPath to parent's directory listing.
let newDirNode, newDirList;
if (newParent === oldParent) {
// Prevent us from re-grabbing the same directory listing, which still
// contains oldName.
newDirNode = oldDirNode;
newDirList = oldDirList;
}
else {
newDirNode = this.findINode(tx, newParent);
newDirList = this.getDirListing(tx, newParent, newDirNode);
}
if (newDirList[newName]) {
// If it's a file, delete it.
const newNameNode = this.getINode(tx, newPath, newDirList[newName]);
if (newNameNode.isFile()) {
try {
tx.del(newNameNode.id);
tx.del(newDirList[newName]);
}
catch (e) {
tx.abort();
throw e;
}
}
else {
// If it's a directory, throw a permissions error.
throw FileError.EPERM(newPath);
}
}
newDirList[newName] = nodeId;
// Commit the two changed directory listings.
try {
tx.put(oldDirNode.id, Buffer.from(JSON.stringify(oldDirList)), true);
tx.put(newDirNode.id, Buffer.from(JSON.stringify(newDirList)), true);
}
catch (e) {
tx.abort();
throw e;
}
tx.commit();
}
statSync(p, isLstat) {
// Get the inode to the item, convert it into a Stats object.
return this.findINode(this.store.beginTransaction('readonly'), p).toStats();
}
createFileSync(p, flag, mode) {
const tx = this.store.beginTransaction('readwrite'), data = emptyBuffer(), newFile = this.commitNewFile(tx, p, FileType.FILE, mode, data);
// Open the file.
return new SyncKeyValueFile(this, p, flag, newFile.toStats(), data);
}
openFileSync(p, flag) {
const tx = this.store.beginTransaction('readonly'), node = this.findINode(tx, p), data = tx.get(node.id);
if (data === undefined) {
throw FileError.ENOENT(p);
}
return new SyncKeyValueFile(this, p, flag, node.toStats(), data);
}
unlinkSync(p) {
this.removeEntry(p, false);
}
rmdirSync(p) {
// Check first if directory is empty.
if (this.readdirSync(p).length > 0) {
throw FileError.ENOTEMPTY(p);
}
else {
this.removeEntry(p, true);
}
}
mkdirSync(p, mode) {
const tx = this.store.beginTransaction('readwrite'), data = Buffer.from('{}');
this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data);
}
readdirSync(p) {
const tx = this.store.beginTransaction('readonly');
return Object.keys(this.getDirListing(tx, p, this.findINode(tx, p)));
}
_syncSync(p, data, stats) {
// @todo Ensure mtime updates properly, and use that to determine if a data
// update is required.
const tx = this.store.beginTransaction('readwrite'),
// We use the _findInode helper because we actually need the INode id.
fileInodeId = this._findINode(tx, paths.dirname(p), paths.basename(p)), fileInode = this.getINode(tx, p, fileInodeId), inodeChanged = fileInode.update(stats);
try {
// Sync data.
tx.put(fileInode.id, data, true);
// Sync metadata.
if (inodeChanged) {
tx.put(fileInodeId, fileInode.toBuffer(), true);
}
}
catch (e) {
tx.abort();
throw e;
}
tx.commit();
}
/**
* Checks if the root directory exists. Creates it if it doesn't.
*/
makeRootDirectory() {
const tx = this.store.beginTransaction('readwrite');
if (tx.get(ROOT_NODE_ID) === undefined) {
// Create new inode.
const currTime = (new Date()).getTime(),
// Mode 0666
dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);
// If the root doesn't exist, the first random ID shouldn't exist,
// either.
tx.put(dirInode.id, getEmptyDirNode(), false);
tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false);
tx.commit();
}
}
/**
* Helper function for findINode.
* @param parent The parent directory of the file we are attempting to find.
* @param filename The filename of the inode we are attempting to find, minus
* the parent.
* @return string The ID of the file's inode in the file system.
*/
_findINode(tx, parent, filename) {
const readDirectory = (inode) => {
// Get the root's directory listing.
const dirList = this.getDirListing(tx, parent, inode);
// Get the file's ID.
if (dirList[filename]) {
return dirList[filename];
}
else {
throw FileError.ENOENT(paths.resolve(parent, filename));
}
};
if (parent === '/') {
if (filename === '') {
// BASE CASE #1: Return the root's ID.
return ROOT_NODE_ID;
}
else {
// BASE CASE #2: Find the item in the root ndoe.
return readDirectory(this.getINode(tx, parent, ROOT_NODE_ID));
}
}
else {
return readDirectory(this.getINode(tx, parent + paths.sep + filename, this._findINode(tx, paths.dirname(parent), paths.basename(parent))));
}
}
/**
* Finds the Inode of the given path.
* @param p The path to look up.
* @return The Inode of the path p.
* @todo memoize/cache
*/
findINode(tx, p) {
return this.getINode(tx, p, this._findINode(tx, paths.dirname(p), paths.basename(p)));
}
/**
* Given the ID of a node, retrieves the corresponding Inode.
* @param tx The transaction to use.
* @param p The corresponding path to the file (used for error messages).
* @param id The ID to look up.
*/
getINode(tx, p, id) {
const inode = tx.get(id);
if (inode === undefined) {
throw FileError.ENOENT(p);
}
return Inode.fromBuffer(inode);
}
/**
* Given the Inode of a directory, retrieves the corresponding directory
* listing.
*/
getDirListing(tx, p, inode) {
if (!inode.isDirectory()) {
throw FileError.ENOTDIR(p);
}
const data = tx.get(inode.id);
if (data === undefined) {
throw FileError.ENOENT(p);
}
return JSON.parse(data.toString());
}
/**
* Creates a new node under a random ID. Retries 5 times before giving up in
* the exceedingly unlikely chance that we try to reuse a random GUID.
* @return The GUID that the data was stored under.
*/
addNewNode(tx, data) {
const retries = 0;
let currId;
while (retries < 5) {
try {
currId = GenerateRandomID();
tx.put(currId, data, false);
return currId;
}
catch (e) {
// Ignore and reroll.
}
}
throw new FileError(ErrorCodes.EIO, 'Unable to commit data to key-value store.');
}
/**
* Commits a new file (well, a FILE or a DIRECTORY) to the file system with
* the given mode.
* Note: This will commit the transaction.
* @param p The path to the new file.
* @param type The type of the new file.
* @param mode The mode to create the new file with.
* @param data The data to store at the file's data node.
* @return The Inode for the new file.
*/
commitNewFile(tx, p, type, mode, data) {
const parentDir = paths.dirname(p), fname = paths.basename(p), parentNode = this.findINode(tx, parentDir), dirListing = this.getDirListing(tx, parentDir, parentNode), currTime = (new Date()).getTime();
// Invariant: The root always exists.
// If we don't check this prior to taking steps below, we will create a
// file with name '' in root should p == '/'.
if (p === '/') {
throw FileError.EEXIST(p);
}
// Check if file already exists.
if (dirListing[fname]) {
throw FileError.EEXIST(p);
}
let fileNode;
try {
// Commit data.
const dataId = this.addNewNode(tx, data);
fileNode = new Inode(dataId, data.length, mode | type, currTime, currTime, currTime);
// Commit file node.
const fileNodeId = this.addNewNode(tx, fileNode.toBuffer());
// Update and commit parent directory listing.
dirListing[fname] = fileNodeId;
tx.put(parentNode.id, Buffer.from(JSON.stringify(dirListing)), true);
}
catch (e) {
tx.abort();
throw e;
}
tx.commit();
return fileNode;
}
/**
* Remove all traces of the given path from the file system.
* @param p The path to remove from the file system.
* @param isDir Does the path belong to a directory, or a file?
* @todo Update mtime.
*/
removeEntry(p, isDir) {
const tx = this.store.beginTransaction('readwrite'), parent = paths.dirname(p), parentNode = this.findINode(tx, parent), parentListing = this.getDirListing(tx, parent, parentNode), fileName = paths.basename(p);
if (!parentListing[fileName]) {
throw FileError.ENOENT(p);
}
// Remove from directory listing of parent.
const fileNodeId = parentListing[fileName];
delete parentListing[fileName];
// Get file inode.
const fileNode = this.getINode(tx, p, fileNodeId);
if (!isDir && fileNode.isDirectory()) {
throw FileError.EISDIR(p);
}
else if (isDir && !fileNode.isDirectory()) {
throw FileError.ENOTDIR(p);
}
try {
// Delete data.
tx.del(fileNode.id);
// Delete node.
tx.del(fileNodeId);
// Update directory listing.
tx.put(parentNode.id, Buffer.from(JSON.stringify(parentListing)), true);
}
catch (e) {
tx.abort();
throw e;
}
// Success.
tx.commit();
}
} |
JavaScript | class DummyEndpointLoadBalacer {
constructor(arn) {
this.loadBalancerArn = arn;
}
} |
JavaScript | class ImageLoadObserver extends Observer {
/**
* @inheritDoc
*/
observe( domRoot ) {
this.listenTo( domRoot, 'load', ( event, domEvent ) => {
const domElement = domEvent.target;
if ( this.checkShouldIgnoreEventFromTarget( domElement ) ) {
return;
}
if ( domElement.tagName == 'IMG' ) {
this._fireEvents( domEvent );
}
// Use capture phase for better performance (#4504).
}, { useCapture: true } );
}
/**
* Fires {@link module:engine/view/document~Document#event:layoutChanged} and
* {@link module:engine/view/document~Document#event:imageLoaded}
* if observer {@link #isEnabled is enabled}.
*
* @protected
* @param {Event} domEvent The DOM event.
*/
_fireEvents( domEvent ) {
if ( this.isEnabled ) {
this.document.fire( 'layoutChanged' );
this.document.fire( 'imageLoaded', domEvent );
}
}
} |
JavaScript | class Token {
/**
* Returns true if obj represents an unresolved value
*
* One of these must be true:
*
* - `obj` is an IResolvable
* - `obj` is a string containing at least one encoded `IResolvable`
* - `obj` is either an encoded number or list
*
* This does NOT recurse into lists or objects to see if they
* containing resolvables.
*
* @param obj The object to test.
*/
static isUnresolved(obj) {
return encoding_1.unresolved(obj);
}
/**
* Return a reversible string representation of this token
*
* If the Token is initialized with a literal, the stringified value of the
* literal is returned. Otherwise, a special quoted string representation
* of the Token is returned that can be embedded into other strings.
*
* Strings with quoted Tokens in them can be restored back into
* complex values with the Tokens restored by calling `resolve()`
* on the string.
*/
static asString(value, options = {}) {
if (typeof value === 'string') {
return value;
}
return token_map_1.TokenMap.instance().registerString(Token.asAny(value), options.displayHint);
}
/**
* Return a reversible number representation of this token
*/
static asNumber(value) {
if (typeof value === 'number') {
return value;
}
return token_map_1.TokenMap.instance().registerNumber(Token.asAny(value));
}
/**
* Return a reversible list representation of this token
*/
static asList(value, options = {}) {
if (Array.isArray(value) && value.every(x => typeof x === 'string')) {
return value;
}
return token_map_1.TokenMap.instance().registerList(Token.asAny(value), options.displayHint);
}
/**
* Return a resolvable representation of the given value
*/
static asAny(value) {
return isResolvableObject(value) ? value : new intrinsic_1.Intrinsic(value);
}
constructor() {
}
} |
JavaScript | class Tokenization {
/**
* Un-encode a string potentially containing encoded tokens
*/
static reverseString(s) {
return token_map_1.TokenMap.instance().splitString(s);
}
/**
* Un-encode a Tokenized value from a number
*/
static reverseNumber(n) {
return token_map_1.TokenMap.instance().lookupNumberToken(n);
}
/**
* Un-encode a Tokenized value from a list
*/
static reverseList(l) {
return token_map_1.TokenMap.instance().lookupList(l);
}
/**
* Resolves an object by evaluating all tokens and removing any undefined or empty objects or arrays.
* Values can only be primitives, arrays or tokens. Other objects (i.e. with methods) will be rejected.
*
* @param obj The object to resolve.
* @param options Prefix key path components for diagnostics.
*/
static resolve(obj, options) {
return resolve_1.resolve(obj, {
scope: options.scope,
resolver: options.resolver,
preparing: (options.preparing !== undefined ? options.preparing : false),
});
}
/**
* Return whether the given object is an IResolvable object
*
* This is different from Token.isUnresolved() which will also check for
* encoded Tokens, whereas this method will only do a type check on the given
* object.
*/
static isResolvable(obj) {
return isResolvableObject(obj);
}
/**
* Stringify a number directly or lazily if it's a Token. If it is an object (i.e., { Ref: 'SomeLogicalId' }), return it as-is.
*/
static stringifyNumber(x) {
// only convert numbers to strings so that Refs, conditions, and other things don't end up synthesizing as [object object]
if (Token.isUnresolved(x)) {
return lazy_1.Lazy.stringValue({ produce: context => {
const resolved = context.resolve(x);
return typeof resolved !== 'number' ? resolved : `${resolved}`;
} });
}
else {
return typeof x !== 'number' ? x : `${x}`;
}
}
constructor() {
}
} |
JavaScript | class Game {
constructor() {
console.log("Game Started");
this.canvas = document.getElementById("canvas");
this.ctx = canvas.getContext('2d');
this.audio = document.getElementById("audio")
this.audio.loop = true;
this.canvas.width = 960;
this.canvas.height = 640;
this.keys = [];
this.paused = false;
this.debug = false;
// this.background = new background();
// this.map = new map(this.chunks);
this.maincharacter = new sprite(this.canvas.width / 2, this.canvas.height / 2, "content/img/joe-jr.png", 460, 600, 10);
let requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
}
render() {
if(this.debug) {
console.log("Render Frame")
}
// Get Arrow Key Inputs
let left = this.keys[37];
let right = this.keys[39];
let up = this.keys[38];
let down = this.keys[40];
// Reset Frame
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Perform Actions
this.maincharacter.move(left, right, up, down);
// Draw Map
// this.map.draw(this.ctx, this.canvas.width, this.canvas.height, 4);
// Draw Sprites
this.maincharacter.draw(this.ctx);
// Draw Health Bar
this.ctx.font = "small-caps 10px 'Press Start 2P'";
this.ctx.fillStyle = "white";
this.ctx.textBaseline = "top";
this.ctx.fillText("HEALTH", 10, 9);
this.ctx.fillStyle = "red";
this.ctx.fillRect(78, 11, 40, 5);
// If Not Paused Next Frame
if (!this.paused) {
requestAnimationFrame(() => this.render());
}
}
reset() {
this.maincharacter.xcoordinate = this.canvas.width / 2;
this.maincharacter.ycoordinate = this.canvas.height / 2;
var promise = this.audio.load();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
}
start() {
var promise = this.audio.play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
window.addEventListener("keyup", (e) => {
this.keyup(e.keyCode);
});
window.addEventListener("keydown", (e) => {
this.keydown(e.keyCode);
});
this.paused = false;
// Start rendering
requestAnimationFrame(() => this.render());
}
stop() {
var promise = this.audio.pause();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
window.addEventListener("keyup", (e) => {
this.keyup(e.keyCode);
});
window.addEventListener("keydown", (e) => {
this.keydown(e.keyCode);
});
this.paused = true
}
keyup(keyCode) {
this.keys[keyCode] = false;
}
keydown(keyCode) {
this.keys[keyCode] = true;
}
} |
JavaScript | class InstructionMajorVersionVerifier {
/**
* @param {ClassInfo} classInfo
*/
constructor(classInfo) {
/**
* @private
* @type {ClassInfo}
*/
this.classInfo = classInfo;
/**
* @private
* @type {Array<Number>}
*/
this.unusableOpcodes = this.findUnusableOpcodes();
}
/**
* Finds all opcodes with a version higher than the {@link ClassInfo} object
* being verified.
*
* Checks against {@link Opcodes.OPCODE_VERSIONS}
* @return {Array<Number>} flat array of opcodes that are not available in
* the Java SE runtime of the JVM Class File.
*/
findUnusableOpcodes() {
return _.flatten(_.filter(OPCODE_VERSIONS, (opcodes, version) => (version > this.classInfo.major)));
}
/**
* Finds the intersection between the unusable opcodes and the opcodes
* present in {@link MethodInfo.instructions}.
* @param {MethodInfo} method
* @return {Array<Number>}
*/
findInvalidMethodOpcodes(method) {
let opcodes = _.pluck(method.instructions, 'opcode');
return _.intersection(opcodes, this.unusableOpcodes);
}
/**
* Determines if the {@link ClassInfo} object only has opcodes that are
* usable for the given Java SE runtime.
* @return {Boolean}
*/
verify() {
return _.every(this.classInfo.methods, (method) => {
let invalid = this.findInvalidMethodOpcodes(method);
if (invalid.length > 0) {
throw WritingErrors.UnsupportedOpcode(unusable[0], this.classInfo, method);
}
return true;
});
}
} |
JavaScript | class InputSpec {
constructor(args) {
this.dtype = args.dtype;
this.shape = args.shape;
/*
TODO(michaelterry): Could throw error if ndim and shape are both defined
(then backport).
*/
if (args.shape != null) {
this.ndim = args.shape.length;
}
else {
this.ndim = args.ndim;
}
this.maxNDim = args.maxNDim;
this.minNDim = args.minNDim;
this.axes = args.axes || {};
}
} |
JavaScript | class Node {
constructor(args,
// TODO(michaelterry): Define actual type for this.
callArgs) {
this.callArgs = callArgs;
this.id = _nextNodeID++;
/*
Layer instance (NOT a list).
this is the layer that takes a list of input tensors
and turns them into a list of output tensors.
the current node will be added to
the inboundNodes of outboundLayer.
*/
this.outboundLayer = args.outboundLayer;
/*
The following 3 properties describe where
the input tensors come from: which layers,
and for each layer, which node and which
tensor output of each node.
*/
// List of layer instances.
this.inboundLayers = args.inboundLayers;
// List of integers, 1:1 mapping with inboundLayers.
this.nodeIndices = args.nodeIndices;
// List of integers, 1:1 mapping with inboundLayers.
this.tensorIndices = args.tensorIndices;
/*
Following 2 properties:
tensor inputs and outputs of outboundLayer.
*/
// List of tensors. 1:1 mapping with inboundLayers.
this.inputTensors = args.inputTensors;
// List of tensors, created by outboundLayer.call().
this.outputTensors = args.outputTensors;
/*
Following 2 properties: input and output masks.
List of tensors, 1:1 mapping with inputTensor.
*/
this.inputMasks = args.inputMasks;
// List of tensors, created by outboundLayer.computeMask().
this.outputMasks = args.outputMasks;
// Following 2 properties: input and output shapes.
// List of shape tuples, shapes of inputTensors.
this.inputShapes = args.inputShapes;
// List of shape tuples, shapes of outputTensors.
this.outputShapes = args.outputShapes;
// Add nodes to all layers involved.
for (const layer of args.inboundLayers) {
if (layer != null) {
layer.outboundNodes.push(this);
}
}
args.outboundLayer.inboundNodes.push(this);
}
getConfig() {
const inboundNames = [];
for (const layer of this.inboundLayers) {
if (layer != null) {
inboundNames.push(layer.name);
}
else {
inboundNames.push(null);
}
}
return {
outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
inboundLayers: inboundNames,
nodeIndices: this.nodeIndices,
tensorIndices: this.tensorIndices
};
}
} |
JavaScript | class ChangePasswordDialog extends Dialog {
_checkSamePass() {
const $pass = this.$control("pass");
const $problem = this.$control("problem");
const p = $pass.val(),
c = this.$control("conf").val();
const ok = (p !== "" && p === c);
if (p === "")
$problem.text(this.tx("Password may not be empty"));
else if (p !== c)
$problem.text(this.tx("Passwords do not match"));
$problem.toggle(!ok);
this.$control("ok").toggle(ok);
return ok;
}
initialise() {
const chk = this._checkSamePass.bind(this);
this.$control("pass")
.simulated_password()
.on("input", chk)
.on("change", chk);
this.$control("conf")
.simulated_password()
.on("input", chk)
.on("change", chk);
}
ok() {
return this.$control("pass").val();
}
open() {
this.$control("pass").val(this.options.encryption_pass());
this._checkSamePass();
}
} |
JavaScript | class RequestOptions {
constructor({ method, headers, body, url, search } = {}) {
this.method = isPresent(method) ? normalizeMethodName(method) : null;
this.headers = isPresent(headers) ? headers : null;
this.body = isPresent(body) ? body : null;
this.url = isPresent(url) ? url : null;
this.search = isPresent(search) ? (isString(search) ? new URLSearchParams((search)) :
(search)) :
null;
}
/**
* Creates a copy of the `RequestOptions` instance, using the optional input as values to override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* Note that `headers` and `search` will override existing values completely if present in
* the `options` object. If these values should be merged, it should be done prior to calling
* `merge` on the `RequestOptions` instance.
*
* ### Example ([live demo](http://plnkr.co/edit/6w8XA8YTkDRcPYpdB9dk?p=preview))
*
* ```typescript
* import {RequestOptions, Request, RequestMethod} from 'angular2/http';
*
* var options = new RequestOptions({
* method: RequestMethod.Post
* });
* var req = new Request(options.merge({
* url: 'https://google.com'
* }));
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // null
* console.log('req.url:', req.url); // https://google.com
* ```
*/
merge(options) {
return new RequestOptions({
method: isPresent(options) && isPresent(options.method) ? options.method : this.method,
headers: isPresent(options) && isPresent(options.headers) ? options.headers : this.headers,
body: isPresent(options) && isPresent(options.body) ? options.body : this.body,
url: isPresent(options) && isPresent(options.url) ? options.url : this.url,
search: isPresent(options) && isPresent(options.search) ?
(isString(options.search) ? new URLSearchParams((options.search)) :
(options.search).clone()) :
this.search
});
}
} |
JavaScript | class BackendRequests {
constructor(config) {
this.config = config;
this.logger = config.logger;
// FSPID of THIS DFSP
this.dfspId = config.dfspId;
this.agent = http.globalAgent;
this.transportScheme = 'http';
// Switch or peer DFSP endpoint
this.backendEndpoint = `${this.transportScheme}://${config.backendEndpoint}`;
}
/**
* Executes a GET /parties request for the specified identifier type and identifier
*
* @returns {object} - JSON response body if one was received
*/
async getParties(idType, idValue, idSubValue) {
const url = `parties/${idType}/${idValue}`
+ (idSubValue ? `/${idSubValue}` : '');
return this._get(url, 'parties');
}
/**
* Executes a POST /quotes request for the specified quote request
*
* @returns {object} - JSON response body if one was received
*/
async postQuoteRequests(quoteRequest) {
return this._post('quoterequests', quoteRequest);
}
/**
* Executes a POST /transfers request for the specified transfer prepare
*
* @returns {object} - JSON response body if one was received
*/
async postTransfers(prepare) {
return this._post('transfers', prepare);
}
/**
* Executes a POST /transactionRequests request for the specified transaction request
*
* @returns {object} - JSON response body if one was received
*/
async postTransactionRequests(transactionRequest) {
return this._post('transactionrequests', transactionRequest);
}
/**
* Utility function for building outgoing request headers as required by the mojaloop api spec
*
* @returns {object} - headers object for use in requests to mojaloop api endpoints
*/
_buildHeaders () {
let headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Date': new Date().toUTCString()
};
return headers;
}
async _get(url) {
const reqOpts = {
method: 'GET',
uri: buildUrl(this.backendEndpoint, url),
headers: this._buildHeaders(),
agent: this.agent,
resolveWithFullResponse: true,
simple: false
};
// Note we do not JWS sign requests with no body i.e. GET requests
try {
this.logger.push({ reqOpts }).log('Executing HTTP GET');
return await request(reqOpts).then(throwOrJson);
}
catch (e) {
this.logger.push({ e }).log('Error attempting HTTP GET');
throw e;
}
}
async _put(url, body) {
const reqOpts = {
method: 'PUT',
uri: buildUrl(this.backendEndpoint, url),
headers: this._buildHeaders(),
body: JSON.stringify(body),
resolveWithFullResponse: true,
simple: false,
};
try {
this.logger.push({ reqOpts }).log('Executing HTTP PUT');
return await request(reqOpts).then(throwOrJson);
}
catch (e) {
this.logger.push({ e }).log('Error attempting HTTP PUT');
throw e;
}
}
async _post(url, body) {
const reqOpts = {
method: 'POST',
uri: buildUrl(this.backendEndpoint, url),
headers: this._buildHeaders(),
body: JSON.stringify(body),
resolveWithFullResponse: true,
simple: false,
};
try {
this.logger.push({ reqOpts }).log('Executing HTTP POST');
return await request(reqOpts).then(throwOrJson);
}
catch (e) {
this.logger.push({ e }).log('Error attempting POST.');
throw e;
}
}
} |
JavaScript | class MochaDotsReporter extends Base {
constructor(runner) {
super(runner);
let wrapCounter = 0;
const printDot = (dot) => {
process.stdout.write(dot);
if (++wrapCounter >= nbDotsPerLine) {
wrapCounter = 0;
process.stdout.write('\n');
}
};
runner
.once(EVENT_RUN_BEGIN, () => {
log('Running tests...');
})
.on(EVENT_TEST_PASS, () => {
printDot(green(icon.success));
})
.on(EVENT_TEST_FAIL, () => {
printDot(red(icon.failure));
})
.on(EVENT_TEST_PENDING, () => {
printDot(yellow(icon.ignore));
})
.once(EVENT_RUN_END, () => {
Base.list(this.failures);
const {passes, pending, failures, tests} = runner.stats;
logWithoutTimestamp(
`Executed ${failures + passes} of ${tests}`,
`(Skipped ${pending})`,
failures == 0 ? green('SUCCESS') : red(`${failures} FAILED`)
);
reportTestFinished(passes, failures);
});
}
} |
JavaScript | class Postgresql {
constructor(config) {
this.config = config;
this.TYPES = [
'bigint',
'bigserial',
'bit',
'bit varying',
'boolean',
'box',
'bytea',
'character',
'character varying',
'cidr',
'circle',
'date',
'double precision',
'inet',
'integer',
'interval',
'json',
'jsonb',
'line',
'lseg',
'macaddr',
'money',
'numeric',
'path',
'pg_lsn',
'point',
'polygon',
'real',
'smallint',
'smallserial',
'serial',
'text',
'time',
'time without time zone',
'time with time zone',
'timestamp',
'timestamp without time zone',
'timestamp with time zone',
'tsquery',
'tsvector',
'txid_snapshot',
'uuid',
'xml'
];
}
/*
Creates a pool of connection against the Postgresql database.
*/
async createPool() {
this.pool = new Pool(this.config);
}
/*
Execute a query against the database.
*/
async query(statement, params) {
const result = await this.pool.query(statement, params);
return result.rows;
}
/*
Execute a insert statement against the database.
*/
insert(statement) {
const sql = statement + ' returning *';
return this.query(sql);
}
/*
Execute a update statement against the database.
*/
update(statement) {
return this.query(statement);
}
/*
Returns a coalesce clause.
*/
isNull(value1, value2) {
return 'Coalesce(' + value1 + ', ' + value2 + ')';
}
/*
Returns a date-formatted value.
*/
toDateValue(value) {
if (!value) {
return 'null';
}
return value;
}
getTableName(table){
const sql = `
select distinct TABLE_NAME from INFORMATION_SCHEMA.TABLES where LOWER(TABLE_NAME) = LOWER('${table}')
`;
return this.query(sql);
}
/*
Return the list of columns from a table.
*/
getColumns(table) {
const quotedTableName = `"${table}"`;
const sql = `
SELECT distinct c.TABLE_NAME as "TABLENAME", c.COLUMN_NAME as "COLUMN_NAME",
c.COLUMN_DEFAULT as "COLUMN_DEFAULT", c.DATA_TYPE as "DATA_TYPE",
c.CHARACTER_MAXIMUM_LENGTH as "CHARACTER_MAXIMUM_LENGTH",
c.NUMERIC_PRECISION as "NUMERIC_PRECISION", c.NUMERIC_PRECISION_RADIX as "NUMERIC_PRECISION_RADIX",
c.NUMERIC_SCALE as "NUMERIC_SCALE", c.DATETIME_PRECISION as "DATETIME_PRECISION",
case when pk.Column_Name = c.COLUMN_NAME then 1 else null end "primaryKey",
case when pg_get_serial_sequence('${quotedTableName}',c.COLUMN_NAME) is null then 1 else 0 end as insertable
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.TABLES t on t.table_schema = c.table_schema
LEFT JOIN (
SELECT Col.Table_Name, Col.Column_Name
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
where Col.Table_Name = '${table}' and Tab.TABLE_NAME = '${table}'
and Tab.Constraint_Type in ('PRIMARY KEY', 'PK_%')
and Tab.CONSTRAINT_NAME = Col.CONSTRAINT_NAME
) pk on pk.Table_Name = '${table}'
WHERE c.TABLE_NAME = '${table}'
`;
return this.query(sql);
}
/*
Close database connection.
*/
disconnect() {
this.pool.end();
}
} |
JavaScript | class SimpleFileCache {
/**
* Constructs a new cache and loads any date from the cache file.
*
* @param {String} cachePathAndFilename Absolute path and filename to the cache file
*/
constructor(cachePathAndFilename) {
this.cachePathAndFilename = cachePathAndFilename;
try {
this.data = fs.existsSync(cachePathAndFilename) ? JSON.parse(fs.readFileSync(cachePathAndFilename)) : {};
} catch (e) {
fs.unlinkSync(cachePathAndFilename);
this.data = {};
}
}
/**
* Gets an entry from this cache identfied by key.
* @param {object} key cache key
* @return {object|null}
*/
get(key) {
return this.has(key) ? this.data[key] : null;
}
/**
* Sets an entry in this cache, overwriting any existing data.
*
* This only happens in-memory, call the persist() method to make sure the
* changes will be persisted to disk.
*
* @param {String} key Key to idenfitify the data
* @param {Object} data The data to store
*/
set(key, data) {
this.data[key] = data;
}
/**
* Checks if this cache contains an entry for the specified key.
*
* @param {String} key The key to check for
* @return {boolean}
*/
has(key) {
return this.data.hasOwnProperty(key);
}
/**
* Returns all keys that are currently in this cache.
* @return {object[]}
*/
keys() {
return Object.keys(this.data);
}
/**
* Removes the cache entry identified by key from this cache.
*
* This only happens in-memory, call the persist() method to make sure the
* changes will be persisted to disk.
*
* @param {String} key The key to remove
*/
remove(key) {
if (this.has(key)) {
delete this.data[key];
}
}
/**
* Removes all data from this cache
*
* This only happens in-memory, call the persist() method to make sure the
* changes will be persisted to disk.
*/
flush() {
this.data = {};
}
/**
* Persists the current state of this cache to disk.
*/
persist() {
var dataToWrite = JSON.stringify(this.data);
const dir = path.dirname(this.cachePathAndFilename);
fs.ensureDirSync(dir);
fs.writeFileSync(this.cachePathAndFilename, dataToWrite);
}
} |
JavaScript | class StudentService {
students;
static get $inject() { return ['$http', '$q', 'SchoolGPAService']; }
constructor ($http, $q, SchoolGPAService) {
this.$http = $http;
this.$q = $q;
this.SchoolGPAService = SchoolGPAService;
}
getCachedStudents = () => {
const deferred = this.$q.defer();
if (this.students) {
deferred.resolve(this.students);
} else {
this.$http.get('app/pages/schoolGPA/stabs/students.json').then((studentsResponse) => {
this.students = studentsResponse.data || [];
this.SchoolGPAService.recalculateAverageGPAByStudentsArray(this.students);
deferred.resolve(this.students);
}, (error) => deferred.reject(error));
}
return deferred.promise;
}
create = (gradeId, student) => {
const deferred = this.$q.defer();
this.getCachedStudents().then(() => {
const id = Date.now();
this.students.unshift({...student, id, gradeId});
this.SchoolGPAService.onStudentAdded(student.gpa, this.students.length);
deferred.resolve(id);
});
return deferred.promise;
}
list = (gradeId, max, offset) => {
const deferred = this.$q.defer();
this.getCachedStudents().then((students) => {
// Creating copy of array by [].concat( ... ) to prevent changing of cache from outside
deferred.resolve([].concat(students.filter((student) => student.gradeId === gradeId).slice(offset, offset + max)));
}, (error) => deferred.reject(error));
return deferred.promise;
}
delete = (studentId) => {
const deferred = this.$q.defer();
this.getCachedStudents().then(() => {
const index = this.students.findIndex((student) => student.id === studentId);
if (index === -1) {
deferred.reject('Not found');
} else {
const removedStudent = this.students[index];
this.students.splice(index, 1);
this.SchoolGPAService.onStudentRemoved(removedStudent.gpa, this.students.length);
deferred.resolve();
}
});
return deferred.promise;
}
deleteByGradeId = (gradeId) => {
this.students = this.students.filter((student) => student.gradeId !== gradeId);
this.SchoolGPAService.recalculateAverageGPAByStudentsArray(this.students);
}
} |
JavaScript | class Letter {
constructor(letter, pos) {
this.DOM = {};
this.DOM.letter = letter;
this.CONFIG = {
triggerProgress: 15
};
this.pos = pos;
this.layout();
this.initEvents();
}
layout() {
this.DOM.letterInner = document.createElement('span');
this.DOM.letterInner.innerHTML = this.DOM.letter.innerHTML;
this.DOM.letterInner.style.transformOrigin = '50% 100%';
this.DOM.letter.innerHTML = '';
this.DOM.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
this.DOM.svg.setAttribute('width', '100px');
this.DOM.svg.setAttribute('height', '150px');
this.DOM.svg.setAttribute('viewBox', '0 0 100 150');
this.DOM.svg.setAttribute('preserveAspectRatio', 'xMaxYMin meet');
for (let i = 0; i < 3; i++) {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('width', 15);
rect.setAttribute('height', 15);
rect.setAttribute('x', 12+i*30);
rect.setAttribute('y', 12);
this.DOM.svg.appendChild(rect);
};
this.DOM.rects = Array.from(this.DOM.svg.querySelectorAll('rect'));
this.DOM.letter.appendChild(this.DOM.svg);
this.DOM.letter.appendChild(this.DOM.letterInner);
}
initEvents() {
this.mousedownFn = () => this.mouseTimeout = setTimeout(() => {
if( this.isActive || this.isAnimating ) return;
this.isActive = true;
anime.remove(this.DOM.letterInner);
anime({
targets: this.DOM.letterInner,
duration: 1500,
easing: 'easeOutExpo',
scaleX: 1.2,
scaleY: 0.4,
update: (a) => {
this.currentProgress = a.progress;
if ( this.currentProgress > this.CONFIG.triggerProgress && !this.isShaking ) {
this.isShaking = true;
anime.remove(this.DOM.letter);
anime({
targets: this.DOM.letter,
duration: 100,
easing: 'linear',
loop: true,
translateX: [{value:-1},{value:1}],
translateY: [{value:-1},{value:1}]
});
}
}
});
}, 50);
this.mouseupFn = () => {
clearTimeout(this.mouseTimeout);
if( !this.isActive || this.isAnimating ) return;
this.isActive = false;
this.isAnimating = true;
anime.remove(this.DOM.letter);
this.isShaking = false;
anime.remove(this.DOM.letterInner);
if ( this.currentProgress > this.CONFIG.triggerProgress ) {
const durationUp = lineEq(80,300,100,this.CONFIG.triggerProgress,this.currentProgress);
const durationDown = lineEq(80,500,100,this.CONFIG.triggerProgress,this.currentProgress);
anime({
targets: this.DOM.letterInner,
translateY: [
{
value: (t) => {
const bcr = t.getBoundingClientRect();
return -1*bcr.top - bcr.height;
},
duration: durationUp,
easing: 'easeInExpo'
},
{
value: (t) => {
const bcr = t.getBoundingClientRect();
return [bcr.top + bcr.height,0];
},
duration: durationDown,
easing: 'easeOutExpo'
}
],
scaleY: [
{
value: 2.8,
duration: durationUp,
easing: 'easeInExpo'
},
{
value: [2.8,1],
duration: durationDown+500,
elasticity: 300
}
],
scaleX: [
{
value: 0.5,
duration: durationUp,
easing: 'easeInExpo'
},
{
value: [0.5,1],
duration: durationDown+500,
elasticity: 300
}
],
transformOrigin: [
{
value: '50% 100%',
duration: 1
},
{
value: '50% 0%',
delay: durationUp,
duration: 1
},
{
value: '50% 100%',
delay: durationDown+500,
duration: 1
}
],
complete: () => { this.isAnimating = false; }
});
let allLettersFiltered = allLetters.filter((el, pos) => {return pos != this.pos});
anime.remove(allLettersFiltered);
anime({
targets: allLettersFiltered,
duration: 200,
easing: 'easeOutQuad',
translateY: [
{
value: [0,-30],
delay: (t,i) => {
let j = i >= this.pos ? i+1 : i;
return 60*(Math.abs(this.pos-j))+durationUp/2;
}
},
{
value: 0,
duration: 800,
easing: 'easeOutElastic'
}
]
});
anime.remove(this.DOM.rects);
anime({
targets: this.DOM.rects,
duration: durationUp,
delay: durationUp/2,
easing: 'easeOutQuint',
opacity: [
{value: 1, duration: 10, easing: 'linear'},
{value: 0, duration: durationUp-10, easing: 'linear'}
],
translateY: (t,i) => { return [-100, anime.random(100,250)]; },
scaleX: [0.5,0.5],
scaleY: () => { return [1, anime.random(3,10)]; }
});
}
else {
anime({
targets: this.DOM.letterInner,
duration: lineEq(1000,300,this.CONFIG.triggerProgress,0,this.currentProgress),
easing: 'easeOutExpo',
scaleX: 1,
scaleY: 1,
complete: () => { this.isAnimating = false; }
});
}
};
this.DOM.letter.addEventListener('mousedown', this.mousedownFn);
this.DOM.letter.addEventListener('mouseup', this.mouseupFn);
this.DOM.letter.addEventListener('mouseleave', this.mouseupFn);
this.DOM.letter.addEventListener('touchstart', this.mousedownFn);
this.DOM.letter.addEventListener('touchend', this.mouseupFn);
}
} |
JavaScript | class Word {
constructor(word) {
this.DOM = {};
this.DOM.word = word;
this.layout();
}
layout() {
charming(this.DOM.word, {classPrefix: 'letter'});
Array.from(this.DOM.word.querySelectorAll('span')).forEach((letter,pos) => {
new Letter(letter, pos);
allLetters.push(letter);
});
}
} |
JavaScript | class JointComponentSystem extends ComponentSystem {
/**
* Create a new JointComponentSystem instance.
*
* @param {Application} app - The application.
*/
constructor(app) {
super(app);
this.id = 'joint';
this.app = app;
this.ComponentType = JointComponent;
this.DataType = JointComponentData;
this.schema = _schema;
}
initializeComponentData(component, data, properties) {
component.initFromData(data);
}
} |
JavaScript | class EmptyRoutes extends Error {
constructor(name) {
super()
this.name = 'No routes provided.'
this.message = `${name} root does not provide routes.`
}
} |
JavaScript | class Base64Encoder extends Encoder {
/**
* Returns brick meta.
* @return {object}
*/
static getMeta () {
return meta
}
/**
* Constructor
*/
constructor () {
super()
this.addSettings([
{
name: 'variant',
type: 'enum',
value: variants[0].name,
elements: variants.map(variant => variant.name),
labels: variants.map(variant => variant.label),
descriptions: variants.map(variant => variant.description),
randomizable: false
},
{
name: 'alphabet',
type: 'text',
value: variants[0].alphabet,
uniqueChars: true,
minLength: 64,
maxLength: 64,
caseSensitivity: true,
visible: false
},
{
name: 'padding',
type: 'text',
value: '=',
blacklistChars: variants[0].alphabet,
minLength: 1,
maxLength: 1,
randomizable: false,
visible: false,
width: 6
},
{
name: 'paddingOptional',
type: 'boolean',
value: false,
randomizable: false,
visible: false,
width: 6
}
])
}
/**
* Performs encode on given content.
* @protected
* @param {Chain} content
* @return {number[]|string|Uint8Array|Chain} Encoded content
*/
performEncode (content) {
// Forward request to the internal byte encoder
return ByteEncoder.base64StringFromBytes(
content.getBytes(),
this.getVariantOptions())
}
/**
* Performs decode on given content.
* @protected
* @param {Chain} content
* @return {number[]|string|Uint8Array|Chain} Decoded content
*/
performDecode (content) {
// Forward request to the internal byte encoder
return ByteEncoder.bytesFromBase64String(
content.getString(),
this.getVariantOptions())
}
/**
* Triggered when a setting field has changed.
* @protected
* @param {Field} setting Sender setting field
* @param {mixed} value New field value
*/
settingValueDidChange (setting, value) {
switch (setting.getName()) {
case 'variant': {
// Make alphabet and padding settings available with the custom variant
this.getSetting('alphabet').setVisible(value === 'custom')
this.getSetting('padding').setVisible(value === 'custom')
this.getSetting('paddingOptional').setVisible(value === 'custom')
break
}
case 'alphabet': {
// Alphabet characters are not allowed to be used as padding
this.getSetting('padding').setBlacklistChars(value)
break
}
}
}
/**
* Returns the current variant options.
* @return {object} Variant options
*/
getVariantOptions () {
const name = this.getSettingValue('variant')
if (name === 'custom') {
// Compose custom options
return {
alphabet: this.getSettingValue('alphabet').getString(),
padding: this.getSettingValue('padding').getCharAt(0),
paddingOptional: this.getSettingValue('paddingOptional')
}
}
// Find variant options
return variants.find(variant => variant.name === name)
}
} |
JavaScript | class Book {
constructor() {
this.id = -1;
this.attr = [];
this.rating = -1;
this.asin = -1;
this.amazonURL = '';
this.imageURL = '';
this.title = '';
this.author = '';
this.description = '';
this.user_id = -1;
}
copy(other) {
for(a in other) {
this[a] = other[a];
}
}
addAttribute(id1, val1, id2, val2, id3, val3) {
this.attributes.push({
id: id1,
val: val1
});
this.attributes.push({
id: id2,
val: val2
});
this.attributes.push({
id: id3,
val: val3
});
}
/*//Construct a book with information from the database
static async fromDatabase(id) {
let result = await post('book', id);
return result;
}*/
} |
JavaScript | class Key {
constructor(key, action) {
this.key = key.toLowerCase()
this.action = action
}
_act() {
this.action()
if (this.gui !== undefined) {
this.gui.update()
}
}
format() {
let code = $.cel("code")
let text = $.ctn(this.key.toUpperCase())
code.appendChild(text)
code.onclick = () => this._act()
return code
}
} |
JavaScript | class Engine {
constructor(cfg) {
cfg = cfg || {};
if (!cfg.api) {
throw new Error(ERROR_API_UNDEFIEND);
}
if (!cfg.service) {
throw new Error(ERROR_SVC_UNDEFIEND);
}
let me = this;
me.cfg = null;
me.isWSAPI = false;
me.isWebChannel = false;
me.isSockChannel = false;
me.Security = null;
me.Generator = null;
me.WebChannel = null;
me.SocketChannel = null;
me.cfg = cfg;
me.isWSAPI = cfg.api === cfg.service && cfg.api.indexOf('ws') == 0;
me.isWebChannel = cfg.service.indexOf('http') === 0;
me.isSockChannel = cfg.service.indexOf('ws') === 0;
if ((me.isWebChannel || me.isSockChannel) === false) {
throw new Error(ERROR_MESSAGE);
}
}
/*
* Initialize engine, throws error,
*/
async init() {
let me = this;
if (me.isActive) return;
me.Security = new Security();
me.Generator = new Generator();
if (me.isWebChannel || me.isWSAPI == false) {
me.WebChannel = new WebChannel();
await me.WebChannel.init(me);
}
if (me.isSockChannel) {
me.SocketChannel = new SocketChannel();
await me.SocketChannel.init(me);
}
}
/**
* Use internaly from channel to register received
* API definitiona and security data
*/
async registerAPI(data) {
let me = this;
// initialize encryption if provided
if (data.signature) {
if (!me.Security.isActive) {
await me.Security.init(data);
}
}
me.Generator.build(data.api);
}
/**
* Stop engine instance by clearing all references
* stoping listeners, stoping socket is avaialble
*/
stop() {
let me = this;
if (me.WebChannel) me.WebChannel.stop();
if (me.SocketChannel) me.SocketChannel.stop();
if (me.Generator) me.Generator.stop();
me.WebChannel = null;
me.SocketChannel = null;
me.Generator = null;
me.Security = null;
me.cfg = null;
}
/*
* Return generated API
*/
get api() {
return this.Generator ? this.Generator.api : null;
}
/*
* Check if engine is active
*/
get isActive() {
return this.api && this.Security;
}
/*
* Return API URL address
*/
get apiURL() {
return this.cfg ? this.cfg.api : null;
}
/*
* Return Service URL address
*/
get serviceURL() {
return this.cfg ? this.cfg.service : null;
}
/*
* Static instance builder
*/
static async init(cfg) {
let engine = new Engine(cfg);
await engine.init();
return engine;
}
} |
JavaScript | class RootComponent extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Layout>
<Content>
<App/>
</Content>
</Layout>
</Provider>
);
}
} |
JavaScript | class TabHeader extends React.Component {
render() {
return <Grid
item
container
alignItems="center"
>
{ this.props.children }
</Grid>;
}
} |
JavaScript | class Webhook {
/**
* Constructs a new <code>Webhook</code>.
* @alias module:sunshine-conversations-client/sunshine-conversations-client.model/Webhook
* @param target {String} URL to be called when the webhook is triggered.
* @param triggers {Array.<String>} An array of triggers the integration is subscribed to. This property is case sensitive. [More details](https://docs.smooch.io/rest/#section/Webhook-Triggers).
*/
constructor(target, triggers) {
Webhook.initialize(this, target, triggers);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, target, triggers) {
obj['target'] = target;
obj['triggers'] = triggers;
}
/**
* Constructs a <code>Webhook</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:sunshine-conversations-client/sunshine-conversations-client.model/Webhook} obj Optional instance to populate.
* @return {module:sunshine-conversations-client/sunshine-conversations-client.model/Webhook} The populated <code>Webhook</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Webhook();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('version')) {
obj['version'] = ApiClient.convertToType(data['version'], 'String');
}
if (data.hasOwnProperty('target')) {
obj['target'] = ApiClient.convertToType(data['target'], 'String');
}
if (data.hasOwnProperty('triggers')) {
obj['triggers'] = ApiClient.convertToType(data['triggers'], ['String']);
}
if (data.hasOwnProperty('secret')) {
obj['secret'] = ApiClient.convertToType(data['secret'], 'String');
}
if (data.hasOwnProperty('includeFullUser')) {
obj['includeFullUser'] = ApiClient.convertToType(data['includeFullUser'], 'Boolean');
}
if (data.hasOwnProperty('includeFullSource')) {
obj['includeFullSource'] = ApiClient.convertToType(data['includeFullSource'], 'Boolean');
}
}
return obj;
}
/**
* Returns A unique identifier for the webhook.
* @return {String}
*/
getId() {
return this.id;
}
/**
* Sets A unique identifier for the webhook.
* @param {String} id A unique identifier for the webhook.
*/
setId(id) {
this['id'] = id;
}
/**
* Returns Schema version of the payload delivered to this webhook. Can be `v1`, `v1.1` or `v2`.
* @return {String}
*/
getVersion() {
return this.version;
}
/**
* Sets Schema version of the payload delivered to this webhook. Can be `v1`, `v1.1` or `v2`.
* @param {String} version Schema version of the payload delivered to this webhook. Can be `v1`, `v1.1` or `v2`.
*/
setVersion(version) {
this['version'] = version;
}
/**
* Returns URL to be called when the webhook is triggered.
* @return {String}
*/
getTarget() {
return this.target;
}
/**
* Sets URL to be called when the webhook is triggered.
* @param {String} target URL to be called when the webhook is triggered.
*/
setTarget(target) {
this['target'] = target;
}
/**
* Returns An array of triggers the integration is subscribed to. This property is case sensitive. [More details](https://docs.smooch.io/rest/#section/Webhook-Triggers).
* @return {Array.<String>}
*/
getTriggers() {
return this.triggers;
}
/**
* Sets An array of triggers the integration is subscribed to. This property is case sensitive. [More details](https://docs.smooch.io/rest/#section/Webhook-Triggers).
* @param {Array.<String>} triggers An array of triggers the integration is subscribed to. This property is case sensitive. [More details](https://docs.smooch.io/rest/#section/Webhook-Triggers).
*/
setTriggers(triggers) {
this['triggers'] = triggers;
}
/**
* Returns Webhook secret, used to verify the origin of incoming requests.
* @return {String}
*/
getSecret() {
return this.secret;
}
/**
* Sets Webhook secret, used to verify the origin of incoming requests.
* @param {String} secret Webhook secret, used to verify the origin of incoming requests.
*/
setSecret(secret) {
this['secret'] = secret;
}
/**
* Returns A boolean specifying whether webhook payloads should include the complete user schema for events involving a specific user.
* @return {Boolean}
*/
getIncludeFullUser() {
return this.includeFullUser;
}
/**
* Sets A boolean specifying whether webhook payloads should include the complete user schema for events involving a specific user.
* @param {Boolean} includeFullUser A boolean specifying whether webhook payloads should include the complete user schema for events involving a specific user.
*/
setIncludeFullUser(includeFullUser) {
this['includeFullUser'] = includeFullUser;
}
/**
* Returns A boolean specifying whether webhook payloads should include the client and device object (when applicable).
* @return {Boolean}
*/
getIncludeFullSource() {
return this.includeFullSource;
}
/**
* Sets A boolean specifying whether webhook payloads should include the client and device object (when applicable).
* @param {Boolean} includeFullSource A boolean specifying whether webhook payloads should include the client and device object (when applicable).
*/
setIncludeFullSource(includeFullSource) {
this['includeFullSource'] = includeFullSource;
}
} |
JavaScript | class Flowable {
static just(...values) {
return new Flowable(subscriber => {
let cancelled = false;
let i = 0;
subscriber.onSubscribe({
cancel: () => {
cancelled = true;
},
request: n => {
while (!cancelled && n > 0 && i < values.length) {
subscriber.onNext(values[i++]);
n--;
}
if (!cancelled && i == values.length) {
subscriber.onComplete();
}
},
});
});
}
static error(error) {
return new Flowable(subscriber => {
subscriber.onSubscribe({
cancel: () => {},
request: () => {
subscriber.onError(error);
},
});
});
}
static never() {
return new Flowable(subscriber => {
subscriber.onSubscribe({
cancel: _emptyFunction2.default,
request: _emptyFunction2.default,
});
});
}
constructor(source, max = Number.MAX_SAFE_INTEGER) {
this._max = max;
this._source = source;
}
subscribe(subscriberOrCallback) {
let partialSubscriber;
if (typeof subscriberOrCallback === 'function') {
partialSubscriber = this._wrapCallback(subscriberOrCallback);
} else {
partialSubscriber = subscriberOrCallback;
}
const subscriber = new FlowableSubscriber(partialSubscriber, this._max);
this._source(subscriber);
}
lift(onSubscribeLift) {
return new Flowable(subscriber =>
this._source(onSubscribeLift(subscriber)));
}
map(fn) {
return this.lift(
subscriber => new _FlowableMapOperator2.default(subscriber, fn)
);
}
take(toTake) {
return this.lift(
subscriber => new _FlowableTakeOperator2.default(subscriber, toTake)
);
}
_wrapCallback(callback) {
const max = this._max;
return {
onNext: callback,
onSubscribe(subscription) {
subscription.request(max);
},
};
}
} |
JavaScript | class SimpleDrawer extends SimpleColors {
//styles function
static get styles() {
return [
css`
:host {
display: block;
z-index: 1000;
}
:host([hidden]) {
display: none;
}
:host div::slotted(*) {
font-size: 14px;
}
.content {
text-align: left;
padding: 8px 24px;
}
.top ::slotted(*) {
font-size: 24px;
margin: 0;
padding: 0 15px;
height: 40px;
line-height: 48px;
}
#close {
position: absolute;
right: 8px;
top: 8px;
padding: 4px;
margin: 0;
text-transform: none;
float: right;
font-size: 12px;
color: var(--simple-drawer-header-color, #ffffff);
background-color: transparent;
min-width: unset;
}
#close iron-icon {
display: inline-block;
width: 16px;
height: 16px;
margin-right: 2px;
}
.top {
font-size: 24px;
margin: 0 0 8px 0;
padding: 0 16px;
height: 64px;
line-height: 64px;
display: flex;
text-align: left;
justify-content: space-between;
background-color: var(--simple-drawer-header-background, #20427b);
color: var(--simple-drawer-header-color, #ffffff);
}
.top h2 {
flex: auto;
color: var(--simple-drawer-header-color, #ffffff);
font-size: 24px;
padding: 0;
line-height: 32px;
margin: 8px;
}
`
];
}
// LitElement
render() {
return html`
<custom-style>
<style>
app-drawer {
--app-drawer-content-container: {
padding: 0;
overflow-y: scroll;
position: fixed;
color: var(--simple-drawer-color, #222222);
background-color: var(--simple-drawer-background-color, #ffffff);
}
}
:host ::slotted(*) {
@apply --simple-drawer-content;
}
.content {
@apply --simple-drawer-content-container;
}
.top {
@apply --simple-drawer-header;
}
.top h2 {
@apply --simple-drawer-heading;
}
</style>
</custom-style>
<app-drawer
tabindex="0"
id="drawer"
?opened="${this.opened}"
@opened-changed="${this.__openedChanged}"
.align="${this.align}"
role="dialog"
>
<div class="wrapper">
<div class="top">
${this.title
? html`
<h2>${this.title}</h2>
`
: ""}
<slot name="header"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
<paper-button id="close" @click="${this.close}">
<iron-icon icon="${this.closeIcon}"></iron-icon> ${this.closeLabel}
</paper-button>
</div>
</app-drawer>
`;
}
// properties available to the custom element for data binding
static get properties() {
return {
...super.properties,
/**
* heading / label of the modal
*/
title: {
name: "title",
type: String
},
/**
* alignment of the drawer
*/
align: {
name: "align",
type: String
},
/**
* open state
*/
opened: {
name: "opened",
type: Boolean,
reflect: true
},
/**
* Close label
*/
closeLabel: {
name: "closeLabel",
type: String
},
/**
* Close icon
*/
closeIcon: {
name: "closeIcon",
type: String
},
/**
* The element that invoked this. This way we can track our way back accessibly
*/
invokedBy: {
name: "invokedBy",
type: Object
}
};
}
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "simple-drawer";
}
/**
* HTMLElement
*/
constructor() {
super();
this.title = "";
this.align = "left";
this.opened = false;
this.closeLabel = "Close";
this.closeIcon = "icons:cancel";
}
/**
* LitElement life cycle - ready
*/
firstUpdated(changedProperties) {
window.addEventListener("simple-drawer-hide", this.close.bind(this));
window.addEventListener("simple-drawer-show", this.showEvent.bind(this));
}
/**
* LitElement life cycle - properties changed callback
*/
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName == "opened") {
this._openedChanged(this[propName], oldValue);
}
});
}
/**
* show event call to open the drawer and display it's content
*/
showEvent(e) {
// if we're already opened and we get told to open again....
// swap out the contents
if (this.opened) {
// wipe the slot of our drawer
while (this.firstChild !== null) {
this.removeChild(this.firstChild);
}
setTimeout(() => {
this.show(
e.detail.title,
e.detail.elements,
e.detail.invokedBy,
e.detail.align,
e.detail.clone
);
}, 100);
} else {
this.show(
e.detail.title,
e.detail.elements,
e.detail.invokedBy,
e.detail.align,
e.detail.size,
e.detail.clone
);
}
}
/**
* Show the drawer and display the material
*/
show(
title,
elements,
invokedBy,
align = "left",
size = "256px",
clone = false
) {
this.invokedBy = invokedBy;
this.title = title;
this.align = align;
// @todo this is a bit of a hack specific to polymer elements in app- world
this.shadowRoot
.querySelector("#drawer")
.updateStyles({ "--app-drawer-width": size });
let element;
// append element areas into the appropriate slots
// ensuring they are set if it wasn't previously
let slots = ["header", "content"];
for (var i in slots) {
if (elements[slots[i]]) {
if (clone) {
element = elements[slots[i]].cloneNode(true);
} else {
element = elements[slots[i]];
}
element.setAttribute("slot", slots[i]);
this.appendChild(element);
}
}
// minor delay to help the above happen prior to opening
setTimeout(() => {
this.opened = true;
// fake a resize event to make contents happy
window.dispatchEvent(new Event("resize"));
}, 100);
}
/**
* check state and if we should clean up on close.
* This keeps the DOM tiddy and allows animation to happen gracefully.
*/
animationEnded(e) {
// wipe the slot of our drawer
this.title = "";
while (this.firstChild !== null) {
this.removeChild(this.firstChild);
}
if (this.invokedBy) {
async.microTask.run(() => {
setTimeout(() => {
this.invokedBy.focus();
}, 500);
});
}
}
/**
* Close the drawer and do some clean up
*/
close() {
this.opened = false;
}
// event bubbling up from drawer
__openedChanged(e) {
this.opened = e.detail.value;
}
// Observer opened for changes
_openedChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined && !newValue) {
this.animationEnded();
const evt = new CustomEvent("simple-drawer-closed", {
bubbles: true,
cancelable: true,
detail: {
opened: false,
invokedBy: this.invokedBy
}
});
this.dispatchEvent(evt);
} else if (newValue) {
const evt = new CustomEvent("simple-drawer-opened", {
bubbles: true,
cancelable: true,
detail: {
opened: true,
invokedBy: this.invokedBy
}
});
this.dispatchEvent(evt);
}
}
/**
* life cycle, element is removed from the DOM
*/
disconnectedCallback() {
window.removeEventListener("simple-drawer-hide", this.close.bind(this));
window.removeEventListener("simple-drawer-show", this.showEvent.bind(this));
super.disconnectedCallback();
}
} |
JavaScript | class CustomControlSpacer extends Spacer {
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
buildCSSClass() {
return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
createEl() {
let el = super.createEl({
className: this.buildCSSClass(),
});
// No-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
el.innerHTML = ' ';
return el;
}
} |
JavaScript | class HFCSDKConnector extends Connector {
constructor(settings){
super();
//console.log(">> HFCSDKConnector");
Connector.call(this, 'hfc-sdk', settings);
this.settings = settings; // Store the settings for ease of access
Common.validateSettings(this.settings);
//logger.info("Info output test");
//logger.debug("Debugging output test");
//logger.error("Error output test");
};
/**
* Install chaincode onto the named peers
* @param {integer[]} peers Peers array to install chaincode on
* @param {ChaincodeInstallRequest} chaincode The chaincode install data. https://fabric-sdk-node.github.io/global.html#ChaincodeInstallRequest
* @param {object} lbConnector The loopback connector object
*
* @returns {any} result Result object
*/
postChaincodes(peers, chaincode, lbConnector){
if(chaincode.chaincodePackage === undefined){
logger.debug("postChaincodes() - no chaincodePackage in request");
var err = new Error("Bad Request");
err.statusCode = 400; //Bad request
return Promise.reject(err);
}
var clientPromise = Common.getClient(lbConnector.settings);
var peerArrayPromise;
if(peers !== undefined){
peerArrayPromise = Common.getPeers(lbConnector.settings, peers);
}
else { //Get all known peers
peerArrayPromise = Common.getPeers(lbConnector.settings);
}
//Once we have both Client and Peers use the client to install chaincode on the Peers
return Promise.all([clientPromise,peerArrayPromise]).then(
(data)=>{
var theClient = data[0];
var peerArray = data[1];
// Convert base64 archive input to a Buffer
var packageBuffer = Buffer.from(chaincode.chaincodePackage, 'base64');
var request = chaincode;
request.targets = peerArray;
request.txId = theClient.newTransactionID();
request.chaincodePackage = packageBuffer;
logger.debug("postChaincodes() - About to call installChaincode, "+request.chaincodeId+", "+request.chaincodeVersion);
//Expects https://fabric-sdk-node.github.io/global.html#ChaincodeInstallRequest with a targets parameter too.
return theClient.installChaincode(request);
}).then((results) => {
var proposalResponses = results[0];
//Do some internal checking to help debug.
var failed = Common.countFailedProposalResponses(proposalResponses);
var resp = {};
resp.peerResponses = results;
//Always send results from Peers even if not all worked.
return Promise.resolve(resp);
}).catch((err)=>{
logger.debug("postChaincodes() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* Query chaincode installed on a peer by ID
* @param {string} id Chaincode ID
* @param {integer[]} peers Peers to query for installed chaincode
* @param {object} lbConnector The loopback connector object
*
*/
getChaincodesId(id, peers, lbConnector){
//1. Get client and known peers
var clientPromise = Common.getClient(lbConnector.settings);
var peerArrayPromise;
if(peers !== undefined){
peerArrayPromise = Common.getPeers(lbConnector.settings, peers);
}
else { //Get all known peers
peerArrayPromise = Common.getPeers(lbConnector.settings);
}
//2. Once we have both Client and Peers use the client to query chaincode on the Peers
return Promise.all([clientPromise,peerArrayPromise]).then( (data)=>{
var aClient = data[0];
var promises = [];
data[1].forEach( function(aPeer,index){
promises[index] = aClient.queryInstalledChaincodes(aPeer);
});
return Promise.all(promises);
}).then((data)=>{
var response = {"queryResult":[]};
//3. Got responses from all peers, check for the named chaincode in result set
data.forEach(function( chaincodeQueryResult,index){
response.queryResult[index] = {}; //Init result for peer to empty object
// If result from peer with chaincode, look at content
if(chaincodeQueryResult !== undefined
&& chaincodeQueryResult.chaincodes !== undefined
){
for (var i = 0, len = chaincodeQueryResult.chaincodes.length; i < len; i++) {
if(chaincodeQueryResult.chaincodes[i].name !== undefined
&& chaincodeQueryResult.chaincodes[i].name == id
){
// If match found add it to index of peer in response
response.queryResult[index] = chaincodeQueryResult.chaincodes[i]
}
}
}
});
return Promise.resolve(response);
}).catch((err)=>{
logger.debug("getChaincodesId() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* Instantiate new chaincode proposal
* @param {string} channelName Name of the channel
* @param {integer[]} peers optional index(es) into datasources.json peers array to request endorsement from.
* @param {chaincodeInstantiate} chaincode The data needed to instantiate chaincode on the channel, see https://fabric-sdk-node.github.io/global.html£ChaincodeInstantiateUpgradeRequest
* @param {object} lbConnector The loopback connector object
*
* @returns {Promise} Resolving to the result
*/
postChannelsChannelNameChaincodes(channelName, peers, chaincode, lbConnector){
var request = {};
var theClient;
var theChannel;
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("postChannelsChannelNameChaincodes() - created client instance");
theClient = aClient;
//2. Get the Channel to instantiate chaincode on
theChannel = theClient.getChannel(channelName);
//3. Channel must be initialized to instantiate chaincode.
return theChannel.initialize();
}).then( (ignored)=>{
//4. build txId
request = chaincode;
request.txId = theClient.newTransactionID();
//5. Propose it
return theChannel.sendInstantiateProposal(request);
}).then( (instantiateResponse)=>{
//6 Check instantiate went okay
var failed = Common.countFailedProposalResponses(instantiateResponse[0]);
//TODO Find endorsement policy and see if enough passed to continue.
if(failed > 0){
logger.info(failed + " bad responses from instantiate requests");
//Pass back failed instantiateResponses to client
var resp = {}
resp.peerResponses = instantiateResponse;
return Promise.resolve(resp);
}
logger.debug("postChannelsChannelNameChaincodes() - proposed okay, sending to orderer");
var tranRequest = {};
tranRequest.proposalResponses = instantiateResponse[0];
tranRequest.proposal = instantiateResponse[1];
//7. Once the proposal results are available we can send to the orderer.
return theChannel.sendTransaction(tranRequest);
}).then( (ordererResponse)=>{
//REST caller may need to know txId for later query
ordererResponse.txId = request.txId;
return Promise.resolve(ordererResponse);
}).catch((err)=>{
logger.debug("postChannelsChannelNameChaincodes() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* Instantiate an update to existing chaincode proposal
* @param {string} channelName Name of the channel
* @param {integer[]} peers optional index(es) into datasources.json peers array to request endorsement from.
* @param {chaincodeInstantiate} chaincode The data needed to instantiate chaincode on the channel
* @param {object} lbConnector The loopback connector object
*
* @returns {Promise} Resolving to the result
*/
putChannelsChannelNameChaincodes(channelName, peers, chaincode, lbConnector){
// Check that chaincode exists, then do the same as postChannelsChannelNameChaincodes.
var request = {};
var theClient;
var theChannel;
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("putChannelsChannelNameChaincodes() - created client instance");
theClient = aClient;
//2. Get the Channel to instantiate chaincode on
theChannel = aClient.getChannel(channelName);
//3. Channel must be initialized to instantiate chaincode.
return theChannel.initialize();
}).then( (ignored)=>{
//4. Check if chaincode exists on channel, return 404 if not as nothing to upgrade.
return theChannel.queryInstantiatedChaincodes();
}).then( (instantiatedChaincodes) =>{
logger.debug("putChannelsChannelNameChaincodes() - queried chaincodes okay");
var id = chaincode.chaincodeId;
var foundIndex = -1;
//5. Loop through response and if no matche found reject with "Not Found", 404
if(instantiatedChaincodes.chaincodes && instantiatedChaincodes.chaincodes.length > 0){
instantiatedChaincodes.chaincodes.forEach( function(aChaincode,index){
if(aChaincode.name === id){
foundIndex = index;;
};
}
)
}
if(foundIndex >= 0){
return Promise.resolve(instantiatedChaincodes.chaincodes[foundIndex]);
} else {
logger.debug("putChannelsChannelNameChaincodes() - chaincode not instantiated: " + id);
var err = new Error("Not Found");
err.statusCode = 404;
return Promise.reject(err);
}
}).then( (found)=>{
// Chaincode exists so okay to try and update it.
logger.debug("putChannelsChannelNameChaincodes() - chaincode found, proposing update");
//6. build txId
request = chaincode;
request.txId = theClient.newTransactionID();
//7. Propose it
return theChannel.sendUpgradeProposal(request);
}).then( (upgradeResponse)=>{
//6 Check instantiate went okay
var failed = Common.countFailedProposalResponses(upgradeResponse[0]);
//TODO Find endorsement policy and see if enough passed to continue.
if(failed > 0){
logger.info(failed + " bad responses from upgrade requests");
//Pass back failed instantiateResponses to client
var resp = {}
resp.peerResponses = upgradeResponse;
return Promise.resolve(resp);
}
logger.debug("putChannelsChannelNameChaincodes() - proposed okay, sending to orderer");
var tranRequest = {};
tranRequest.proposalResponses = upgradeResponse[0];
tranRequest.proposal = upgradeResponse[1];
//8. Once the proposal results are available we can send to the orderer.
return theChannel.sendTransaction(tranRequest);
}).then( (ordererResponse)=>{
//REST caller may need to know txId for later query
ordererResponse.txId = request.txId;
return Promise.resolve(ordererResponse);
}).catch((err)=>{
logger.debug("putChannelsChannelNameChaincodes() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* Transaction proposal
* @param {string} channelName Name of the channel
* @param {integer[]} peers optional index(es) into datasources.json peers array to request endorsement from.
* @param {transaction} transaction The transaction to commit and any proposal response.
* @param {object} lbConnector The loopback connector object
*
* @returns {Promise}
*/
postChannelsChannelNameEndorse(channelName, peers, transaction, lbConnector){
var errMsg = "";
var response = {};
//Check key fields were passed in.
if(transaction.proposal === undefined){errMsg = "proposal"}
else {
if(transaction.proposal.chaincodeId === undefined){errMsg = "proposal.chaincodeId "}
if(transaction.proposal.args === undefined){
errMsg = errMsg+"proposal.args";
}
}
if(errMsg.length > 0) return Promise.reject("Missing parameters: "+errMsg);
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient)=>{
//2. Once the client is configured set theChannel instance to use later.
logger.debug("postChannelsChannelNameEndorse() - getting the channel");
var theChannel = aClient.getChannel(channelName);
//3. Do endorsement
// Resolve step with https://fabric-sdk-node.github.io/global.html#TransactionRequest
logger.debug("postChannelsChannelNameEndorse() - Endorsement");
var endorseRequest = transaction.proposal;
// Generate a transaction ID if needed.
if(transaction.proposal.txId === undefined){
endorseRequest.txId = aClient.newTransactionID();
}
// Now request endorsement
return Common.sendTxProposal(theChannel,endorseRequest);
}).catch((err)=>{
logger.debug("postChannelsChannelNameEndorse() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* Commit a transaction, if no proposal responses propose and commit.
* @param {string} channelName Name of the channel
* @param {transaction} transaction The transaction to commit and any proposal response.
* @param {object} lbConnector The loopback connector object
*
* @returns {Promise}
*/
postChannelsChannelNameTransactions(channelName, transaction, lbConnector){
var errMsg = "";
var response = {};
var theChannel;
var txId;
//Check key fields were passed in.
if(transaction.proposal === undefined){errMsg = "proposal"}
else if(transaction.proposal.header !== undefined){
// If a header property exists this is an endorsement repsonse passed through
logger.debug("postChannelsChannelNameTransactions() - proposal is a Buffer");
/*TODO allow this once the sdk allows data only input to sendTransaction()
* OR the objects can be stored across REST client requests
* OR the data can be easily turned back into the right objects
*/
var err = new Error("ProposalResponses passed over REST are not supported at this time");
err.statusCode = 501;
return Promise.reject(err);
}
else {
if(transaction.proposal.chaincodeId === undefined){errMsg = "proposal.chaincodeId "}
if(transaction.proposal.args === undefined){
errMsg = errMsg+"proposal.args";
}
}
if(errMsg.length > 0) return Promise.reject("Missing parameters: "+errMsg);
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient)=>{
//2. Once the client is configured set theChannel instance to use later.
logger.debug("postChannelsChannelNameTransactions() - getting the channel");
theChannel = aClient.getChannel(channelName);
//3. Do endorsement if needed
// Resolve step with https://fabric-sdk-node.github.io/global.html#TransactionRequest
// If nothing in proposalResponses as array or single ProposalResponse do endorsement first.
if(transaction.proposalResponses === undefined
|| (transaction.proposalResponses.length === 0 && transaction.proposalResponses.payload === undefined)
){
logger.debug("postChannelsChannelNameTransactions() - Endorsement needed");
var endorseRequest = transaction.proposal;
// Generate a transaction ID if needed.
if(transaction.proposal.txId === undefined){
txId = aClient.newTransactionID();
endorseRequest.txId = txId;
}
// Now request endorsement
return Common.sendTxProposal(theChannel,endorseRequest);
} else {
logger.debug("postChannelsChannelNameTransactions() - NO endorsement");
// Need to convert data only proposal input into the object the SDK expects
//TODO Work out how or get SDK updated.
return Promise.resolve(transaction);
}
}).then( (tranReq)=>{
//5. Once the proposal results are available we can sendTransaction.
return theChannel.sendTransaction(tranReq);
}).then( (broadcastResponse)=>{
//6. Format out the status returned on the broadcastResponse.status fields
var finalResp = {};
finalResp.status = broadcastResponse.status;
finalResp.txId = txId;
logger.debug(JSON.stringify(finalResp));
if(broadcastResponse.status === "SUCCESS"){
return Promise.resolve(finalResp);
} else {
return Promise.reject(finalResp);
}
}).catch((err)=>{
logger.debug("postChannelsChannelNameTransactions() - Error caught");
if(err instanceof Error && !err.statusCode) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* @param {object} lbConnector The loopback connector object
*
* @returns Promise
*/
getChannels(lbConnector){
var clientPromise = Common.getClient(lbConnector.settings);
var peerPromise = Common.getPeer(lbConnector.settings);
//Once we have both Client and Peer query the Peer for the known Channels
return Promise.all([clientPromise,peerPromise]).then(
(data)=>{
// Assigning to vars for readability
var aClient = data[0];
var aPeer = data[1];
// Query the Peer for known channels
return aClient.queryChannels(aPeer);
}
).then(
(response)=>{
//console.log(">> result");
//Expected response from queryChannels call is a ChannelQueryResponse proto Object
return Promise.resolve(response);
}
).catch((error)=>{
//Failed to perform function log error and reject promise
logger.error("Failed to queryChannels: "+ error);
return Promise.reject(error);
}
);
}
/**
* @returns {Promise}
*
* @param {string} channelName Name of the channel to GET
* @param {object} lbConnector The loopback connector object
*/
getChannelsChannelName(channelName, lbConnector){
var response = {};
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("getChannelsChannelName() - created client instance");
//3. Initialize the Channel and query it's Info
var theChannel = aClient.getChannel(channelName);
theChannel.initialize();
response = theChannel;
return theChannel.queryInfo();
}).then( (channelInfo) =>{
logger.debug("getChannelsChannelName() - queried channel okay");
//Remove the _clientContext property from the Channel to avoid cyclic references in JSON response.
// If the Client is ever persisted across requests this delete could cause problems.
delete response._clientContext;
//4. Resolve with Channel and the queryInfo
response.queryInfo = channelInfo;
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* @returns {Promise}
*
* @param {string} channelName Name of the channel
* @param {string} id Name of the chaincode
* @param {object} lbConnector The loopback connector object
*/
getChannelsChannelNameChaincodesId(channelName, id, lbConnector){
var response = {};
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("getChannelsChannelNameChaincodesId() - created client instance");
//3. Initialize the Channel and query it's chaincodes
var theChannel = aClient.getChannel(channelName);
return theChannel.queryInstantiatedChaincodes();
}).then( (installedChaincodes) =>{
logger.debug("getChannelsChannelNameChaincodesId() - queried chaincodes okay");
//4. Loop through response and if a name matches set the response to that else {} returned.
if(installedChaincodes.chaincodes && installedChaincodes.chaincodes.length > 0){
installedChaincodes.chaincodes.forEach( function(aChaincode,index){
if(aChaincode.name && aChaincode.name === id){
response = aChaincode;
};
}
)
}
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* @returns {Promise}
*
* @param {string} channelName Name of the channel
* @param {object} lbConnector The loopback connector object
*/
getChannelsChannelNameChaincodes(channelName, lbConnector){
var response = {};
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("getChannelsChannelNameChaincodes() - created client instance");
//3. Initialize the Channel and query it's Info
var theChannel = aClient.getChannel(channelName);
theChannel.initialize();
return theChannel.queryInstantiatedChaincodes();
}).then( (installedChaincodes) =>{
logger.debug("getChannelsChannelNameChaincodes() - queried channel for chaincode okay");
response = installedChaincodes; //Indirection not needed here.
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error) err.statusCode = 501;
return Promise.reject(err);
});
}
/**
* @returns {Promise}
*
* Query the channel's ledger
* @param {string} channelName Name of the channel
* @param {string} chaincodeId Chaincode ID to look for
* @param {integer} blockId Block ID to look for
* @param {string} blockHash Block Hash to look for
* @param {string} txnId Transaction ID to look for
* @param {args} args Optional args for query by chaincode
* @param {object} lbConnector The loopback connector object
*/
postChannelsChannelNameLedger(channelName, chaincodeId, blockId, blockHash, txnId, body, lbConnector){
var response = {};
var queryRequest = {};
var queryType = "NOT SET"
var queryParmCount = 0;
logger.debug(">postChannelsChannelNameLedger()");
//Validate that the number of query parameters is valid
if(chaincodeId !== undefined && chaincodeId !== null){ queryParmCount++; queryType = "chaincodeId"}
if(blockId !== undefined && blockId !== null){ queryParmCount++; queryType = "blockId"}
if(blockHash !== undefined && blockHash !== null){ queryParmCount++; queryType = "blockHash"}
if(txnId !== undefined && txnId !== null){ queryParmCount++; queryType = "txnId"}
if(queryParmCount > 1 || queryParmCount == 0){
return Promise.reject("1 query parameter must be used on this request, "+queryParmCount+" found");
}
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("postChannelsChannelNameLedger() - configured client instance");
//3. Get the Channel, build request and send it
var theChannel = aClient.getChannel(channelName);
if(chaincodeId !== undefined && chaincodeId !== null){
queryRequest.chaincodeId = chaincodeId;
if(body !== undefined && body.args !== null && body.fcn !== null){
queryRequest.args = body.args;
queryRequest.fcn = body.fcn;
} else {
var parmsError = new Error("Either \"args\" or \"fcn\" is missing for chaincode query")
parmsError.statusCode = 400; //Bad Request
return Promise.reject(parmsError);
}
logger.debug("postChannelsChannelNameLedger query: "+JSON.stringify(queryRequest));
return theChannel.queryByChaincode(queryRequest);
} else if(blockId !== undefined && blockId !== null){
return theChannel.queryBlock(blockId);
} else if(blockHash !== undefined && blockHash !== null){
return theChannel.queryBlockByHash(blockHash);
} else if(txnId !== undefined && txnId !== null){
return theChannel.queryTransaction(txnId);
} else {
return Promise.reject("postChannelsChannelNameLedger unknown query");
}
}).then( (queryResult) =>{
logger.debug("postChannelsChannelNameLedger() - queried channel for " + queryType);
try{
response = Common.formatBufferResponse(queryResult[0]);
} catch(err){
logger.debug("postChannelsChannelNameLedger() - return 404");
return Promise.reject(err);
}
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error && !err.statusCode) err.statusCode = 500;
return Promise.reject(err);
});
}
/**
* @returns {Promise}
*
* Query a block on a channel by ID or Hash
* @param {string} channelName Name of the channel
* @param {string} blockId Query data
* @param {string} blockHash Query data
* @param {object} lbConnector The loopback connector object
*/
getChannelsChannelNameBlocks(channelName, blockId, blockHash, lbConnector){
var response = {};
var queryType = "NOT SET"
var queryParmCount = 0;
logger.debug(">getChannelsChannelNameBlocks()");
//Validate that the number of query parameters is valid
if(blockId !== undefined && blockId !== null){ queryParmCount++; queryType = "blockId"}
if(blockHash !== undefined && blockHash !== null){ queryParmCount++; queryType = "blockHash"}
if(queryParmCount > 1 || queryParmCount == 0){
return Promise.reject("1 query parameter must be used on this request, "+queryParmCount+" found");
}
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("getChannelsChannelNameBlocks() - configured client instance");
//3. Get the Channel, build request and send it
var theChannel = aClient.getChannel(channelName);
if(blockId !== undefined && blockId !== null){
return theChannel.queryBlock(blockId);
} else if(blockHash !== undefined && blockHash !== null){
return theChannel.queryBlockByHash(blockHash);
} else {
return Promise.reject("getChannelsChannelNameBlocks unknown query");
}
}).then( (queryResult) =>{
logger.debug("getChannelsChannelNameBlocks() - queried channel for " + queryType);
response = queryResult; //Indirection not needed here.
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error && !err.statusCode){
if(err.message.startsWith("chaincode error (status: 500, message: Failed to get block")){
//TODO Fragile test, but not much else to go on.
err.statusCode = 404; //Not Found
} else {
err.statusCode = 500; //Internal Server Error
}
}
return Promise.reject(err);
});
}
getChannelsChannelNameTransactionsTransactionID(channelName, transactionID, lbConnector){
var response = {};
logger.debug("getChannelsChannelNameTransactionsTransactionID()");
//1. Get a new client instance.
return Common.getClientWithChannels(lbConnector.settings).then( (aClient) =>{
logger.debug("getChannelsChannelNameTransactionsTransactionID() - configured client instance");
//3. Get the Channel, build request and send it
var theChannel = aClient.getChannel(channelName);
return theChannel.queryTransaction(transactionID);
}).then( (queryResult) =>{
logger.debug("getChannelsChannelNameTransactionsTransactionID() - queried channel for " + transactionID);
response = queryResult; //Indirection not needed here.
return Promise.resolve( response );
}).catch((err)=>{
if(err instanceof Error && !err.statusCode){
if(err.message.startsWith("chaincode error (status: 500, message: Failed to get transaction with id")){
//TODO Fragile test, but not much else to go on.
err.statusCode = 404; //Not Found
} else {
err.statusCode = 500; //Internal Server Error
}
}
return Promise.reject(err);
});
}
} |
JavaScript | class AsPropRenamer {
constructor(actionOrStateIndex, propName) {
this.actionOrStateIndex = actionOrStateIndex
this.propName = propName
}
} |
JavaScript | class NotificationsModal extends Component {
/**
* Constructor for notifications modal.
*
* @param {object} props
* @return {void}
*/
constructor(props) {
super(props)
const dataSource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
this.state = {
dataSource,
isModalVisible: false
}
}
/**
* Hide notifications on unmount.
*
* @return {void}
*/
componentWillUnmount() {
this.hideNotificationsModal()
}
/**
* Load user notifications when modal is shown.
*
* @return {void}
*/
showNotificationsModal() {
const userId = this.props.user.objectId
if (userId) {
this.props.getNotifications(userId, true)
}
}
/**
* Mark user notifications as seen when modal is hidden.
*
* @return {void}
*/
hideNotificationsModal() {
const notifications = this.props.notifications
if (notifications.length) {
this.props.markUserNotificationAsSeen(notifications)
}
}
/**
* Render notification item row.
*
* @param {object} rowData - the notification record
* @return {object}
*/
renderRow(rowData) {
const types = {
"comment": {
"onPress": this.props.actions.routes.comments(rowData),
"icon": "comment"
}
}
// "message": {
// "onPress": () => this.props.actions.routes.messageDetail(rowData),
// "icon": "message"
// }
const type = rowData.type
if (!types[type]) {
return
}
let photo
if (!rowData.photo) {
photo = (
<View style={[
BaseStyles.photoSmall,
BaseStyles.mediumBg,
BaseStyles.row,
BaseStyles.verticalCenteredCols,
BaseStyles.centeredCols
]}>
<MaterialIcon
name="user"
style={[
BaseStyles.fontSmall,
BaseStyles.textLessMuted
]} />
</View>
)
} else {
photo = (
<Image
resizeMode="contain"
style={BaseStyles.photoSmall}
source={{uri: rowData.photo}} />
)
}
return (
<TouchableHighlight
onPress={types[type].onPress}
underlayColor="#efefef"
style={[
NotificationStyles.notificationPress,
BaseStyles.col1
]}>
<View style={[
NotificationStyles.notificationItem,
BaseStyles.paddingHorz,
BaseStyles.paddingVert,
BaseStyles.borderBottomLight,
BaseStyles.row
]}>
{photo}
<View style={[
NotificationStyles.notificationDetails,
BaseStyles.col1,
BaseStyles.marginLeft
]}>
<View style={[
NotificationStyles.userDetails,
BaseStyles.row,
BaseStyles.justifiedCols,
BaseStyles.marginBottom
]}>
<FontAwesome
name={types[type].icon}
style={[
NotificationStyles.fontIcon,
BaseStyles.textDark,
BaseStyles.fontExtraSmall
]} />
<Text style={[
NotificationStyles.notificationDate,
BaseStyles.sansSerifLight,
BaseStyles.textMuted,
BaseStyles.fontExtraSmall
]}>
<TimeAgo time={rowData.createdAt} />
</Text>
</View>
<Text style={[
NotificationStyles.excerpt,
BaseStyles.sansSerifRegular,
BaseStyles.textDark,
BaseStyles.fontSmall
]}>
{rowData.excerpt}
</Text>
</View>
</View>
</TouchableHighlight>
)
}
/**
* Render notification list component.
*
* @return {object} component
*/
render() {
if (this.props.isLoading) {
return (<LoadingView />)
}
return (
<Modal
visible={this.state.isModalVisible}
transparent={true}
animated={true}>
<ListView
style={[
NotificationStyles.feedList,
BaseStyles.col1
]}
dataSource={this.state.dataSource.cloneWithRows(this.props.notifications)}
renderRow={this.renderRow.bind(this)}
automaticallyAdjustContentInsets={false} />
</Modal>
)
}
} |
JavaScript | class DistrictService {
/**
* Query the first 100 entries on the district index.
* @param callback a function with one parameter, that will be called when the results are ready. The first parameter
* will be an array containing the district results of type IDistrictResultSlim.
*/
loadDistricts(callback) {
const searchQuery = {
index: districtIndex,
body: {
size: 100,
_source: ['properties', 'center', 'geometry'],
},
}
client
.search(searchQuery, ((error, body) => {
if (error) {
console.trace('error', error.message)
}
let districts = []
if (body && body.hits) {
const results = body.hits.hits
for (const { _id, _source: { properties: district, center: { coordinates }, geometry } } of results) {
districts.push({
id: _id,
name: district.Name,
number: district.Nr,
centerLat: coordinates[1],
centerLon: coordinates[0],
polygon: geometry,
})
}
}
// sort
districts = districts.sort((a, b) => a.name.localeCompare(b.name))
callback(districts)
}))
}
/**
* Query the district index for the geometry that contains the given geo position.
*
* @return a Promise that will return the one matching district name or an empty string, if no matching district
* was found
*/
queryDistrictByCoordinates({ latitude, longitude }) {
const searchQuery = {
index: districtIndex,
body: {
size: 1,
_source: ['properties.Name'],
query: {
geo_shape: {
geometry: {
relation: 'contains',
shape: {
type: 'point',
coordinates: [
longitude, latitude,
],
},
},
},
},
},
}
return new Promise(((resolve, reject) => {
client
.search(searchQuery, ((error, body) => {
if (error) {
console.trace('error', error.message)
return reject(error)
}
if (body && body.hits) {
const result = body.hits.hits[0]
if (result) {
return resolve(result._source.properties.Name)
}
}
return resolve('')
}))
}))
}
} |
JavaScript | class AppElement {
constructor(index, parentIndex, parentView, nativeElement) {
this.index = index;
this.parentIndex = parentIndex;
this.parentView = parentView;
this.nativeElement = nativeElement;
this.nestedViews = null;
this.componentView = null;
}
get elementRef() { return new ElementRef(this.nativeElement); }
get vcRef() { return new ViewContainerRef_(this); }
initComponent(component, componentConstructorViewQueries, view) {
this.component = component;
this.componentConstructorViewQueries = componentConstructorViewQueries;
this.componentView = view;
}
get parentInjector() { return this.parentView.injector(this.parentIndex); }
get injector() { return this.parentView.injector(this.index); }
mapNestedViews(nestedViewClass, callback) {
var result = [];
if (isPresent(this.nestedViews)) {
this.nestedViews.forEach((nestedView) => {
if (nestedView.clazz === nestedViewClass) {
result.push(callback(nestedView));
}
});
}
return result;
}
attachView(view, viewIndex) {
if (view.type === ViewType.COMPONENT) {
throw new BaseException(`Component views can't be moved!`);
}
var nestedViews = this.nestedViews;
if (nestedViews == null) {
nestedViews = [];
this.nestedViews = nestedViews;
}
ListWrapper.insert(nestedViews, viewIndex, view);
var refRenderNode;
if (viewIndex > 0) {
var prevView = nestedViews[viewIndex - 1];
refRenderNode = prevView.lastRootNode;
}
else {
refRenderNode = this.nativeElement;
}
if (isPresent(refRenderNode)) {
view.renderer.attachViewAfter(refRenderNode, view.flatRootNodes);
}
view.addToContentChildren(this);
}
detachView(viewIndex) {
var view = ListWrapper.removeAt(this.nestedViews, viewIndex);
if (view.type === ViewType.COMPONENT) {
throw new BaseException(`Component views can't be moved!`);
}
view.renderer.detachView(view.flatRootNodes);
view.removeFromContentChildren(this);
return view;
}
} |
JavaScript | class BaseCard extends React.Component {
constructor (props) {
super(props)
this.state = {
edit: props.editMode,
}
this.propTypeKeys = Object.keys(BaseCard.propTypes)
this.clickEdit = this.clickEdit.bind(this)
this.clickCancel = this.clickCancel.bind(this)
this.clickSave = this.clickSave.bind(this)
this.renderChildren = this.renderChildren.bind(this)
}
clickEdit () {
if (this.props.onStartEdit() !== false) {
this.setState({ edit: true })
}
}
clickCancel () {
if (this.props.onCancel() !== false) {
this.setState({ edit: false })
}
}
clickSave () {
if (this.props.onSave() !== false) {
this.setState({ edit: false })
}
}
renderChildren (childProps) {
const children = this.props.children || noop
return typeof children === 'function' ? children(childProps)
: React.isValidElement(children) ? React.cloneElement(children, childProps)
: children
}
render () {
const {
title = undefined,
icon = undefined,
itemCount = undefined,
editMode = undefined,
editable = true,
editTooltip,
} = this.props
const editing = editMode === undefined ? this.state.edit : editMode
const hasHeading = !!title
const hasBadge = itemCount !== undefined
const hasIcon = icon && icon.type && icon.name
const RenderChildren = this.renderChildren
return (
<Card className={style['base-card']} {...excludeKeys(this.props, this.propTypeKeys)}>
{hasHeading && (
<CardHeading className={style['base-card-heading']}>
{editable && <CardEditButton tooltip={editTooltip} editEnabled={editing} onClick={this.clickEdit} />}
<CardTitle>
{hasIcon && <Icon type={icon.type} name={icon.name} className={style['base-card-title-icon']} />}
{title}
{hasBadge && <Badge className={style['base-card-item-count-badge']}>{itemCount}</Badge>}
</CardTitle>
</CardHeading>
)}
<CardBody className={style['base-card-body']}>
{(!hasHeading && editable) && (
<CardEditButton tooltip={editTooltip} editEnabled={editing} onClick={this.clickEdit} />
)}
<RenderChildren isEditing={editing} />
</CardBody>
{editing && (
<CardFooter className={style['base-card-footer']}>
<Button bsStyle='primary' onClick={this.clickSave}><Icon type='fa' name='check' /></Button>
<Button onClick={this.clickCancel}><Icon type='pf' name='close' /></Button>
</CardFooter>
)}
</Card>
)
}
} |
JavaScript | class STFT{
constructor( windowSize = 1024, fftSize = 1024,
hopSize = 512, sampleRate = 44100) {
this.windowSize = windowSize;
this.fftSize = fftSize;
this.hopSize = hopSize;
this.sampleRate = sampleRate;
this.window = new dsp.WindowFunction(dsp.DSP.HANN);
this.fft = new dsp.FFT(fftSize, this.sampleRate);
this.prevRaw = new array(this.fftSize); // previous unprocessed buffer
this.prevProcessed = new array(this.fftSize); // previous buffer after processing
}
magnitude(real, imag){
return real.map((val, i) =>
Math.sqrt(Math.pow(val, 2) +
Math.pow(imag[i], 2))
);
}
phase(real, imag){
return real.map((val, i) =>
Math.atan(imag[i] / real[i])
);
}
overlapAdd(buffer, processFunc) {
let overlapWindow = new Float32Array(this.fftSize);
overlapWindow.set(
this.prevRaw.slice(this.hopSize, this.fftSize)
);
overlapWindow.set(
buffer.slice(0, this.hopSize),
this.hopSize
);
overlapWindow = this.window.process(overlapWindow);
this.fft.forward(overlapWindow);
let overlapProcessed = processFunc(this.fft.real, this.fft.imag);
overlapWindow = this.fft.inverse(
overlapProcessed.real, overlapProcessed.imag
);
let currentWindow = buffer.slice(0, this.fftSize);
currentWindow = this.window.process(currentWindow);
this.fft.forward(currentWindow);
let currentProcessed = processFunc(this.fft.real, this.fft.imag);
let currentResult = this.fft.inverse(currentProcessed.real, currentProcessed.imag);
// return the result of the previous window plus overlap
let result = new Float32Array(this.fftSize);
result.set(this.prevProcessed);
for(let i = 0; i < this.hopSize; i++){
result[i + this.hopSize] += overlapWindow[i];
}
// store overlap for future
this.prevProcessed = currentResult;
for(let i = 0; i < this.hopSize; i++){
this.prevProcessed[i] += overlapWindow[i +this.hopSize];
}
this.prevRaw = array;
return result;
}
processSegment(buffer, processFunc) {
this.fft.forward(buffer);
processFunc(this.fft.real, this.fft.imag);
return this.fft.inverse(this.fft.real, this.fft.imag);
}
analyze(buffer, processFunc, maxHops = 100000) {
let frames = new Array();
let arrayHops = Math.floor(
(buffer.length - this.fftSize) / parseFloat(this.hopSize)
);
let numHops = Math.min(arrayHops, maxHops);
let size = Math.round(this.fftSize / 2 ) + 1;
for (let n = 0; n < numHops; n++){
let start = n * this.hopSize;
let end = start + this.fftSize;
let windowed = this.window.process(buffer.slice(start, end));
this.processSegment(windowed,
(real, imag) => {
let mag = this.magnitude(real, imag);
frames.push(mag.slice(0, size));
});
}
return frames;
}
} |
JavaScript | class Destination extends ToneAudioNode {
constructor() {
super(optionsFromArguments(Destination.getDefaults(), arguments));
this.name = "Destination";
this.input = new Volume({ context: this.context });
this.output = new Gain({ context: this.context });
/**
* The volume of the master output.
*/
this.volume = this.input.volume;
const options = optionsFromArguments(Destination.getDefaults(), arguments);
connectSeries(this.input, this.output, this.context.rawContext.destination);
this.mute = options.mute;
this._internalChannels = [this.input, this.context.rawContext.destination, this.output];
}
static getDefaults() {
return Object.assign(ToneAudioNode.getDefaults(), {
mute: false,
volume: 0,
});
}
/**
* Mute the output.
* @example
* const oscillator = new Tone.Oscillator().start().toDestination();
* setTimeout(() => {
* // mute the output
* Tone.Destination.mute = true;
* }, 1000);
*/
get mute() {
return this.input.mute;
}
set mute(mute) {
this.input.mute = mute;
}
/**
* Add a master effects chain. NOTE: this will disconnect any nodes which were previously
* chained in the master effects chain.
* @param args All arguments will be connected in a row and the Master will be routed through it.
* @example
* // route all audio through a filter and compressor
* const lowpass = new Tone.Filter(800, "lowpass");
* const compressor = new Tone.Compressor(-18);
* Tone.Destination.chain(lowpass, compressor);
*/
chain(...args) {
this.input.disconnect();
args.unshift(this.input);
args.push(this.output);
connectSeries(...args);
return this;
}
/**
* The maximum number of channels the system can output
* @example
* console.log(Tone.Destination.maxChannelCount);
*/
get maxChannelCount() {
return this.context.rawContext.destination.maxChannelCount;
}
/**
* Clean up
*/
dispose() {
super.dispose();
this.volume.dispose();
return this;
}
} |
JavaScript | class ThreadChart extends React.Component {
/**
* The object structure of the margin variable in the props of ThreadChart
*
* @typedef {Object} Margin
* @property {number} top the top margin of the ThreadChart component
* @property {number} right the right margin of the ThreadChart component
* @property {number} bottom the bottom margin of the ThreadChart component
* @property {number} left the left margin of the ThreadChart component
*
* @see ThreadChartProps
*/
/**
* The object structure of the domain variable in the props of ThreadChart
*
* @typedef {Object} Domain
* @property {number[]} xDomain the x domain of the x scale
* @property {string[]} yDomain the y domain of the y scale
*
* @see ThreadChartProps
*/
/**
* onDownload callback notifies the App component when the user clicks on the "Download current replay" button
*
* @callback onDownload
*
* @see ThreadChartProps
* @see App
*/
/**
* onLoad callback notifies the App component when the user clicks on the "Load a replay" button
*
* @callback onLoad
* @param {Object} e the event containing the uploaded replay file
*
* @see SidebarProps
* @see App
*/
/**
* onPan callback notifies the App component when the user clicks on either the pan left or the pan right buttons
*
* @callback onPan
* @param {number} direction either -1 or 1, indicating whether the user wants to pan to the left or right, respectively
*
* @see SidebarProps
* @see App
*/
/**
* onReset callback notifies the App component when the user clicks on the "reset" button
*
* @callback onReset
*
* @see SidebarProps
* @see App
*/
/**
* The object structure of the newDomain parameter used in the onZoom callback
*
* @typedef {Object} NewDomains
* @property {number[]} xDomain the new x domain
* @property {string[]} yDomain the new y domain
*
* @see onZoom
*/
/**
* onZoom callback notifies the App component when the user zooms in on either the ContextView or the FocusView with the new domains of x- and y-axes
*
* @callback onZoom
* @param {NewDomains} newDomain the new domains of the x- and y-axes
*
* @see SidebarProps
* @see App
*/
/**
* onZoomOut callback notifies the App component when the user clicks on the "Go Back" button.
* Since the "Go Back" button can not only go back in zoom levels but also panning positions,
* this callback is triggered in either of these two scenarios.
*
* @callback onZoomOut
*
* @see SidebarProps
* @see App
*/
/**
* The object structure of the props used by ThreadChart component
*
* @typedef {Object} ThreadChartProps
* @property {Thread[]} allData an array containing all the threads
* @property {boolean} atTopZoomLevel a boolean indicating if the ThreadChart component is at the top(default) zoom level
* @property {Thread[]} data an array containing the visible threads in the ThreadChart component
* @property {boolean} databaseError a boolean indicating if an error occurs while attemping to read from the database
* @property {Domain} domain an array containing all the thread objects
* @property {number} height the computed height of the ThreadChart component
* @property {onDownload} onDownload a callback
* @property {onLoad} onLoad an object representing the margins of the ThreadChart component
* @property {onPan} onPan an object representing the margins of the ThreadChart component
* @property {onReset} onReset an object representing the margins of the ThreadChart component
* @property {onZoom} onZoom an object representing the margins of the ThreadChart component
* @property {onZoomOut} onZoomOut an object representing the margins of the ThreadChart component
* @property {Map} scColor a map associating the names of the system calls to their states of visibility and their colors
* @property {Map} margin an object representing the margins of the ThreadChart component
* @property {boolean} showSysCalls a boolean indicating if the system calls are visible
* @property {number} width the width of the ThreadChart component
*
*/
/**
* Constructor of TheadChart component
*
* @param {ThreadChartProps} props
*/
constructor(props) {
super(props)
}
render() {
if (this.props.databaseError) {
return <h1>Error Connecting to Database</h1>
}
return (
<div>
<article className='thread-chart'>
<ContextView
data={this.props.data}
scColor={this.props.scColor}
scargs={this.props.scargs}
domain={this.props.domain}
showSysCalls={this.props.showSysCalls}
onZoom={this.props.onZoom}
width={this.props.width}
height={this.props.height / 40 * 30}
margin={this.props.margin}
/>
<FocusView
data={this.props.allData}
domain={this.props.domain}
onZoom={this.props.onZoom}
width={this.props.width}
height={this.props.height / 40 * 10}
margin={this.props.margin}
/>
</article>
<button onClick={this.props.onZoomOut}>Go Back</button>
<button onClick={this.props.onReset}>reset</button>
<button onClick={this.props.onDownload}>Download current replay</button>
<a> Load a replay:</a>
<input type="file"
onChange={this.props.onLoad} />
{!this.props.atTopZoomLevel &&
<div>
<span className="thread-chart__pan-left" onClick={() => this.props.onPan(-1)}>❮</span>
<span className="thread-chart__pan-right" onClick={() => this.props.onPan(1)}>❯</span>
</div>
}
{/* <button onClick={this.props.onLoad}>load a replay</button> */}
</div>
)
}
} |
JavaScript | class FuroDocClassMethodsItem extends FBP(LitElement) {
constructor() {
super();
this.method;
}
data(data) {
this.method = data;
if (data.privacy === "protected") {
this.setAttribute("hidden", "")
}
this._FBPTriggerWire("--data", data);
this.requestUpdate();
}
/**
* flow is ready lifecycle method
*/
_FBPReady() {
super._FBPReady();
//this._FBPTraceWires()
}
/**
* Themable Styles
* @private
* @return {CSSResult}
*/
static get styles() {
// language=CSS
return Theme.getThemeForComponent(this.name) || css`
:host {
display: block;
font-size: 13px;
margin-bottom: 36px;
}
strong {
font-weight: 700;
font-family: "Roboto Mono";
}
:host([hidden]) {
display: none;
}
span.name {
color: green;
}
span.paramname {
font-family: "Roboto Mono";
color: #717171;
}
span.type, span.return {
color: #717171;
font-weight: 900;
}
span.type:after {
content: ","
}
.inherited{
font-style: italic;
line-height: 24px;
color: #7f7f7f;
}
`
}
/**
* @private
* @returns {TemplateResult}
*/
render() {
// language=HTML
if (!this.method.return) {
this.method.return = {};
}
return html`
<strong>${this.method.name}</strong> (<template is="flow-repeat" ƒ-inject-items="--data(*.params)">
<span class="name" ƒ-.inner-text="--item(*.name)"></span> :
<span class="type" ƒ-.inner-text="--item(*.type)"></span></template>) ⟹ <span class="return">${this.method.return.type}</span>
<span class="inherited"> Inherited from ${this.method.inheritedFrom}</span>
<furo-markdown ƒ-parse-markdown="--data(*.description)"></furo-markdown>
<ul>
<template is="flow-repeat" ƒ-inject-items="--data(*.params)">
<li><span class="paramname" ƒ-.inner-text="--item(*.name)">fd</span> <br>
<furo-markdown ƒ-parse-markdown="--item(*.description)">></furo-markdown></li>
</template></ul>
`;
}
} |
JavaScript | class Spoilers extends Plugin {
/**
* Get the data for the table cells
* @returns {Array}
*/
getData() {
const counts = {};
const pangramCount = data.getCount('pangrams');
const foundPangramCount = data.getCount('foundPangrams');
const cellData = [
['', '✓', '?', '∑'],
[
'Pangrams',
foundPangramCount,
pangramCount - foundPangramCount,
pangramCount
]
];
data.getList('answers').forEach(term => {
counts[term.length] = counts[term.length] || {
found: 0,
missing: 0,
total: 0
};
if (data.getList('foundTerms').includes(term)) {
counts[term.length].found++;
} else {
counts[term.length].missing++;
}
counts[term.length].total++;
});
let keys = Object.keys(counts);
keys.sort((a, b) => a - b);
keys.forEach(count => {
cellData.push([
count + ' ' + (count > 1 ? 'letters' : 'letter'),
counts[count].found,
counts[count].missing,
counts[count].total
]);
});
return cellData;
};
constructor(app) {
super(app, 'Spoilers', {
canChangeState: true
});
this.ui = el.details();
// add and populate content pane
const pane = tbl.build(this.getData());
this.ui.append(el.summary({
text: this.title
}), pane);
// update on demand
app.on(prefix('wordsUpdated'), () => {
tbl.refresh(this.getData(), pane);
});
this.add();
}
} |
JavaScript | class Text extends THREE.Mesh {
constructor() {
const geometry = new GlyphsGeometry();
super(geometry, null);
// === Text layout properties: === //
/**
* @member {string} text
* The string of text to be rendered.
*/
this.text = '';
/**
* @deprecated Use `anchorX` and `anchorY` instead
* @member {Array<number>} anchor
* Defines where in the text block should correspond to the mesh's local position, as a set
* of horizontal and vertical percentages from 0 to 1. A value of `[0, 0]` (the default)
* anchors at the top-left, `[1, 1]` at the bottom-right, and `[0.5, 0.5]` centers the
* block at the mesh's position.
*/
//this.anchor = null
/**
* @member {number|string} anchorX
* Defines the horizontal position in the text block that should line up with the local origin.
* Can be specified as a numeric x position in local units, a string percentage of the total
* text block width e.g. `'25%'`, or one of the following keyword strings: 'left', 'center',
* or 'right'.
*/
this.anchorX = 0;
/**
* @member {number|string} anchorX
* Defines the vertical position in the text block that should line up with the local origin.
* Can be specified as a numeric y position in local units (note: down is negative y), a string
* percentage of the total text block height e.g. `'25%'`, or one of the following keyword strings:
* 'top', 'top-baseline', 'middle', 'bottom-baseline', or 'bottom'.
*/
this.anchorY = 0;
/**
* @member {number} curveRadius
* Defines a cylindrical radius along which the text's plane will be curved. Positive numbers put
* the cylinder's centerline (oriented vertically) that distance in front of the text, for a concave
* curvature, while negative numbers put it behind the text for a convex curvature. The centerline
* will be aligned with the text's local origin; you can use `anchorX` to offset it.
*
* Since each glyph is by default rendered with a simple quad, each glyph remains a flat plane
* internally. You can use `glyphGeometryDetail` to add more vertices for curvature inside glyphs.
*/
this.curveRadius = 0;
/**
* @member {string} direction
* Sets the base direction for the text. The default value of "auto" will choose a direction based
* on the text's content according to the bidi spec. A value of "ltr" or "rtl" will force the direction.
*/
this.direction = 'auto';
/**
* @member {string} font
* URL of a custom font to be used. Font files can be any of the formats supported by
* OpenType (see https://github.com/opentypejs/opentype.js).
* Defaults to the Roboto font loaded from Google Fonts.
*/
this.font = null; //will use default from TextBuilder
/**
* @member {number} fontSize
* The size at which to render the font in local units; corresponds to the em-box height
* of the chosen `font`.
*/
this.fontSize = 0.1;
/**
* @member {number} letterSpacing
* Sets a uniform adjustment to spacing between letters after kerning is applied. Positive
* numbers increase spacing and negative numbers decrease it.
*/
this.letterSpacing = 0;
/**
* @member {number|string} lineHeight
* Sets the height of each line of text, as a multiple of the `fontSize`. Defaults to 'normal'
* which chooses a reasonable height based on the chosen font's ascender/descender metrics.
*/
this.lineHeight = 'normal';
/**
* @member {number} maxWidth
* The maximum width of the text block, above which text may start wrapping according to the
* `whiteSpace` and `overflowWrap` properties.
*/
this.maxWidth = Infinity;
/**
* @member {string} overflowWrap
* Defines how text wraps if the `whiteSpace` property is `normal`. Can be either `'normal'`
* to break at whitespace characters, or `'break-word'` to allow breaking within words.
* Defaults to `'normal'`.
*/
this.overflowWrap = 'normal';
/**
* @member {string} textAlign
* The horizontal alignment of each line of text within the overall text bounding box.
*/
this.textAlign = 'left';
/**
* @member {number} textIndent
* Indentation for the first character of a line; see CSS `text-indent`.
*/
this.textIndent = 0;
/**
* @member {string} whiteSpace
* Defines whether text should wrap when a line reaches the `maxWidth`. Can
* be either `'normal'` (the default), to allow wrapping according to the `overflowWrap` property,
* or `'nowrap'` to prevent wrapping. Note that `'normal'` here honors newline characters to
* manually break lines, making it behave more like `'pre-wrap'` does in CSS.
*/
this.whiteSpace = 'normal';
// === Presentation properties: === //
/**
* @member {THREE.Material} material
* Defines a _base_ material to be used when rendering the text. This material will be
* automatically replaced with a material derived from it, that adds shader code to
* decrease the alpha for each fragment (pixel) outside the text glyphs, with antialiasing.
* By default it will derive from a simple white MeshBasicMaterial, but you can use any
* of the other mesh materials to gain other features like lighting, texture maps, etc.
*
* Also see the `color` shortcut property.
*/
this.material = null;
/**
* @member {string|number|THREE.Color} color
* This is a shortcut for setting the `color` of the text's material. You can use this
* if you don't want to specify a whole custom `material`. Also, if you do use a custom
* `material`, this color will only be used for this particuar Text instance, even if
* that same material instance is shared across multiple Text objects.
*/
this.color = null;
/**
* @member {object|null} colorRanges
* WARNING: This API is experimental and may change.
* This allows more fine-grained control of colors for individual or ranges of characters,
* taking precedence over the material's `color`. Its format is an Object whose keys each
* define a starting character index for a range, and whose values are the color for each
* range. The color value can be a numeric hex color value, a `THREE.Color` object, or
* any of the strings accepted by `THREE.Color`.
*/
this.colorRanges = null;
/**
* @member {number|string} outlineWidth
* WARNING: This API is experimental and may change.
* The width of an outline/halo to be drawn around each text glyph using the `outlineColor` and `outlineOpacity`.
* Can be specified as either an absolute number in local units, or as a percentage string e.g.
* `"12%"` which is treated as a percentage of the `fontSize`. Defaults to `0`, which means
* no outline will be drawn unless an `outlineOffsetX/Y` or `outlineBlur` is set.
*/
this.outlineWidth = 0;
/**
* @member {string|number|THREE.Color} outlineColor
* WARNING: This API is experimental and may change.
* The color of the text outline, if `outlineWidth`/`outlineBlur`/`outlineOffsetX/Y` are set.
* Defaults to black.
*/
this.outlineColor = 0x000000;
/**
* @member {number} outlineOpacity
* WARNING: This API is experimental and may change.
* The opacity of the outline, if `outlineWidth`/`outlineBlur`/`outlineOffsetX/Y` are set.
* Defaults to `1`.
*/
this.outlineOpacity = 1;
/**
* @member {number|string} outlineBlur
* WARNING: This API is experimental and may change.
* A blur radius applied to the outer edge of the text's outline. If the `outlineWidth` is
* zero, the blur will be applied at the glyph edge, like CSS's `text-shadow` blur radius.
* Can be specified as either an absolute number in local units, or as a percentage string e.g.
* `"12%"` which is treated as a percentage of the `fontSize`. Defaults to `0`.
*/
this.outlineBlur = 0;
/**
* @member {number|string} outlineOffsetX
* WARNING: This API is experimental and may change.
* A horizontal offset for the text outline.
* Can be specified as either an absolute number in local units, or as a percentage string e.g. `"12%"`
* which is treated as a percentage of the `fontSize`. Defaults to `0`.
*/
this.outlineOffsetX = 0;
/**
* @member {number|string} outlineOffsetY
* WARNING: This API is experimental and may change.
* A vertical offset for the text outline.
* Can be specified as either an absolute number in local units, or as a percentage string e.g. `"12%"`
* which is treated as a percentage of the `fontSize`. Defaults to `0`.
*/
this.outlineOffsetY = 0;
/**
* @member {number|string} strokeWidth
* WARNING: This API is experimental and may change.
* The width of an inner stroke drawn inside each text glyph using the `strokeColor` and `strokeOpacity`.
* Can be specified as either an absolute number in local units, or as a percentage string e.g. `"12%"`
* which is treated as a percentage of the `fontSize`. Defaults to `0`.
*/
this.strokeWidth = 0;
/**
* @member {string|number|THREE.Color} strokeColor
* WARNING: This API is experimental and may change.
* The color of the text stroke, if `strokeWidth` is greater than zero. Defaults to gray.
*/
this.strokeColor = defaultStrokeColor;
/**
* @member {number} strokeOpacity
* WARNING: This API is experimental and may change.
* The opacity of the stroke, if `strokeWidth` is greater than zero. Defaults to `1`.
*/
this.strokeOpacity = 1;
/**
* @member {number} fillOpacity
* WARNING: This API is experimental and may change.
* The opacity of the glyph's fill from 0 to 1. This behaves like the material's `opacity` but allows
* giving the fill a different opacity than the `strokeOpacity`. A fillOpacity of `0` makes the
* interior of the glyph invisible, leaving just the `strokeWidth`. Defaults to `1`.
*/
this.fillOpacity = 1;
/**
* @member {number} depthOffset
* This is a shortcut for setting the material's `polygonOffset` and related properties,
* which can be useful in preventing z-fighting when this text is laid on top of another
* plane in the scene. Positive numbers are further from the camera, negatives closer.
*/
this.depthOffset = 0;
/**
* @member {Array<number>} clipRect
* If specified, defines a `[minX, minY, maxX, maxY]` of a rectangle outside of which all
* pixels will be discarded. This can be used for example to clip overflowing text when
* `whiteSpace='nowrap'`.
*/
this.clipRect = null;
/**
* @member {string} orientation
* Defines the axis plane on which the text should be laid out when the mesh has no extra
* rotation transform. It is specified as a string with two axes: the horizontal axis with
* positive pointing right, and the vertical axis with positive pointing up. By default this
* is '+x+y', meaning the text sits on the xy plane with the text's top toward positive y
* and facing positive z. A value of '+x-z' would place it on the xz plane with the text's
* top toward negative z and facing positive y.
*/
this.orientation = defaultOrient;
/**
* @member {number} glyphGeometryDetail
* Controls number of vertical/horizontal segments that make up each glyph's rectangular
* plane. Defaults to 1. This can be increased to provide more geometrical detail for custom
* vertex shader effects, for example.
*/
this.glyphGeometryDetail = 1;
/**
* @member {number|null} sdfGlyphSize
* The size of each glyph's SDF (signed distance field) used for rendering. This must be a
* power-of-two number. Defaults to 64 which is generally a good balance of size and quality
* for most fonts. Larger sizes can improve the quality of glyph rendering by increasing
* the sharpness of corners and preventing loss of very thin lines, at the expense of
* increased memory footprint and longer SDF generation time.
*/
this.sdfGlyphSize = null;
this.debugSDF = false;
}
/**
* Updates the text rendering according to the current text-related configuration properties.
* This is an async process, so you can pass in a callback function to be executed when it
* finishes.
* @param {function} [callback]
*/
sync(callback) {
if (this._needsSync) {
this._needsSync = false;
// If there's another sync still in progress, queue
if (this._isSyncing) {
(this._queuedSyncs || (this._queuedSyncs = [])).push(callback);
} else {
this._isSyncing = true;
this.dispatchEvent(syncStartEvent);
getTextRenderInfo({
text: this.text,
font: this.font,
fontSize: this.fontSize || 0.1,
letterSpacing: this.letterSpacing || 0,
lineHeight: this.lineHeight || 'normal',
maxWidth: this.maxWidth,
direction: this.direction || 'auto',
textAlign: this.textAlign,
textIndent: this.textIndent,
whiteSpace: this.whiteSpace,
overflowWrap: this.overflowWrap,
anchorX: this.anchorX,
anchorY: this.anchorY,
colorRanges: this.colorRanges,
includeCaretPositions: true, //TODO parameterize
sdfGlyphSize: this.sdfGlyphSize
}, textRenderInfo => {
this._isSyncing = false;
// Save result for later use in onBeforeRender
this._textRenderInfo = textRenderInfo;
// Update the geometry attributes
this.geometry.updateGlyphs(
textRenderInfo.glyphBounds,
textRenderInfo.glyphAtlasIndices,
textRenderInfo.blockBounds,
textRenderInfo.chunkedBounds,
textRenderInfo.glyphColors
);
// If we had extra sync requests queued up, kick it off
const queued = this._queuedSyncs;
if (queued) {
this._queuedSyncs = null;
this._needsSync = true;
this.sync(() => {
queued.forEach(fn => fn && fn());
});
}
this.dispatchEvent(syncCompleteEvent);
if (callback) {
callback();
}
});
}
}
}
/**
* Initiate a sync if needed - note it won't complete until next frame at the
* earliest so if possible it's a good idea to call sync() manually as soon as
* all the properties have been set.
* @override
*/
onBeforeRender(renderer, scene, camera, geometry, material, group) {
this.sync();
// This may not always be a text material, e.g. if there's a scene.overrideMaterial present
if (material.isTroikaTextMaterial) {
this._prepareForRender(material);
}
}
/**
* Shortcut to dispose the geometry specific to this instance.
* Note: we don't also dispose the derived material here because if anything else is
* sharing the same base material it will result in a pause next frame as the program
* is recompiled. Instead users can dispose the base material manually, like normal,
* and we'll also dispose the derived material at that time.
*/
dispose() {
this.geometry.dispose();
}
/**
* @property {TroikaTextRenderInfo|null} textRenderInfo
* @readonly
* The current processed rendering data for this TextMesh, returned by the TextBuilder after
* a `sync()` call. This will be `null` initially, and may be stale for a short period until
* the asynchrous `sync()` process completes.
*/
get textRenderInfo() {
return this._textRenderInfo || null
}
// Handler for automatically wrapping the base material with our upgrades. We do the wrapping
// lazily on _read_ rather than write to avoid unnecessary wrapping on transient values.
get material() {
let derivedMaterial = this._derivedMaterial;
const baseMaterial = this._baseMaterial || this._defaultMaterial || (this._defaultMaterial = defaultMaterial.clone());
if (!derivedMaterial || derivedMaterial.baseMaterial !== baseMaterial) {
derivedMaterial = this._derivedMaterial = createTextDerivedMaterial(baseMaterial);
// dispose the derived material when its base material is disposed:
baseMaterial.addEventListener('dispose', function onDispose() {
baseMaterial.removeEventListener('dispose', onDispose);
derivedMaterial.dispose();
});
}
// If text outline is configured, render it as a preliminary draw using Three's multi-material
// feature (see GlyphsGeometry which sets up `groups` for this purpose) Doing it with multi
// materials ensures the layers are always rendered consecutively in a consistent order.
// Each layer will trigger onBeforeRender with the appropriate material.
if (this.outlineWidth || this.outlineBlur || this.outlineOffsetX || this.outlineOffsetY) {
let outlineMaterial = derivedMaterial._outlineMtl;
if (!outlineMaterial) {
outlineMaterial = derivedMaterial._outlineMtl = Object.create(derivedMaterial, {
id: {value: derivedMaterial.id + 0.1}
});
outlineMaterial.isTextOutlineMaterial = true;
outlineMaterial.depthWrite = false;
outlineMaterial.map = null; //???
derivedMaterial.addEventListener('dispose', function onDispose() {
derivedMaterial.removeEventListener('dispose', onDispose);
outlineMaterial.dispose();
});
}
return [
outlineMaterial,
derivedMaterial
]
} else {
return derivedMaterial
}
}
set material(baseMaterial) {
if (baseMaterial && baseMaterial.isTroikaTextMaterial) { //prevent double-derivation
this._derivedMaterial = baseMaterial;
this._baseMaterial = baseMaterial.baseMaterial;
} else {
this._baseMaterial = baseMaterial;
}
}
get glyphGeometryDetail() {
return this.geometry.detail
}
set glyphGeometryDetail(detail) {
this.geometry.detail = detail;
}
get curveRadius() {
return this.geometry.curveRadius
}
set curveRadius(r) {
this.geometry.curveRadius = r;
}
// Create and update material for shadows upon request:
get customDepthMaterial() {
return first(this.material).getDepthMaterial()
}
get customDistanceMaterial() {
return first(this.material).getDistanceMaterial()
}
_prepareForRender(material) {
const isOutline = material.isTextOutlineMaterial;
const uniforms = material.uniforms;
const textInfo = this.textRenderInfo;
if (textInfo) {
const {sdfTexture, blockBounds} = textInfo;
uniforms.uTroikaSDFTexture.value = sdfTexture;
uniforms.uTroikaSDFTextureSize.value.set(sdfTexture.image.width, sdfTexture.image.height);
uniforms.uTroikaSDFGlyphSize.value = textInfo.sdfGlyphSize;
uniforms.uTroikaSDFExponent.value = textInfo.sdfExponent;
uniforms.uTroikaTotalBounds.value.fromArray(blockBounds);
uniforms.uTroikaUseGlyphColors.value = !isOutline && !!textInfo.glyphColors;
let distanceOffset = 0;
let blurRadius = 0;
let strokeWidth = 0;
let fillOpacity;
let strokeOpacity;
let strokeColor;
let offsetX = 0;
let offsetY = 0;
if (isOutline) {
let {outlineWidth, outlineOffsetX, outlineOffsetY, outlineBlur, outlineOpacity} = this;
distanceOffset = this._parsePercent(outlineWidth) || 0;
blurRadius = Math.max(0, this._parsePercent(outlineBlur) || 0);
fillOpacity = outlineOpacity;
offsetX = this._parsePercent(outlineOffsetX) || 0;
offsetY = this._parsePercent(outlineOffsetY) || 0;
} else {
strokeWidth = Math.max(0, this._parsePercent(this.strokeWidth) || 0);
if (strokeWidth) {
strokeColor = this.strokeColor;
uniforms.uTroikaStrokeColor.value.set(strokeColor == null ? defaultStrokeColor : strokeColor);
strokeOpacity = this.strokeOpacity;
if (strokeOpacity == null) strokeOpacity = 1;
}
fillOpacity = this.fillOpacity;
}
uniforms.uTroikaDistanceOffset.value = distanceOffset;
uniforms.uTroikaPositionOffset.value.set(offsetX, offsetY);
uniforms.uTroikaBlurRadius.value = blurRadius;
uniforms.uTroikaStrokeWidth.value = strokeWidth;
uniforms.uTroikaStrokeOpacity.value = strokeOpacity;
uniforms.uTroikaFillOpacity.value = fillOpacity == null ? 1 : fillOpacity;
uniforms.uTroikaCurveRadius.value = this.curveRadius || 0;
let clipRect = this.clipRect;
if (clipRect && Array.isArray(clipRect) && clipRect.length === 4) {
uniforms.uTroikaClipRect.value.fromArray(clipRect);
} else {
// no clipping - choose a finite rect that shouldn't ever be reached by overflowing glyphs or outlines
const pad = (this.fontSize || 0.1) * 100;
uniforms.uTroikaClipRect.value.set(
blockBounds[0] - pad,
blockBounds[1] - pad,
blockBounds[2] + pad,
blockBounds[3] + pad
);
}
this.geometry.applyClipRect(uniforms.uTroikaClipRect.value);
}
uniforms.uTroikaSDFDebug.value = !!this.debugSDF;
material.polygonOffset = !!this.depthOffset;
material.polygonOffsetFactor = material.polygonOffsetUnits = this.depthOffset || 0;
// Shortcut for setting material color via `color` prop on the mesh; this is
// applied only to the derived material to avoid mutating a shared base material.
const color = isOutline ? (this.outlineColor || 0) : this.color;
if (color == null) {
delete material.color; //inherit from base
} else {
const colorObj = material.hasOwnProperty('color') ? material.color : (material.color = new THREE.Color());
if (color !== colorObj._input || typeof color === 'object') {
colorObj.set(colorObj._input = color);
}
}
// base orientation
let orient = this.orientation || defaultOrient;
if (orient !== material._orientation) {
let rotMat = uniforms.uTroikaOrient.value;
orient = orient.replace(/[^-+xyz]/g, '');
let match = orient !== defaultOrient && orient.match(/^([-+])([xyz])([-+])([xyz])$/);
if (match) {
let [, hSign, hAxis, vSign, vAxis] = match;
tempVec3a.set(0, 0, 0)[hAxis] = hSign === '-' ? 1 : -1;
tempVec3b.set(0, 0, 0)[vAxis] = vSign === '-' ? -1 : 1;
tempMat4.lookAt(origin, tempVec3a.cross(tempVec3b), tempVec3b);
rotMat.setFromMatrix4(tempMat4);
} else {
rotMat.identity();
}
material._orientation = orient;
}
}
_parsePercent(value) {
if (typeof value === 'string') {
let match = value.match(/^(-?[\d.]+)%$/);
let pct = match ? parseFloat(match[1]) : NaN;
value = (isNaN(pct) ? 0 : pct / 100) * this.fontSize;
}
return value
}
/**
* Translate a point in local space to an x/y in the text plane.
*/
localPositionToTextCoords(position, target = new THREE.Vector2()) {
target.copy(position); //simple non-curved case is 1:1
const r = this.curveRadius;
if (r) { //flatten the curve
target.x = Math.atan2(position.x, Math.abs(r) - Math.abs(position.z)) * Math.abs(r);
}
return target
}
/**
* Translate a point in world space to an x/y in the text plane.
*/
worldPositionToTextCoords(position, target = new THREE.Vector2()) {
tempVec3a.copy(position);
return this.localPositionToTextCoords(this.worldToLocal(tempVec3a), target)
}
/**
* @override Custom raycasting to test against the whole text block's max rectangular bounds
* TODO is there any reason to make this more granular, like within individual line or glyph rects?
*/
raycast(raycaster, intersects) {
const {textRenderInfo, curveRadius} = this;
if (textRenderInfo) {
const bounds = textRenderInfo.blockBounds;
const raycastMesh = curveRadius ? getCurvedRaycastMesh() : getFlatRaycastMesh();
const geom = raycastMesh.geometry;
const {position, uv} = geom.attributes;
for (let i = 0; i < uv.count; i++) {
let x = bounds[0] + (uv.getX(i) * (bounds[2] - bounds[0]));
const y = bounds[1] + (uv.getY(i) * (bounds[3] - bounds[1]));
let z = 0;
if (curveRadius) {
z = curveRadius - Math.cos(x / curveRadius) * curveRadius;
x = Math.sin(x / curveRadius) * curveRadius;
}
position.setXYZ(i, x, y, z);
}
geom.boundingSphere = this.geometry.boundingSphere;
geom.boundingBox = this.geometry.boundingBox;
raycastMesh.matrixWorld = this.matrixWorld;
raycastMesh.material.side = this.material.side;
tempArray.length = 0;
raycastMesh.raycast(raycaster, tempArray);
for (let i = 0; i < tempArray.length; i++) {
tempArray[i].object = this;
intersects.push(tempArray[i]);
}
}
}
copy(source) {
// Prevent copying the geometry reference so we don't end up sharing attributes between instances
const geom = this.geometry;
super.copy(source);
this.geometry = geom;
COPYABLE_PROPS.forEach(prop => {
this[prop] = source[prop];
});
return this
}
clone() {
return new this.constructor().copy(this)
}
} |
JavaScript | class resume extends Component {
render() {
return (
<div className="resume-container">
<div>
<Navigationbar />
</div>
<div className="resume">
<ResumeDownload />
{/* <iframe
title="resume"
src="https://resume.creddle.io/embed/6v3z8k47n2q"
width="100%"
height="100%"
seamless
/> */}
<MobileResponsiveResume />
</div>
</div>
);
}
} |
JavaScript | class Logger {
/**
* Create logger instance.
* @param {Number} level Log level.
* @param {String} prefix Prefix of logged messages.
*/
constructor(level = 2, prefix = undefined) {
this.setLevel(level)
this.setPrefix(prefix)
}
// Option setters and getters.
/**
* Get log level value.
* @returns {Number} log level value.
*/
getLevel () {
return this._level
}
/**
* Set log level value.
* @param {Number} level Log level value.
*/
setLevel (level) {
if (level !== null && level !== undefined && typeof (level) !== 'number') {
throw new Error('Log level value not of type number.')
}
this._level = level
}
/**
* Get log prefix value.
* @returns {String} Log prefix value.
*/
getPrefix () {
return this._prefix
}
/**
* Set log prefix value.
* @param {Number} prefix Log prefix value.
*/
setPrefix (prefix) {
if (prefix !== null && prefix !== undefined && typeof (prefix) !== 'string') {
throw new Error('Log prefix value not of type string.')
}
this._prefix = prefix
}
// Logging functions.
/**
* Undocumented alias for `info` function.
*/
log (parameters) {
return this.info(...parameters)
}
/**
* Logs info message to console if level is greater than 2.
* @param {String} message Message to output.
* @param {...Any} optionalParams Additional optional parameters.
*/
info (message, ...optionalParams) {
if (this._level < 3) {
return
}
if (this.getPrefix()) {
message = `${this.getPrefix()}: ${message}`
}
console.log(message, ...optionalParams)
}
/**
* Logs warning message to console if level is greater than 1.
* @param {String} message Message to output.
* @param {...Any} optionalParams Additional optional parameters.
*/
warn (message, ...optionalParams) {
if (this._level < 2) {
return
}
if (this.getPrefix()) {
message = `${this.getPrefix()}: ${message}`
}
console.warn(message, ...optionalParams)
}
/**
* Logs error message to console if level is greater than 1.
* @param {String} message Message to output.
* @param {...Any} optionalParams Additional optional parameters.
*/
error (message, ...optionalParams) {
if (this._level < 1) {
return
}
if (this.getPrefix()) {
message = `${this.getPrefix()}: ${message}`
}
console.error(message, ...optionalParams)
}
/**
* Logs trace to console.
* @param {String} message Message to output.
* @param {...Any} optionalParams Additional optional parameters.
*/
trace (message, ...optionalParams) {
if (this.getPrefix()) {
message = `${this.getPrefix()}: ${message}`
}
console.trace(message, ...optionalParams)
}
} |
JavaScript | class MatchlistProvider extends Provider {
/**
* @constructor
* @param {MatchlistProviderDefinition} def
*/
constructor(def) {
super(def);
this.Rebuild();
setInterval(x => this.Rebuild(), ((this.def.options && this.def.options.refresh) || 15) * 60 * 1000);
}
/**
* Called to rebuild the result set and populate the hain indexer with the results
*/
Rebuild() {
this.BuildMatchlist()
.then((AllItems) => {
if(this.def.log && this.def.log.results && AllItems.length > 0)
psl.log(AllItems);
let [IncludedItems, ExcludedItems] = this.FilterResultsWithRules(AllItems, this.def.rules || []);
let IncludedHainItems = this.TransformItems(IncludedItems);
if(this.def.log) {
if(this.def.log.included) {
psl.log(`Included Items (${this.def.name}):\n${indent(
IncludedHainItems.pluck('primaryText')
.sort()
.join('\n'))}`);
}
if(this.def.log.excluded) {
let ExcludedHainItems = this.TransformItems(ExcludedItems);
psl.log(`Excluded Items (${this.def.name}):\n${indent(
ExcludedHainItems.pluck('primaryText')
.sort()
.join('\n'))}`);
}
}
psl.indexer.set(this.def.name, IncludedHainItems);
psl.log(`Included ${IncludedItems.length}/${AllItems.length} items for ${this.def.name}`);
}).catch((err) => {
if(err instanceof Error) {
psl.log(err.stack);
} else {
psl.log(err);
}
psl.toast.enqueue(`Failed building resultset for ${this.constructor.name}.`);
});
}
/**
* @param Results {object[]}
* @param rules {PropertyFilterRule[]}
*
* @returns {[object[],object[]]}
*/
FilterResultsWithRules(Results, rules) {
let included = [],
excluded = [];
if(rules.length === 0)
return [Results, excluded];
for(let item of Results) {
let include = true;
for(let rule of rules) {
if(rule.exclude) {
if(this.RuleMatches(rule.exclude, item))
include = false;
} else if(rule.include) {
if(this.RuleMatches(rule.include, item))
include = true;
}
}
(include
? included
: excluded).push(item);
}
return [included, excluded];
}
/**
* Returns true if the given rule matches the item
* @param {object} rule
* @param {object} item
*/
RuleMatches(rule, item) {
for(let key of Object.keys(rule)) {
if(item[key] === undefined)
continue;
if(typeof item[key] === 'string') {
if(!(new RegExp(rule[key], 'i')).test(item[key]))
return false;
} else {
if(item[key] !== rule[key])
return false;
}
}
return true;
}
/**
*
* @param items {object[]}
* @returns {hain.IndexedResult[]}
*/
TransformItems(items) {
return items.
map((item) => {
let cmd = ResolveLiteral(this.def.result.cmd, item);
return {
id : cmd,
primaryText : ResolveLiteral(this.def.result.title, item),
secondaryText: ResolveLiteral(this.def.result.desc, item),
icon : this.def.result.icon ? ResolveLiteral(this.def.result.icon, item) : ResolveIcon(cmd),
group : 'Providers',
};
});
}
/**
* Called to build the matchlist
*
* @returns {Promise<object[]>}
*/
BuildMatchlist() {
throw new Error("MatchlistProvider.BuildMatchlist() must be over-ridden.");
}
} |
JavaScript | class TrackDOMNodeToTreeNode extends LitHtml.Directive.Directive {
constructor(partInfo) {
super(partInfo);
if (partInfo.type !== LitHtml.Directive.PartType.ATTRIBUTE) {
throw new Error('TrackDOMNodeToTreeNode directive must be used as an attribute.');
}
}
update(part, [weakMap, treeNode]) {
const elem = part.element;
if (!(elem instanceof HTMLLIElement)) {
throw new Error('trackTreeNodeToDOMNode must be used on <li> elements.');
}
weakMap.set(elem, treeNode);
}
/*
* Because this directive doesn't render anything, there's no implementation
* here for the render method. But we need it to state the params the
* directive takes so the update() method's types are correct. Unfortunately
* we have to pass any as the generic type because we can't define this class
* using a generic - the generic gets lost when wrapped in the directive call
* below.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
render(_weakmap, _treeNode) {
}
} |
JavaScript | class Businesses {
/**
*
*Register business
*@param {any} req - request value - handles data coming from the user
*@param {any} res - response value - this is the response gotten after
interaction with the Api routes
*@return {json} response object gotten
*@memberof Businesses
*/
static createBusiness(req, res) {
const {
name, email, address, location, category
} = req.body;
const filteredBusiness = businesses.filter(business => business.name === name)[0];
if (filteredBusiness) {
res.status(400).json({
message: 'Business with name, is already taken',
error: true
});
}
if (!filteredBusiness) {
businesses.push({
id: businesses[businesses.length - 1].id + 1,
name,
email,
address,
location,
category
});
}
return res.status(201).json({
message: 'Business registration successful',
error: 'false'
});
}
/**
*
*Display all business
*@param {any} req - request value - handles data coming from the user
*@param {any} res - response value - this is the response gotten after
interaction with the Api routes
*@return {json} response object gotten
*@memberof Businesses
*/
static getBusiness(req, res) {
return res.status(200).json({
businesses,
error: 'false'
});
}
/**
*
*Get a business by id
*@param {any} req - request value - handles data coming from the user
*@param {any} res - response value - this is the response gotten after
interaction with the Api routes
*@return {json} response object gotten
*@memberof filterBusiness
*/
static getOneBusiness(req, res) {
const businessId = parseInt(req.params.businessId, 10);
const filteredBusiness = businesses.filter(business => business.id === businessId)[0];
if (!filteredBusiness) {
res.status(404).json({
messsage: 'Business not found',
error: true
});
}
res.status(200).json(filteredBusiness);
}
/**
*
*Update a business by id
*@param {any} req - request value - handles data coming from the user
*@param {any} res - response value - this is the response gotten after
interaction with the Api routes
*@return {json} response object gotten
*@memberof Businesses
*/
static updateBusiness(req, res) {
const {
name, email, address, location, category
} = req.body;
const businessId = parseInt(req.params.businessId, 10);
const filteredBusiness = businesses.filter(business => business.id === businessId)[0];
if (!filteredBusiness) {
res.status(404).json({
messsage: 'Business not found',
error: true
});
}
filteredBusiness.name = name || filteredBusiness.name;
filteredBusiness.email = email || filteredBusiness.email;
filteredBusiness.address = address || filteredBusiness.address;
filteredBusiness.location = location || filteredBusiness.location;
filteredBusiness.category = category || filteredBusiness.category;
return res.status(201).json({
message: 'Business profile updated',
error: false
});
}
/**
*
*Delete a business by id
*@param {any} req - request value - handles data coming from the user
*@param {any} res - response value - this is the response gotten after
interaction with the Api routes
*@return {status} response object gotten
*@memberof Businesses
*/
static deleteBusiness(req, res) {
const businessId = parseInt(req.params.businessId, 10);
for (let i = 0; i <= businesses.length; i += 1) {
if (businessId === businesses[i].id) {
businesses.splice(i, 1);
res.sendStatus(204);
}
}
// return res.status(404).json({
// messsage: 'Business not found',
// error: true
// });
}
} |
JavaScript | class CardIdentifier{
/**
* CardIdentifier constructor.
* The parameters are provided here to customize the functionality of checks by altering
* the level of checks, the probabilities assigned to various validations, the constants
* used for validation and the markers used to identify suspected entries
*
* @param {number} thresholdAlert the threshold used for separating numbers which we are sure about and those we aren't
* @param {number} thresholdNotice the threshold used for separating numbers which we are sure about and those we aren't
* @param {int} checkLevel the level of check used to inspect the text and identify numbers [1-2]
* @param {string} alert the text used to identify the numbers that are identified with certainty
* @param {string} notice the text used to identify the numbers that are identified without uncertainty
* @param {int} maxCardLength the maximum length of card to detect, this is used to break the text into fragments only
* @param {int} minCardLength the minimum length of card to detect, this is used to break the text into fragments only
* @param {Object} probabilities the probabilities assigned to various validations in ValidationFunctions
* @param {ValidationConstants} constantsClass the constants used for validation
*/
constructor(thresholdAlert = null,thresholdNotice = null, checkLevel = null, alert = null,
notice = null, maxCardLength = null, minCardLength = null, probabilities = null,
constantsClass = null){
this.alert = (alert === null) ? 'ALERT' : alert;
this.checkLevel = (checkLevel === null) ? 2 : checkLevel;
this.notice = (notice === null) ? 'NOTICE' : notice;
this.textManipulator = new TextManipulator(maxCardLength, minCardLength);
this.thresholdAlert = thresholdAlert;
this.thresholdNotice = thresholdNotice;
this.validator = new CardNumberValidator(probabilities, constantsClass);
}
/**
* inspectText
* inspects the provided text and formats the text to reflect identified
* card numbers in the text.
* This function works without setting any of the properties in the constructor
* with defaults in all the subsequent classes.
*
* @param {string} text the text that needs to be inspected
* @return string formatted text
*/
inspectText(text){
const fragments = this.textManipulator.getSuspectedFragments(text, this.checkLevel);
for(let i=0; i<fragments.length; i++){
const number = this.textManipulator.extractNumberFromText(fragments[i]);
if(number !== null){
if(this.validator.isPossibleToBeACreditCard(number)){
if(this.validator.isSurelyACreditCardNumber(number, this.thresholdAlert)){
text = this.textManipulator.markFragment(text,fragments[i],this.alert);
}
}
}
}
return text;
}
/**
* inspectTextWithNotices
* inspects the provided text and formats the text to reflect identified
* card numbers in the text.
* A notice is added to numbers that have a probability more than thresholdNotice
* of being a credit card.
*
* To make use of this function properly set the thresholdAlert and thresholdNotice
* in the constructor to a desired value. If you don't want any thresholds for the
* notices then just leave it blank or pass null.
*
* @param {string} text the text that needs to be inspected
* @return string formatted text
*/
inspectTextWithNotices(text){
const fragments = this.textManipulator.getSuspectedFragments(text, this.checkLevel);
for(let i=0; i<fragments.length; i++){
const number = this.textManipulator.extractNumberFromText(fragments[i]);
if(number !== null){
if(this.validator.isPossibleToBeACreditCard(number)){
const probability = this.validator.calculateProbabilityOfBeingACreditCard(number);
if(this.thresholdAlert === null || probability > this.thresholdAlert){
text = this.textManipulator.markFragment(text,fragments[i],this.alert);
}
else if(this.thresholdNotice === null || probability > this.thresholdNotice){
text = this.textManipulator.markFragment(text,fragments[i],this.notice);
}
}
}
}
return text;
}
} |
JavaScript | class MouseShadowElement extends ECE {
/**
* @param {object} domElement - DOM element that is transformed
* @param {object} cssClasses - CSS classes that will be added to the
* dom element
*/
constructor(domElement, cssClasses) {
/**
* @type {object}
*/
super(domElement, cssClasses.concat(['mouse-shadow-element']));
}
} |
JavaScript | class Block{
constructor(timestamp,transactions,previousHash=''){
this.timestamp = timestamp;
this.transactions = transactions;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
//Block also contains its own hash and hash of previous block
calculateHash(){
return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions)+this.nonce).toString();
}
//Nonce value of hash function changes until substring of hash is equal to array of zeros
mineBlock(difficulty){
while(this.hash.substring(0,difficulty)!==Array(difficulty + 1).join("0")){
this.nonce++;
this.hash = this.calculateHash();
}
console.log("BLOCK MINED:"+this.hash);
}
//Verify all the transaction in the current block
hashValidTransactions(){
for(const tx of this.transactions){
if(!tx.isValid()){
return false;
}
}
return true;
}
} |
JavaScript | class Blockchain{
//When a Blockchain object is created, an initial Block is also created
constructor(){
this.chain = [this.createGenesisBlock()];
this.difficulty = 2;
this.pendingTransaction = [];
this.miningReward = 100;
}
//Method is only called when the a BlockChain object is created
createGenesisBlock(){
return new Block("01/02/2000","","0")
}
//Return the last Block in the Blockchain
getLatestBlock(){
return this.chain[this.chain.length-1];
}
//Adds a Block to Blockchain after mining
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
newBlock.mineBlock(this.difficulty)
this.chain.push(newBlock);
}
myPendingTransaction(miningRewardAddress){
let block = new Block(Date.now(),this.pendingTransaction);
block.mineBlock(this.difficulty);
console.log("Block Successfully Mined!");
this.addBlock(block);
//this.chain.push(block);
this.pendingTransaction = [];
this.pendingTransaction.push(new Transaction(null,miningRewardAddress,this.miningReward));
}
addTransaction(transaction){
//from and to address must be filled in
if(!transaction.fromAddress || !transaction.toAddress){
throw new Error("Transaction must include from and to address");
}
//Transaction must be valid
if(!transaction.isValid()){
throw new Error("Cannot add invalid transaction to chain");
}
this.pendingTransaction.push(transaction);
//console.log(this.pendingTransaction.length);
}
getBalanceOfAddress(addressOfMiner){
let balance = 0;
//console.log("How many blocks:",this.chain.length);
for(const block of this.chain){
//console.log("How many transactions:",block.transactions[0].toAddress);
for(const trans of block.transactions){
if(trans.fromAddress===addressOfMiner){
balance -=trans.amount;
//console.log("Balance is :",balance);
}
if(trans.toAddress===addressOfMiner){
balance +=trans.amount;
}
//console.log("trans.toAddress is :",trans.toAddress);
}
}
return balance;
}
//Shows that the block can not be manipulated
//Verifies that the hashes are correct and each block links to previous block
isChainValid(){
for(let i=1;i<this.chain.length;i++){
const currentBlock = this.chain[i];
const previousBlock = this.chain[i-1];
//Verifies that the transaction in the current block are valid
if(!currentBlock.hashValidTransactions()){
//Blockchain in invalid state
return false;
}
//Chain is false if current and recalculated Hash donot match
if(currentBlock.hash!==currentBlock.calculateHash()){
//Blockchain in invalid state
return false;
}
//Chain is false if previousHash of current block does not match with hash of previousBlock
if(currentBlock.previousHash!==previousBlock.hash){
//Blockchain in invalid state
return false;
}
}
return true;
}
} |
JavaScript | class MouseObserver {
/**
* @param {Element} domElement - the dom element to observe mouse events in
* @param {Object} params - parameters object
* @param {Integer} params.hoverTimeout - timeout in ms until the {@link MouseSignals.hovered}
* signal is fired, set to -1 to ignore hovering
* @param {Boolean} params.handleScroll - whether or not to handle scroll events
* @param {Integer} params.doubleClickSpeed - max time in ms to trigger double click
*/
constructor (domElement, params) {
/**
* Events emitted by the mouse observer
* @type {MouseSignals}
*/
this.signals = {
moved: new Signal(),
scrolled: new Signal(),
dragged: new Signal(),
dropped: new Signal(),
clicked: new Signal(),
hovered: new Signal(),
doubleClicked: new Signal()
}
var p = Object.assign({}, params)
this.hoverTimeout = defaults(p.hoverTimeout, 50)
this.handleScroll = defaults(p.handleScroll, true)
this.doubleClickSpeed = defaults(p.doubleClickSpeed, 500)
this.domElement = domElement
this.domElement.style.touchAction = 'none'
/**
* Position on page
* @type {Vector2}
*/
this.position = new Vector2()
/**
* Previous position on page
* @type {Vector2}
*/
this.prevPosition = new Vector2()
/**
* Position on page when clicked
* @type {Vector2}
*/
this.down = new Vector2()
/**
* Position on dom element
* @type {Vector2}
*/
this.canvasPosition = new Vector2()
/**
* Flag indicating if the mouse is moving
* @type {Boolean}
*/
this.moving = false
/**
* Flag indicating if the mouse is hovering
* @type {Boolean}
*/
this.hovering = true
/**
* Flag indicating if there was a scolling event
* since the last mouse move
* @type {Boolean}
*/
this.scrolled = false
/**
* Timestamp of last mouse move
* @type {Number}
*/
this.lastMoved = Infinity
/**
* Indicates which mouse button was pressed:
* 0: No button; 1: Left button; 2: Middle button; 3: Right button
* @type {Integer}
*/
this.which = undefined
/**
* Indicates which mouse buttons were pressed:
* 0: No button; 1: Left button; 2: Right button; 4: Middle button
* @type {Integer}
*/
this.buttons = undefined
/**
* Flag indicating if the mouse is pressed down
* @type {Boolean}
*/
this.pressed = undefined
/**
* Flag indicating if the alt key is pressed
* @type {Boolean}
*/
this.altKey = undefined
/**
* Flag indicating if the ctrl key is pressed
* @type {Boolean}
*/
this.ctrlKey = undefined
/**
* Flag indicating if the meta key is pressed
* @type {Boolean}
*/
this.metaKey = undefined
/**
* Flag indicating if the shift key is pressed
* @type {Boolean}
*/
this.shiftKey = undefined
this._listen = this._listen.bind(this)
this._onMousewheel = this._onMousewheel.bind(this)
this._onMousemove = this._onMousemove.bind(this)
this._onMousedown = this._onMousedown.bind(this)
this._onMouseup = this._onMouseup.bind(this)
this._onContextmenu = this._onContextmenu.bind(this)
this._onTouchstart = this._onTouchstart.bind(this)
this._onTouchend = this._onTouchend.bind(this)
this._onTouchmove = this._onTouchmove.bind(this)
this._listen()
document.addEventListener('mousewheel', this._onMousewheel)
document.addEventListener('wheel', this._onMousewheel)
document.addEventListener('MozMousePixelScroll', this._onMousewheel)
document.addEventListener('mousemove', this._onMousemove)
document.addEventListener('mousedown', this._onMousedown)
document.addEventListener('mouseup', this._onMouseup)
document.addEventListener('contextmenu', this._onContextmenu)
document.addEventListener('touchstart', this._onTouchstart)
document.addEventListener('touchend', this._onTouchend)
document.addEventListener('touchmove', this._onTouchmove)
this.prevClickCP = new Vector2()
}
get key () {
let key = 0
if (this.altKey) key += 1
if (this.ctrlKey) key += 2
if (this.metaKey) key += 4
if (this.shiftKey) key += 8
return key
}
setParameters (params) {
var p = Object.assign({}, params)
this.hoverTimeout = defaults(p.hoverTimeout, this.hoverTimeout)
}
/**
* listen to mouse actions
* @emits {MouseSignals.clicked} when clicked
* @emits {MouseSignals.hovered} when hovered
* @return {undefined}
*/
_listen () {
const now = window.performance.now()
const cp = this.canvasPosition
if (this.doubleClickPending && now - this.lastClicked > this.doubleClickSpeed) {
this.doubleClickPending = false
}
if (now - this.lastMoved > this.hoverTimeout) {
this.moving = false
}
if (this.scrolled || (!this.moving && !this.hovering)) {
this.scrolled = false
if (this.hoverTimeout !== -1 && this.overElement) {
this.hovering = true
this.signals.hovered.dispatch(cp.x, cp.y)
}
}
window.requestAnimationFrame(this._listen)
}
/**
* handle mouse scroll
* @emits {MouseSignals.scrolled} when scrolled
* @param {Event} event - mouse event
* @return {undefined}
*/
_onMousewheel (event) {
if (event.target !== this.domElement || !this.handleScroll) {
return
}
event.preventDefault()
this._setKeys(event)
var delta = 0
if (event.wheelDelta) {
// WebKit / Opera / Explorer 9
delta = event.wheelDelta / 40
} else if (event.detail) {
// Firefox
delta = -event.detail / 3
} else {
// Firefox or IE 11
delta = -event.deltaY / (event.deltaMode ? 0.33 : 30)
}
this.signals.scrolled.dispatch(delta)
setTimeout(() => {
this.scrolled = true
}, this.hoverTimeout)
}
/**
* handle mouse move
* @emits {MouseSignals.moved} when moved
* @emits {MouseSignals.dragged} when dragged
* @param {Event} event - mouse event
* @return {undefined}
*/
_onMousemove (event) {
if (event.target === this.domElement) {
event.preventDefault()
this.overElement = true
} else {
this.overElement = false
}
this._setKeys(event)
this.moving = true
this.hovering = false
this.lastMoved = window.performance.now()
this.prevPosition.copy(this.position)
this.position.set(event.clientX, event.clientY)
this._setCanvasPosition(event)
const dx = this.prevPosition.x - this.position.x
const dy = this.prevPosition.y - this.position.y
this.signals.moved.dispatch(dx, dy)
if (this.pressed) {
this.signals.dragged.dispatch(dx, dy)
}
}
_onMousedown (event) {
if (event.target !== this.domElement) {
return
}
event.preventDefault()
this._setKeys(event)
this.moving = false
this.hovering = false
this.down.set(event.clientX, event.clientY)
this.position.set(event.clientX, event.clientY)
this.which = event.which
this.buttons = getMouseButtons(event)
this.pressed = true
this._setCanvasPosition(event)
}
/**
* handle mouse up
* @emits {MouseSignals.doubleClicked} when double clicked
* @emits {MouseSignals.dropped} when dropped
* @param {Event} event - mouse event
* @return {undefined}
*/
_onMouseup (event) {
if (event.target === this.domElement) {
event.preventDefault()
}
this._setKeys(event)
const cp = this.canvasPosition
if (this._distance() < 4) {
this.lastClicked = window.performance.now()
if (this.doubleClickPending && this.prevClickCP.distanceTo(cp) < 4) {
this.signals.doubleClicked.dispatch(cp.x, cp.y)
this.doubleClickPending = false
} else {
this.signals.clicked.dispatch(cp.x, cp.y)
this.doubleClickPending = true
}
this.prevClickCP.copy(cp)
}
this.which = undefined
this.buttons = undefined
this.pressed = undefined
// if (this._distance() > 3 || event.which === RightMouseButton) {
// this.signals.dropped.dispatch();
// }
}
_onContextmenu (event) {
if (event.target === this.domElement) {
event.preventDefault()
}
}
_onTouchstart (event) {
if (event.target !== this.domElement) {
return
}
event.preventDefault()
this.pressed = true
switch (event.touches.length) {
case 1: {
this.moving = false
this.hovering = false
this.down.set(
event.touches[ 0 ].pageX,
event.touches[ 0 ].pageY
)
this.position.set(
event.touches[ 0 ].pageX,
event.touches[ 0 ].pageY
)
this._setCanvasPosition(event.touches[ 0 ])
break
}
case 2: {
this.down.set(
(event.touches[ 0 ].pageX + event.touches[ 1 ].pageX) / 2,
(event.touches[ 0 ].pageY + event.touches[ 1 ].pageY) / 2
)
this.position.set(
(event.touches[ 0 ].pageX + event.touches[ 1 ].pageX) / 2,
(event.touches[ 0 ].pageY + event.touches[ 1 ].pageY) / 2
)
this.lastTouchDistance = getTouchDistance(event)
}
}
}
_onTouchend (event) {
if (event.target === this.domElement) {
event.preventDefault()
}
this.which = undefined
this.buttons = undefined
this.pressed = undefined
}
_onTouchmove (event) {
if (event.target === this.domElement) {
event.preventDefault()
this.overElement = true
} else {
this.overElement = false
}
switch (event.touches.length) {
case 1: {
this._setKeys(event)
this.which = LeftMouseButton
this.buttons = 1
this.moving = true
this.hovering = false
this.lastMoved = window.performance.now()
this.prevPosition.copy(this.position)
this.position.set(
event.touches[ 0 ].pageX,
event.touches[ 0 ].pageY
)
this._setCanvasPosition(event.touches[ 0 ])
const dx = this.prevPosition.x - this.position.x
const dy = this.prevPosition.y - this.position.y
this.signals.moved.dispatch(dx, dy)
if (this.pressed) {
this.signals.dragged.dispatch(dx, dy)
}
break
}
case 2: {
const touchDistance = getTouchDistance(event)
const delta = touchDistance - this.lastTouchDistance
this.lastTouchDistance = touchDistance
this.prevPosition.copy(this.position)
this.position.set(
(event.touches[ 0 ].pageX + event.touches[ 1 ].pageX) / 2,
(event.touches[ 0 ].pageY + event.touches[ 1 ].pageY) / 2
)
if (Math.abs(delta) > 2 && this.handleScroll &&
this.position.distanceTo(this.prevPosition) < 2
) {
this.which = 0
this.buttons = 0
this.signals.scrolled.dispatch(delta / 2)
} else {
this.which = RightMouseButton
this.buttons = 2
const dx = this.prevPosition.x - this.position.x
const dy = this.prevPosition.y - this.position.y
this.signals.moved.dispatch(dx, dy)
if (this.pressed) {
this.signals.dragged.dispatch(dx, dy)
}
}
}
}
}
_distance () {
return this.position.distanceTo(this.down)
}
_setCanvasPosition (event) {
const box = this.domElement.getBoundingClientRect()
let offsetX, offsetY
if ('offsetX' in event && 'offsetY' in event) {
offsetX = event.offsetX
offsetY = event.offsetY
} else {
offsetX = event.clientX - box.left
offsetY = event.clientY - box.top
}
this.canvasPosition.set(offsetX, box.height - offsetY)
}
_setKeys (event) {
this.altKey = event.altKey
this.ctrlKey = event.ctrlKey
this.metaKey = event.metaKey
this.shiftKey = event.shiftKey
}
dispose () {
document.removeEventListener('mousewheel', this._onMousewheel)
document.removeEventListener('wheel', this._onMousewheel)
document.removeEventListener('MozMousePixelScroll', this._onMousewheel)
document.removeEventListener('mousemove', this._onMousemove)
document.removeEventListener('mousedown', this._onMousedown)
document.removeEventListener('mouseup', this._onMouseup)
document.removeEventListener('contextmenu', this._onContextmenu)
document.removeEventListener('touchstart', this._onTouchstart)
document.removeEventListener('touchend', this._onTouchend)
document.removeEventListener('touchmove', this._onTouchmove)
}
} |
JavaScript | class FallbackEngineHost {
constructor() {
this._hosts = [];
}
addHost(host) {
this._hosts.push(host);
}
createCollectionDescription(name) {
for (const host of this._hosts) {
try {
const description = host.createCollectionDescription(name);
return { name, host, description };
}
catch (_) {
}
}
throw new src_1.UnknownCollectionException(name);
}
createSchematicDescription(name, collection) {
const description = collection.host.createSchematicDescription(name, collection.description);
if (!description) {
return null;
}
return { name, collection, description };
}
getSchematicRuleFactory(schematic, collection) {
return collection.host.getSchematicRuleFactory(schematic.description, collection.description);
}
createSourceFromUrl(url, context) {
return context.schematic.collection.description.host.createSourceFromUrl(url, context);
}
transformOptions(schematic, options, context) {
// tslint:disable-next-line:no-any https://github.com/ReactiveX/rxjs/issues/3989
return (rxjs_1.of(options)
.pipe(...this._hosts
.map(host => operators_1.mergeMap((opt) => host.transformOptions(schematic, opt, context)))));
}
transformContext(context) {
let result = context;
this._hosts.forEach(host => {
result = (host.transformContext(result) || result);
});
return result;
}
/**
* @deprecated Use `listSchematicNames`.
*/
listSchematics(collection) {
return this.listSchematicNames(collection.description);
}
listSchematicNames(collection) {
const allNames = new Set();
this._hosts.forEach(host => {
try {
host.listSchematicNames(collection.description).forEach(name => allNames.add(name));
}
catch (_) { }
});
return [...allNames];
}
createTaskExecutor(name) {
for (const host of this._hosts) {
if (host.hasTaskExecutor(name)) {
return host.createTaskExecutor(name);
}
}
return rxjs_1.throwError(new src_1.UnregisteredTaskException(name));
}
hasTaskExecutor(name) {
for (const host of this._hosts) {
if (host.hasTaskExecutor(name)) {
return true;
}
}
return false;
}
} |
JavaScript | class Hash {
// Creates a new hash
constructor() {
// Data fed to this hash
this._data = null;
// Resulting digest
this._digest = null;
this.reset();
}
// Retrieves digest (finalizes this hash if needed)
get digest() {
if (!this._digest) {
this.finalize();
}
return this._digest;
}
// Resets this hash, voiding the digest and allowing new feeds
reset() {
this._data = new ByteBuffer(0, ByteBuffer.BIG_ENDIAN, true);
this._digest = null;
return this;
}
// Feeds hash given value
feed(value) {
if (this._digest) {
return this;
}
if (value.constructor === String) {
this._data.writeString(value);
} else {
this._data.write(value);
}
return this;
}
// Finalizes this hash, calculates the digest and blocks additional feeds
finalize() {
return this;
}
} |
JavaScript | class HashTable {
constructor(initialCapacity = 13) {
this.inserts = 0;
this.table = createTable(initialCapacity);
}
put(key = null, value = null) {
const self = this;
const {table, inserts} = self;
const searchResult = search(key, table);
const {bucket, index} = searchResult;
if (index === -1) {
insert(key, value, table);
self.inserts += 1;
if (shouldRehash(inserts + 1, table)) {
self.rehash();
}
} else {
bucket[index + 1] = value;
}
return self;
}
getVal(key) {
const searchResult = search(key, this.table);
const {bucket, index} = searchResult;
return index !== -1 ? bucket[index + 1] : undefined;
}
remove(key) {
const self = this;
const searchResult = search(key, self.table);
const {bucket, index} = searchResult;
if (index !== -1) {
self.inserts -= 1;
bucket.splice(index, 2);
return true;
}
return false;
}
contains(key) {
return this.getVal(key) !== undefined;
}
/**
* Resizes (2x) and rehashes all keys in HashTable
* @returns {undefined}
*/
rehash() {
const oldTable = this.table;
const newTable = createTable(oldTable.length * 2);
const oldLen = oldTable.length;
for (let i = 0; i < oldLen; i += 1) {
const currentBucket = oldTable[i];
for (let j = 0; j < currentBucket.length; j += 2) {
const oldKey = currentBucket[j];
const oldValue = currentBucket[j + 1];
insert(oldKey, oldValue, newTable);
}
}
oldTable.length = 0;
this.table = newTable;
}
keys() {
return getKeysOrValues('keys', this.table);
}
values() {
return getKeysOrValues('values', this.table);
}
/**
* Returns the number of buckets in the Associative Array
* @returns {number} Size of inner Associative Array
*/
tableSize() {
return this.table.length;
}
clear() {
const self = this;
self.table.length = 0;
self.inserts = 0;
self.table = createTable(13);
}
size() {
return this.inserts;
}
} |
JavaScript | class Scope {
constructor(name, dependencyGraphKey, program) {
this.name = name;
this.dependencyGraphKey = dependencyGraphKey;
this.program = program;
this.programHandles = [];
this.cache = new Cache_1.Cache();
/**
* The list of diagnostics found specifically for this scope. Individual file diagnostics are stored on the files themselves.
*/
this.diagnostics = [];
this.isValidated = false;
//used for improved logging performance
this._debugLogComponentName = `Scope '${chalk_1.default.redBright(this.name)}'`;
//anytime a dependency for this scope changes, we need to be revalidated
this.programHandles.push(this.program.dependencyGraph.onchange(this.dependencyGraphKey, this.onDependenciesChanged.bind(this), true));
}
/**
* A dictionary of namespaces, indexed by the lower case full name of each namespace.
* If a namespace is declared as "NameA.NameB.NameC", there will be 3 entries in this dictionary,
* "namea", "namea.nameb", "namea.nameb.namec"
*/
get namespaceLookup() {
return this.cache.getOrAdd('namespaceLookup', () => this.buildNamespaceLookup());
}
/**
* Get the class with the specified name.
* @param className - the all-lower-case namespace-included class name
*/
getClass(className) {
const classMap = this.getClassMap();
return classMap.get(className);
}
/**
* A dictionary of all classes in this scope. This includes namespaced classes always with their full name.
* The key is stored in lower case
*/
getClassMap() {
return this.cache.getOrAdd('classMap', () => {
const map = new Map();
this.enumerateFiles((file) => {
var _a;
for (let cls of file.parser.references.classStatements) {
const lowerClassName = (_a = cls.getName(parser_1.ParseMode.BrighterScript)) === null || _a === void 0 ? void 0 : _a.toLowerCase();
//only track classes with a defined name (i.e. exclude nameless malformed classes)
if (lowerClassName) {
map.set(lowerClassName, cls);
}
}
});
return map;
});
}
onDependenciesChanged(key) {
this.logDebug('invalidated because dependency graph said [', key, '] changed');
this.invalidate();
}
/**
* Clean up all event handles
*/
dispose() {
for (let disconnect of this.programHandles) {
disconnect();
}
}
/**
* Does this scope know about the given namespace name?
* @param namespaceName - the name of the namespace (i.e. "NameA", or "NameA.NameB", etc...)
*/
isKnownNamespace(namespaceName) {
let namespaceNameLower = namespaceName.toLowerCase();
this.enumerateFiles((file) => {
for (let namespace of file.parser.references.namespaceStatements) {
let loopNamespaceNameLower = namespace.name.toLowerCase();
if (loopNamespaceNameLower === namespaceNameLower || loopNamespaceNameLower.startsWith(namespaceNameLower + '.')) {
return true;
}
}
});
return false;
}
/**
* Get the parent scope for this scope (for source scope this will always be the globalScope).
* XmlScope overrides this to return the parent xml scope if available.
* For globalScope this will return null.
*/
getParentScope() {
let scope;
//use the global scope if we didn't find a sope and this is not the global scope
if (this.program.globalScope !== this) {
scope = this.program.globalScope;
}
if (scope) {
return scope;
}
else {
//passing null to the cache allows it to skip the factory function in the future
return null;
}
}
/**
* Get the file with the specified pkgPath
*/
getFile(pathAbsolute) {
pathAbsolute = util_1.standardizePath `${pathAbsolute}`;
let files = this.getFiles();
for (let file of files) {
if (file.pathAbsolute === pathAbsolute) {
return file;
}
}
}
getFiles() {
return this.cache.getOrAdd('files', () => {
let result = [];
let dependencies = this.program.dependencyGraph.getAllDependencies(this.dependencyGraphKey);
for (let dependency of dependencies) {
//skip scopes and components
if (dependency.startsWith('component:')) {
continue;
}
let file = this.program.getFileByPkgPath(dependency);
if (file) {
result.push(file);
}
}
this.logDebug('getFiles', () => result.map(x => x.pkgPath));
return result;
});
}
get fileCount() {
return Object.keys(this.getFiles()).length;
}
/**
* Get the list of errors for this scope. It's calculated on the fly, so
* call this sparingly.
*/
getDiagnostics() {
let diagnosticLists = [this.diagnostics];
//add diagnostics from every referenced file
this.enumerateFiles((file) => {
diagnosticLists.push(file.getDiagnostics());
});
let allDiagnostics = Array.prototype.concat.apply([], diagnosticLists);
let filteredDiagnostics = allDiagnostics.filter((x) => {
return !util_1.util.diagnosticIsSuppressed(x);
});
//filter out diangostics that match any of the comment flags
return filteredDiagnostics;
}
addDiagnostics(diagnostics) {
this.diagnostics.push(...diagnostics);
}
/**
* Get the list of callables available in this scope (either declared in this scope or in a parent scope)
*/
getAllCallables() {
//get callables from parent scopes
let parentScope = this.getParentScope();
if (parentScope) {
return [...this.getOwnCallables(), ...parentScope.getAllCallables()];
}
else {
return [...this.getOwnCallables()];
}
}
/**
* Get the callable with the specified name.
* If there are overridden callables with the same name, the closest callable to this scope is returned
* @param name
*/
getCallableByName(name) {
let lowerName = name.toLowerCase();
let callables = this.getAllCallables();
for (let callable of callables) {
if (callable.callable.getName(parser_1.ParseMode.BrighterScript).toLowerCase() === lowerName) {
return callable.callable;
}
}
}
enumerateFiles(callback) {
const files = this.getFiles();
for (const file of files) {
//skip files that have a typedef
if (file.hasTypedef) {
continue;
}
callback(file);
}
}
/**
* Get the list of callables explicitly defined in files in this scope.
* This excludes ancestor callables
*/
getOwnCallables() {
let result = [];
this.logDebug('getOwnCallables() files: ', () => this.getFiles().map(x => x.pkgPath));
//get callables from own files
this.enumerateFiles((file) => {
for (let callable of file.callables) {
result.push({
callable: callable,
scope: this
});
}
});
return result;
}
/**
* Builds a tree of namespace objects
*/
buildNamespaceLookup() {
let namespaceLookup = {};
this.enumerateFiles((file) => {
var _a;
for (let namespace of file.parser.references.namespaceStatements) {
//TODO should we handle non-brighterscript?
let name = namespace.nameExpression.getName(parser_1.ParseMode.BrighterScript);
let nameParts = name.split('.');
let loopName = null;
//ensure each namespace section is represented in the results
//(so if the namespace name is A.B.C, this will make an entry for "A", an entry for "A.B", and an entry for "A.B.C"
for (let part of nameParts) {
loopName = loopName === null ? part : `${loopName}.${part}`;
let lowerLoopName = loopName.toLowerCase();
namespaceLookup[lowerLoopName] = (_a = namespaceLookup[lowerLoopName]) !== null && _a !== void 0 ? _a : {
file: file,
fullName: loopName,
nameRange: namespace.nameExpression.range,
lastPartName: part,
namespaces: {},
classStatements: {},
functionStatements: {},
statements: []
};
}
let ns = namespaceLookup[name.toLowerCase()];
ns.statements.push(...namespace.body.statements);
for (let statement of namespace.body.statements) {
if (reflection_1.isClassStatement(statement)) {
ns.classStatements[statement.name.text.toLowerCase()] = statement;
}
else if (reflection_1.isFunctionStatement(statement)) {
ns.functionStatements[statement.name.text.toLowerCase()] = statement;
}
}
}
//associate child namespaces with their parents
for (let key in namespaceLookup) {
let ns = namespaceLookup[key];
let parts = ns.fullName.split('.');
if (parts.length > 1) {
//remove the last part
parts.pop();
let parentName = parts.join('.');
namespaceLookup[parentName.toLowerCase()].namespaces[ns.lastPartName.toLowerCase()] = ns;
}
}
});
return namespaceLookup;
}
getNamespaceStatements() {
let result = [];
this.enumerateFiles((file) => {
result.push(...file.parser.references.namespaceStatements);
});
return result;
}
logDebug(...args) {
this.program.logger.debug(this._debugLogComponentName, ...args);
}
validate(force = false) {
//if this scope is already validated, no need to revalidate
if (this.isValidated === true && !force) {
this.logDebug('validate(): already validated');
return;
}
this.program.logger.time(Logger_1.LogLevel.info, [this._debugLogComponentName, 'validate()'], () => {
let parentScope = this.getParentScope();
//validate our parent before we validate ourself
if (parentScope && parentScope.isValidated === false) {
this.logDebug('validate(): validating parent first');
parentScope.validate(force);
}
//clear the scope's errors list (we will populate them from this method)
this.diagnostics = [];
let callables = this.getAllCallables();
//sort the callables by filepath and then method name, so the errors will be consistent
callables = callables.sort((a, b) => {
return (
//sort by path
a.callable.file.pathAbsolute.localeCompare(b.callable.file.pathAbsolute) ||
//then sort by method name
a.callable.name.localeCompare(b.callable.name));
});
//get a list of all callables, indexed by their lower case names
let callableContainerMap = util_1.util.getCallableContainersByLowerName(callables);
let files = this.getFiles();
this.program.plugins.emit('beforeScopeValidate', this, files, callableContainerMap);
//find all duplicate function declarations
this.diagnosticFindDuplicateFunctionDeclarations(callableContainerMap);
//detect missing and incorrect-case script imports
this.diagnosticValidateScriptImportPaths();
//enforce a series of checks on the bodies of class methods
this.validateClasses();
//do many per-file checks
this.enumerateFiles((file) => {
this.diagnosticDetectCallsToUnknownFunctions(file, callableContainerMap);
this.diagnosticDetectFunctionCallsWithWrongParamCount(file, callableContainerMap);
this.diagnosticDetectShadowedLocalVars(file, callableContainerMap);
this.diagnosticDetectFunctionCollisions(file);
this.detectVariableNamespaceCollisions(file);
});
this.program.plugins.emit('afterScopeValidate', this, files, callableContainerMap);
this.isValidated = true;
});
}
/**
* Mark this scope as invalid, which means its `validate()` function needs to be called again before use.
*/
invalidate() {
this.isValidated = false;
//clear out various lookups (they'll get regenerated on demand the next time they're requested)
this.cache.clear();
}
detectVariableNamespaceCollisions(file) {
//find all function parameters
for (let func of file.parser.references.functionExpressions) {
for (let param of func.parameters) {
let lowerParamName = param.name.text.toLowerCase();
let namespace = this.namespaceLookup[lowerParamName];
//see if the param matches any starting namespace part
if (namespace) {
this.diagnostics.push(Object.assign(Object.assign({ file: file }, DiagnosticMessages_1.DiagnosticMessages.parameterMayNotHaveSameNameAsNamespace(param.name.text)), { range: param.name.range, relatedInformation: [{
message: 'Namespace declared here',
location: vscode_languageserver_1.Location.create(vscode_uri_1.URI.file(namespace.file.pathAbsolute).toString(), namespace.nameRange)
}] }));
}
}
}
for (let assignment of file.parser.references.assignmentStatements) {
let lowerAssignmentName = assignment.name.text.toLowerCase();
let namespace = this.namespaceLookup[lowerAssignmentName];
//see if the param matches any starting namespace part
if (namespace) {
this.diagnostics.push(Object.assign(Object.assign({ file: file }, DiagnosticMessages_1.DiagnosticMessages.variableMayNotHaveSameNameAsNamespace(assignment.name.text)), { range: assignment.name.range, relatedInformation: [{
message: 'Namespace declared here',
location: vscode_languageserver_1.Location.create(vscode_uri_1.URI.file(namespace.file.pathAbsolute).toString(), namespace.nameRange)
}] }));
}
}
}
/**
* Find various function collisions
*/
diagnosticDetectFunctionCollisions(file) {
const classMap = this.getClassMap();
for (let func of file.callables) {
const funcName = func.getName(parser_1.ParseMode.BrighterScript);
const lowerFuncName = funcName === null || funcName === void 0 ? void 0 : funcName.toLowerCase();
if (lowerFuncName) {
//find function declarations with the same name as a stdlib function
if (globalCallables_1.globalCallableMap.has(lowerFuncName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.scopeFunctionShadowedByBuiltInFunction()), { range: func.nameRange, file: file }));
}
//find any functions that have the same name as a class
if (classMap.has(lowerFuncName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.functionCannotHaveSameNameAsClass(funcName)), { range: func.nameRange, file: file }));
}
}
}
}
getNewExpressions() {
let result = [];
this.enumerateFiles((file) => {
let expressions = file.parser.references.newExpressions;
for (let expression of expressions) {
expression.file = file;
result.push(expression);
}
});
return result;
}
validateClasses() {
let validator = new ClassValidator_1.BsClassValidator();
validator.validate(this);
this.diagnostics.push(...validator.diagnostics);
}
/**
* Detect calls to functions with the incorrect number of parameters
* @param file
* @param callableContainersByLowerName
*/
diagnosticDetectFunctionCallsWithWrongParamCount(file, callableContainersByLowerName) {
//validate all function calls
for (let expCall of file.functionCalls) {
let callableContainersWithThisName = callableContainersByLowerName.get(expCall.name.toLowerCase());
//use the first item from callablesByLowerName, because if there are more, that's a separate error
let knownCallableContainer = callableContainersWithThisName ? callableContainersWithThisName[0] : undefined;
if (knownCallableContainer) {
//get min/max parameter count for callable
let minParams = 0;
let maxParams = 0;
for (let param of knownCallableContainer.callable.params) {
maxParams++;
//optional parameters must come last, so we can assume that minParams won't increase once we hit
//the first isOptional
if (param.isOptional === false) {
minParams++;
}
}
let expCallArgCount = expCall.args.length;
if (expCall.args.length > maxParams || expCall.args.length < minParams) {
let minMaxParamsText = minParams === maxParams ? maxParams : `${minParams}-${maxParams}`;
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.mismatchArgumentCount(minMaxParamsText, expCallArgCount)), { range: expCall.nameRange,
//TODO detect end of expression call
file: file }));
}
}
}
}
/**
* Detect local variables (function scope) that have the same name as scope calls
* @param file
* @param callableContainerMap
*/
diagnosticDetectShadowedLocalVars(file, callableContainerMap) {
const classMap = this.getClassMap();
//loop through every function scope
for (let scope of file.functionScopes) {
//every var declaration in this function scope
for (let varDeclaration of scope.variableDeclarations) {
const varName = varDeclaration.name;
const lowerVarName = varName.toLowerCase();
//if the var is a function
if (reflection_1.isFunctionType(varDeclaration.type)) {
//local var function with same name as stdlib function
if (
//has same name as stdlib
globalCallables_1.globalCallableMap.has(lowerVarName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.localVarFunctionShadowsParentFunction('stdlib')), { range: varDeclaration.nameRange, file: file }));
//this check needs to come after the stdlib one, because the stdlib functions are included
//in the scope function list
}
else if (
//has same name as scope function
callableContainerMap.has(lowerVarName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.localVarFunctionShadowsParentFunction('scope')), { range: varDeclaration.nameRange, file: file }));
}
//var is not a function
}
else if (
//is NOT a callable from stdlib (because non-function local vars can have same name as stdlib names)
!globalCallables_1.globalCallableMap.has(lowerVarName)) {
//is same name as a callable
if (callableContainerMap.has(lowerVarName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.localVarShadowedByScopedFunction()), { range: varDeclaration.nameRange, file: file }));
//has the same name as an in-scope class
}
else if (classMap.has(lowerVarName)) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.localVarSameNameAsClass(classMap.get(lowerVarName).getName(parser_1.ParseMode.BrighterScript))), { range: varDeclaration.nameRange, file: file }));
}
}
}
}
}
/**
* Detect calls to functions that are not defined in this scope
* @param file
* @param callablesByLowerName
*/
diagnosticDetectCallsToUnknownFunctions(file, callablesByLowerName) {
//validate all expression calls
for (let expCall of file.functionCalls) {
const lowerName = expCall.name.toLowerCase();
//for now, skip validation on any method named "super" within `.bs` contexts.
//TODO revise this logic so we know if this function call resides within a class constructor function
if (file.extension === '.bs' && lowerName === 'super') {
continue;
}
//get the local scope for this expression
let scope = file.getFunctionScopeAtPosition(expCall.nameRange.start);
//if we don't already have a variable with this name.
if (!(scope === null || scope === void 0 ? void 0 : scope.getVariableByName(lowerName))) {
let callablesWithThisName = callablesByLowerName.get(lowerName);
//use the first item from callablesByLowerName, because if there are more, that's a separate error
let knownCallable = callablesWithThisName ? callablesWithThisName[0] : undefined;
//detect calls to unknown functions
if (!knownCallable) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.callToUnknownFunction(expCall.name, this.name)), { range: expCall.nameRange, file: file }));
}
}
else {
//if we found a variable with the same name as the function, assume the call is "known".
//If the variable is a different type, some other check should add a diagnostic for that.
}
}
}
/**
* Create diagnostics for any duplicate function declarations
* @param callablesByLowerName
*/
diagnosticFindDuplicateFunctionDeclarations(callableContainersByLowerName) {
//for each list of callables with the same name
for (let [lowerName, callableContainers] of callableContainersByLowerName) {
let globalCallables = [];
let nonGlobalCallables = [];
let ownCallables = [];
let ancestorNonGlobalCallables = [];
for (let container of callableContainers) {
if (container.scope === this.program.globalScope) {
globalCallables.push(container);
}
else {
nonGlobalCallables.push(container);
if (container.scope === this) {
ownCallables.push(container);
}
else {
ancestorNonGlobalCallables.push(container);
}
}
}
//add info diagnostics about child shadowing parent functions
if (ownCallables.length > 0 && ancestorNonGlobalCallables.length > 0) {
for (let container of ownCallables) {
//skip the init function (because every component will have one of those){
if (lowerName !== 'init') {
let shadowedCallable = ancestorNonGlobalCallables[ancestorNonGlobalCallables.length - 1];
if (!!shadowedCallable && shadowedCallable.callable.file === container.callable.file) {
//same file: skip redundant imports
continue;
}
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.overridesAncestorFunction(container.callable.name, container.scope.name, shadowedCallable.callable.file.pkgPath,
//grab the last item in the list, which should be the closest ancestor's version
shadowedCallable.scope.name)), { range: container.callable.nameRange, file: container.callable.file }));
}
}
}
//add error diagnostics about duplicate functions in the same scope
if (ownCallables.length > 1) {
for (let callableContainer of ownCallables) {
let callable = callableContainer.callable;
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.duplicateFunctionImplementation(callable.name, callableContainer.scope.name)), { range: util_1.util.createRange(callable.nameRange.start.line, callable.nameRange.start.character, callable.nameRange.start.line, callable.nameRange.end.character), file: callable.file }));
}
}
}
}
/**
* Get the list of all script imports for this scope
*/
getScriptImports() {
let result = [];
this.enumerateFiles((file) => {
if (reflection_1.isBrsFile(file)) {
result.push(...file.ownScriptImports);
}
else if (reflection_1.isXmlFile(file)) {
result.push(...file.scriptTagImports);
}
});
return result;
}
/**
* Verify that all of the scripts imported by each file in this scope actually exist
*/
diagnosticValidateScriptImportPaths() {
let scriptImports = this.getScriptImports();
//verify every script import
for (let scriptImport of scriptImports) {
let referencedFile = this.getFileByRelativePath(scriptImport.pkgPath);
//if we can't find the file
if (!referencedFile) {
let dInfo;
if (scriptImport.text.trim().length === 0) {
dInfo = DiagnosticMessages_1.DiagnosticMessages.scriptSrcCannotBeEmpty();
}
else {
dInfo = DiagnosticMessages_1.DiagnosticMessages.referencedFileDoesNotExist();
}
this.diagnostics.push(Object.assign(Object.assign({}, dInfo), { range: scriptImport.filePathRange, file: scriptImport.sourceFile }));
//if the character casing of the script import path does not match that of the actual path
}
else if (scriptImport.pkgPath !== referencedFile.pkgPath) {
this.diagnostics.push(Object.assign(Object.assign({}, DiagnosticMessages_1.DiagnosticMessages.scriptImportCaseMismatch(referencedFile.pkgPath)), { range: scriptImport.filePathRange, file: scriptImport.sourceFile }));
}
}
}
/**
* Find the file with the specified relative path
* @param relativePath
*/
getFileByRelativePath(relativePath) {
let files = this.getFiles();
for (let file of files) {
if (file.pkgPath.toLowerCase() === relativePath.toLowerCase()) {
return file;
}
}
}
/**
* Determine if this scope is referenced and known by the file.
* @param file
*/
hasFile(file) {
let files = this.getFiles();
let hasFile = files.includes(file);
return hasFile;
}
/**
* Get all callables as completionItems
*/
getCallablesAsCompletions(parseMode) {
let completions = [];
let callables = this.getAllCallables();
if (parseMode === parser_1.ParseMode.BrighterScript) {
//throw out the namespaced callables (they will be handled by another method)
callables = callables.filter(x => x.callable.hasNamespace === false);
}
for (let callableContainer of callables) {
completions.push({
label: callableContainer.callable.getName(parseMode),
kind: vscode_languageserver_1.CompletionItemKind.Function,
detail: callableContainer.callable.shortDescription,
documentation: callableContainer.callable.documentation ? { kind: 'markdown', value: callableContainer.callable.documentation } : undefined
});
}
return completions;
}
/**
* Get the definition (where was this thing first defined) of the symbol under the position
*/
getDefinition(file, position) {
// Overridden in XMLScope. Brs files use implementation in BrsFile
return [];
}
/**
* Scan all files for property names, and return them as completions
*/
getPropertyNameCompletions() {
let results = [];
this.enumerateFiles((file) => {
results.push(...file.propertyNameCompletions);
});
return results;
}
} |
JavaScript | class ArrayInput extends Element {
/**
* Creates a new ArrayInput.
*
* @param {object} args - The arguments.
* @param {string} [args.type] - The type of values that the array can hold.
* @param {boolean} [args.fixedSize] - If true then editing the number of elements that the array has will not be allowed.
* @param {object} [args.elementArgs] - Arguments for each array Element.
*/
constructor(args) {
args = Object.assign({}, args);
// remove binding because we want to set it later
const binding = args.binding;
delete args.binding;
const container = new Container({
dom: args.dom,
flex: true
});
super(container.dom, args);
this._container = container;
this._container.parent = this;
this.class.add(CLASS_ARRAY_INPUT, CLASS_ARRAY_EMPTY);
this._usePanels = args.usePanels || false;
this._fixedSize = !!args.fixedSize;
this._inputSize = new NumericInput({
class: [CLASS_ARRAY_SIZE],
placeholder: 'Array Size',
value: 0,
hideSlider: true,
step: 1,
precision: 0,
min: 0,
readOnly: this._fixedSize
});
this._inputSize.on('change', this._onSizeChange.bind(this));
this._inputSize.on('focus', this._onFocus.bind(this));
this._inputSize.on('blur', this._onBlur.bind(this));
this._suspendSizeChangeEvt = false;
this._container.append(this._inputSize);
this._containerArray = new Container({
class: CLASS_ARRAY_CONTAINER,
hidden: true
});
this._containerArray.on('append', () => {
this._containerArray.hidden = false;
});
this._containerArray.on('remove', () => {
this._containerArray.hidden = this._arrayElements.length == 0;
});
this._container.append(this._containerArray);
this._suspendArrayElementEvts = false;
this._arrayElementChangeTimeout = null;
this._getDefaultFn = args.getDefaultFn || null;
let valueType = args.elementArgs && args.elementArgs.type || args.type;
if (!ArrayInput.DEFAULTS.hasOwnProperty(valueType)) {
valueType = 'string';
}
delete args.dom;
this._valueType = valueType;
this._elementType = args.type;
this._elementArgs = args.elementArgs || args;
this._arrayElements = [];
// set binding now
this.binding = binding;
this._values = [];
if (args.value) {
this.value = args.value;
}
this.renderChanges = args.renderChanges || false;
}
_onSizeChange(size) {
// if size is explicitely 0 then add empty class
// size can also be null with multi-select so do not
// check just !size
if (size === 0) {
this.class.add(CLASS_ARRAY_EMPTY);
} else {
this.class.remove(CLASS_ARRAY_EMPTY);
}
if (size === null) return;
if (this._suspendSizeChangeEvt) return;
// initialize default value for each new array element
let defaultValue;
const initDefaultValue = () => {
if (this._getDefaultFn) {
defaultValue = this._getDefaultFn();
} else {
defaultValue = ArrayInput.DEFAULTS[this._valueType];
if (this._valueType === 'curveset') {
defaultValue = utils.deepCopy(defaultValue);
if (Array.isArray(this._elementArgs.curves)) {
for (let i = 0; i < this._elementArgs.curves.length; i++) {
defaultValue.keys.push([0, 0]);
}
}
} else if (this._valueType === 'gradient') {
defaultValue = utils.deepCopy(defaultValue);
if (this._elementArgs.channels) {
for (let i = 0; i < this._elementArgs.channels; i++) {
defaultValue.keys.push([0, 1]);
}
}
}
}
};
// resize array
const values = this._values.map((array) => {
if (!array) {
array = new Array(size);
for (let i = 0; i < size; i++) {
array[i] = utils.deepCopy(ArrayInput.DEFAULTS[this._valueType]);
if (defaultValue === undefined) initDefaultValue();
array[i] = utils.deepCopy(defaultValue);
}
} else if (array.length < size) {
const newArray = new Array(size - array.length);
for (let i = 0; i < newArray.length; i++) {
newArray[i] = utils.deepCopy(ArrayInput.DEFAULTS[this._valueType]);
if (defaultValue === undefined) initDefaultValue();
newArray[i] = utils.deepCopy(defaultValue);
}
array = array.concat(newArray);
} else {
const newArray = new Array(size);
for (let i = 0; i < size; i++) {
newArray[i] = utils.deepCopy(array[i]);
}
array = newArray;
}
return array;
});
if (!values.length) {
const array = new Array(size);
for (let i = 0; i < size; i++) {
array[i] = utils.deepCopy(ArrayInput.DEFAULTS[this._valueType]);
if (defaultValue === undefined) initDefaultValue();
array[i] = utils.deepCopy(defaultValue);
}
values.push(array);
}
this._updateValues(values, true);
}
_onFocus() {
this.emit('focus');
}
_onBlur() {
this.emit('blur');
}
_createArrayElement() {
const args = Object.assign({}, this._elementArgs);
if (args.binding) {
args.binding = args.binding.clone();
} else if (this._binding) {
args.binding = this._binding.clone();
}
// set renderChanges after value is set
// to prevent flashing on initial value set
args.renderChanges = false;
let container;
if (this._usePanels) {
container = new Panel({
headerText: `[${this._arrayElements.length}]`,
removable: !this._fixedSize,
collapsible: true,
class: [CLASS_ARRAY_ELEMENT, CLASS_ARRAY_ELEMENT + '-' + this._elementType]
});
} else {
container = new Container({
flex: true,
flexDirection: 'row',
alignItems: 'center',
class: [CLASS_ARRAY_ELEMENT, CLASS_ARRAY_ELEMENT + '-' + this._elementType]
});
}
if (this._elementType === 'json' && args.attributes) {
args.attributes = args.attributes.map((attr) => {
if (!attr.path) return attr;
// fix paths to include array element index
attr = Object.assign({}, attr);
const parts = attr.path.split('.');
parts.splice(parts.length - 1, 0, this._arrayElements.length);
attr.path = parts.join('.');
return attr;
});
}
const element = Element.create(this._elementType, args);
container.append(element);
element.renderChanges = this.renderChanges;
const entry = {
container: container,
element: element
};
this._arrayElements.push(entry);
if (!this._usePanels) {
if (!this._fixedSize) {
const btnDelete = new Button({
icon: 'E289',
size: 'small',
class: CLASS_ARRAY_DELETE,
tabIndex: -1 // skip buttons on tab
});
btnDelete.on('click', () => {
this._removeArrayElement(entry);
});
container.append(btnDelete);
}
} else {
container.on('click:remove', () => {
this._removeArrayElement(entry);
});
}
element.on('change', (value) => {
this._onArrayElementChange(entry, value);
});
this._containerArray.append(container);
return entry;
}
_removeArrayElement(entry) {
const index = this._arrayElements.indexOf(entry);
if (index === -1) return;
// remove row from every array in values
const values = this._values.map((array) => {
if (!array) return null;
array.splice(index, 1);
return array;
});
this._updateValues(values, true);
}
_onArrayElementChange(entry, value) {
if (this._suspendArrayElementEvts) return;
const index = this._arrayElements.indexOf(entry);
if (index === -1) return;
// Set the value to the same row of every array in values.
this._values.forEach((array) => {
if (array && array.length > index) {
array[index] = value;
}
});
// use a timeout here because when our values change they will
// first emit change events on each array element. However since the
// whole array changed we are going to fire a 'change' event later from
// our '_updateValues' function. We only want to emit a 'change' event
// here when only the array element changed value and not the whole array so
// wait a bit and fire the change event later otherwise the _updateValues function
// will cancel this timeout and fire a change event for the whole array instead
this._arrayElementChangeTimeout = setTimeout(() => {
this._arrayElementChangeTimeout = null;
this.emit('change', this.value);
});
}
_linkArrayElement(element, index) {
const observers = this._binding.observers;
const paths = this._binding.paths;
const useSinglePath = paths.length === 1 || observers.length !== paths.length;
element.unlink();
element.value = null;
this.emit('unlinkElement', element, index);
const path = (useSinglePath ? paths[0] + `.${index}` : paths.map((path) => `${path}.${index}`));
element.link(observers, path);
this.emit('linkElement', element, index, path);
}
_updateValues(values, applyToBinding) {
this._values = values || [];
this._suspendArrayElementEvts = true;
this._suspendSizeChangeEvt = true;
// apply values to the binding
if (applyToBinding && this._binding) {
this._binding.setValues(values);
}
// each row of this array holds
// all the values for that row
const valuesPerRow = [];
// holds the length of each array
const arrayLengths = [];
values.forEach((array) => {
if (!array) return;
arrayLengths.push(array.length);
array.forEach((item, i) => {
if (!valuesPerRow[i]) {
valuesPerRow[i] = [];
}
valuesPerRow[i].push(item);
});
});
let lastElementIndex = -1;
for (let i = 0; i < valuesPerRow.length; i++) {
// if the number of values on this row does not match
// the number of arrays then stop adding rows
if (valuesPerRow[i].length !== values.length) {
break;
}
// create row if it doesn't exist
if (!this._arrayElements[i]) {
this._createArrayElement();
}
// bind to observers for that row or just display the values
if (this._binding && this._binding.observers) {
this._linkArrayElement(this._arrayElements[i].element, i);
} else {
if (valuesPerRow[i].length > 1) {
this._arrayElements[i].element.values = valuesPerRow[i];
} else {
this._arrayElements[i].element.value = valuesPerRow[i][0];
}
}
lastElementIndex = i;
}
// destory elements that are no longer in our values
for (let i = this._arrayElements.length - 1; i > lastElementIndex; i--) {
this._arrayElements[i].container.destroy();
this._arrayElements.splice(i, 1);
}
this._inputSize.values = arrayLengths;
this._suspendSizeChangeEvt = false;
this._suspendArrayElementEvts = false;
if (this._arrayElementChangeTimeout) {
clearTimeout(this._arrayElementChangeTimeout);
this._arrayElementChangeTimeout = null;
}
this.emit('change', this.value);
}
focus() {
this._inputSize.focus();
}
blur() {
this._inputSize.blur();
}
/**
* @name ArrayInput#forEachArrayElement
* @description Executes the specified function for each array element.
* @param {Function} fn - The function with signature (element, index) => bool to execute. If the function returns
* false then the iteration will early out.
*/
forEachArrayElement(fn) {
this._containerArray.forEachChild((container, i) => {
return fn(container.dom.firstChild.ui, i);
});
}
destroy() {
if (this._destroyed) return;
this._arrayElements.length = 0;
super.destroy();
}
get binding() {
return super.binding;
}
// override binding setter to create
// the same type of binding on each array element too
set binding(value) {
super.binding = value;
this._arrayElements.forEach((entry) => {
entry.element.binding = value ? value.clone() : null;
});
}
get value() {
// construct value from values of array elements
return this._arrayElements.map((entry) => entry.element.value);
}
set value(value) {
if (!Array.isArray(value)) {
value = [];
}
const current = this.value || [];
if (utils.arrayEquals(current, value)) return;
// update values and binding
this._updateValues(new Array(this._values.length || 1).fill(value), true);
}
/* eslint accessor-pairs: 0 */
set values(values) {
if (utils.arrayEquals(this._values, values)) return;
// update values but do not update binding
this._updateValues(values, false);
}
get renderChanges() {
return this._renderChanges;
}
set renderChanges(value) {
this._renderChanges = value;
this._arrayElements.forEach((entry) => {
entry.element.renderChanges = value;
});
}
} |
JavaScript | class Listen extends Command {
/**
* @constructor
* @param {string} fileName
*/
constructor(fileName) {
super(fileName);
}
execute(message, args) {
// Stop direct messages, check if channel is configured for communication
let com = new Communication(message);
let userId = com.getUserId();
if (com.isDirect()) {
return message.channel.send(com.getDefaults("directMessage", userId));
}
// Communication on channel is not allowed
let asAdmin = true;
if (!com.isAllowed(asAdmin)) {
return message.channel.send(com.getReason());
}
let guildId = com.getGuildId();
let isWaiting = this.storage.get("admin." + guildId + "." + userId + ".waiting");
// User is already waiting
if (isWaiting) {
// Stop listening
if (args.includes("stop")) {
this.__removeUserFromList(guildId, userId);
return message.channel.send(this.getResponse("stopListen", userId));
}
return message.channel.send(this.getResponse("alreadyListen", userId));
}
this.__addUserToList(guildId, userId);
return message.channel.send(this.getResponse("startListen", userId));
}
/**
* Set waiting status of the user to false and remove him from the waiting list of the server.
*
* @private
* @param {number} guildId The unique identifier of the guild
* @param {number} userId The unique identifer of the user
*/
__removeUserFromList(guildId, userId) {
// Set user state to not waiting
let key = "admin." + guildId + "." + userId + ".waiting";
this.storage.set(key, false);
// Update the waiting list
let listKey = "admin." + guildId +".waiting";
let waitingList = this.storage.get(listKey) || [];
let newWaitingList = waitingList.filter(user => user != userId);
// Update if list lenghts differ
if (waitingList.length != newWaitingList.length) {
this.storage.set(listKey, newWaitingList);
}
}
/**
* Add a user to the waiting list.
*
* @private
* @param {number} guildId The unique identifier of the guild
* @param {number} userId The unique identifer of the user
*/
__addUserToList(guildId, userId) {
// Set user state to waiting
let key = "admin." + guildId + "." + userId + ".waiting";
this.storage.set(key, true);
// update the waiting list
let listKey = "admin." + guildId + ".waiting";
let currentlyWaiting = this.storage.get(listKey) || [];
currentlyWaiting.push(userId);
this.storage.set(listKey, currentlyWaiting);
}
} |
JavaScript | class Vector {
// - vector (array - array[number]) Two [x, y, z] points to draw the vector
// - thickness (number) Value to serve as thickness of components
// - material (Material) Three.js material to use for the components
constructor ({vector=[[0, 0, 0],[1, 1, 1]], thickness=0, material=null}) {
//set length of arrow
var arrowLength = 20,
//set margin of vector at base
baseMargin = 10,
//create vectors
[basePoint, pointB] = vector.map(p => new Vector3(...p)),
//create additional vectors
fullVector = pointB.clone(),
threeVector = pointB.clone(),
baseMarginPercent, pointA, cylinder, cylinderLength, cone, coneLength;
//subtract basePoint from pointB
fullVector.sub(basePoint);
//caclculate base margin as a percentage of length
baseMarginPercent = baseMargin/fullVector.length();
//apply margin to basePoint to get pointA
pointA = new Vector3(...basePoint.toArray().map((it, i) => {
return it + (pointB.toArray()[i]-it)*baseMarginPercent;
}));
//subtract pointA from pointB
threeVector.sub(pointA);
//set lengths
cylinderLength = threeVector.length() - arrowLength;
coneLength = arrowLength;
//normalize vector
threeVector.normalize();
//store components
this.components = [];
//create cylinder (line) of vector
cylinder = new Cylinder({
geometry: {
radiusTop: thickness/2,
radiusBottom: thickness/2,
height: cylinderLength
},
material,
//geometry will be translated so that position is at pointA
//pos: [pointA.x, pointA.y, pointA.z]
position: [pointA.x, pointA.y, pointA.z]
});
//add to components
this.components.push(cylinder);
//shift geometry up, so that position is at beginning of vector
cylinder.geometry.translate(0, cylinderLength/2, 0);
//update mesh
//this.component.native = new Mesh(this.component.geometry, this.component.material);
//align to vector
this._alignToVector(cylinder, threeVector);
//create cone (arrow) of vector
cone = new Cone({
geometry: {
//radiusTop: thickness,
//radiusBottom: thickness,
radius: thickness,
height: coneLength
},
material,
//geometry will be translated so that position is at pointB
//pos: [pointA.x, pointA.y, pointA.z]
position: [pointB.x, pointB.y, pointB.z]
});
//add to components
this.components.push(cone);
//shift geometry down, so that position is at end of vector
cone.geometry.translate(0, -coneLength/2, 0);
//update mesh
//this.component.native = new Mesh(this.component.geometry, this.component.material);
//align to vector
this._alignToVector(cone, threeVector);
}
_alignToVector (component, vector) {
//create quaternion
var quaternion = new Quaternion();
//set vector on quarternion
quaternion.setFromUnitVectors(new Vector3(0, 1, 0), vector);
//apply quaternion to component
component.native.applyQuaternion(quaternion);
}
addTo (instance) {
//wraps .addTo() method of all of our WHS components
//loop components
for (let i=0; i<this.components.length; i++) {
//call addTo()
this.components[i].addTo(instance);
}
}
} |
JavaScript | class TrackRecorder {
/**
* @param track The JitsiTrack the object is going to hold
*/
constructor(track) {
// The JitsiTrack holding the stream
this.track = track;
// The MediaRecorder recording the stream
this.recorder = null;
// The array of data chunks recorded from the stream
// acts as a buffer until the data is stored on disk
this.data = null;
// the name of the person of the JitsiTrack. This can be undefined and/or
// not unique
this.name = null;
// the time of the start of the recording
this.startTime = null;
}
} |
JavaScript | class ViewportBindingIosEmbedWrapper_ {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {!Window} */
this.win = win;
/** @private {!../vsync-impl.Vsync} */
this.vsync_ = Services.vsyncFor(win);
const doc = this.win.document;
const {documentElement} = doc;
const topClasses = documentElement.className;
documentElement.classList.add('i-amphtml-ios-embed');
const wrapper = doc.createElement('html');
/** @private @const {!Element} */
this.wrapper_ = wrapper;
wrapper.id = 'i-amphtml-wrapper';
wrapper.className = topClasses;
/** @private @const {!Observable} */
this.scrollObservable_ = new Observable();
/** @private @const {!Observable} */
this.resizeObservable_ = new Observable();
/** @const {function()} */
this.boundScrollEventListener_ = this.onScrolled_.bind(this);
/** @const {function()} */
this.boundResizeEventListener_ = () => this.resizeObservable_.fire();
/** @private @const {boolean} */
this.useLayers_ = isExperimentOn(this.win, 'layers');
/** @private {number} */
this.paddingTop_ = 0;
// Setup UI.
/** @private {boolean} */
this.setupDone_ = false;
waitForBodyOpen(doc, this.setup_.bind(this));
// Set overscroll (`-webkit-overflow-scrolling: touch`) later to avoid
// iOS rendering bugs. See #8798 for details.
whenDocumentReady(doc).then(() => {
documentElement.classList.add('i-amphtml-ios-overscroll');
});
dev().fine(TAG_, 'initialized ios-embed-wrapper viewport');
}
/** @override */
ensureReadyForElements() {
this.setup_();
}
/** @private */
setup_() {
if (this.setupDone_) {
return;
}
this.setupDone_ = true;
// Embedded scrolling on iOS is rather complicated. IFrames cannot be sized
// and be scrollable. Sizing iframe by scrolling height has a big negative
// that "fixed" position is essentially impossible. The only option we
// found is to reset scrolling on the AMP doc, which wraps the natural BODY
// inside the `overflow:auto` element. For reference, here are related
// iOS issues (Chrome issues are also listed for reference):
// - https://code.google.com/p/chromium/issues/detail?id=2891
// - https://code.google.com/p/chromium/issues/detail?id=157855
// - https://bugs.webkit.org/show_bug.cgi?id=106133
// - https://bugs.webkit.org/show_bug.cgi?id=149264
const doc = this.win.document;
const body = dev().assertElement(doc.body, 'body is not available');
doc.documentElement.appendChild(this.wrapper_);
this.wrapper_.appendChild(body);
// Redefine `document.body`, otherwise it'd be `null`.
Object.defineProperty(doc, 'body', {
get: () => body,
});
// Make sure the scroll position is adjusted correctly.
this.onScrolled_();
}
/** @override */
connect() {
this.win.addEventListener('resize', this.boundResizeEventListener_);
this.wrapper_.addEventListener('scroll', this.boundScrollEventListener_);
}
/** @override */
disconnect() {
this.win.removeEventListener('resize', this.boundResizeEventListener_);
this.wrapper_.removeEventListener('scroll', this.boundScrollEventListener_);
}
/** @override */
getBorderTop() {
// iOS needs an extra pixel to avoid scroll freezing.
return 1;
}
/** @override */
requiresFixedLayerTransfer() {
if (!isExperimentOn(this.win, 'ios-fixed-no-transfer')) {
return true;
}
// The jumping fixed elements have been fixed in iOS 12.2.
const iosVersion = parseFloat(
Services.platformFor(this.win).getIosVersionString()
);
return iosVersion < 12.2;
}
/** @override */
overrideGlobalScrollTo() {
return true;
}
/** @override */
supportsPositionFixed() {
return true;
}
/** @override */
onScroll(callback) {
this.scrollObservable_.add(callback);
}
/** @override */
onResize(callback) {
this.resizeObservable_.add(callback);
}
/** @override */
updatePaddingTop(paddingTop) {
this.paddingTop_ = paddingTop;
setImportantStyles(this.wrapper_, {
'padding-top': px(paddingTop),
});
}
/** @override */
hideViewerHeader(transient, unusedLastPaddingTop) {
if (!transient) {
this.updatePaddingTop(0);
}
}
/** @override */
showViewerHeader(transient, paddingTop) {
if (!transient) {
this.updatePaddingTop(paddingTop);
}
}
/** @override */
disableScroll() {
// TODO(jridgewell): Recursively disable scroll
this.wrapper_.classList.add('i-amphtml-scroll-disabled');
}
/** @override */
resetScroll() {
// TODO(jridgewell): Recursively disable scroll
this.wrapper_.classList.remove('i-amphtml-scroll-disabled');
}
/** @override */
updateLightboxMode(unusedLightboxMode) {
// The layout is always accurate.
return Promise.resolve();
}
/** @override */
getSize() {
return {
width: this.win./*OK*/ innerWidth,
height: this.win./*OK*/ innerHeight,
};
}
/** @override */
getScrollTop() {
return this.wrapper_./*OK*/ scrollTop;
}
/** @override */
getScrollLeft() {
// The wrapper is set to overflow-x: hidden so the document cannot be
// scrolled horizontally. The scrollLeft will always be 0.
return 0;
}
/** @override */
getScrollWidth() {
return this.wrapper_./*OK*/ scrollWidth;
}
/** @override */
getScrollHeight() {
return this.wrapper_./*OK*/ scrollHeight;
}
/** @override */
getContentHeight() {
// The wrapped body, not this.wrapper_ itself, will have the correct height.
const content = this.win.document.body;
const {height} = content./*OK*/ getBoundingClientRect();
// Unlike other viewport bindings, there's no need to include the
// rect top since the wrapped body accounts for the top margin of children.
// However, the parent's padding-top (this.paddingTop_) must be added.
// As of Safari 12.1.1, the getBoundingClientRect().height does not include
// the bottom margin of children and there's no other API that does.
const childMarginBottom = marginBottomOfLastChild(this.win, content);
const style = computedStyle(this.win, content);
return (
parseInt(style.marginTop, 10) +
this.paddingTop_ +
height +
childMarginBottom +
parseInt(style.marginBottom, 10)
);
}
/** @override */
contentHeightChanged() {}
/** @override */
getLayoutRect(el, opt_scrollLeft, opt_scrollTop) {
const b = el./*OK*/ getBoundingClientRect();
if (this.useLayers_) {
return layoutRectLtwh(b.left, b.top, b.width, b.height);
}
const scrollTop =
opt_scrollTop != undefined ? opt_scrollTop : this.getScrollTop();
const scrollLeft =
opt_scrollLeft != undefined ? opt_scrollLeft : this.getScrollLeft();
return layoutRectLtwh(
Math.round(b.left + scrollLeft),
Math.round(b.top + scrollTop),
Math.round(b.width),
Math.round(b.height)
);
}
/** @override */
getRootClientRectAsync() {
return Promise.resolve(null);
}
/** @override */
setScrollTop(scrollTop) {
// If scroll top is 0, it's set to 1 to avoid scroll-freeze issue. See
// `onScrolled_` for more details.
this.wrapper_./*OK*/ scrollTop = scrollTop || 1;
}
/**
* @param {!Event=} opt_event
* @private
*/
onScrolled_(opt_event) {
// Scroll document into a safe position to avoid scroll freeze on iOS.
// This means avoiding scrollTop to be minimum (0) or maximum value.
// This is very sad but very necessary. See #330 for more details.
// Unfortunately, the same is very expensive to do on the bottom, due to
// costly scrollHeight.
if (this.wrapper_./*OK*/ scrollTop == 0) {
this.wrapper_./*OK*/ scrollTop = 1;
if (opt_event) {
opt_event.preventDefault();
}
}
if (opt_event) {
this.scrollObservable_.fire();
}
}
/** @override */
getScrollingElement() {
return this.wrapper_;
}
/** @override */
getScrollingElementScrollsLikeViewport() {
return false;
}
} |
JavaScript | class TreeWalker {
constructor(consumerFn, arrayWrapper) {
this.consumerFn = consumerFn;
this.arrayWrapper = arrayWrapper;
}
/**
* Processes the literal node inside schema tree
*/
processLiteralNode(field, node, dotPath, arrayPath) {
const pointer = arrayPath.concat(dotPath).concat(field).join('.');
return this.consumerFn(field, node.type, node.rules, dotPath, pointer);
}
/**
* Process the object node inside the parsed. All children are parsed
* recursively
*/
processObjectNode(field, node, dotPath, arrayPath) {
let output = [];
/**
* If object itself has rules, then we need to consume that
* as well.
*/
if (node.rules.length) {
const pointer = arrayPath.concat(dotPath).concat(field).join('.');
output.push(this.consumerFn(field, node.type, node.rules, dotPath, pointer));
}
/**
* Walker over object children
*/
output = output.concat(this.walk(node.children, dotPath.concat(field), arrayPath));
return output;
}
/**
* Process the array node of the schema tree. This method will call
* the `arrayWrapper` function and passes all array children to it.
*/
processArrayNode(field, node, dotPath, arrayPath) {
let output = [];
const basePath = arrayPath.concat(dotPath).concat(field);
/**
* If array itself has rules, then we need to process that
* as well
*/
if (node.rules.length) {
const pointer = basePath.join('.');
output.push(this.consumerFn(field, node.type, node.rules, dotPath, pointer));
}
/**
* Processing children for each index. The index of the tree can be a
* wildcard `*`, which means we rely on runtime data to know the
* actual length of the array.
*/
Object.keys(node.each).forEach((index) => {
let child = [];
if (node.each[index].rules.length) {
const pointer = basePath.concat(index).join('.');
child.push(this.consumerFn('::tip::', 'literal', node.each[index].rules, [], pointer));
}
child = child.concat(this.walk(node.each[index].children, [], basePath.concat(index)));
output = output.concat(this.arrayWrapper(index, field, child, dotPath));
});
return output;
}
/**
* Walks the schema tree and invokes the `consumerFn` for each node.
* The output of the consumer is collected and returned back as an
* array.
*/
walk(schema, dotPath = [], arrayPath = []) {
return Object.keys(schema).reduce((result, field) => {
const node = schema[field];
if (node.type === 'literal') {
result = result.concat(this.processLiteralNode(field, node, dotPath, arrayPath));
}
if (node.type === 'object') {
result = result.concat(this.processObjectNode(field, node, dotPath, arrayPath));
}
if (node.type === 'array') {
result = result.concat(this.processArrayNode(field, node, dotPath, arrayPath));
}
return result;
}, []);
}
} |
JavaScript | class TokenAddressModel extends ModelBase {
/**
* Constructor for token address model
*
* @constructor
*/
constructor() {
super({ dbName: dbName });
const oThis = this;
oThis.tableName = 'token_addresses';
}
get kinds() {
return kinds;
}
get invertedKinds() {
return invertedKinds;
}
get statuses() {
return statuses;
}
get invertedStatuses() {
return invertedStatuses;
}
get deployedChainKinds() {
return deployedChainKinds;
}
get invertedDeployedChainKinds() {
return invertedDeployedChainKinds;
}
/**
* Get token address details by token_id and kind
*
* @param params
*
* @return {*|void}
*/
async getAddressByTokenIdAndKind(params) {
const oThis = this;
let response = await oThis
.select('*')
.where([
'token_id = ? AND kind = ? AND status = ?',
params.tokenId,
params.kind,
invertedStatuses[tokenAddressConstants.activeStatus]
])
.fire();
return responseHelper.successWithData(response[0]);
}
/**
* Get token address details by token_id and kind
*
* @param params
*
* @return {*|void}
*/
async getTokenAddressById(params) {
const oThis = this;
let response = await oThis
.select('*')
.where({ id: params.tokenAddressId })
.fire();
return responseHelper.successWithData(response[0]);
}
/**
* fetch addresses
*
* @param {object} params - external passed parameters
* @param {Integer} params.tokenId - tokenId
*
* @return {Promise}
*/
async fetchAllAddresses(params) {
const oThis = this;
let returnData = {};
let dbRows = await oThis
.select('*')
.where(['token_id = ? AND status = ?', params.tokenId, invertedStatuses[tokenAddressConstants.activeStatus]])
.fire();
for (let i = 0; i < dbRows.length; i++) {
let dbRow = dbRows[i],
addressKindStr = kinds[dbRow.kind.toString()];
if (tokenAddressConstants.uniqueKinds.indexOf(addressKindStr) > -1) {
returnData[addressKindStr] = dbRow.address;
} else {
if (!returnData[addressKindStr]) {
returnData[addressKindStr] = [];
}
returnData[addressKindStr].push(dbRow.address);
}
}
return responseHelper.successWithData(returnData);
}
/***
*
* @return {Promise<void>}
*/
async insertAddress(params) {
const oThis = this;
let insertRsp = await oThis
.insert({
token_id: params.tokenId,
kind: params.kind,
address: params.address.toLowerCase(),
known_address_id: params.knownAddressId,
deployed_chain_id: params.deployedChainId,
deployed_chain_kind: params.deployedChainKind
})
.fire();
await TokenAddressModel.flushCache(params.tokenId, insertRsp.insertId);
return responseHelper.successWithData(insertRsp);
}
/**
* Get token id from address and chain id
*
* @param params
*
* @return {*|void}
*/
async getTokenIdByAddress(params) {
const oThis = this;
let query = oThis
.select('token_id, kind, address')
.where(['address IN (?) AND status = ?', params.addresses, invertedStatuses[tokenAddressConstants.activeStatus]]);
if (invertedKinds[params.chainId]) {
query.where(['AND deployed_chain_id = ?', oThis.chainId]);
}
let response = await query.fire();
let result = {};
for (let i = 0; i < response.length; i++) {
let data = response[i];
result[data.address] = data;
}
return responseHelper.successWithData(result);
}
/**
* flush cache
*
* @param tokenId
* @param tokenAddressId
* @return {Promise<any[]>}
*/
static flushCache(tokenId, tokenAddressId) {
const TokenAddressCache = require(rootPrefix + '/lib/cacheManagement/kitSaas/TokenAddress');
const TokenAddressByIdCache = require(rootPrefix + '/lib/cacheManagement/kitSaas/TokenAddressById');
let promiseArray = [];
promiseArray.push(
new TokenAddressCache({
tokenId: tokenId
}).clear()
);
promiseArray.push(
new TokenAddressByIdCache({
tokenAddressId: tokenAddressId
}).clear()
);
return Promise.all(promiseArray);
}
} |
JavaScript | class emailPopUp extends Component {
constructor(props) {
super(props)
this.state = {
open : this.props.status,
companyName: '',
body : '',
complete: false,
}
this.handleClose = this.handleClose.bind(this)
this.handleOpen = this.handleOpen.bind(this)
}
handleClose(){
this.setState({
open : false
}
)
}
handleOpen(){
this.setState({
open : true
}
)
}
render() {
return(
<React.Fragment>
<EmailIcon onClick={this.handleOpen}/>
<Dialog open={this.state.open} >
<DialogTitle>
Thank you.
<HighlightOffSharpIcon color="error" fontsize="large" onClick={this.handleClose} style={{position:'absolute',left:'83%'}}/>
</DialogTitle>
<DialogContent>
<DialogContentText>
<Typography variant="body1">
Thank you for showing interest in me. Please compose a message to send to me.
</Typography>
</DialogContentText>
<Grid container spacing={1}>
<Grid item xs={12}>
<TextField value = {this.state.companyName} autoFocus margin='dense' label="Company Name" type="text" onChange={
(e)=>{
this.setState({
companyName : e.target.value
})
}
}/>
</Grid>
<Grid item xs={12}>
<br/>
</Grid>
<Grid item xs={12}>
<TextareaAutosize rowsMin={5} placeholder="Edit this to type the body of the email." value ={this.state.body} onChange={
(e)=>{
this.setState({
body : e.target.value
})
}
}/>
</Grid>
<br/>
<Grid item xs={4}>
</Grid>
<DialogActions>
<Grid item xs={1}>
<Button variant="contained" onClick={()=>{
window.open(`mailto:${this.props.userDetials.email}?subject=Hiring you in ${this.state.companyName}&body=${this.state.body}`)
this.handleClose()
}}>Send</Button>
</Grid>
</DialogActions>
</Grid>
</DialogContent>
</Dialog>
</React.Fragment>
)
}
} |
JavaScript | class SwitchBrowserTab extends EventEmitter {
command (index) {
this.api.perform((browser, done) => {
browser.window_handles((result) => {
browser.switchWindow(result.value[index])
done()
})
this.emit('complete')
})
return this
}
} |
JavaScript | class ImageList extends Component {
constructor(props) {
const { onSelectNext, onSelectPrevious } = props;
super(props);
this.state = {
internalItemId: props.selectedItemId
};
const selectNextId = nextId => {
const { selectItem } = this.props;
this.setState(
{
internalItemId: nextId
},
() => {
setTimeout(() => {
if (nextId === this.state.internalItemId) {
selectItem(nextId);
}
}, 150);
}
);
};
onSelectNext(evt => {
const { list } = this.props;
const { internalItemId } = this.state;
const nextIndex = list.findIndex(item => internalItemId === item.id) + 1;
if (nextIndex < list.length) {
selectNextId(list[nextIndex].id);
}
return false;
});
onSelectPrevious(evt => {
const { list } = this.props;
const { internalItemId } = this.state;
const previousIndex =
list.findIndex(item => internalItemId === item.id) - 1;
if (previousIndex >= 0) {
selectNextId(list[previousIndex].id);
}
return false;
});
}
componentWillReceiveProps(nextProps) {
this.setState({
internalItemId: nextProps.selectedItemId
});
}
render() {
const { list, selectItem } = this.props;
const { internalItemId } = this.state;
const index = list.findIndex(item => item.id === internalItemId);
return (
<VirtualList
width="100%"
height={70}
itemSize={25}
itemCount={list.length}
scrollToAlignment="center"
scrollToIndex={index || 0}
renderItem={({ index, style }) => {
const item = list[index];
const isSelected = item.id === internalItemId;
return (
<div key={item.id} style={style}>
<ImageListItem
{...{
item,
isComplete: item.complete,
selectItem,
isSelected,
position: `[${index + 1}/${list.length}] `
}}
/>
</div>
);
}}
/>
);
}
} |
JavaScript | class PageSource extends ClientCommand {
get returnsFullResultObject() {
return true;
}
performAction(callback) {
this.api.source(callback);
}
} |
JavaScript | class ComponentRegistry {
/**
* Gets the constructor function for the given component name, or
* undefined if it hasn't been registered yet.
* @param {string} name The component's name.
* @return {?function}
* @static
*/
static getConstructor(name) {
var constructorFn = ComponentRegistry.components_[name];
if (!constructorFn) {
console.error(
'There\'s no constructor registered for the component ' +
'named ' + name + '. Components need to be registered via ' +
'ComponentRegistry.register.'
);
}
return constructorFn;
}
/**
* Registers a component, so it can be found by its name.
* @param {!Function} constructorFn The component's constructor function.
* @param {string=} opt_name Name of the registered component. If none is given
* the name defined by the NAME static variable will be used instead. If that
* isn't set as well, the name of the constructor function will be used.
* @static
*/
static register(constructorFn, opt_name) {
var name = opt_name;
if (!name) {
if (constructorFn.hasOwnProperty('NAME')) {
name = constructorFn.NAME;
} else {
name = core.getFunctionName(constructorFn);
}
}
constructorFn.NAME = name;
ComponentRegistry.components_[name] = constructorFn;
}
} |
JavaScript | class SiteTopMenu extends _polymerElement.PolymerElement {
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "site-top-menu";
}
constructor() {
super();
this.__disposer = [];
new Promise((res, rej) => _require.default(["../../../../../@polymer/paper-icon-button/paper-icon-button.js"], res, rej));
new Promise((res, rej) => _require.default(["../../../../../@polymer/paper-button/paper-button.js"], res, rej));
} // render function
static get template() {
return _polymerElement.html`
<style>
:host {
display: block;
--site-top-menu-bg: var(--haxcms-color, #ffffff);
--site-top-menu-indicator-arrow: 6px;
transition: 0.2s opacity linear;
opacity: 1;
}
:host([edit-mode]) {
opacity: 0.2;
pointer-events: none;
}
:host([sticky]) {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1000;
@apply --site-top-menu-sticky;
}
.wrapper {
display: flex;
justify-content: space-evenly;
background-color: var(--site-top-menu-bg);
@apply --site-top-menu-wrapper;
}
:host .wrapper ::slotted(div.spacing) {
display: inline-flex;
@apply --site-top-menu-spacing;
}
.spacing {
display: inline-flex;
@apply --site-top-menu-spacing;
}
.link {
color: var(--site-top-menu-link-color, #444444);
@apply --site-top-menu-link;
}
paper-button {
text-transform: unset;
min-width: unset;
@apply --site-top-menu-button;
}
.active {
color: var(--site-top-menu-link-active-color, #000000);
@apply --site-top-menu-link-active;
}
#indicator {
transition: 0.4s ease-in-out left;
transition-delay: 0.2s;
position: relative;
width: 0;
height: 0;
visibility: hidden;
}
:host([indicator="line"]) #indicator {
border-bottom: 2px solid var(--site-top-menu-indicator-color, #000000);
@apply --site-top-menu-indicator;
}
:host([indicator="arrow"]) #indicator {
border-left: var(--site-top-menu-indicator-arrow) solid transparent;
border-right: var(--site-top-menu-indicator-arrow) solid transparent;
border-bottom: var(--site-top-menu-indicator-arrow) solid
var(--site-top-menu-indicator-color, #000000);
@apply --site-top-menu-indicator;
}
#indicator.activated {
visibility: visible;
position: absolute;
@apply --site-top-menu-indicator-activated;
}
:host([notitle]) .spacing .link-title {
display: none;
}
.spacing .link-index {
display: none;
}
:host([showindex]) .spacing .link-index {
display: inline-flex;
}
.mobiletitle,
paper-icon-button {
display: none;
}
@media screen and (max-width: 640px) {
.wrapper .spacing {
display: none;
}
.wrapper .mobiletitle,
.wrapper paper-icon-button {
display: inline-block;
}
.wrapper {
display: block;
}
}
@media screen and (max-width: 640px) {
#indicator {
display: none !important;
}
.wrapper.responsive {
position: relative;
}
.wrapper.responsive .spacing {
float: none;
display: block;
text-align: left;
}
}
</style>
<site-query
result="{{__items}}"
sort="[[sort]]"
conditions="[[conditions]]"
></site-query>
<div id="wrapper" class="wrapper">
<paper-icon-button
icon="menu"
id="menu"
title="Open navigation"
></paper-icon-button>
<span class="mobiletitle">[[mobileTitle]]</span>
<slot name="prefix"></slot>
<dom-repeat items="[[__items]]" mutable-data>
<template>
<div class="spacing">
<a
data-id$="[[item.id]]"
class="link"
tabindex="-1"
title$="Go to [[item.title]]"
href$="[[item.location]]"
>
<paper-button id$="item-[[item.id]]" noink="[[noink]]">
<span class="link-index">[[humanIndex(index)]]</span>
<span class="link-title">[[item.title]]</span>
</paper-button>
</a>
</div>
</template>
</dom-repeat>
<slot name="suffix"></slot>
</div>
<div id="indicator"></div>
`;
}
/**
* Props
*/
static get properties() {
return {
/**
* manifest of everything, in case we need to check on children of parents
*/
manifest: {
type: Object
},
/**
* acitvely selected item
*/
activeId: {
type: String,
observer: "_activeIdChanged"
},
/**
* visually stick to top of interface at all times
*/
sticky: {
type: Boolean,
reflectToAttribute: true,
value: false
},
/**
* visualize the indicator as a a line, arrow, or not at all
*/
indicator: {
type: String,
reflectToAttribute: true,
value: "line"
},
/**
* ink on the buttons
*/
noink: {
type: Boolean,
reflectToAttribute: true,
value: false
},
/**
* hide title on the buttons
*/
notitle: {
type: Boolean,
reflectToAttribute: true,
value: false
},
/**
* ink on the buttons
*/
showindex: {
type: Boolean,
reflectToAttribute: true,
value: false
},
/**
* Stupid but faster then calculating on the fly for sure
*/
arrowSize: {
type: Number,
value: 6
},
/**
* Allow customization of sort
*/
sort: {
type: Object,
value: {
order: "ASC"
}
},
/**
* Allow customization of the conditions if needed
*/
conditions: {
type: Object,
value: {
parent: null
}
},
mobileTitle: {
type: String,
value: "Navigation"
},
editMode: {
type: Boolean,
reflectToAttribute: true
}
};
}
humanIndex(index) {
return index + 1;
}
toggleOpen() {
var wrapper = this.shadowRoot.querySelector("#wrapper");
if (wrapper.classList.contains("responsive")) {
wrapper.classList.remove("responsive");
} else {
wrapper.classList.add("responsive");
}
}
/**
* When active ID changes, see if we know what to highlight automatically
*/
_activeIdChanged(newValue) {
// as long as didn't disable the indicator, do this processing
if (this.indicator != "none") {
if (newValue) {
this.$.indicator.classList.add("activated");
let el = null; //ensure that this level is included
if (this.shadowRoot.querySelector('[data-id="' + newValue + '"]')) {
el = this.shadowRoot.querySelector('[data-id="' + newValue + '"]');
} else {
let tmpItem = this.manifest.items.find(i => i.id == newValue); // fallback, maybe there's a child of this currently active
while (el === null && tmpItem && tmpItem.parent != null) {
// take the parent object of this current item
tmpItem = this.manifest.items.find(i => i.id == tmpItem.parent); // see if IT lives in the dom, if not, keep going until we run out
if (tmpItem && this.shadowRoot.querySelector('[data-id="' + tmpItem.id + '"]')) {
el = this.shadowRoot.querySelector('[data-id="' + tmpItem.id + '"]');
}
}
}
if (this._prevEl) {
this._prevEl.classList.remove("active");
}
if (el) {
el.classList.add("active");
this._prevEl = el;
if (this.indicator == "arrow") {
this.$.indicator.style.left = el.offsetLeft + el.offsetWidth / 2 - this.arrowSize + "px";
this.$.indicator.style.top = el.offsetTop + el.offsetHeight - this.arrowSize + "px";
} else {
this.$.indicator.style.left = el.offsetLeft + "px";
this.$.indicator.style.top = el.offsetTop + el.offsetHeight + "px";
this.$.indicator.style.width = el.offsetWidth + "px";
}
}
} else {
// shouldn't be possible but might as well list
this.$.indicator.classList.remove("activated");
}
}
}
connectedCallback() {
super.connectedCallback();
this.shadowRoot.querySelector("#menu").addEventListener("click", this.toggleOpen.bind(this));
(0, _mobxModule.autorun)(reaction => {
this.manifest = (0, _mobxModule.toJS)(_haxcmsSiteStore.store.manifest);
this.__disposer.push(reaction);
});
(0, _mobxModule.autorun)(reaction => {
this.editMode = (0, _mobxModule.toJS)(_haxcmsSiteStore.store.editMode);
this.__disposer.push(reaction);
}); // minor timing thing to ensure store has picked active
// needed if routes set on first paint or lifecycles miss
setTimeout(() => {
(0, _mobxModule.autorun)(reaction => {
this.activeId = (0, _mobxModule.toJS)(_haxcmsSiteStore.store.activeId);
this.__disposer.push(reaction);
});
}, 50);
window.addEventListener("resize", () => {
this._activeIdChanged(this.activeId);
}, true);
}
disconnectedCallback() {
// clean up state
for (var i in this.__disposer) {
this.__disposer[i].dispose();
}
window.removeEventListener("resize", () => {
this._activeIdChanged(this.activeId);
}, true);
super.disconnectedCallback();
}
} |
JavaScript | class RegExpRecognizer extends intentRecognizer_1.IntentRecognizer {
/**
* Creates a new instance of the recognizer.
*
* @param settings (Optional) settings to customize the recognizer.
*/
constructor(settings) {
super();
this.intents = {};
this.settings = Object.assign({
minScore: 0.0
}, settings);
if (this.settings.minScore < 0 || this.settings.minScore > 1.0) {
throw new Error(`RegExpRecognizer: a minScore of '${this.settings.minScore}' is out of range.`);
}
this.onRecognize((context) => {
const intents = [];
const utterance = (context.request.text || '').trim();
const minScore = this.settings.minScore;
for (const name in this.intents) {
const map = this.intents[name];
const expressions = this.getExpressions(context, map);
let top;
(expressions || []).forEach((exp) => {
const intent = RegExpRecognizer.recognize(utterance, exp, [], minScore);
if (intent && (!top || intent.score > top.score)) {
top = intent;
}
});
if (top) {
top.name = name;
intents.push(top);
}
}
return intents;
});
}
/**
* Adds a definition for a named intent to the recognizer.
*
* **Usage Example**
*
* ```js
* // init recognizer
* let foodRecognizer = new RegExpRecognizer();
*
* // add intents to recognizer
* foodRecognizer.addIntent('TacosIntent', /taco/i);
* foodRecognizer.addIntent('BurritosIntent', /burrito/i);
* foodRecognizer.addIntent('EnchiladasIntent', /enchiladas/i);
*
* // add recognizer to bot
* bot.use(foodRecognizer);
* bot.onRecognize((context) => {
* if (context.ifIntent('TacosIntent')) {
* // handle tacos intent
* context.reply('Added one taco to your order');
* }
* else if (context.ifIntent('BurritosIntent')) {
* // handle burritos intent
* context.reply('Added one burrito to your order');
* }
* else if (context.ifIntent('EnchiladasIntent')) {
* // handle enchiladas intent
* context.reply('Added one enchilada to your order');
* }
* else {
* // handle other messages
* }
* })
* ```
*
* @param name Name of the intent to return when one of the expression(s) is matched.
* @param expressions Expression(s) to match for this intent. Passing a `RegExpLocaleMap` lets
* specify an alternate set of expressions for each language that your bot supports.
*/
addIntent(name, expressions) {
if (this.intents.hasOwnProperty(name)) {
throw new Error(`RegExpRecognizer: an intent name '${name}' already exists.`);
}
// Register as locale map
if (Array.isArray(expressions)) {
this.intents[name] = { '*': expressions };
}
else if (expressions instanceof RegExp) {
this.intents[name] = { '*': [expressions] };
}
else {
this.intents[name] = expressions;
}
return this;
}
getExpressions(context, map) {
const locale = context.request.locale || '*';
const entry = map.hasOwnProperty(locale) ? map[locale] : map['*'];
return entry ? (Array.isArray(entry) ? entry : [entry]) : undefined;
}
/**
* Matches a text string using the given expression. If matched, an `Intent` will be returned
* containing a coverage score, from 0.0 to 1.0, indicating how much of the text matched
* the expression. The more of the text the matched the greater the score. The name of
* the intent will be the value of `expression.toString()` and any capture groups will be
* returned as individual entities of type `string`.
*
* @param text The text string to match against.
* @param expression The expression to match.
* @param entityTypes (Optional) array of types to assign to each entity returned for a numbered
* capture group. As an example, for the expression `/flight from (.*) to (.*)/i` you could
* pass a value of `['fromCity', 'toCity']`. The entity returned for the first capture group will
* have a type of `fromCity` and the entity for the second capture group will have a type of
* `toCity`. The default entity type returned when not specified is `string`.
* @param minScore (Optional) minimum score to return for the coverage score. The default value
* is 0.0 but if provided, the calculated coverage score will be scaled to a value between the
* minScore and 1.0. For example, a expression that matches 50% of the text will result in a
* base coverage score of 0.5. If the minScore supplied is also 0.5 the returned score will be
* scaled to be 0.75 or 50% between 0.5 and 1.0. As another example, providing a minScore of 1.0
* will always result in a match returning a score of 1.0.
*/
static recognize(text, expression, entityTypes = [], minScore = 0.0) {
if (typeof minScore !== 'number' || minScore < 0 || minScore > 1.0) {
throw new Error(`RegExpRecognizer: a minScore of '${minScore}' is out of range for expression '${expression.toString()}'.`);
}
const matched = expression.exec(text);
if (matched) {
// Calculate coverage
const coverage = matched[0].length / text.length;
const score = minScore + ((1.0 - minScore) * coverage);
// Populate entities
const entities = [];
if (matched.length > 1) {
for (let i = 1; i < matched.length; i++) {
const type = (i - 1) < entityTypes.length ? entityTypes[i - 1] : entityObject_1.EntityTypes.string;
entities.push({ type: type, score: 1.0, value: matched[i] });
}
}
// Return intent
return { name: expression.toString(), score: score, entities: entities };
}
return undefined;
}
} |
JavaScript | class InsertColumnCommand extends Command {
/**
* Creates a new `InsertColumnCommand` instance.
*
* @param {module:core/editor/editor~Editor} editor An editor on which this command will be used.
* @param {Object} options
* @param {String} [options.order="right"] The order of insertion relative to the column in which the caret is located.
* Possible values: `"left"` and `"right"`.
*/
constructor(editor, options = {}) {
super(editor);
/**
* The order of insertion relative to the column in which the caret is located.
*
* @readonly
* @member {String} module:table/commands/insertcolumncommand~InsertColumnCommand#order
*/
this.order = options.order || 'right';
}
/**
* @inheritDoc
*/
refresh() {
const selection = this.editor.model.document.selection;
const tableParent = findAncestor('table', selection.getFirstPosition());
this.isEnabled = !!tableParent;
}
/**
* Executes the command.
*
* Depending on the command's {@link #order} value, it inserts a column to the `'left'` or `'right'` of the column
* in which the selection is set.
*
* @fires execute
*/
execute() {
const editor = this.editor;
const selection = editor.model.document.selection;
const tableUtils = editor.plugins.get('TableUtils');
const firstPosition = selection.getFirstPosition();
const tableCell = findAncestor('tableCell', firstPosition);
const table = tableCell.parent.parent;
const { column } = tableUtils.getCellLocation(tableCell);
const insertAt = this.order === 'right' ? column + 1 : column;
tableUtils.insertColumns(table, { columns: 1, at: insertAt });
}
} |
JavaScript | class ExtendedContextMenu {
constructor() {
// vv Stole this function from Zere's Plugin Library vv //
this.getReactInstance = function (node) {
if (!(node instanceof jQuery) && !(node instanceof Element))
return undefined;
var domNode = node instanceof jQuery ? node[0] : node;
return domNode[Object.keys(domNode).find((key) => key.startsWith("__reactInternalInstance"))];
};
// ^^ Stole this function from Zere's Plugin Library ^^ //
}
getName() {
return "Extended Context Menu";
}
getDescription() {
return "Add useful stuff to the context menu.";
}
getVersion() {
return "0.0.4";
}
getAuthor() {
return "Qwerasd";
}
load() {
this.getChannel = BdApi.findModuleByProps('getChannelId').getChannelId;
this.getServer = BdApi.findModuleByProps('getGuildId').getGuildId;
this.listener = this.oncontextmenu.bind(this);
this.copyText = require('electron').clipboard.writeText;
}
start() {
document.addEventListener('contextmenu', this.listener);
}
stop() {
document.removeEventListener('contextmenu', this.listener);
}
oncontextmenu() {
const menu = document.getElementsByClassName('da-contextMenu')[0];
const reactInstance = this.getReactInstance(menu);
if (!reactInstance)
return;
const props = reactInstance.return.memoizedProps;
const message = props.message;
const channel = props.channel;
const target = props.target;
const finalGroup = menu.lastChild;
if (message) {
finalGroup.appendChild(this.createButton('Copy Message Link', (function () {
this.copyText(this.getMessageURL(this.getServer(), this.getChannel(), message.id));
return true;
}).bind(this)));
finalGroup.appendChild(this.createButton('Copy Message', (function () {
this.copyText(message.content);
return true;
}).bind(this)));
}
else if (channel) {
finalGroup.appendChild(this.createButton('Mention', (function () {
this.addTextToTextarea(`<#${channel.id}>`);
return true;
}).bind(this)));
}
if (target && target.className && (target.className.includes('hljs') || target.tagName === 'CODE')) {
let codeNode = target;
while (codeNode.tagName !== 'CODE' && codeNode.tagName === 'SPAN')
codeNode = codeNode.parentNode;
finalGroup.appendChild(this.createButton('Copy Codeblock', (function () {
this.copyText(codeNode.innerText);
return true;
}).bind(this)));
}
reactInstance.return.stateNode.props.onHeightUpdate();
}
createButton(text, func) {
const button = document.createElement('div');
button.tabIndex = 0;
button.setAttribute('role', 'button');
button.className = 'item-1Yvehc da-item extendedContextMenu';
button.addEventListener('click', e => {
const close = func(e);
if (close)
document.body.click();
});
const span = document.createElement('span');
span.innerText = text;
const hint = document.createElement('div');
hint.className = 'hint-22uc-R da-hint';
button.appendChild(span);
button.appendChild(hint);
return button;
}
getMessageURL(server, channel, message) {
return `${document.location.origin}/channels/${server ? server : '@me'}/${channel}/${message}`;
}
addTextToTextarea(text) {
const textarea = document.getElementsByTagName('textarea')[0];
textarea.select();
document.execCommand('insertText', false, text);
}
} |
JavaScript | class BaseAi {
/**
* Constructor
* @param {Creature} creature the creature to control
*/
constructor(creature) {
this.creature = creature;
}
/**
* Get the scene the AI's creature belongs to
* @returns {EntityScene} the scene the controlled creature belongs to
*/
get scene() {
return this.creature.scene;
}
/**
* Control the creature for one turn - SHOULD BE IMPLEMENTED BY SUBCLASSES
*/
takeTurn() {}
} |
JavaScript | class HeadersMenuBuilder {
constructor(options = {}) {
this.headers = options.headerSelector ? [...document.querySelectorAll(options.headerSelector)] : [...document.querySelectorAll('.js--headers-menu-item')];
this.headersTrue = this.headers.length > 0;
this.mContainer = options.mContainer ? document.querySelector(options.mContainer) : document.querySelector('.js--headers-menu');
this.class = {
scrolled: 'js--headers-menu-item--scrolled'
};
// this.speed = options.speed ? options.speed : 450;
}
setupCheck() {
return (this.headersTrue !== 0 && this.mContainer);
}
getScrollHeight() {
this.currentHeight = window.pageYOffset || window.scrollY;
return this.currentHeight;
}
checkHeadersScrolled() {
const scrollHeight = this.getScrollHeight();
this.headers.forEach((header) => {
if (header.offsetTop <= scrollHeight) header.dataset.scrolled = 'true';
else header.dataset.scrolled = 'false';
});
}
createMenuLinks() {
// Create the parent list element
const list = document.createElement('ul');
list.classList.add('HeadersMenu__List');
this.headersMenu = this.headers.map((el) => {
const linkEl = document.createElement('li');
linkEl.textContent = el.textContent;
linkEl.classList.add('HeadersMenu__Item');
linkEl.addEventListener('click', () => {
el.scrollIntoView({ behavior: 'smooth' });
});
list.appendChild(linkEl);
return linkEl;
});
this.mContainer.appendChild(list);
this.mContainer.classList.remove('hidden');
}
init() {
if (this.setupCheck()) {
this.createMenuLinks();
this.checkHeadersScrolled();
}
}
} |
JavaScript | class Identity {
/**
* @constructor
* @param {Object} options - An object containing the access token and the base URL
*/
constructor(options) {
this.apiCall = new APICall(options);
this.keys = new IdentitiesKeyUtil(options);
}
/**
* @param {String} params.identityChainId='' The chain id of the desired Identity.
* @return {Promise} Returns a Promise that, when fulfilled, will either return an Object
* with the Identity or an Error with the problem.
*/
async get(params = {}) {
if (!params.identityChainId) {
throw new Error('identityChainId is required.');
}
const response = await this.apiCall.send(
constants.GET_METHOD,
`${constants.IDENTITIES_URL}/${params.identityChainId}`,
{},
params.baseUrl,
params.accessToken,
);
return response;
}
/**
* @param {String[]} params.names=[]
* @param {String[]} params.keys=[]
* @param {String} params.callbackUrl=''
* @param {String[]} params.callbackStages=[]
* @return {Promise} Returns a Promise that, when fulfilled, will either return an Object
* with the chain or an Error with the problem
*/
async create(params = {}) {
if (CommonUtil.isEmptyArray(params.names)) {
throw new Error('at least 1 name is required.');
}
if (!Array.isArray(params.names)) {
throw new Error('names must be an array.');
}
const keyPairs = [];
let signerKeys = [];
if (typeof params.keys !== 'undefined') {
if (CommonUtil.isEmptyArray(params.keys)) {
throw new Error('at least 1 key is required.');
}
if (!Array.isArray(params.keys)) {
throw new Error('keys must be an array.');
}
signerKeys = params.keys;
} else {
for (let i = 0; i < 3; i += 1) {
const pair = KeyCommon.createKeyPair();
keyPairs.push(pair);
signerKeys.push(pair.publicKey);
}
}
if (params.callbackStages && !Array.isArray(params.callbackStages)) {
throw new Error('callbackStages must be an array.');
}
const keysInvalid = KeyCommon.getInvalidKeys({ signerKeys: signerKeys });
if (keysInvalid.length) {
throw new Error(keysInvalid);
}
const duplicates = KeyCommon.getDuplicateKeys({ signerKeys: signerKeys });
if (duplicates.length) {
throw new Error(duplicates);
}
if (
!CommonUtil.isEmptyString(params.callbackUrl)
&& !isUrl(params.callbackUrl)
) {
throw new Error('callbackUrl is an invalid url format.');
}
let nameByteCounts = 0;
params.names.forEach((o) => {
nameByteCounts += Buffer.from(o).length;
});
// 2 bytes for the size of extid + 13 for actual IdentityChain ext-id text
// 2 bytes per name for size * (number of names) + size of all names
// 23 bytes for `{"keys":[],"version":1}`
// 58 bytes per `"idpub2PHPArpDF6S86ys314D3JDiKD8HLqJ4HMFcjNJP6gxapoNsyFG",` array element
// -1 byte because last key element has no comma
// = 37 + name_byte_count + 2(number_of_names) + 58(number_of_keys)
const totalBytes = 37 + nameByteCounts + 2 * params.names.length + signerKeys.length * 58;
if (totalBytes > 10240) {
throw new Error(`calculated bytes of names and keys is ${totalBytes}. It must be less than 10240, use less/shorter names or less keys.`);
}
const namesBase64 = [];
params.names.forEach((o) => {
namesBase64.push(Buffer.from(o.trim()).toString('base64'));
});
const data = {
names: namesBase64,
keys: signerKeys,
};
if (!CommonUtil.isEmptyString(params.callbackUrl)) {
data.callback_url = params.callbackUrl;
}
if (Array.isArray(params.callbackStages)) {
data.callback_stages = params.callbackStages;
}
const response = await this.apiCall.send(constants.POST_METHOD, constants.IDENTITIES_URL,
data, params.baseUrl, params.accessToken);
if (typeof params.keys === 'undefined') {
const pairs = [];
keyPairs.forEach((i) => {
pairs.push({
public_key: i.publicKey,
private_key: i.privateKey,
});
});
response.key_pairs = pairs;
}
return response;
}
} |
JavaScript | class ConnectionProfileManager {
/**
* The composer-common module cannot load connector modules from parent modules
* when the dependencies are linked together using npm link or lerna. To work
* around this, the packages that require the connectors register themselves as
* modules that can load connection managers.
* @param {Object} module The module that can load connector modules.
*/
static registerConnectionManagerLoader (module) {
connectionManagerLoaders.push(module);
}
/**
* Register a new ConnectionManager class.
* @param {string} type - the profile type identifier of the ConnectionManager
* @param {function} ctor - the constructor of the ConnectionManager
*/
static registerConnectionManager (type, ctor) {
connectionManagerClasses[type] = ctor;
}
/**
* Adds a ConnectionManager to the mappings of this ConnectionProfileManager
* @param {string} type - the profile type identifier of the ConnectionManager
* @param {ConnectionManager} connectionManager - the instance
*/
addConnectionManager (type, connectionManager) {
LOG.info('addConnectionManager', 'Adding a new connection manager', type);
connectionManagers[type] = connectionManager;
}
/**
* Retrieves the ConnectionManager for the given connection type.
*
* @param {String} connectionType The connection type, eg hlfv1, embedded, embedded@proxy
* @return {Promise} A promise that is resolved with a {@link ConnectionManager}
* object once the connection is established, or rejected with a connection error.
*/
getConnectionManagerByType (connectionType) {
const METHOD = 'getConnectionManagerByType';
if (!connectionType) {
let err = new Error('No connection type provided, probably because the connection profile has no \'x-type\' property defined.');
LOG.error(METHOD, err);
return Promise.reject(err);
}
LOG.info(METHOD, 'Looking up a connection manager for type', connectionType);
let errorList = [];
return Promise.resolve()
.then(() => {
let connectionManager = connectionManagers[connectionType];
if (!connectionManager) {
const delegateTypeIndex = connectionType.toLowerCase().lastIndexOf('@');
const mod = delegateTypeIndex === -1 || delegateTypeIndex === connectionType.length - 1 ? `composer-connector-${connectionType}` : `composer-connector-${connectionType.substring(delegateTypeIndex + 1)}`;
LOG.debug(METHOD, 'Looking for module', mod);
try {
// Check for the connection manager class registered using
// registerConnectionManager (used by the web connector).
const actualType = delegateTypeIndex !== -1 && delegateTypeIndex < connectionType.length - 1 ? connectionType.substring(delegateTypeIndex + 1) : connectionType;
const connectionManagerClass = connectionManagerClasses[actualType];
if (connectionManagerClass) {
connectionManager = new (connectionManagerClass)(this);
} else {
// Not registered using registerConnectionManager, we now
// need to search for the connector module in our module
// and all of the parent modules (the ones who required
// us) as we do not depend on any connector modules.
let curmod = module;
while (curmod) {
try {
connectionManager = new (curmod.require(mod))(this);
break;
} catch (e) {
errorList.push(e.message);
LOG.info(METHOD, 'No yet located the module ', e.message);
// Continue to search the parent.
}
curmod = curmod.parent;
}
LOG.info(METHOD, 'Using this connection manager ', connectionManager);
if (!connectionManager) {
connectionManagerLoaders.some((connectionManagerLoader) => {
try {
connectionManager = new (connectionManagerLoader.require(mod))(this);
return true;
} catch (e) {
// Search the next one.
errorList.push(e.message);
LOG.info(METHOD, e);
return false;
}
});
}
if (!connectionManager) {
LOG.info(METHOD, 'not located the module - final try ');
// We still didn't find it, so try plain old require
// one last time.
connectionManager = new (require(mod))(this);
}
}
} catch (e) {
// takes the error list, and filters out duplicate lines
errorList.push(e.message);
errorList.filter((element, index, self) => {
return index === self.indexOf(element);
});
const newError = new Error(`Failed to load connector module "${mod}" for connection type "${connectionType}". ${errorList.join('-')}`);
LOG.error(METHOD, newError);
throw newError;
}
connectionManagers[connectionType] = connectionManager;
}
return connectionManager;
});
}
/**
* Establish a connection to the business network, using connection information
* from the connection profile.
*
* @param {string} connectionProfileName The name of the connection profile
* @param {string} businessNetworkIdentifier The identifier of the business network, or null if this is an admin connection
* @param {Object} connectionProfileData the actual connection profile
* @return {Promise} A promise that is resolved with a {@link Connection}
* object once the connection is established, or rejected with a connection error.
*/
connect(connectionProfileName, businessNetworkIdentifier, connectionProfileData) {
LOG.info('connect', 'Connecting using ' + connectionProfileName, businessNetworkIdentifier);
return this.getConnectionManagerByType(connectionProfileData['x-type'])
.then((connectionManager) => {
return connectionManager.connect(connectionProfileName, businessNetworkIdentifier, connectionProfileData);
});
}
/**
* Connect with the actual connection profile data, so the look up of the connection profile
* is by passed as this has come direct from the business network card.
*
* @param {Object} connectionProfileData object representing of the connection profile
* @param {String} businessNetworkIdentifier id of the business network
* @param {Object} [additionalConnectOptions] additional options
* @return {Promise} A promise that is resolved with a {@link Connection}
* object once the connection is established, or rejected with a connection error.
*/
connectWithData(connectionProfileData, businessNetworkIdentifier, additionalConnectOptions) {
let connectOptions = connectionProfileData;
return Promise.resolve().then(() => {
if (additionalConnectOptions) {
connectOptions = Object.assign(connectOptions, additionalConnectOptions);
}
return this.getConnectionManagerByType(connectOptions['x-type']);
})
.then((connectionManager) => {
return connectionManager.connect(connectOptions.name, businessNetworkIdentifier, connectOptions);
});
}
/**
* Clear the static object containing all the connection managers
*/
static removeAllConnectionManagers () {
connectionManagerLoaders.length = 0;
Object.keys(connectionManagerClasses).forEach((key) => {
connectionManagerClasses[key] = null;
});
Object.keys(connectionManagers).forEach((key) => {
connectionManagers[key] = null;
});
}
} |
JavaScript | class ButtonCustom extends Component {
render() {
return (
<button>Brabo demais</button>
)
}
} |
JavaScript | class UpdateIfMatch extends Component {
shouldComponentUpdate(nextProps) {
return nextProps.match !== this.props.match || nextProps.children !== this.props.children
}
render() {
return this.props.children
}
} |
JavaScript | class SelectionDropdown extends Component {
render() {
// Tweaks to the default react-select styles so that it'll look good with tube maps.
const styles = {
control: base => ({
...base,
minHeight: "unset",
height: "calc(2.25rem - 2px)"
}),
valueContainer: base => ({
...base,
// Roughly calculate the width that can fit the largest text. This can't be updated dynamically.
width: Math.max(...this.props.options.map(option => option.length)) * 8 + 16,
minWidth: "48px",
position: "unset"
}),
indicatorsContainer: base => ({
...base,
height: "inherit",
}),
menu: base => ({
...base,
width: "max-content",
minWidth: "100%"
}),
}
const dropdownOptions = this.props.options.map(option => ({
label: option,
value: option,
}));
const onChange = (option) => {
this.props.onChange({
target: {
id: this.props.id,
value: option.value,
}
});
}
return (
<Select
id={this.props.id}
className={this.props.className}
value={dropdownOptions.find((option) => option.value === this.props.value) || {}}
styles={styles}
isSearchable={true}
onChange={onChange}
options={dropdownOptions}
openMenuOnClick={dropdownOptions.length < 2000}
/>
)
}
} |
JavaScript | class Compiler extends Events {
constructor (file) {
super();
this.file = file;
this.cacheDir = join(CACHE_FOLDER, this.constructor.name.toLowerCase());
this.watcherEnabled = false;
this._watchers = {};
this._compiledOnce = {};
if (!existsSync(this.cacheDir)) {
mkdirSync(this.cacheDir, { recursive: true });
}
}
/**
* Enables the file watcher. Will emit "src-update" event if any of the files are updated.
*/
enableWatcher () {
this.watcherEnabled = true;
}
/**
* Disables the file watcher. MUST be called if you no longer need the compiler and the watcher
* was previously enabled.
*/
disableWatcher () {
this.watcherEnabled = false;
Object.values(this._watchers).forEach(w => w.close());
this._watchers = {};
}
/**
* Arbitrary configuration for the compiler. Useless if not implemented in the _compile method.
* *NOTE*: Will fire "src-update" if the watcher is enabled and at least one compilation has been performed.
* @param {Object} options Options for the compiler
*/
setCompileOptions (options) {
// @todo: finish this
this.compileOptions = options;
}
/**
* Compiles the file (if necessary), and perform cache-related operations.
* @returns {Promise<String>|String} Compilation result
*/
compile () {
// Attemt to fetch from cache
const cacheKey = this.computeCacheKey();
if (cacheKey instanceof Promise) {
return cacheKey.then(key => this._doCompilation(key));
}
return this._doCompilation(cacheKey);
}
/** @private */
_doCompilation (cacheKey) {
let cacheFile;
if (cacheKey) {
cacheFile = join(this.cacheDir, cacheKey);
if (existsSync(cacheFile)) {
const compiled = readFileSync(cacheFile, 'utf8');
this._finishCompilation(null, compiled);
return compiled;
}
}
// Perform compilation
const compiled = this._compile();
if (compiled instanceof Promise) {
return compiled.then(finalCompiled => {
this._finishCompilation(cacheFile, finalCompiled);
return finalCompiled;
});
}
this._finishCompilation(cacheFile, compiled);
return compiled;
}
/** @private */
_finishCompilation (cacheFile, compiled) {
if (cacheFile) {
writeFileSync(cacheFile, compiled, () => void 0);
}
if (this.watcherEnabled) {
this._watchFiles();
}
}
/** @private */
async _watchFiles () {
const files = await this.listFiles();
// Filter no longer used watchers
Object.keys(this._watchers).forEach(k => {
if (!files.includes(k)) {
this._watchers[k].close();
delete this._watchers[k];
}
});
// Add new watchers
files.forEach(f => {
if (!this._watchers[f]) {
this._watchers[f] = watch(f, () => this.emit('src-update'));
}
});
}
/**
* Lists all files involved during the compilation (parent file + imported files)
* Only applicable if files are concatenated during compilation (e.g. scss files)
* @returns {Promise<String[]>|String[]}
*/
listFiles () {
return [ this.file ];
}
/**
* Computes the hash corresponding to the file we're compiling.
* MUST take into account imported files (if any) and always return the same hash for the same given file.
* @returns {Promise<String|null>|String|null} Cache key, or null if cache isn't available
*/
computeCacheKey () {
const files = this.listFiles();
if (files instanceof Promise) {
return files.then(this._computeCacheKey.bind(this));
}
return this._computeCacheKey(files);
}
/** @private */
_computeCacheKey (files) {
const hashes = files.map(this.computeFileHash.bind(this));
if (hashes.length === 1) {
return hashes[0];
}
const hash = createHash('sha1');
hashes.forEach(h => hash.update(h));
return hash.digest('hex');
}
/**
* Computes the hash of a given file
* @param {String} file File path
*/
computeFileHash (file) {
if (!existsSync(file)) {
throw new Error('File doesn\'t exist!');
}
const fileBuffer = readFileSync(file);
return createHash('sha1')
.update(this._metadata)
.update(fileBuffer)
.digest('hex');
}
/**
* Compiles the file. Should NOT perform any cache-related actions
* @returns {Promise<String>} Compilation results.
*/
_compile () {
throw new Error('Not implemented');
}
/**
* @returns {String} Compiler metadata (compiler used, version)
*/
get _metadata () {
return '';
}
} |
JavaScript | class LayerSwitcher extends Control {
constructor(options) {
super(options);
this.dialog = null;
this.baseLayersDiv = null;
this.overlaysDiv = null;
this._id = LayerSwitcher.numSwitches++;
}
static get numSwitches() {
if (!this._counter && this._counter !== 0) {
this._counter = 0;
}
return this._counter;
}
static set numSwitches(n) {
this._counter = n;
}
oninit() {
this.planet.events.on("layeradd", this.onLayerAdded, this);
this.planet.events.on("layerremove", this.onLayerRemoved, this);
this.createSwitcher();
this.createDialog();
}
onLayerAdded(layer) {
if (layer.displayInLayerSwitcher) {
if (layer.isBaseLayer()) {
this.addSwitcher("radio", layer, this.baseLayersDiv);
} else {
this.addSwitcher("checkbox", layer, this.overlaysDiv, this._id);
}
}
}
onLayerRemoved(layer) {
layer._removeCallback();
layer._removeCallback = null;
}
addSwitcher(type, obj, container, id) {
var lineDiv = document.createElement("div");
var that = this;
var center = document.createElement("div");
center.classList.add("ogViewExtentBtn");
center.onclick = function () {
that.planet.flyExtent(obj.getExtent());
};
var inp = document.createElement("input");
inp.type = type;
inp.name = "ogBaseLayerRadiosId" + (id || "");
inp.checked = obj.getVisibility();
inp.className = "ogLayerSwitcherInput";
inp.onclick = function () {
obj.setVisibility(this.checked);
};
obj.events &&
obj.events.on("visibilitychange", function (e) {
inp.checked = e.getVisibility();
});
var lbl = document.createElement("label");
lbl.className = "ogLayerSwitcherLabel";
lbl.innerHTML = (obj.name || obj.src || "noname") + "</br>";
obj._removeCallback = function () {
container.removeChild(lineDiv);
};
lineDiv.appendChild(center);
lineDiv.appendChild(inp);
lineDiv.appendChild(lbl);
container.appendChild(lineDiv);
}
createBaseLayersContainer() {
var layersDiv = document.createElement("div");
layersDiv.className = "layersDiv";
this.dialog.appendChild(layersDiv);
var baseLayersLbl = document.createElement("div");
baseLayersLbl.className = "layersDiv";
baseLayersLbl.innerHTML = "Base Layer";
layersDiv.appendChild(baseLayersLbl);
this.baseLayersDiv = document.createElement("div");
layersDiv.appendChild(this.baseLayersDiv);
}
createOverlaysContainer() {
var overlaysDiv = document.createElement("div");
overlaysDiv.className = "layersDiv";
this.dialog.appendChild(overlaysDiv);
var overlaysLbl = document.createElement("div");
overlaysLbl.className = "layersDiv";
overlaysLbl.innerHTML = "Overlays";
overlaysDiv.appendChild(overlaysLbl);
this.overlaysDiv = document.createElement("div");
overlaysDiv.appendChild(this.overlaysDiv);
}
createDialog() {
this.dialog = document.createElement("div");
this.dialog.id = "ogLayerSwitcherDialog";
this.dialog.className = "displayNone";
this.renderer.div.appendChild(this.dialog);
this.createBaseLayersContainer();
this.createOverlaysContainer();
if (this.planet) {
for (var i = 0; i < this.planet.layers.length; i++) {
this.onLayerAdded(this.planet.layers[i]);
}
}
}
createSwitcher() {
var button = document.createElement("div");
button.className = "ogLayerSwitcherButton";
button.id = "ogLayerSwitcherButtonMaximize";
var that = this;
button.onclick = function (e) {
if (this.id === "ogLayerSwitcherButtonMaximize") {
this.id = "ogLayerSwitcherButtonMinimize";
that.dialog.className = "displayBlock";
} else {
this.id = "ogLayerSwitcherButtonMaximize";
that.dialog.className = "displayNone";
}
};
this.renderer.div.appendChild(button);
}
} |
JavaScript | class LocaleEditor extends HashBrown.Entity.View.Field.FieldBase {
/**
* Constructor
*/
constructor(params) {
super(params);
this.editorTemplate = require('template/field/editor/localeEditor');
}
/**
* Gets the value label
*
* @return {String}
*/
async getValueLabel() {
if(this.state.value) {
return this.state.value;
}
return await super.getValueLabel();
}
/**
* Fetches view data
*/
async fetch() {
await super.fetch();
this.state.localeOptions = {};
for(let locale of this.context.project.settings.locales) {
this.state.localeOptions[HashBrown.Service.LocaleService.getLocaleName(locale)] = locale;
}
}
} |
JavaScript | class SawtoothBatch {
constructor({ transactions }) {
this.transactions = transactions;
}
} |
JavaScript | class Server {
constructor() {
/**
* Configuration informations.
* Defaults to:
* ```
* {
* env: {
* type: 'development',
* port: 8000,
* subfolder: '',
* useHttps: false,
* },
* app: {
* name: 'soundworks',
* },
* }
* ```
*/
this.config = {};
/**
* Router. Internally use polka.
* (cf. {@link https://github.com/lukeed/polka})
*/
this.router = polka();
// compression (must be set before serve-static)
this.router.use(compression());
/**
* Http(s) server instance. The node `http` or `https` module instance
* (cf. {@link https://nodejs.org/api/http.html})
*/
this.httpServer = null;
/**
* Key / value storage with Promise based Map API
* basically a wrapper around kvey (cf. {@link https://github.com/lukechilds/keyv})
* @private
*/
this.db = new Db();
/**
* The {@link server.Sockets} instance. A small wrapper around
* [`ws`](https://github.com/websockets/ws) server.
* @see {@link server.Sockets}
* @type {server.Sockets}
*/
this.sockets = new Sockets();
/**
* The {@link server.PluginManager} instance.
* @see {@link server.PluginManager}
* @type {server.PluginManager}
*/
this.pluginManager = new PluginManager(this);
/**
* The {@link server.SharedStateManagerServer} instance.
* @see {@link server.SharedStateManagerServer}
* @type {server.SharedStateManagerServer}
*/
this.stateManager = new SharedStateManagerServer();
/**
* Template engine that should implement a `compile` method.
* @type {Object}
*/
this.templateEngine = null;
/**
* Path to the directory containing the templates.
* Any filename corresponding to a registered browser client type will be used
* in priority, if not present fallback to `default`, i.e `${clientType}.tmpl`
* fallbacks to `default.tmpl`. Template files should have the `.tmpl` extension.
* @param {String}
*/
this.templateDirectory = null;
// private stuff
/**
* Required activities that must be started. Only used in Experience
* and Plugin - do not expose.
* @private
*/
this.activities = new Set();
/**
* Key and certificates (may be generated and self-signed) for https server.
* @todo - put in config...
* @private
*/
this._httpsInfos = null;
/**
* Mapping between a `clientType` and its related activities.
* @private
*/
this._clientTypeActivitiesMap = {};
/**
* Optionnal routing defined for each client.
* @type {Object}
* @private
*/
this._routes = {};
/**
* @private
*/
this._htmlTemplateConfig = {
engine: null,
directory: null,
}
}
/**
*
* Method to be called before `start` in the initialization lifecycle of the
* soundworks server.
*
* @param {Object} config
* @param {String} [config.defaultClient='player'] - Client that can access
* the application at its root url.
* @param {String} [config.env='development']
* @param {String} [config.port=8000] - Port on which the http(s) server will
* listen
* @param {String} [config.subpath] - If the application runs behind a
* proxy server (e.g. https://my-domain.com/my-app/`), path to the
* application root (i.e. 'my-app')
* @param {Boolean} [config.useHttps=false] - Define wheter to use or not an
* an https server.
* @param {Object} [config.httpsInfos=null] - if `useHttps` is `true`, object
* that give the path to `cert` and `key` files (`{ cert, key }`). If `null`
* an auto generated certificate will be generated, be aware that browsers
* will consider the application as not safe in the case.
*
* @param {Function} clientConfigFunction - function that filters / defines
* the configuration object that will be sent to a connecting client.
*
* @example
* // defaults to
* await server.init(
* {
* env: {
* type: 'development',
* port: 8000,
* subpath: '',
* useHttps: false,
* },
* app: {
* name: 'soundworks',
* author: 'someone'
* }
* },
* (clientType, serverConfig, httpRequest) => {
* return { clientType, ...serverConfig };
* }
* );
*/
async init(
config,
clientConfigFunction = (clientType, serverConfig, httpRequest) => ({ clientType })
) {
const defaultConfig = {
env: {
type: 'development',
port: 8000,
subpath: '',
websockets: {
path: 'socket',
pingInterval: 5000
},
useHttps: false,
},
app: {
name: 'soundworks',
}
};
this.config = merge({}, defaultConfig, config);
// @note: do not remove
// backward compatibility w/ assetsDomain and `soundworks-template`
// cf. https://github.com/collective-soundworks/soundworks/issues/35
// see also '@soundworks/plugin-audio-buffer-loader' (could be updated more
// easily as the `assetsDomain` entry was not documented)
// - we need to handle 3 cases:
// + old config style / old template
// + new config style / old template
// + new template
// @note: keep `websocket.path` as defined should be enough
if (!this.config.env.assetsDomain && this.config.env.subpath !== undefined) {
const subpath = this.config.env.subpath.replace(/^\//, '').replace(/\/$/, '');
if (subpath) {
this.config.env.assetsDomain = `/${subpath}/`;
} else {
this.config.env.assetsDomain = `/`;
}
}
this._clientConfigFunction = clientConfigFunction;
return Promise.resolve();
}
/**
* Method to be called when `init` step is done in the initialization
* lifecycle of the soundworks server. Basically initialize plugins,
* define the routing and start the http-server.
*/
async start() {
try {
// ------------------------------------------------------------
// init acitvities
// ------------------------------------------------------------
this.activities.forEach((activity) => {
activity.clientTypes.forEach((clientType) => {
if (!this._clientTypeActivitiesMap[clientType]) {
this._clientTypeActivitiesMap[clientType] = new Set();
}
this._clientTypeActivitiesMap[clientType].add(activity);
});
});
// start http server
const useHttps = this.config.env.useHttps || false;
return Promise.resolve()
// ------------------------------------------------------------
// create HTTP(S) SERVER
// ------------------------------------------------------------
.then(() => {
// create http server
if (!useHttps) {
const httpServer = http.createServer();
return Promise.resolve(httpServer);
} else {
const httpsInfos = this.config.env.httpsInfos;
if (httpsInfos.key && httpsInfos.cert) {
// use given certificate
try {
const key = fs.readFileSync(httpsInfos.key);
const cert = fs.readFileSync(httpsInfos.cert);
this._httpsInfos = { key, cert };
const httpsServer = https.createServer(this._httpsInfos);
return Promise.resolve(httpsServer);
} catch(err) {
console.error(
`Invalid certificate files, please check your:
- key file: ${httpsInfos.key}
- cert file: ${httpsInfos.cert}
`);
throw err;
}
} else {
return new Promise(async (resolve, reject) => {
const key = await this.db.get('server:httpsKey');
const cert = await this.db.get('server:httpsCert');
if (key && cert) {
this._httpsInfos = { key, cert };
const httpsServer = https.createServer(this._httpsInfos);
resolve(httpsServer);
} else {
// generate certificate on the fly (for development purposes)
pem.createCertificate({ days: 1, selfSigned: true }, async (err, keys) => {
if (err) {
return console.error(err.stack);
}
this._httpsInfos = {
key: keys.serviceKey,
cert: keys.certificate,
};
await this.db.set('server:httpsKey', this._httpsInfos.key);
await this.db.set('server:httpsCert', this._httpsInfos.cert);
const httpsServer = https.createServer(this._httpsInfos);
resolve(httpsServer);
});
}
});
}
}
}).then(httpServer => {
this.httpServer = httpServer;
this.router.server = httpServer;
return Promise.resolve();
}).then(() => {
if (this.templateEngine === null) {
throw new Error('Undefined "server.templateEngine": please provide a valid template engine');
}
if (this.templateDirectory === null) {
throw new Error('Undefined "server.templateDirectory": please provide a valid template directory');
}
// ------------------------------------------------------------
// INIT ROUTING
// ------------------------------------------------------------
logger.title(`configured clients and routing`);
const routes = [];
let defaultClientType = null;
for (let clientType in this.config.app.clients) {
if (this.config.app.clients[clientType].default === true) {
defaultClientType = clientType;
}
}
// we must open default route last
for (let clientType in this._clientTypeActivitiesMap) {
if (clientType !== defaultClientType) {
const path = this._openClientRoute(clientType, this.router);
routes.push({ clientType, path });
}
}
// open default route last
for (let clientType in this._clientTypeActivitiesMap) {
if (clientType === defaultClientType) {
const path = this._openClientRoute(clientType, this.router, true);
routes.unshift({ clientType, path });
}
}
logger.clientConfigAndRouting(routes, this.config.app.clients, this.config.env.serverIp);
return Promise.resolve();
}).then(() => {
// ------------------------------------------------------------
// START SOCKET SERVER
// ------------------------------------------------------------
this.sockets.start(
this.httpServer,
this.config.env.websockets,
(clientType, socket) => this._onSocketConnection(clientType, socket)
);
return Promise.resolve();
}).then(async () => {
// ------------------------------------------------------------
// START SERVICE MANAGER
// ------------------------------------------------------------
return this.pluginManager.start();
}).then(() => {
// ------------------------------------------------------------
// START HTTP SERVER
// ------------------------------------------------------------
return new Promise((resolve, reject) => {
const port = this.config.env.port;
const useHttps = this.config.env.useHttps || false;
const protocol = useHttps ? 'https' : 'http';
const ifaces = os.networkInterfaces();
this.router.listen(port, () => {
logger.title(`${protocol} server listening on`);
Object.keys(ifaces).forEach(dev => {
ifaces[dev].forEach(details => {
if (details.family === 'IPv4') {
logger.ip(protocol, details.address, port);
}
});
});
resolve();
});
});
});
await this.pluginManager.start();
return Promise.resolve();
} catch(err) {
console.error(err)
}
}
/**
* Open the route for the given client.
* @private
*/
_openClientRoute(clientType, router, isDefault = false) {
let route = '/';
if (!isDefault) {
route += `${clientType}`;
}
if (this._routes[clientType]) {
route += this._routes[clientType];
}
// define template filename: `${clientType}.html` or `default.html`
const templateDirectory = this.templateDirectory;
const clientTmpl = path.join(templateDirectory, `${clientType}.tmpl`);
const defaultTmpl = path.join(templateDirectory, `default.tmpl`);
// make it sync
let template;
try {
const stats = fs.statSync(clientTmpl);
template = stats.isFile() ? clientTmpl : defaultTmpl;
} catch(err) {
template = defaultTmpl;
}
let tmplString;
try {
tmplString = fs.readFileSync(template, 'utf8');
} catch(err) {
throw new Error(`[@soundworks/core] html template file "${template}" not found`);
}
const tmpl = this.templateEngine.compile(tmplString);
// http request
router.get(route, (req, res) => {
const data = this._clientConfigFunction(clientType, this.config, req);
// @note: do not remove
// backward compatibility w/ assetsDomain and `soundworks-template`
// cf. https://github.com/collective-soundworks/soundworks/issues/35
if (this.config.env.subpath && !data.env.subpath) {
data.env.subpath = this.config.env.subpath;
}
const appIndex = tmpl(data);
res.end(appIndex);
});
// return route infos for logging on server start
return route;
}
/**
* Socket connection callback.
* @private
*/
_onSocketConnection(clientType, socket) {
const client = new Client(clientType, socket);
const activities = this._clientTypeActivitiesMap[clientType];
socket.addListener('close', () => {
// clean sockets
socket.terminate();
// remove client from activities
activities.forEach(activity => activity.disconnect(client));
// destroy client
client.destroy();
});
socket.addListener('s:client:handshake', data => {
// in development, if plugin required client-side but not server-side,
// complain properly client-side.
if (this.config.env.type !== 'production') {
// check coherence between client-side and server-side plugin requirements
const clientRequiredPlugins = data.requiredPlugins || [];
const serverRequiredPlugins = this.pluginManager.getRequiredPlugins(clientType);
const missingPlugins = [];
clientRequiredPlugins.forEach(pluginId => {
if (serverRequiredPlugins.indexOf(pluginId) === -1) {
missingPlugins.push(pluginId);
}
});
if (missingPlugins.length > 0) {
const err = {
type: 'plugins',
data: missingPlugins,
};
socket.send('s:client:error', err);
return;
}
}
activities.forEach(activity => activity.connect(client));
const { id, uuid } = client;
socket.send('s:client:start', { id, uuid });
});
}
} |
JavaScript | class TaskQueue {
constructor(m_options) {
var _a;
this.m_options = m_options;
this.m_taskLists = new Map();
(_a = this.m_options.groups) === null || _a === void 0 ? void 0 : _a.forEach(group => {
this.m_taskLists.set(group, []);
});
if (this.m_options.prioSortFn) {
this.sort = this.m_options.prioSortFn;
}
}
/**
* Updates the lists in the queue depending on their priority functions and removes
* expired Tasks, based on their isExpired functions result.
*
* @param group The Group to update, if not set all groups will be updated.
*/
update(group) {
if (group === undefined) {
this.m_taskLists.forEach(taskList => {
this.updateTaskList(taskList);
});
}
else {
const taskList = this.getTaskList(group);
if (taskList) {
this.updateTaskList(taskList);
}
}
}
/**
* Adds a Task to the Queue
*
* @param task
* @returns true if succesfully added, otherwise false
*/
add(task) {
var _a;
if (this.m_taskLists.has(task.group)) {
const taskList = this.m_taskLists.get(task.group);
if (!(taskList === null || taskList === void 0 ? void 0 : taskList.includes(task))) {
(_a = this.m_taskLists.get(task.group)) === null || _a === void 0 ? void 0 : _a.push(task);
return true;
}
}
return false;
}
/**
* Removes a Task from the Queue
*
* @param task
* @returns true if succesfully removed, otherwise false
*/
remove(task) {
var _a, _b;
if (this.m_taskLists.has(task.group)) {
const index = (_a = this.m_taskLists.get(task.group)) === null || _a === void 0 ? void 0 : _a.indexOf(task);
if (index !== -1) {
(_b = this.m_taskLists.get(task.group)) === null || _b === void 0 ? void 0 : _b.splice(index, 1);
return true;
}
}
return false;
}
/**
* Returns the number of remaining tasks.
*
* @param group if group is set, it will return only the remaining tasks for this group,
* otherwise it will return the complete amount of tasks left.
*/
numItemsLeft(group) {
var _a, _b;
let numLeft = 0;
if (group === undefined) {
this.m_taskLists.forEach(tasklist => {
numLeft += tasklist.length;
});
}
else {
numLeft += (_b = (_a = this.getTaskList(group)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
}
return numLeft;
}
/**
* Processes the next Tasks for a group
*
* @param group The group the Tasks are pulled from.
* @param shouldProcess A condition that, if set will be executed before the task is processed,
* if returns true, the task will run
* @param n The amount of tasks that should be pulled, @defaults to 1
* @returns false if thte list was empty
*/
processNext(group, shouldProcess, n = 1) {
if (!this.getTaskList(group) || this.numItemsLeft(group) <= 0) {
return false;
}
for (let i = 0; i < n && this.numItemsLeft(group) > 0; i++) {
const nextTask = this.pull(group, true);
if (nextTask !== undefined) {
//if a condition is set, execute it
if (!shouldProcess || (shouldProcess === null || shouldProcess === void 0 ? void 0 : shouldProcess(nextTask))) {
nextTask.execute();
}
else {
//as the task was not executed but already pulled, add it back
//TODO: dont even pull it if it will not execute, this currently
// interferes with the skipping and removal of expired tasks on this.pull
this.add(nextTask);
}
}
}
return true;
}
pull(group, checkIfExpired = false) {
var _a, _b;
const taskList = this.getTaskList(group);
let nextTask;
if (taskList) {
nextTask = (_a = this.getTaskList(group)) === null || _a === void 0 ? void 0 : _a.pop();
if (checkIfExpired && nextTask && ((_b = nextTask.isExpired) === null || _b === void 0 ? void 0 : _b.call(nextTask))) {
return this.pull(group, checkIfExpired);
}
}
return nextTask;
}
sort(a, b) {
// the highest number in the beginning as the last in the array with
// highest priority which equals 0 will start to be processed
return b.getPriority() - a.getPriority();
}
getTaskList(group) {
return this.m_taskLists.get(group);
}
updateTaskList(taskList) {
var _a;
for (let i = 0; i < taskList.length; i++) {
const task = taskList[i];
if ((_a = task === null || task === void 0 ? void 0 : task.isExpired) === null || _a === void 0 ? void 0 : _a.call(task)) {
taskList.splice(i, 1);
i--;
}
}
taskList.sort(this.sort);
}
} |
JavaScript | class Profile extends Model {
// Attributes
@attr('string')
nombre;
@attr('string')
sexo;
@attr('string')
puesto;
@attr('string')
dependencia;
@attr('string')
departamento;
@attr('string')
institucion;
@attr('string')
fechalaboral;
@attr('string')
nocolegiado;
@attr('string')
estado;
@attr('string')
estadocivil;
@attr('string')
profesion;
@attr('string')
anosexperiencia;
@attr('string')
experienciaProfesional;
@attr('string')
experienciaAcademica;
@attr('string')
proyeccionHumana;
@attr('string')
publicaciones;
@attr('string')
fotoURL;
@attr('string')
correo;
@attr('string')
tw;
@attr('string')
fb;
// Documentos
@attr('string')
cv;
@attr('string')
expediente;
@attr('string')
resumen;
// Relationships
@belongsTo('institution', { async: true, defaultValue: null })
institution;
@belongsTo('election', {
inverse: 'committee',
async: true,
defaultValue: null
})
comission;
@belongsTo('election', {
inverse: 'candidates',
async: true,
defaultValue: null
})
election;
// Computed properties
/**
* This computed property set a default image if fotoURL is blank.
*/
@computed('fotoURL', 'sexo')
get photo() {
// if (!isBlank(this.fotoURL)) {
// return this.fotoURL;
// }
if (this.sexo === 'Masculino') {
return 'mi-guatemala/img/candidato.png';
}
if (this.sexo === 'Femenino') {
return 'mi-guatemala/img/candidata.png';
}
return 'mi-guatemala/img/candidata.png';
}
} |
JavaScript | class MysqlDatabaseSystem extends OkitArtifact {
/*
** Create
*/
constructor (data={}, okitjson={}) {
super(okitjson);
// Configure default values
this.display_name = this.generateDefaultName(okitjson.mysql_database_systems.length + 1);
this.compartment_id = data.parent_id;
this.availability_domain = 1;
this.hostname_label = this.display_name.toLowerCase();
this.shape_name = '';
this.configuration_id = '';
this.subnet_id = '';
this.admin_username = 'admin';
this.admin_password = '';
this.description ='';
this.mysql_version = '';
this.port = '';
this.port_x = '';
this.data_storage_size_in_gb = 256;
this.fault_domain = '';
this.description = this.name;
// Update with any passed data
this.merge(data);
this.convert();
// Check if built from a query
if (this.availability_domain.length > 1) {
this.region_availability_domain = this.availability_domain;
this.availability_domain = this.getAvailabilityDomainNumber(this.region_availability_domain);
}
}
/*
** Clone Functionality
*/
clone() {
return new MysqlDatabaseSystem(JSON.clone(this), this.getOkitJson());
}
getNamePrefix() {
return super.getNamePrefix() + 'mysql';
}
/*
** Static Functionality
*/
static getArtifactReference() {
return 'MySQL Database System';
}
} |
JavaScript | class FunctionUtils {
/**
* Validate that expression has a certain number of children that are of any of the supported types.
* @param expression Expression to validate.
* @param minArity Minimum number of children.
* @param maxArity Maximum number of children.
* @param returnType Allowed return types for children.
* If a child has a return type of Object then validation will happen at runtime.
*/
static validateArityAndAnyType(expression, minArity, maxArity, returnType = returnType_1.ReturnType.Object) {
if (expression.children.length < minArity) {
throw new Error(`${expression} should have at least ${minArity} children.`);
}
if (expression.children.length > maxArity) {
throw new Error(`${expression} can't have more than ${maxArity} children.`);
}
if ((returnType & returnType_1.ReturnType.Object) === 0) {
for (const child of expression.children) {
if ((child.returnType & returnType_1.ReturnType.Object) === 0 && (returnType & child.returnType) === 0) {
throw new Error(FunctionUtils.buildTypeValidatorError(returnType, child, expression));
}
}
}
}
/**
* Validate the number and type of arguments to a function.
* @param expression Expression to validate.
* @param optional Optional types in order.
* @param types Expected types in order.
*/
static validateOrder(expression, optional, ...types) {
if (optional === undefined) {
optional = [];
}
if (expression.children.length < types.length || expression.children.length > types.length + optional.length) {
throw new Error(optional.length === 0
? `${expression} should have ${types.length} children.`
: `${expression} should have between ${types.length} and ${types.length + optional.length} children.`);
}
for (let i = 0; i < types.length; i++) {
const child = expression.children[i];
const type = types[i];
if ((type & returnType_1.ReturnType.Object) === 0 &&
(child.returnType & returnType_1.ReturnType.Object) === 0 &&
(type & child.returnType) === 0) {
throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression));
}
}
for (let i = 0; i < optional.length; i++) {
const ic = i + types.length;
if (ic >= expression.children.length) {
break;
}
const child = expression.children[ic];
const type = optional[i];
if ((type & returnType_1.ReturnType.Object) === 0 &&
(child.returnType & returnType_1.ReturnType.Object) === 0 &&
(type & child.returnType) === 0) {
throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression));
}
}
}
/**
* Validate at least 1 argument of any type.
* @param expression Expression to validate.
*/
static validateAtLeastOne(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER);
}
/**
* Validate 1 or more numeric arguments.
* @param expression Expression to validate.
*/
static validateNumber(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.Number);
}
/**
* Validate 1 or more string arguments.
* @param expression Expression to validate.
*/
static validateString(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.String);
}
/**
* Validate there are two children.
* @param expression Expression to validate.
*/
static validateBinary(expression) {
FunctionUtils.validateArityAndAnyType(expression, 2, 2);
}
/**
* Validate 2 numeric arguments.
* @param expression Expression to validate.
*/
static validateBinaryNumber(expression) {
FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.Number);
}
/**
* Validate 1 or 2 numeric arguments.
* @param expression Expression to validate.
*/
static validateUnaryOrBinaryNumber(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, 2, returnType_1.ReturnType.Number);
}
/**
* Validate 2 or more than 2 numeric arguments.
* @param expression Expression to validate.
*/
static validateTwoOrMoreThanTwoNumbers(expression) {
FunctionUtils.validateArityAndAnyType(expression, 2, Number.MAX_VALUE, returnType_1.ReturnType.Number);
}
/**
* Validate there are 2 numeric or string arguments.
* @param expression Expression to validate.
*/
static validateBinaryNumberOrString(expression) {
FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.Number | returnType_1.ReturnType.String);
}
/**
* Validate there is a single argument.
* @param expression Expression to validate.
*/
static validateUnary(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, 1);
}
/**
* Validate there is a single argument.
* @param expression Expression to validate.
*/
static validateUnaryNumber(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.Number);
}
/**
* Validate there is a single string argument.
* @param expression Expression to validate.
*/
static validateUnaryString(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.String);
}
/**
* Validate there is one or two string arguments.
* @param expression Expression to validate.
*/
static validateUnaryOrBinaryString(expression) {
FunctionUtils.validateArityAndAnyType(expression, 1, 2, returnType_1.ReturnType.String);
}
/**
* Validate there is a single boolean argument.
* @param expression Expression to validate.
*/
static validateUnaryBoolean(expression) {
FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Boolean);
}
/**
* Verify value is numeric.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyNumber(value, expression, _) {
let error;
if (!FunctionUtils.isNumber(value)) {
error = `${expression} is not a number.`;
}
return error;
}
/**
* Verify value is numeric.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyNumberOrNumericList(value, expression, _) {
let error;
if (FunctionUtils.isNumber(value)) {
return error;
}
if (!Array.isArray(value)) {
error = `${expression} is neither a list nor a number.`;
}
else {
for (const elt of value) {
if (!FunctionUtils.isNumber(elt)) {
error = `${elt} is not a number in ${expression}.`;
break;
}
}
}
return error;
}
/**
* Verify value is numeric list.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyNumericList(value, expression, _) {
let error;
if (!Array.isArray(value)) {
error = `${expression} is not a list.`;
}
else {
for (const elt of value) {
if (!FunctionUtils.isNumber(elt)) {
error = `${elt} is not a number in ${expression}.`;
break;
}
}
}
return error;
}
/**
* Verify value contains elements.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyContainer(value, expression, _) {
let error;
if (!(typeof value === 'string') &&
!Array.isArray(value) &&
!(value instanceof Map) &&
!(typeof value === 'object')) {
error = `${expression} must be a string, list, map or object.`;
}
return error;
}
/**
* Verify value contains elements or null.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyContainerOrNull(value, expression, _) {
let error;
if (value != null &&
!(typeof value === 'string') &&
!Array.isArray(value) &&
!(value instanceof Map) &&
!(typeof value === 'object')) {
error = `${expression} must be a string, list, map or object.`;
}
return error;
}
/**
* Verify value is not null or undefined.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if valid.
*/
static verifyNotNull(value, expression, _) {
let error;
if (value == null) {
error = `${expression} is null.`;
}
return error;
}
/**
* Verify value is an integer.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyInteger(value, expression, _) {
let error;
if (!Number.isInteger(value)) {
error = `${expression} is not a integer.`;
}
return error;
}
/**
* Verify value is an list.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyList(value, expression) {
let error;
if (!Array.isArray(value)) {
error = `${expression} is not a list or array.`;
}
return error;
}
/**
* Verify value is a string.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyString(value, expression, _) {
let error;
if (typeof value !== 'string') {
error = `${expression} is not a string.`;
}
return error;
}
/**
* Verify an object is neither a string nor null.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyStringOrNull(value, expression, _) {
let error;
if (typeof value !== 'string' && value !== undefined) {
error = `${expression} is neither a string nor a null object.`;
}
return error;
}
/**
* Verify value is a number or string or null.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyNumberOrStringOrNull(value, expression, _) {
let error;
if (typeof value !== 'string' && value !== undefined && !FunctionUtils.isNumber(value)) {
error = `${expression} is neither a number nor string`;
}
return error;
}
/**
* Verify value is a number or string.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyNumberOrString(value, expression, _) {
let error;
if (value === undefined || (!FunctionUtils.isNumber(value) && typeof value !== 'string')) {
error = `${expression} is not string or number.`;
}
return error;
}
/**
* Verify value is boolean.
* @param value Value to check.
* @param expression Expression that led to value.
* @returns Error or undefined if invalid.
*/
static verifyBoolean(value, expression, _) {
let error;
if (typeof value !== 'boolean') {
error = `${expression} is not a boolean.`;
}
return error;
}
/**
* Evaluate expression children and return them.
* @param expression Expression with children.
* @param state Global state.
* @param verify Optional function to verify each child's result.
* @returns List of child values or error message.
*/
static evaluateChildren(expression, state, options, verify) {
const args = [];
let value;
let error;
let pos = 0;
for (const child of expression.children) {
({ value, error } = child.tryEvaluate(state, options));
if (error) {
break;
}
if (verify !== undefined) {
error = verify(value, child, pos);
}
if (error) {
break;
}
args.push(value);
++pos;
}
return { args, error };
}
/**
* Generate an expression delegate that applies function after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static apply(func, verify) {
return (expression, state, options) => {
let value;
const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify);
let error = childrenError;
if (!error) {
try {
value = func(args);
}
catch (e) {
error = e.message;
}
}
return { value, error };
};
}
/**
* Generate an expression delegate that applies function after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static applyWithError(func, verify) {
return (expression, state, options) => {
let value;
const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify);
let error = childrenError;
if (!error) {
try {
({ value, error } = func(args));
}
catch (e) {
error = e.message;
}
}
return { value, error };
};
}
/**
* Generate an expression delegate that applies function after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static applyWithOptionsAndError(func, verify) {
return (expression, state, options) => {
let value;
const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify);
let error = childrenError;
if (!error) {
try {
({ value, error } = func(args, options));
}
catch (e) {
error = e.message;
}
}
return { value, error };
};
}
/**
* Generate an expression delegate that applies function after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static applyWithOptions(func, verify) {
return (expression, state, options) => {
let value;
const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify);
let error = childrenError;
if (!error) {
try {
value = func(args, options);
}
catch (e) {
error = e.message;
}
}
return { value, error };
};
}
/**
* Generate an expression delegate that applies function on the accumulated value after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static applySequence(func, verify) {
return FunctionUtils.apply((args) => {
const binaryArgs = [undefined, undefined];
let soFar = args[0];
for (let i = 1; i < args.length; i++) {
binaryArgs[0] = soFar;
binaryArgs[1] = args[i];
soFar = func(binaryArgs);
}
return soFar;
}, verify);
}
/**
* Generate an expression delegate that applies function on the accumulated value after verifying all children.
* @param func Function to apply.
* @param verify Function to check each arg for validity.
* @returns Delegate for evaluating an expression.
*/
static applySequenceWithError(func, verify) {
return FunctionUtils.applyWithError((args) => {
const binaryArgs = [undefined, undefined];
let soFar = args[0];
let value;
let error;
for (let i = 1; i < args.length; i++) {
binaryArgs[0] = soFar;
binaryArgs[1] = args[i];
({ value, error } = func(binaryArgs));
if (error) {
return { value, error };
}
else {
soFar = value;
}
}
return { value: soFar, error: undefined };
}, verify);
}
/**
*
* @param args An array of arguments.
* @param locale A locale string
* @param maxArgsLength The max length of a given function.
*/
static determineLocale(args, maxArgsLength, locale = 'en-us') {
if (args.length === maxArgsLength) {
const lastArg = args[maxArgsLength - 1];
if (typeof lastArg === 'string') {
locale = lastArg;
}
}
return locale;
}
/**
*
* @param args An array of arguments.
* @param format A format string.
* @param locale A locale string.
* @param maxArgsLength The max length of a given function.
*/
static determineFormatAndLocale(args, maxArgsLength, format, locale = 'en-us') {
if (maxArgsLength >= 2) {
if (args.length === maxArgsLength) {
const lastArg = args[maxArgsLength - 1];
const secondLastArg = args[maxArgsLength - 2];
if (typeof lastArg === 'string' && typeof secondLastArg === 'string') {
format =
secondLastArg !== ''
? FunctionUtils.timestampFormatter(secondLastArg)
: FunctionUtils.DefaultDateTimeFormat;
locale = lastArg.substr(0, 2); //dayjs only support two-letter locale representattion
}
}
else if (args.length === maxArgsLength - 1) {
const lastArg = args[maxArgsLength - 2];
if (typeof lastArg === 'string') {
format = FunctionUtils.timestampFormatter(lastArg);
}
}
}
return { format: format, locale: locale };
}
/**
* Timestamp formatter, convert C# datetime to day.js format.
* @param formatter C# datetime format
*/
static timestampFormatter(formatter) {
if (!formatter) {
return FunctionUtils.DefaultDateTimeFormat;
}
let result = formatter;
try {
result = datetimeFormatConverter_1.convertCSharpDateTimeToDayjs(formatter);
}
catch (e) {
// do nothing
}
return result;
}
/**
* State object for resolving memory paths.
* @param expression Expression.
* @param state Scope.
* @param options Options used in evaluation.
* @returns Return the accumulated path and the expression left unable to accumulate.
*/
static tryAccumulatePath(expression, state, options) {
let path = '';
let left = expression;
while (left !== undefined) {
if (left.type === expressionType_1.ExpressionType.Accessor) {
path = left.children[0].value + '.' + path;
left = left.children.length === 2 ? left.children[1] : undefined;
}
else if (left.type === expressionType_1.ExpressionType.Element) {
const { value, error } = left.children[1].tryEvaluate(state, options);
if (error !== undefined) {
return { path: undefined, left: undefined, error };
}
if (FunctionUtils.isNumber(parseInt(value))) {
path = `[${value}].${path}`;
}
else if (typeof value === 'string') {
path = `['${value}'].${path}`;
}
else {
return {
path: undefined,
left: undefined,
error: `${left.children[1].toString()} doesn't return an int or string`,
};
}
left = left.children[0];
}
else {
break;
}
}
// make sure we generated a valid path
path = path.replace(/(\.*$)/g, '').replace(/(\.\[)/g, '[');
if (path === '') {
path = undefined;
}
return { path, left, error: undefined };
}
/**
* Is number helper function.
* @param instance Input.
* @returns True if the input is a number.
*/
static isNumber(instance) {
return instance != null && typeof instance === 'number' && !Number.isNaN(instance);
}
/**
* Equal helper function.
* @param args Input args. Compare the first param and second param.
*/
static commonEquals(obj1, obj2) {
if (obj1 == null || obj2 == null) {
return obj1 == null && obj2 == null;
}
// Array Comparison
if (Array.isArray(obj1) && Array.isArray(obj2)) {
if (obj1.length !== obj2.length) {
return false;
}
return obj1.every((item, i) => FunctionUtils.commonEquals(item, obj2[i]));
}
// Object Comparison
const propertyCountOfObj1 = FunctionUtils.getPropertyCount(obj1);
const propertyCountOfObj2 = FunctionUtils.getPropertyCount(obj2);
if (propertyCountOfObj1 >= 0 && propertyCountOfObj2 >= 0) {
if (propertyCountOfObj1 !== propertyCountOfObj2) {
return false;
}
const jsonObj1 = FunctionUtils.convertToObj(obj1);
const jsonObj2 = FunctionUtils.convertToObj(obj2);
return lodash_isequal_1.default(jsonObj1, jsonObj2);
}
// Number Comparison
if (FunctionUtils.isNumber(obj1) && FunctionUtils.isNumber(obj2)) {
if (Math.abs(obj1 - obj2) < Number.EPSILON) {
return true;
}
}
try {
return obj1 === obj2;
}
catch (_a) {
return false;
}
}
/**
* @private
*/
static buildTypeValidatorError(returnType, childExpr, expr) {
const names = Object.keys(returnType_1.ReturnType).filter((x) => !(parseInt(x) >= 0));
const types = [];
for (const name of names) {
const value = returnType_1.ReturnType[name];
if ((returnType & value) !== 0) {
types.push(name);
}
}
if (types.length === 1) {
return `${childExpr} is not a ${types[0]} expression in ${expr}.`;
}
else {
const typesStr = types.join(', ');
return `${childExpr} in ${expr} is not any of [${typesStr}].`;
}
}
/**
* Helper function of get the number of properties of an object.
* @param obj An object.
*/
static getPropertyCount(obj) {
let count = -1;
if (obj != null && !Array.isArray(obj)) {
if (obj instanceof Map) {
count = obj.size;
}
else if (typeof obj === 'object' && !(obj instanceof Date)) {
count = Object.keys(obj).length;
}
}
return count;
}
/**
* @private
*/
static convertToObj(instance) {
if (FunctionUtils.getPropertyCount(instance) >= 0) {
const entries = instance instanceof Map ? Array.from(instance.entries()) : Object.entries(instance);
return entries.reduce((acc, [key, value]) => (Object.assign({}, acc, { [key]: FunctionUtils.convertToObj(value) })), {});
}
else if (Array.isArray(instance)) {
// Convert Array
return instance.map((item) => FunctionUtils.convertToObj(item));
}
return instance;
}
} |
JavaScript | class ImageCoverterPlugin {
/**
* constructor of the ImageCoverterPlugin class.
* @param {String} options The object of build folder.
*/
constructor(options) {
this.options = options;
}
/**
* Find all image paths in png、jpg、bmp、jpeg format in the directory.
* @param {String} buildPath The path of build folder.
* @return {Array} Image path array.
*/
getDir(buildPath) {
const pngPath = global.__requireContext('', buildPath, true, REGEXP_PNG);
const pathArray = pngPath.keys().map((element) => {
return _path.join(buildPath, element);
});
return pathArray;
}
/**
* Convert image format asynchronously, return code 0 successfully, otherwise return 1.
* @param {Object} compiler API specification, all configuration information of Webpack environment.
*/
apply(compiler) {
const buildPath = this.options.build;
const getDir = this.getDir;
compiler.hooks.done.tap('image coverter', function(compilation, callback) {
const pathArray = getDir(buildPath);
const writeResult = (content) => {
fs.writeFile(_path.resolve(buildPath, 'image_convert_result.txt'), content, (err) => {
if (err) {
return console.error(err);
}
});
};
const totalImageCount = pathArray.length;
if (totalImageCount > 0) {
const promiseArray = pathArray.map((path) => {
return img2bin(path);
});
Promise.all(promiseArray).then(() => {
writeResult('{exitCode:0}');
}).catch(() => {
writeResult('{exitCode:1}');
});
} else {
writeResult('{exitCode:0}');
}
if (iconPath !== '') {
const iconArray = getDir(iconPath);
iconArray.forEach((path) => {
img2bin(path);
});
}
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.