language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class UserDefinedFunction { /** * @hidden * @param container The parent {@link Container}. * @param id The id of the given {@link UserDefinedFunction}. */ constructor(container, id, clientContext) { this.container = container; this.id = id; this.clientContext = clientContext; } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return createUserDefinedFunctionUri(this.container.database.id, this.container.id, this.id); } /** * Read the {@link UserDefinedFunctionDefinition} for the given {@link UserDefinedFunction}. * @param options */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.read({ path, resourceType: exports.ResourceType.udf, resourceId: id, options }); return new UserDefinedFunctionResponse(response.result, response.headers, response.code, this); }); } /** * Replace the given {@link UserDefinedFunction} with the specified {@link UserDefinedFunctionDefinition}. * @param body The specified {@link UserDefinedFunctionDefinition}. * @param options */ replace(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { if (body.body) { body.body = body.body.toString(); } const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.replace({ body, path, resourceType: exports.ResourceType.udf, resourceId: id, options }); return new UserDefinedFunctionResponse(response.result, response.headers, response.code, this); }); } /** * Delete the given {@link UserDefined}. * @param options */ delete(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.delete({ path, resourceType: exports.ResourceType.udf, resourceId: id, options }); return new UserDefinedFunctionResponse(response.result, response.headers, response.code, this); }); } }
JavaScript
class UserDefinedFunctions { /** * @hidden * @param container The parent {@link Container}. */ constructor(container, clientContext) { this.container = container; this.clientContext = clientContext; } query(query, options) { const path = getPathFromLink(this.container.url, exports.ResourceType.udf); const id = getIdFromLink(this.container.url); return new QueryIterator(this.clientContext, query, options, (innerOptions) => { return this.clientContext.queryFeed({ path, resourceType: exports.ResourceType.udf, resourceId: id, resultFn: (result) => result.UserDefinedFunctions, query, options: innerOptions }); }); } /** * Read all User Defined Functions. * @param options * @example Read all User Defined Functions to array. * ```typescript * const {body: udfList} = await container.userDefinedFunctions.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } /** * Create a UserDefinedFunction. * * Azure Cosmos DB supports JavaScript UDFs which can be used inside queries, stored procedures and triggers. * * For additional details, refer to the server-side JavaScript API documentation. * */ create(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { if (body.body) { body.body = body.body.toString(); } const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.container.url, exports.ResourceType.udf); const id = getIdFromLink(this.container.url); const response = yield this.clientContext.create({ body, path, resourceType: exports.ResourceType.udf, resourceId: id, options }); const ref = new UserDefinedFunction(this.container, response.result.id, this.clientContext); return new UserDefinedFunctionResponse(response.result, response.headers, response.code, ref); }); } }
JavaScript
class ContainerResponse extends ResourceResponse { constructor(resource, headers, statusCode, container) { super(resource, headers, statusCode); this.container = container; } }
JavaScript
class Offer { /** * @hidden * @param client The parent {@link CosmosClient} for the Database Account. * @param id The id of the given {@link Offer}. */ constructor(client, id, clientContext) { this.client = client; this.id = id; this.clientContext = clientContext; } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return `/${Constants.Path.OffersPathSegment}/${this.id}`; } /** * Read the {@link OfferDefinition} for the given {@link Offer}. * @param options */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const response = yield this.clientContext.read({ path: this.url, resourceType: exports.ResourceType.offer, resourceId: this.id, options }); return new OfferResponse(response.result, response.headers, response.code, this); }); } /** * Replace the given {@link Offer} with the specified {@link OfferDefinition}. * @param body The specified {@link OfferDefinition} * @param options */ replace(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const response = yield this.clientContext.replace({ body, path: this.url, resourceType: exports.ResourceType.offer, resourceId: this.id, options }); return new OfferResponse(response.result, response.headers, response.code, this); }); } }
JavaScript
class Offers { /** * @hidden * @param client The parent {@link CosmosClient} for the offers. */ constructor(client, clientContext) { this.client = client; this.clientContext = clientContext; } query(query, options) { return new QueryIterator(this.clientContext, query, options, (innerOptions) => { return this.clientContext.queryFeed({ path: "/offers", resourceType: exports.ResourceType.offer, resourceId: "", resultFn: (result) => result.Offers, query, options: innerOptions }); }); } /** * Read all offers. * @param options * @example Read all offers to array. * ```typescript * const {body: offerList} = await client.offers.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } }
JavaScript
class Container { /** * Returns a container instance. Note: You should get this from `database.container(id)`, rather than creating your own object. * @param database The parent {@link Database}. * @param id The id of the given container. * @hidden */ constructor(database, id, clientContext) { this.database = database; this.id = id; this.clientContext = clientContext; } /** * Operations for creating new items, and reading/querying all items * * For reading, replacing, or deleting an existing item, use `.item(id)`. * * @example Create a new item * ```typescript * const {body: createdItem} = await container.items.create({id: "<item id>", properties: {}}); * ``` */ get items() { if (!this.$items) { this.$items = new Items(this, this.clientContext); } return this.$items; } /** * All operations for Stored Procedures, Triggers, and User Defined Functions */ get scripts() { if (!this.$scripts) { this.$scripts = new Scripts(this, this.clientContext); } return this.$scripts; } /** * Opertaions for reading and querying conflicts for the given container. * * For reading or deleting a specific conflict, use `.conflict(id)`. */ get conflicts() { if (!this.$conflicts) { this.$conflicts = new Conflicts(this, this.clientContext); } return this.$conflicts; } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return createDocumentCollectionUri(this.database.id, this.id); } /** * Used to read, replace, or delete a specific, existing {@link Item} by id. * * Use `.items` for creating new items, or querying/reading all items. * * @param id The id of the {@link Item}. * @param partitionKeyValue The value of the {@link Item} partition key * @example Replace an item * const {body: replacedItem} = await container.item("<item id>", "<partition key value>").replace({id: "<item id>", title: "Updated post", authorID: 5}); */ item(id, partitionKeyValue) { return new Item(this, id, partitionKeyValue, this.clientContext); } /** * Used to read, replace, or delete a specific, existing {@link Conflict} by id. * * Use `.conflicts` for creating new conflicts, or querying/reading all conflicts. * @param id The id of the {@link Conflict}. */ conflict(id) { return new Conflict(this, id, this.clientContext); } /** Read the container's definition */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.read({ path, resourceType: exports.ResourceType.container, resourceId: id, options }); this.clientContext.partitionKeyDefinitionCache[this.url] = response.result.partitionKey; return new ContainerResponse(response.result, response.headers, response.code, this); }); } /** Replace the container's definition */ replace(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.replace({ body, path, resourceType: exports.ResourceType.container, resourceId: id, options }); return new ContainerResponse(response.result, response.headers, response.code, this); }); } /** Delete the container */ delete(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.delete({ path, resourceType: exports.ResourceType.container, resourceId: id, options }); return new ContainerResponse(response.result, response.headers, response.code, this); }); } /** * Gets the partition key definition first by looking into the cache otherwise by reading the collection. * @deprecated This method has been renamed to readPartitionKeyDefinition. * @param {string} collectionLink - Link to the collection whose partition key needs to be extracted. * @param {function} callback - \ * The arguments to the callback are(in order): error, partitionKeyDefinition, response object and response headers */ getPartitionKeyDefinition() { return tslib.__awaiter(this, void 0, void 0, function* () { return this.readPartitionKeyDefinition(); }); } /** * Gets the partition key definition first by looking into the cache otherwise by reading the collection. * @ignore * @param {string} collectionLink - Link to the collection whose partition key needs to be extracted. * @param {function} callback - \ * The arguments to the callback are(in order): error, partitionKeyDefinition, response object and response headers */ readPartitionKeyDefinition() { return tslib.__awaiter(this, void 0, void 0, function* () { // $ISSUE-felixfan-2016-03-17: Make name based path and link based path use the same key // $ISSUE-felixfan-2016-03-17: Refresh partitionKeyDefinitionCache when necessary if (this.url in this.clientContext.partitionKeyDefinitionCache) { return new ResourceResponse(this.clientContext.partitionKeyDefinitionCache[this.url], {}, 0); } const { headers, statusCode } = yield this.read(); return new ResourceResponse(this.clientContext.partitionKeyDefinitionCache[this.url], headers, statusCode); }); } /** * Gets offer on container. If none exists, returns an OfferResponse with undefined. * @param options */ readOffer(options = {}) { return tslib.__awaiter(this, void 0, void 0, function* () { const { resource: container } = yield this.read(); const path = "/offers"; const url = container._self; const response = yield this.clientContext.queryFeed({ path, resourceId: "", resourceType: exports.ResourceType.offer, query: `SELECT * from root where root.resource = "${url}"`, resultFn: (result) => result.Offers, options }); const offer = response.result[0] ? new Offer(this.database.client, response.result[0].id, this.clientContext) : undefined; return new OfferResponse(response.result[0], response.headers, response.code, offer); }); } getQueryPlan(query) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); return this.clientContext.getQueryPlan(path + "/docs", exports.ResourceType.item, getIdFromLink(this.url), query); }); } readPartitionKeyRanges(feedOptions) { feedOptions = feedOptions || {}; return this.clientContext.queryPartitionKeyRanges(this.url, undefined, feedOptions); } }
JavaScript
class Containers { constructor(database, clientContext) { this.database = database; this.clientContext = clientContext; } query(query, options) { const path = getPathFromLink(this.database.url, exports.ResourceType.container); const id = getIdFromLink(this.database.url); return new QueryIterator(this.clientContext, query, options, (innerOptions) => { return this.clientContext.queryFeed({ path, resourceType: exports.ResourceType.container, resourceId: id, resultFn: (result) => result.DocumentCollections, query, options: innerOptions }); }); } /** * Creates a container. * * A container is a named logical container for items. * * A database may contain zero or more named containers and each container consists of * zero or more JSON items. * * Being schema-free, the items in a container do not need to share the same structure or fields. * * * Since containers are application resources, they can be authorized using either the * master key or resource keys. * * @param body Represents the body of the container. * @param options Use to set options like response page size, continuation tokens, etc. */ create(body, options = {}) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.database.url, exports.ResourceType.container); const id = getIdFromLink(this.database.url); validateOffer(body); if (body.maxThroughput) { const autoscaleParams = { maxThroughput: body.maxThroughput }; if (body.autoUpgradePolicy) { autoscaleParams.autoUpgradePolicy = body.autoUpgradePolicy; } const autoscaleHeader = JSON.stringify(autoscaleParams); options.initialHeaders = Object.assign({}, options.initialHeaders, { [Constants.HttpHeaders.AutoscaleSettings]: autoscaleHeader }); delete body.maxThroughput; delete body.autoUpgradePolicy; } if (body.throughput) { options.initialHeaders = Object.assign({}, options.initialHeaders, { [Constants.HttpHeaders.OfferThroughput]: body.throughput }); delete body.throughput; } if (typeof body.partitionKey === "string") { if (!body.partitionKey.startsWith("/")) { throw new Error("Partition key must start with '/'"); } body.partitionKey = { paths: [body.partitionKey] }; } // If they don't specify a partition key, use the default path if (!body.partitionKey || !body.partitionKey.paths) { body.partitionKey = { paths: [DEFAULT_PARTITION_KEY_PATH] }; } const response = yield this.clientContext.create({ body, path, resourceType: exports.ResourceType.container, resourceId: id, options }); const ref = new Container(this.database, response.result.id, this.clientContext); return new ContainerResponse(response.result, response.headers, response.code, ref); }); } /** * Checks if a Container exists, and, if it doesn't, creates it. * This will make a read operation based on the id in the `body`, then if it is not found, a create operation. * You should confirm that the output matches the body you passed in for non-default properties (i.e. indexing policy/etc.) * * A container is a named logical container for items. * * A database may contain zero or more named containers and each container consists of * zero or more JSON items. * * Being schema-free, the items in a container do not need to share the same structure or fields. * * * Since containers are application resources, they can be authorized using either the * master key or resource keys. * * @param body Represents the body of the container. * @param options Use to set options like response page size, continuation tokens, etc. */ createIfNotExists(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { if (!body || body.id === null || body.id === undefined) { throw new Error("body parameter must be an object with an id property"); } /* 1. Attempt to read the Container (based on an assumption that most containers will already exist, so its faster) 2. If it fails with NotFound error, attempt to create the container. Else, return the read results. */ try { const readResponse = yield this.database.container(body.id).read(options); return readResponse; } catch (err) { if (err.code === StatusCodes.NotFound) { const createResponse = yield this.create(body, options); // Must merge the headers to capture RU costskaty mergeHeaders(createResponse.headers, err.headers); return createResponse; } else { throw err; } } }); } /** * Read all containers. * @param options Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return all containers in an array or iterate over them one at a time. * @example Read all containers to array. * ```typescript * const {body: containerList} = await client.database("<db id>").containers.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } }
JavaScript
class Permission { /** * @hidden * @param user The parent {@link User}. * @param id The id of the given {@link Permission}. */ constructor(user, id, clientContext) { this.user = user; this.id = id; this.clientContext = clientContext; } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return createPermissionUri(this.user.database.id, this.user.id, this.id); } /** * Read the {@link PermissionDefinition} of the given {@link Permission}. * @param options */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.read({ path, resourceType: exports.ResourceType.permission, resourceId: id, options }); return new PermissionResponse(response.result, response.headers, response.code, this); }); } /** * Replace the given {@link Permission} with the specified {@link PermissionDefinition}. * @param body The specified {@link PermissionDefinition}. * @param options */ replace(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.replace({ body, path, resourceType: exports.ResourceType.permission, resourceId: id, options }); return new PermissionResponse(response.result, response.headers, response.code, this); }); } /** * Delete the given {@link Permission}. * @param options */ delete(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.delete({ path, resourceType: exports.ResourceType.permission, resourceId: id, options }); return new PermissionResponse(response.result, response.headers, response.code, this); }); } }
JavaScript
class Permissions { /** * @hidden * @param user The parent {@link User}. */ constructor(user, clientContext) { this.user = user; this.clientContext = clientContext; } query(query, options) { const path = getPathFromLink(this.user.url, exports.ResourceType.permission); const id = getIdFromLink(this.user.url); return new QueryIterator(this.clientContext, query, options, (innerOptions) => { return this.clientContext.queryFeed({ path, resourceType: exports.ResourceType.permission, resourceId: id, resultFn: (result) => result.Permissions, query, options: innerOptions }); }); } /** * Read all permissions. * @param options * @example Read all permissions to array. * ```typescript * const {body: permissionList} = await user.permissions.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } /** * Create a permission. * * A permission represents a per-User Permission to access a specific resource * e.g. Item or Container. * @param body Represents the body of the permission. */ create(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.user.url, exports.ResourceType.permission); const id = getIdFromLink(this.user.url); const response = yield this.clientContext.create({ body, path, resourceType: exports.ResourceType.permission, resourceId: id, options }); const ref = new Permission(this.user, response.result.id, this.clientContext); return new PermissionResponse(response.result, response.headers, response.code, ref); }); } /** * Upsert a permission. * * A permission represents a per-User Permission to access a * specific resource e.g. Item or Container. */ upsert(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.user.url, exports.ResourceType.permission); const id = getIdFromLink(this.user.url); const response = yield this.clientContext.upsert({ body, path, resourceType: exports.ResourceType.permission, resourceId: id, options }); const ref = new Permission(this.user, response.result.id, this.clientContext); return new PermissionResponse(response.result, response.headers, response.code, ref); }); } }
JavaScript
class User { /** * @hidden * @param database The parent {@link Database}. * @param id */ constructor(database, id, clientContext) { this.database = database; this.id = id; this.clientContext = clientContext; this.permissions = new Permissions(this, this.clientContext); } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return createUserUri(this.database.id, this.id); } /** * Operations to read, replace, or delete a specific Permission by id. * * See `client.permissions` for creating, upserting, querying, or reading all operations. * @param id */ permission(id) { return new Permission(this, id, this.clientContext); } /** * Read the {@link UserDefinition} for the given {@link User}. * @param options */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.read({ path, resourceType: exports.ResourceType.user, resourceId: id, options }); return new UserResponse(response.result, response.headers, response.code, this); }); } /** * Replace the given {@link User}'s definition with the specified {@link UserDefinition}. * @param body The specified {@link UserDefinition} to replace the definition. * @param options */ replace(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.replace({ body, path, resourceType: exports.ResourceType.user, resourceId: id, options }); return new UserResponse(response.result, response.headers, response.code, this); }); } /** * Delete the given {@link User}. * @param options */ delete(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.delete({ path, resourceType: exports.ResourceType.user, resourceId: id, options }); return new UserResponse(response.result, response.headers, response.code, this); }); } }
JavaScript
class Users { /** * @hidden * @param database The parent {@link Database}. */ constructor(database, clientContext) { this.database = database; this.clientContext = clientContext; } query(query, options) { const path = getPathFromLink(this.database.url, exports.ResourceType.user); const id = getIdFromLink(this.database.url); return new QueryIterator(this.clientContext, query, options, (innerOptions) => { return this.clientContext.queryFeed({ path, resourceType: exports.ResourceType.user, resourceId: id, resultFn: (result) => result.Users, query, options: innerOptions }); }); } /** * Read all users. * @param options * @example Read all users to array. * ```typescript * const {body: usersList} = await database.users.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } /** * Create a database user with the specified {@link UserDefinition}. * @param body The specified {@link UserDefinition}. * @param options */ create(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.database.url, exports.ResourceType.user); const id = getIdFromLink(this.database.url); const response = yield this.clientContext.create({ body, path, resourceType: exports.ResourceType.user, resourceId: id, options }); const ref = new User(this.database, response.result.id, this.clientContext); return new UserResponse(response.result, response.headers, response.code, ref); }); } /** * Upsert a database user with a specified {@link UserDefinition}. * @param body The specified {@link UserDefinition}. * @param options */ upsert(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } const path = getPathFromLink(this.database.url, exports.ResourceType.user); const id = getIdFromLink(this.database.url); const response = yield this.clientContext.upsert({ body, path, resourceType: exports.ResourceType.user, resourceId: id, options }); const ref = new User(this.database, response.result.id, this.clientContext); return new UserResponse(response.result, response.headers, response.code, ref); }); } }
JavaScript
class DatabaseResponse extends ResourceResponse { constructor(resource, headers, statusCode, database) { super(resource, headers, statusCode); this.database = database; } }
JavaScript
class Database { /** Returns a new {@link Database} instance. * * Note: the intention is to get this object from {@link CosmosClient} via `client.database(id)`, not to instantiate it yourself. */ constructor(client, id, clientContext) { this.client = client; this.id = id; this.clientContext = clientContext; this.containers = new Containers(this, this.clientContext); this.users = new Users(this, this.clientContext); } /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return createDatabaseUri(this.id); } /** * Used to read, replace, or delete a specific, existing {@link Database} by id. * * Use `.containers` creating new containers, or querying/reading all containers. * * @example Delete a container * ```typescript * await client.database("<db id>").container("<container id>").delete(); * ``` */ container(id) { return new Container(this, id, this.clientContext); } /** * Used to read, replace, or delete a specific, existing {@link User} by id. * * Use `.users` for creating new users, or querying/reading all users. */ user(id) { return new User(this, id, this.clientContext); } /** Read the definition of the given Database. */ read(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.read({ path, resourceType: exports.ResourceType.database, resourceId: id, options }); return new DatabaseResponse(response.result, response.headers, response.code, this); }); } /** Delete the given Database. */ delete(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const path = getPathFromLink(this.url); const id = getIdFromLink(this.url); const response = yield this.clientContext.delete({ path, resourceType: exports.ResourceType.database, resourceId: id, options }); return new DatabaseResponse(response.result, response.headers, response.code, this); }); } /** * Gets offer on database. If none exists, returns an OfferResponse with undefined. * @param options */ readOffer(options = {}) { return tslib.__awaiter(this, void 0, void 0, function* () { const { resource: record } = yield this.read(); const path = "/offers"; const url = record._self; const response = yield this.clientContext.queryFeed({ path, resourceId: "", resourceType: exports.ResourceType.offer, query: `SELECT * from root where root.resource = "${url}"`, resultFn: (result) => result.Offers, options }); const offer = response.result[0] ? new Offer(this.client, response.result[0].id, this.clientContext) : undefined; return new OfferResponse(response.result[0], response.headers, response.code, offer); }); } }
JavaScript
class Databases { /** * @hidden * @param client The parent {@link CosmosClient} for the Database. */ constructor(client, clientContext) { this.client = client; this.clientContext = clientContext; } query(query, options) { const cb = (innerOptions) => { return this.clientContext.queryFeed({ path: "/dbs", resourceType: exports.ResourceType.database, resourceId: "", resultFn: (result) => result.Databases, query, options: innerOptions }); }; return new QueryIterator(this.clientContext, query, options, cb); } /** * Send a request for creating a database. * * A database manages users, permissions and a set of containers. * Each Azure Cosmos DB Database Account is able to support multiple independent named databases, * with the database being the logical container for data. * * Each Database consists of one or more containers, each of which in turn contain one or more * documents. Since databases are an administrative resource, the Service Master Key will be * required in order to access and successfully complete any action using the User APIs. * * @param body The {@link DatabaseDefinition} that represents the {@link Database} to be created. * @param options Use to set options like response page size, continuation tokens, etc. */ create(body, options = {}) { return tslib.__awaiter(this, void 0, void 0, function* () { const err = {}; if (!isResourceValid(body, err)) { throw err; } validateOffer(body); if (body.maxThroughput) { const autoscaleParams = { maxThroughput: body.maxThroughput }; if (body.autoUpgradePolicy) { autoscaleParams.autoUpgradePolicy = body.autoUpgradePolicy; } const autoscaleHeaders = JSON.stringify(autoscaleParams); options.initialHeaders = Object.assign({}, options.initialHeaders, { [Constants.HttpHeaders.AutoscaleSettings]: autoscaleHeaders }); delete body.maxThroughput; delete body.autoUpgradePolicy; } if (body.throughput) { options.initialHeaders = Object.assign({}, options.initialHeaders, { [Constants.HttpHeaders.OfferThroughput]: body.throughput }); delete body.throughput; } const path = "/dbs"; // TODO: constant const response = yield this.clientContext.create({ body, path, resourceType: exports.ResourceType.database, resourceId: undefined, options }); const ref = new Database(this.client, body.id, this.clientContext); return new DatabaseResponse(response.result, response.headers, response.code, ref); }); } /** * Check if a database exists, and if it doesn't, create it. * This will make a read operation based on the id in the `body`, then if it is not found, a create operation. * * A database manages users, permissions and a set of containers. * Each Azure Cosmos DB Database Account is able to support multiple independent named databases, * with the database being the logical container for data. * * Each Database consists of one or more containers, each of which in turn contain one or more * documents. Since databases are an an administrative resource, the Service Master Key will be * required in order to access and successfully complete any action using the User APIs. * * @param body The {@link DatabaseDefinition} that represents the {@link Database} to be created. * @param options */ createIfNotExists(body, options) { return tslib.__awaiter(this, void 0, void 0, function* () { if (!body || body.id === null || body.id === undefined) { throw new Error("body parameter must be an object with an id property"); } /* 1. Attempt to read the Database (based on an assumption that most databases will already exist, so its faster) 2. If it fails with NotFound error, attempt to create the db. Else, return the read results. */ try { const readResponse = yield this.client.database(body.id).read(options); return readResponse; } catch (err) { if (err.code === StatusCodes.NotFound) { const createResponse = yield this.create(body, options); // Must merge the headers to capture RU costskaty mergeHeaders(createResponse.headers, err.headers); return createResponse; } else { throw err; } } }); } // TODO: DatabaseResponse for QueryIterator? /** * Reads all databases. * @param options Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return all databases in an array or iterate over them one at a time. * @example Read all databases to array. * ```typescript * const {body: databaseList} = await client.databases.readAll().fetchAll(); * ``` */ readAll(options) { return this.query(undefined, options); } }
JavaScript
class DefaultRetryPolicy { constructor(operationType) { this.operationType = operationType; this.maxTries = 10; this.currentRetryAttemptCount = 0; this.retryAfterInMs = 1000; } /** * Determines whether the request should be retried or not. * @param {object} err - Error returned by the request. */ shouldRetry(err) { return tslib.__awaiter(this, void 0, void 0, function* () { if (err) { if (this.currentRetryAttemptCount < this.maxTries && needsRetry(this.operationType, err.code)) { this.currentRetryAttemptCount++; return true; } } return false; }); } }
JavaScript
class EndpointDiscoveryRetryPolicy { /** * @constructor EndpointDiscoveryRetryPolicy * @param {object} globalEndpointManager The GlobalEndpointManager instance. */ constructor(globalEndpointManager, operationType) { this.globalEndpointManager = globalEndpointManager; this.operationType = operationType; this.maxTries = EndpointDiscoveryRetryPolicy.maxTries; this.currentRetryAttemptCount = 0; this.retryAfterInMs = EndpointDiscoveryRetryPolicy.retryAfterInMs; } /** * Determines whether the request should be retried or not. * @param {object} err - Error returned by the request. */ shouldRetry(err, retryContext, locationEndpoint) { return tslib.__awaiter(this, void 0, void 0, function* () { if (!err) { return false; } if (!retryContext || !locationEndpoint) { return false; } if (!this.globalEndpointManager.enableEndpointDiscovery) { return false; } if (this.currentRetryAttemptCount >= this.maxTries) { return false; } this.currentRetryAttemptCount++; if (isReadRequest(this.operationType)) { yield this.globalEndpointManager.markCurrentLocationUnavailableForRead(locationEndpoint); } else { yield this.globalEndpointManager.markCurrentLocationUnavailableForWrite(locationEndpoint); } retryContext.retryCount = this.currentRetryAttemptCount; retryContext.clearSessionTokenNotAvailable = false; retryContext.retryRequestOnPreferredLocations = false; return true; }); } }
JavaScript
class ResourceThrottleRetryPolicy { /** * @constructor ResourceThrottleRetryPolicy * @param {int} maxTries - Max number of retries to be performed for a request. * @param {int} fixedRetryIntervalInMs - Fixed retry interval in milliseconds to wait between each \ * retry ignoring the retryAfter returned as part of the response. * @param {int} timeoutInSeconds - Max wait time in seconds to wait for a request while the \ * retries are happening. */ constructor(maxTries = 9, fixedRetryIntervalInMs = 0, timeoutInSeconds = 30) { this.maxTries = maxTries; this.fixedRetryIntervalInMs = fixedRetryIntervalInMs; /** Current retry attempt count. */ this.currentRetryAttemptCount = 0; /** Cummulative wait time in milliseconds for a request while the retries are happening. */ this.cummulativeWaitTimeinMs = 0; /** Retry interval in milliseconds to wait before the next request will be sent. */ this.retryAfterInMs = 0; this.timeoutInMs = timeoutInSeconds * 1000; this.currentRetryAttemptCount = 0; this.cummulativeWaitTimeinMs = 0; } /** * Determines whether the request should be retried or not. * @param {object} err - Error returned by the request. */ shouldRetry(err) { return tslib.__awaiter(this, void 0, void 0, function* () { // TODO: any custom error object if (err) { if (this.currentRetryAttemptCount < this.maxTries) { this.currentRetryAttemptCount++; this.retryAfterInMs = 0; if (this.fixedRetryIntervalInMs) { this.retryAfterInMs = this.fixedRetryIntervalInMs; } else if (err.retryAfterInMs) { this.retryAfterInMs = err.retryAfterInMs; } if (this.cummulativeWaitTimeinMs < this.timeoutInMs) { this.cummulativeWaitTimeinMs += this.retryAfterInMs; return true; } } } return false; }); } }
JavaScript
class SessionRetryPolicy { /** * @constructor SessionReadRetryPolicy * @param {object} globalEndpointManager - The GlobalEndpointManager instance. * @property {object} request - The Http request information */ constructor(globalEndpointManager, resourceType, operationType, connectionPolicy) { this.globalEndpointManager = globalEndpointManager; this.resourceType = resourceType; this.operationType = operationType; this.connectionPolicy = connectionPolicy; /** Current retry attempt count. */ this.currentRetryAttemptCount = 0; /** Retry interval in milliseconds. */ this.retryAfterInMs = 0; } /** * Determines whether the request should be retried or not. * @param {object} err - Error returned by the request. * @param {function} callback - The callback function which takes bool argument which specifies whether the request\ * will be retried or not. */ shouldRetry(err, retryContext) { return tslib.__awaiter(this, void 0, void 0, function* () { if (!err) { return false; } if (!retryContext) { return false; } if (!this.connectionPolicy.enableEndpointDiscovery) { return false; } if (this.globalEndpointManager.canUseMultipleWriteLocations(this.resourceType, this.operationType)) { // If we can write to multiple locations, we should against every write endpoint until we succeed const endpoints = isReadRequest(this.operationType) ? yield this.globalEndpointManager.getReadEndpoints() : yield this.globalEndpointManager.getWriteEndpoints(); if (this.currentRetryAttemptCount > endpoints.length) { return false; } else { retryContext.retryCount = ++this.currentRetryAttemptCount - 1; retryContext.retryRequestOnPreferredLocations = this.currentRetryAttemptCount > 1; retryContext.clearSessionTokenNotAvailable = this.currentRetryAttemptCount === endpoints.length; return true; } } else { if (this.currentRetryAttemptCount > 1) { return false; } else { retryContext.retryCount = ++this.currentRetryAttemptCount - 1; retryContext.retryRequestOnPreferredLocations = false; // Forces all operations to primary write endpoint retryContext.clearSessionTokenNotAvailable = true; return true; } } }); } }
JavaScript
class VectorSessionToken { constructor(version, globalLsn, localLsnByregion, sessionToken) { this.version = version; this.globalLsn = globalLsn; this.localLsnByregion = localLsnByregion; this.sessionToken = sessionToken; if (!this.sessionToken) { const regionAndLocalLsn = []; for (const [key, value] of this.localLsnByregion.entries()) { regionAndLocalLsn.push(`${key}${VectorSessionToken.REGION_PROGRESS_SEPARATOR}${value}`); } const regionProgress = regionAndLocalLsn.join(VectorSessionToken.SEGMENT_SEPARATOR); if (regionProgress === "") { this.sessionToken = `${this.version}${VectorSessionToken.SEGMENT_SEPARATOR}${this.globalLsn}`; } else { this.sessionToken = `${this.version}${VectorSessionToken.SEGMENT_SEPARATOR}${this.globalLsn}${VectorSessionToken.SEGMENT_SEPARATOR}${regionProgress}`; } } } static create(sessionToken) { if (!sessionToken) { return null; } const [versionStr, globalLsnStr, ...regionSegments] = sessionToken.split(VectorSessionToken.SEGMENT_SEPARATOR); const version = parseInt(versionStr, 10); const globalLsn = parseFloat(globalLsnStr); if (typeof version !== "number" || typeof globalLsn !== "number") { return null; } const lsnByRegion = new Map(); for (const regionSegment of regionSegments) { const [regionIdStr, localLsnStr] = regionSegment.split(VectorSessionToken.REGION_PROGRESS_SEPARATOR); if (!regionIdStr || !localLsnStr) { return null; } const regionId = parseInt(regionIdStr, 10); let localLsn; try { localLsn = localLsnStr; } catch (err) { // TODO: log error return null; } if (typeof regionId !== "number") { return null; } lsnByRegion.set(regionId, localLsn); } return new VectorSessionToken(version, globalLsn, lsnByRegion, sessionToken); } equals(other) { return !other ? false : this.version === other.version && this.globalLsn === other.globalLsn && this.areRegionProgressEqual(other.localLsnByregion); } merge(other) { if (other == null) { throw new Error("other (Vector Session Token) must not be null"); } if (this.version === other.version && this.localLsnByregion.size !== other.localLsnByregion.size) { throw new Error(`Compared session tokens ${this.sessionToken} and ${other.sessionToken} have unexpected regions`); } const [higherVersionSessionToken, lowerVersionSessionToken] = this.version < other.version ? [other, this] : [this, other]; const highestLocalLsnByRegion = new Map(); for (const [regionId, highLocalLsn] of higherVersionSessionToken.localLsnByregion.entries()) { const lowLocalLsn = lowerVersionSessionToken.localLsnByregion.get(regionId); if (lowLocalLsn) { highestLocalLsnByRegion.set(regionId, max(highLocalLsn, lowLocalLsn)); } else if (this.version === other.version) { throw new Error(`Compared session tokens have unexpected regions. Session 1: ${this.sessionToken} - Session 2: ${this.sessionToken}`); } else { highestLocalLsnByRegion.set(regionId, highLocalLsn); } } return new VectorSessionToken(Math.max(this.version, other.version), Math.max(this.globalLsn, other.globalLsn), highestLocalLsnByRegion); } toString() { return this.sessionToken; } areRegionProgressEqual(other) { if (this.localLsnByregion.size !== other.size) { return false; } for (const [regionId, localLsn] of this.localLsnByregion.entries()) { const otherLocalLsn = other.get(regionId); if (localLsn !== otherLocalLsn) { return false; } } return true; } }
JavaScript
class GlobalEndpointManager { /** * @constructor GlobalEndpointManager * @param {object} options - The document client instance. */ constructor(options, readDatabaseAccount) { this.readDatabaseAccount = readDatabaseAccount; this.options = options; this.defaultEndpoint = options.endpoint; this.enableEndpointDiscovery = options.connectionPolicy.enableEndpointDiscovery; this.isRefreshing = false; this.preferredLocations = this.options.connectionPolicy.preferredLocations; } /** * Gets the current read endpoint from the endpoint cache. */ getReadEndpoint() { return tslib.__awaiter(this, void 0, void 0, function* () { return this.resolveServiceEndpoint(exports.ResourceType.item, exports.OperationType.Read); }); } /** * Gets the current write endpoint from the endpoint cache. */ getWriteEndpoint() { return tslib.__awaiter(this, void 0, void 0, function* () { return this.resolveServiceEndpoint(exports.ResourceType.item, exports.OperationType.Replace); }); } getReadEndpoints() { return tslib.__awaiter(this, void 0, void 0, function* () { return this.readableLocations.map((loc) => loc.databaseAccountEndpoint); }); } getWriteEndpoints() { return tslib.__awaiter(this, void 0, void 0, function* () { return this.writeableLocations.map((loc) => loc.databaseAccountEndpoint); }); } markCurrentLocationUnavailableForRead(endpoint) { return tslib.__awaiter(this, void 0, void 0, function* () { yield this.refreshEndpointList(); const location = this.readableLocations.find((loc) => loc.databaseAccountEndpoint === endpoint); if (location) { location.unavailable = true; } }); } markCurrentLocationUnavailableForWrite(endpoint) { return tslib.__awaiter(this, void 0, void 0, function* () { yield this.refreshEndpointList(); const location = this.writeableLocations.find((loc) => loc.databaseAccountEndpoint === endpoint); if (location) { location.unavailable = true; } }); } canUseMultipleWriteLocations(resourceType, operationType) { let canUse = this.options.connectionPolicy.useMultipleWriteLocations; if (resourceType) { canUse = canUse && (resourceType === exports.ResourceType.item || (resourceType === exports.ResourceType.sproc && operationType === exports.OperationType.Execute)); } return canUse; } resolveServiceEndpoint(resourceType, operationType) { return tslib.__awaiter(this, void 0, void 0, function* () { // If endpoint discovery is disabled, always use the user provided endpoint if (!this.options.connectionPolicy.enableEndpointDiscovery) { return this.defaultEndpoint; } // If getting the database account, always use the user provided endpoint if (resourceType === exports.ResourceType.none) { return this.defaultEndpoint; } if (!this.readableLocations || !this.writeableLocations) { const { resource: databaseAccount } = yield this.readDatabaseAccount({ urlConnection: this.defaultEndpoint }); this.writeableLocations = databaseAccount.writableLocations; this.readableLocations = databaseAccount.readableLocations; } const locations = isReadRequest(operationType) ? this.readableLocations : this.writeableLocations; let location; // If we have preferred locations, try each one in order and use the first available one if (this.preferredLocations && this.preferredLocations.length > 0) { for (const preferredLocation of this.preferredLocations) { location = locations.find((loc) => loc.unavailable !== true && normalizeEndpoint(loc.name) === normalizeEndpoint(preferredLocation)); if (location) { break; } } } // If no preferred locations or one did not match, just grab the first one that is available if (!location) { location = locations.find((loc) => { return loc.unavailable !== true; }); } return location ? location.databaseAccountEndpoint : this.defaultEndpoint; }); } /** * Refreshes the endpoint list by retrieving the writable and readable locations * from the geo-replicated database account and then updating the locations cache. * We skip the refreshing if enableEndpointDiscovery is set to False */ refreshEndpointList() { return tslib.__awaiter(this, void 0, void 0, function* () { if (!this.isRefreshing && this.enableEndpointDiscovery) { this.isRefreshing = true; const databaseAccount = yield this.getDatabaseAccountFromAnyEndpoint(); if (databaseAccount) { this.refreshEndpoints(databaseAccount); } this.isRefreshing = false; } }); } refreshEndpoints(databaseAccount) { for (const location of databaseAccount.writableLocations) { const existingLocation = this.writeableLocations.find((loc) => loc.name === location.name); if (!existingLocation) { this.writeableLocations.push(location); } } for (const location of databaseAccount.writableLocations) { const existingLocation = this.readableLocations.find((loc) => loc.name === location.name); if (!existingLocation) { this.readableLocations.push(location); } } } /** * Gets the database account first by using the default endpoint, and if that doesn't returns * use the endpoints for the preferred locations in the order they are specified to get * the database account. * @memberof GlobalEndpointManager * @instance * @param {function} callback - The callback function which takes databaseAccount(object) as an argument. */ getDatabaseAccountFromAnyEndpoint() { return tslib.__awaiter(this, void 0, void 0, function* () { try { const options = { urlConnection: this.defaultEndpoint }; const { resource: databaseAccount } = yield this.readDatabaseAccount(options); return databaseAccount; // If for any reason(non - globaldb related), we are not able to get the database // account from the above call to readDatabaseAccount, // we would try to get this information from any of the preferred locations that the user // might have specified (by creating a locational endpoint) // and keeping eating the exception until we get the database account and return None at the end, // if we are not able to get that info from any endpoints } catch (err) { // TODO: Tracing } if (this.preferredLocations) { for (const location of this.preferredLocations) { try { const locationalEndpoint = GlobalEndpointManager.getLocationalEndpoint(this.defaultEndpoint, location); const options = { urlConnection: locationalEndpoint }; const { resource: databaseAccount } = yield this.readDatabaseAccount(options); if (databaseAccount) { return databaseAccount; } } catch (err) { // TODO: Tracing } } } }); } /** * Gets the locational endpoint using the location name passed to it using the default endpoint. * @memberof GlobalEndpointManager * @instance * @param {string} defaultEndpoint - The default endpoint to use for the endpoint. * @param {string} locationName - The location name for the azure region like "East US". */ static getLocationalEndpoint(defaultEndpoint, locationName) { // For defaultEndpoint like 'https://contoso.documents.azure.com:443/' parse it to generate URL format // This defaultEndpoint should be global endpoint(and cannot be a locational endpoint) // and we agreed to document that const endpointUrl = new URL(defaultEndpoint); // hostname attribute in endpointUrl will return 'contoso.documents.azure.com' if (endpointUrl.hostname) { const hostnameParts = endpointUrl.hostname .toString() .toLowerCase() .split("."); if (hostnameParts) { // globalDatabaseAccountName will return 'contoso' const globalDatabaseAccountName = hostnameParts[0]; // Prepare the locationalDatabaseAccountName as contoso-EastUS for location_name 'East US' const locationalDatabaseAccountName = globalDatabaseAccountName + "-" + locationName.replace(" ", ""); // Replace 'contoso' with 'contoso-EastUS' and // return locationalEndpoint as https://contoso-EastUS.documents.azure.com:443/ const locationalEndpoint = defaultEndpoint .toLowerCase() .replace(globalDatabaseAccountName, locationalDatabaseAccountName); return locationalEndpoint; } } return null; } }
JavaScript
class CosmosClient { constructor(optionsOrConnectionString) { if (typeof optionsOrConnectionString === "string") { optionsOrConnectionString = parseConnectionString(optionsOrConnectionString); } const endpoint = checkURL(optionsOrConnectionString.endpoint); if (!endpoint) { throw new Error("Invalid endpoint specified"); } optionsOrConnectionString.connectionPolicy = Object.assign({}, defaultConnectionPolicy, optionsOrConnectionString.connectionPolicy); optionsOrConnectionString.defaultHeaders = optionsOrConnectionString.defaultHeaders || {}; optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.CacheControl] = "no-cache"; optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.Version] = Constants.CurrentVersion; if (optionsOrConnectionString.consistencyLevel !== undefined) { optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.ConsistencyLevel] = optionsOrConnectionString.consistencyLevel; } optionsOrConnectionString.defaultHeaders[Constants.HttpHeaders.UserAgent] = getUserAgent(optionsOrConnectionString.userAgentSuffix); const globalEndpointManager = new GlobalEndpointManager(optionsOrConnectionString, (opts) => tslib.__awaiter(this, void 0, void 0, function* () { return this.getDatabaseAccount(opts); })); this.clientContext = new ClientContext(optionsOrConnectionString, globalEndpointManager); this.databases = new Databases(this, this.clientContext); this.offers = new Offers(this, this.clientContext); } /** * Get information about the current {@link DatabaseAccount} (including which regions are supported, etc.) */ getDatabaseAccount(options) { return tslib.__awaiter(this, void 0, void 0, function* () { const response = yield this.clientContext.getDatabaseAccount(options); return new ResourceResponse(response.result, response.headers, response.code); }); } /** * Gets the currently used write endpoint url. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getWriteEndpoint() { return this.clientContext.getWriteEndpoint(); } /** * Gets the currently used read endpoint. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getReadEndpoint() { return this.clientContext.getReadEndpoint(); } /** * Used for reading, updating, or deleting a existing database by id or accessing containers belonging to that database. * * This does not make a network call. Use `.read` to get info about the database after getting the {@link Database} object. * * @param id The id of the database. * @example Create a new container off of an existing database * ```typescript * const container = client.database("<database id>").containers.create("<container id>"); * ``` * * @example Delete an existing database * ```typescript * await client.database("<id here>").delete(); * ``` */ database(id) { return new Database(this, id, this.clientContext); } /** * Used for reading, or updating a existing offer by id. * @param id The id of the offer. */ offer(id) { return new Offer(this, id, this.clientContext); } }
JavaScript
class LanguageJournalSheet extends JournalSheet { get journal(){ return this.object; } static get defaultOptions() { const options = super.defaultOptions; options.baseApplication = "JournalSheet"; options.classes.push('language-journal'); return options; } /* * Useful in creating a custom TinyMCE editor, to be looked into for further * tinkering in that direction. */ // _createEditor(target, editorOptions, initialContent) { // editorOptions.content_css = "./dark-slate-journal.css"; // return super._createEditor(target, editorOptions, initialContent); // }; // Add the sheet configuration button to the journal header _getHeaderButtons() { let buttons = super._getHeaderButtons(); // Journal Configuration const canConfigure = game.user.isGM || this.entity.owner; if (this.options.editable && canConfigure) { buttons = [ { label: "Language", class: "configure-sheet", icon: "fas fa-language", onclick: ev => this._onConfigureSheet(ev) } ].concat(buttons); } return buttons } // Allow the sheet configuration button to actually *do* something _onConfigureSheet(event) { event.preventDefault(); new EntitySheetConfig(this.journal, { top: this.position.top + 40, left: this.position.left + ((this.position.width - 400) / 2) }).render(true); } }
JavaScript
class ElvishSylvanUndercommon extends LanguageJournalSheet { static get defaultOptions() { const options = super.defaultOptions; options.classes.push('rellanic-journal'); return options; } }
JavaScript
class Tree { /** * Creates a Tree Object * Populates a single attribute that contains a list (array) of Node objects to be used by the other functions in this class * note: Node objects will have a name, parentNode, parentName, children, level, and position * @param {json[]} json - array of json object with name and parent fields */ constructor(json) { // Create an array of newly instantiated node objects this.nodes = json.map(n => { return new Node(n.name, n.parent); }); console.log(this.nodes) // Iterate through array and populate with parentNodes // note: may be integrated into buildTree() this.nodes.forEach(node => { node.parentNode = this.nodes.find(n => { return n.name === node.parentName; }); }); } /** * Function that builds a tree from a list of nodes with parent refs */ buildTree() { // Populate children this.nodes.forEach(n => { console.log("n", n) // for each node if (n.parentNode !== undefined) { // if parentNode exists n.parentNode.addChild(n); // add node as child to parentNode } }); // Find root let root = this.nodes.find(n => { return !n.parentNode; }); // Assign levels and positions to each node, starting at root this.assignLevel(root, 0); this.assignPosition(root, 0); // For generating nodeStructure image // console.log(this.nodes[2]); // For generating wrong image // this.nodes.filter(n => n.level === 3).forEach(n => n.position = n.position-2) } /** * Recursive function that assign levels to each node */ assignLevel(node, level) { // Assign level node.level = level; // Recursively call assignLevel on this node's children; node.children.forEach(n => { this.assignLevel(n, level + 1); }); } /** * Recursive function that assign positions to each node */ // Better Solution assignPosition(node, position) { node.position = position; if (node.children.length === 0) return ++position; node.children.forEach((child) => { position = this.assignPosition(child, position); }); return position; } /** * Function that renders the tree */ renderTree() { // ----------- Custom ----------- // Convenience structure for updating variables (not required) let custom_vars = { x_scale: 160, y_scale: 100, x_offset: 50, y_offset: 50, radius: 43 }; // ----------- Initalize SVG ----------- // Create svg if it doesn't already exist (!) Lab Discussion 1 -- Explain why this check exists let svg = d3.select('#container'); if (svg.size() === 0) { svg = d3.select('body') .append('svg') .attr('id', 'container'); } // Style svg svg.attr('width', 1200) .attr('height', 1200); // ----------- Render Edges ----------- //(!) Lab Discussion 2 -- Update, Enter, Exit Loop ///New d3V5 data binding/// let allEdges = svg.selectAll('line') .data(this.nodes.filter(n => { return n.parentNode; })).join('line'); // Update properties according to data allEdges.attr('x1', n => { return n.level * custom_vars.x_scale + custom_vars.x_offset; }) .attr('x2', n => { return n.parentNode.level * custom_vars.x_scale + custom_vars.x_offset; }) .attr('y1', n => { return n.position * custom_vars.y_scale + custom_vars.y_offset; }) .attr('y2', n => { return n.parentNode.position * custom_vars.y_scale + custom_vars.y_offset; }); /** * This is an update to for the homework, designed to provide more experience * with nesting structures... -- required for full credit * */ // ----------- Render Nodes (Full Credit) ----------- //Existing(Update) Selection let allNodeGroups = svg.selectAll('.nodeGroup') .data(this.nodes).join('g').classed('nodeGroup', true); // Update properties according to data (!) Lab Discussion 3 -- Judicious Use of Groups, SVG Order importance allNodeGroups .attr("transform", d => { return "translate(" + (d.level * custom_vars.x_scale + custom_vars.x_offset) // x position + "," + (d.position * custom_vars.y_scale + custom_vars.y_offset) // y position + ")" } ); console.log(allNodeGroups) // -- Add circles to each group allNodeGroups.append("circle") .attr("r", custom_vars.radius); // -- Add text to each group allNodeGroups.append("text") .attr("class", "label") .text(d => { return d.name.toUpperCase(); }); // For generating node position image // .text(d => { // return d.level+","+d.position; // }); } }
JavaScript
class ArcPreferencesProxy { /** * @constructor */ constructor() { this._readHandler = this._readHandler.bind(this); this._changeHandler = this._changeHandler.bind(this); this._mainPrefsHandler = this._mainPrefsHandler.bind(this); this._mainChangedHandler = this._mainChangedHandler.bind(this); this.promises = []; this.lastRequestId = 0; } /** * Observers window and IPC events which makes this class work. */ observe() { window.addEventListener('settings-read', this._readHandler); window.addEventListener('settings-changed', this._changeHandler); ipcRenderer.on('app-preference-updated', this._mainChangedHandler); ipcRenderer.on('app-preferences', this._mainPrefsHandler); } /** * Stop observing window and IPC events */ unobserve() { window.removeEventListener('settings-read', this._readHandler); window.removeEventListener('settings-changed', this._changeHandler); ipcRenderer.removeListener('app-preference-updated', this._mainChangedHandler); ipcRenderer.removeListener('app-preferences', this._mainPrefsHandler); } /** * Handler for the `settings-read` custom event. Reads current settings. * It set's the `result` property on event's detail object with the * promise from calling `load()` function. * * @param {CustomEvent} e Custom event */ _readHandler(e) { e.preventDefault(); e.stopPropagation(); e.detail.result = this.load(); } /** * Loads application settings from the main thread. * @return {Promise} */ load() { return new Promise((resolve) => { const id = (++this.lastRequestId); this.promises.push({ type: 'read', resolve, id }); ipcRenderer.send('read-app-preferences', id); }); } /** * A handler for app-preferences event from the main process. * The event is dispatched to the window that requested this information * so the corresponding promise can be fulfilled. * * The implementation is in ../main/preferences-manager.js file. * * @param {Event} e * @param {Object} settings Restored application settings. * @param {String} id The id used to request the data */ _mainPrefsHandler(e, settings, id) { if (!id) { return; } let p; for (let i = 0, len = this.promises.length; i < len; i++) { if (this.promises[i].id === id) { p = this.promises[i]; this.promises.splice(i, 1); break; } } if (p) { p.resolve(settings); } } /** * A handler for window `settings-changed` custom event. * Sends the intent to the main proces to update preferences. * @param {CustomEvent} e */ _changeHandler(e) { if (!e.cancelable) { return; } e.preventDefault(); e.stopPropagation(); const { name } = e.detail; if (!name) { e.detail.result = Promise.reject(new Error('Name is not set.')); return; } e.detail.result = this.store(name, e.detail.value); } /** * Updates the data and stores it in the settings file. * @param {String} name Property name * @param {?any} value Property value * @return {Promise} Promise resolved when the changes has been commited to * the file. */ store(name, value) { return new Promise((resolve) => { this.promises.push({ type: 'store', resolve, name }); ipcRenderer.send('update-app-preference', name, value); }); } /** * Handler for `app-preference-updated` main process event. * The event is dispatched each time a preference change. * * If corresponding promise exists it will resolve it. * It always dispatches `app-preference-updated` custom event. * * @param {Event} e * @param {String} name Name of changed property * @param {any} value */ _mainChangedHandler(e, name, value) { let p; for (let i = 0, len = this.promises.length; i < len; i++) { const item = this.promises[i]; if (item.type === 'store' && item.name === name) { p = item; this.promises.splice(i, 1); break; } } if (p) { p.resolve(); } document.body.dispatchEvent(new CustomEvent('settings-changed', { bubbles: true, detail: { name, value, } })); } }
JavaScript
class ProgressBarDisplay extends PureComponent { render() { const { progressClassName, progressStyle, progress, progressDirection, handle, progressBarRef, ...attributes } = this.props; return ( <div {...attributes} ref={progressBarRef}> <div style={{ position: 'relative', width: '100%', height: '100%', touchAction: 'none' }} > <div className={progressClassName} style={{ ...(progressStyle || {}), ...getProgressStyle(progress, progressDirection) }} /> {handle && ( <div style={getHandleStyle(progress, progressDirection)}> {handle} </div> )} </div> </div> ); } }
JavaScript
class Dashboard { constructor(viewer, panel, container, selectcontainer, property) { var _this = this; this._viewer = viewer; this._panel = panel; this._container = container; this._selectcontainer = selectcontainer; this._property = property; this._listcreated = false; _this.loadPanels(); } loadPanels () { var _this = this; var data = new ModelData(this); data.init(function () { $('#'+_this._container).empty(); if(_this._listcreated === false){ _this.createList(Object.getOwnPropertyNames(data._modelData)) _this.listcreated = true; } _this._panel.load(_this._container, viewer, data); }); } createList(categories){ var _this = this; let template = '<select id="'+_this._selectcontainer+'"'+' >'; for (let index = 0; index < categories.length; index++) { if (categories[index] === _this._property) { template += '<option selected value="'+categories[index]+'">'+categories[index]+'</option>' } else { template += '<option value="'+categories[index]+'">'+categories[index]+'</option>' } } template += '</select>'; $('#'+_this._selectcontainer).html(template); $('#'+_this._selectcontainer).change(function() { console.log($('#'+_this._selectcontainer+' option:selected').text()) _this._panel.loadWithCustomProperty($('#'+_this._selectcontainer+' option:selected').text()) }); } }
JavaScript
class TextEncoder { /** * Validates a single Unicode code point. * @return {boolean} True, if code point is valid */ static validateCodePoint (codePoint) { return ( !isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) !== codePoint ) } /** * Returns a string containing as many code units as necessary * to represent the Unicode code points given by the first argument. * @author Norbert Lindenberg * @see http://norbertlindenberg.com/2012/05/ecmascript-supplementary-characters/ * @param {number[]} codePoints Array of Unicode code points * @throws {Error} Throws an error when encountering an invalid code point. * @returns {String} String (UCS-2) */ static stringFromCodePoints (codePoints) { let chars = [] codePoints.forEach((codePoint, index) => { if (TextEncoder.validateCodePoint(codePoint)) { throw new TextEncodingError( `Invalid code point '${codePoint}' at index ${index}`) } if (codePoint < 0x10000) { // BMP character chars.push(codePoint) } else { // character with surrogates codePoint -= 0x10000 chars.push((codePoint >> 10) + 0xD800) chars.push((codePoint % 0x400) + 0xDC00) } }) // create string from char codes // doing this in a way that does not cause a RangeError due to too many args return chars.map(charCode => String.fromCharCode(charCode)).join('') } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @author Mathias Bynens * @see https://github.com/bestiejs/punycode.js * @param {String} string String (UCS-2) * @returns {number[]} Array of Unicode code points */ static codePointsFromString (string) { const codePoints = [] const length = string.length let i = 0 while (i < length) { const value = string.charCodeAt(i++) if (value >= 0xD800 && value <= 0xDBFF && i < length) { // it's a high surrogate, and there is a next character const extra = string.charCodeAt(i++) if ((extra & 0xFC00) === 0xDC00) { // low surrogate codePoints.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000) } else { // it's an unmatched surrogate; only append this code unit, in case // the next code unit is the high surrogate of a surrogate pair codePoints.push(value) i-- } } else { codePoints.push(value) } } return codePoints } /** * Encodes Unicode code points to bytes using given encoding. * @param {number[]} codePoints * @param {String} [encoding='utf8'] * @throws {Error} Throws an error if given encoding is not supported. * @throws {Error} Throws an error when encountering an invalid code point. * @return {Uint8Array} Uint8Array of bytes */ static bytesFromCodePoints (codePoints, encoding = 'utf8') { switch (encoding) { case 'utf8': return TextEncoder._encodeCodePointsToUTF8Bytes(codePoints) default: throw new Error( `Encoding to '${encoding}' is currently not supported.`) } } /** * Decodes Unicode code points from bytes using given encoding. * @param {Uint8Array} bytes * @param {String} [encoding='utf8'] * @throws {Error} Throws an error if given encoding is not supported. * @throws {TextEncodingError} Throws an error if given bytes are malformed. * @return {number[]} Array of Unicode code points */ static codePointsFromBytes (bytes, encoding = 'utf8') { switch (encoding) { case 'utf8': return TextEncoder._decodeCodePointsFromUTF8Bytes(bytes) default: throw new Error( `Decoding from '${encoding}' is currently not supported.`) } } static _encodeCodePointsToUTF8Bytes (codePoints) { const bytes = [] codePoints.forEach((codePoint, index) => { if (TextEncoder.validateCodePoint(codePoint)) { throw new TextEncodingError( `Invalid code point '${codePoint}' at ${index}`) } // append code point bytes if (codePoint <= 0x7F) { // 1 byte: 0xxxxxxx bytes.push(codePoint) } else if (codePoint <= 0x7FF) { // 2 bytes: 110xxxxx 10xxxxxx bytes.push(0b11000000 | (codePoint >> 6)) bytes.push(0b10000000 | (codePoint % 64)) } else if (codePoint <= 0xFFFF) { // 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx bytes.push(0b11100000 | (codePoint >> 12)) bytes.push(0b10000000 | (codePoint % 4096 >> 6)) bytes.push(0b10000000 | (codePoint % 64)) } else { // 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx bytes.push(0b11110000 | (codePoint >> 18)) bytes.push(0b10000000 | (codePoint % 262144 >> 12)) bytes.push(0b10000000 | (codePoint % 4096 >> 6)) bytes.push(0b10000000 | (codePoint % 64)) } }) return new Uint8Array(bytes) } static _decodeCodePointsFromUTF8Bytes (bytes) { const codePoints = [] const size = bytes.length let remainingBytes = 0 let i = -1 let byte let codePoint while (++i < size) { byte = bytes[i] if (byte > 0b01111111 && byte <= 0b10111111) { // this is a continuation byte if (--remainingBytes < 0) { throw new TextEncodingError( `Invalid UTF-8 encoded text: ` + `Unexpected continuation byte at 0x${i.toString(16)}`, i) } // append bits to current code point codePoint = (codePoint << 6) | (byte % 64) if (remainingBytes === 0) { // completed a code point codePoints.push(codePoint) } } else if (remainingBytes > 0) { // this must be a continuation byte throw new TextEncodingError( `Invalid UTF-8 encoded text: ` + `Continuation byte expected at 0x${i.toString(16)}`, i) } else if (byte <= 0b01111111) { // 1 byte code point // this already is a complete code point codePoints.push(byte) } else if (byte <= 0b11011111) { // 2 byte code point codePoint = byte % 32 remainingBytes = 1 } else if (byte <= 0b11101111) { // 3 byte code point codePoint = byte % 16 remainingBytes = 2 } else if (byte <= 0b11110111) { // 4 byte code point codePoint = byte % 8 remainingBytes = 3 } else { throw new TextEncodingError( `Invalid UTF-8 encoded text: ` + `Invalid byte ${byte} at 0x${i.toString(16)}`, i) } } if (remainingBytes !== 0) { throw new TextEncodingError( `Invalid UTF-8 encoded text: Unexpected end of bytes`) } return codePoints } }
JavaScript
class ClientOptionsHandler { /*** * * @param {Object[]} fileSources - Files to show in the Load/Save pane * @param {string} fileSources.name - UI display name of the file * @param {string} fileSources.urlpart - Relative url path to fetch the file from * @param {CompilerProps} compilerProps * @param {Object} defArgs - Compiler Explorer arguments */ constructor(fileSources, compilerProps, defArgs) { this.compilerProps = compilerProps.get.bind(compilerProps); this.ceProps = compilerProps.ceProps; const ceProps = compilerProps.ceProps; const sources = _.sortBy(fileSources.map(source => { return {name: source.name, urlpart: source.urlpart}; }), 'name'); /*** * @type {CELanguages} */ const languages = compilerProps.languages; this.supportsBinary = this.compilerProps(languages, 'supportsBinary', true, res => !!res); this.supportsExecutePerLanguage = this.compilerProps(languages, 'supportsExecute', true, (res, lang) => { return this.supportsBinary[lang.id] && !!res; }); this.supportsExecute = Object.values(this.supportsExecutePerLanguage).some(value => value); const libs = this.parseLibraries(this.compilerProps(languages, 'libs')); const tools = this.parseTools(this.compilerProps(languages, 'tools')); const cookiePolicyEnabled = !!ceProps('cookiePolicyEnabled'); const privacyPolicyEnabled = !!ceProps('privacyPolicyEnabled'); const cookieDomainRe = ceProps('cookieDomainRe', ''); this.options = { googleAnalyticsAccount: ceProps('clientGoogleAnalyticsAccount', 'UA-55180-6'), googleAnalyticsEnabled: ceProps('clientGoogleAnalyticsEnabled', false), sharingEnabled: ceProps('clientSharingEnabled', true), githubEnabled: ceProps('clientGitHubRibbonEnabled', true), gapiKey: ceProps('googleApiKey', ''), googleShortLinkRewrite: ceProps('googleShortLinkRewrite', '').split('|'), urlShortenService: ceProps('urlShortenService', 'none'), defaultSource: ceProps('defaultSource', ''), compilers: [], libs: libs, tools: tools, defaultLibs: this.compilerProps(languages, 'defaultLibs', ''), defaultCompiler: this.compilerProps(languages, 'defaultCompiler', ''), compileOptions: this.compilerProps(languages, 'defaultOptions', ''), supportsBinary: this.supportsBinary, supportsExecute: this.supportsExecute, languages: languages, sources: sources, raven: ceProps('ravenUrl', ''), release: defArgs.gitReleaseName, environment: defArgs.env, cookieDomainRe: cookieDomainRe, localStoragePrefix: ceProps('localStoragePrefix'), cvCompilerCountMax: ceProps('cvCompilerCountMax', 6), defaultFontScale: ceProps('defaultFontScale', 1.0), doCache: defArgs.doCache, policies: { cookies: { enabled: cookiePolicyEnabled, hash: cookiePolicyEnabled ? ClientOptionsHandler.getFileHash( path.join(defArgs.staticDir, "policies", "cookies.html")) : null }, privacy: { enabled: privacyPolicyEnabled, hash: privacyPolicyEnabled ? ClientOptionsHandler.getFileHash( path.join(defArgs.staticDir, "policies", "privacy.html")) : null, // How we store this privacy hash on the local storage key: 'privacy_status' } }, motdUrl: ceProps('motdUrl', '') }; } parseTools(baseTools) { const tools = {}; _.each(baseTools, (forLang, lang) => { if (lang && forLang) { tools[lang] = {}; _.each(forLang.split(':'), tool => { const toolBaseName = `tools.${tool}`; const className = this.compilerProps(lang, toolBaseName + '.class'); const Tool = require("./tooling/" + className); tools[lang][tool] = new Tool({ id: tool, name: this.compilerProps(lang, toolBaseName + '.name'), type: this.compilerProps(lang, toolBaseName + '.type'), exe: this.compilerProps(lang, toolBaseName + '.exe'), exclude: this.compilerProps(lang, toolBaseName + '.exclude'), options: this.compilerProps(lang, toolBaseName + '.options') }, { ceProps: this.ceProps, compilerProps: (propname) => this.compilerProps(lang, propname) }); }); } }); return tools; } parseLibraries(baseLibs) { const libraries = {}; _.each(baseLibs, (forLang, lang) => { if (lang && forLang) { libraries[lang] = {}; _.each(forLang.split(':'), lib => { const libBaseName = `libs.${lib}`; libraries[lang][lib] = { name: this.compilerProps(lang, libBaseName + '.name'), url: this.compilerProps(lang, libBaseName + '.url'), description: this.compilerProps(lang, libBaseName + '.description') }; libraries[lang][lib].versions = {}; const listedVersions = `${this.compilerProps(lang, libBaseName + '.versions')}`; if (listedVersions) { _.each(listedVersions.split(':'), version => { const libVersionName = libBaseName + `.versions.${version}`; libraries[lang][lib].versions[version] = {}; libraries[lang][lib].versions[version].version = this.compilerProps(lang, libVersionName + '.version'); const includes = this.compilerProps(lang, libVersionName + '.path'); libraries[lang][lib].versions[version].path = []; if (includes) { libraries[lang][lib].versions[version].path = includes.split(':'); } else { logger.warn(`Library ${lib} ${version} (${lang}) has no include paths`); } }); } else { logger.warn(`No versions found for ${lib} library`); } }); } }); return libraries; } _asSafeVer(semver) { return semverParser.valid(semver, true) || semverParser.valid(semver + '.0', true) || "9999999.99999.999"; } setCompilers(compilers) { const blacklistedKeys = ['exe', 'versionFlag', 'versionRe', 'compilerType', 'demangler', 'objdumper', 'postProcess', 'demanglerClassFile', 'isSemVer']; const copiedCompilers = JSON.parse(JSON.stringify(compilers)); let semverGroups = {}; _.each(copiedCompilers, (compiler, compilersKey) => { if (compiler.isSemVer) { if (!semverGroups[compiler.group]) semverGroups[compiler.group] = []; // Desired index which will keep the array in order const index = _.sortedIndex(semverGroups[compiler.group], compiler.semver, (lhg) => { return semverParser.compare(this._asSafeVer(lhg.semver), this._asSafeVer(compiler.semver)); }); semverGroups[compiler.group].splice(index, 0, compiler); } _.each(compiler, (_, propKey) => { if (blacklistedKeys.includes(propKey)) { delete copiedCompilers[compilersKey][propKey]; } }); }); _.each(semverGroups, group => { let order = 0; // Set $order to -index on array. As group is an array, iteration order is guaranteed. _.each(group, compiler => compiler['$order'] = -order++); }); this.options.compilers = copiedCompilers; } get() { return this.options; } static getFileHash(path) { if (!fs.existsSync(path)) { logger.error(`File ${path} requested for hashing not found`); // Should we throw? What should happen here? } return getHash(fs.readFileSync(path, 'utf-8'), HashVersion); } }
JavaScript
class PackagesTablePaths extends React.Component { constructor(props) { super(); this.state = { data: props.data, expanded: props.expanded }; } onExpandTitle = (e) => { e.stopPropagation(); this.setState(prevState => ({ expanded: !prevState.expanded })); }; render() { const { data: pkgObj, expanded } = this.state; if (Array.isArray(pkgObj.paths) && pkgObj.paths.length === 0) { return null; } if (!expanded) { return ( <h4> <button className="ort-btn-expand" onClick={this.onExpandTitle} onKeyDown={this.onExpandTitle} type="button" > <span> Package Dependency Paths {' '} </span> <Icon type="right" /> </button> </h4> ); } return ( <div className="ort-package-deps-paths"> <h4> <button className="ort-btn-expand" onClick={this.onExpandTitle} onKeyUp={this.onExpandTitle} type="button" > Package Dependency Paths {' '} <Icon type="down" /> </button> </h4> <List grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 2, xl: 2, xxl: 2 }} itemLayout="vertical" size="small" pagination={{ hideOnSinglePage: true, pageSize: 2, size: 'small' }} dataSource={pkgObj.paths} renderItem={pathsItem => ( <List.Item> <h5> {pathsItem.scope} </h5> <Steps progressDot direction="vertical" size="small" current={pathsItem.path.length + 1}> {pathsItem.path.map(item => <Step key={item} title={item} />)} <Step key={pkgObj.id} title={pkgObj.id} /> </Steps> </List.Item> )} /> </div> ); } }
JavaScript
class VideoProvider { constructor() { /** * Default value for mirrored frames. * @type boolean */ this.mirror = true; /** * Cache frames for this many ms. * @type number */ this._frameCacheTimeout = 16; /** * DOM Video element * @private */ this._video = null; /** * Usermedia stream track * @private */ this._track = null; /** * Stores some canvas/frame data per resolution/mirror states */ this._workspace = []; } static get FORMAT_IMAGE_DATA() { return 'image-data'; } static get FORMAT_CANVAS() { return 'canvas'; } /** * Dimensions the video stream is analyzed at after its rendered to the * sample canvas. * @type {Array.<number>} */ static get DIMENSIONS() { return [480, 360]; } /** * Order preview drawable is inserted at in the renderer. * @type {number} */ static get ORDER() { return 1; } /** * Get the HTML video element containing the stream */ get video() { return this._video; } /** * Request video be enabled. Sets up video, creates video skin and enables preview. * * @return {Promise.<Video>} resolves a promise to this video provider when video is ready. */ enableVideo() { this.enabled = true; return this._setupVideo(); } /** * Disable video stream (turn video off) */ disableVideo() { this.enabled = false; // If we have begun a setup process, call _teardown after it completes if (this._singleSetup) { this._singleSetup .then(this._teardown.bind(this)) .catch(err => this.onError(err)); } } /** * async part of disableVideo * @private */ _teardown() { // we might be asked to re-enable before _teardown is called, just ignore it. if (this.enabled === false) { const disableTrack = requestDisableVideo(); this._singleSetup = null; // by clearing refs to video and track, we should lose our hold over the camera this._video = null; if (this._track && disableTrack) { this._track.stop(); } this._track = null; } } /** * Return frame data from the video feed in a specified dimensions, format, and mirroring. * * @param {object} frameInfo A descriptor of the frame you would like to receive. * @param {Array.<number>} frameInfo.dimensions [width, height] array of numbers. Defaults to [480,360] * @param {boolean} frameInfo.mirror If you specificly want a mirror/non-mirror frame, defaults to true * @param {string} frameInfo.format Requested video format, available formats are 'image-data' and 'canvas'. * @param {number} frameInfo.cacheTimeout Will reuse previous image data if the time since capture is less than * the cacheTimeout. Defaults to 16ms. * * @return {ArrayBuffer|Canvas|string|null} Frame data in requested format, null when errors. */ getFrame({ dimensions = VideoProvider.DIMENSIONS, mirror = this.mirror, format = VideoProvider.FORMAT_IMAGE_DATA, cacheTimeout = this._frameCacheTimeout, }) { if (!this.videoReady) { return null; } const [width, height] = dimensions; const workspace = this._getWorkspace({ dimensions, mirror: Boolean(mirror), }); const { videoWidth, videoHeight } = this._video; const { canvas, context, lastUpdate, cacheData } = workspace; const now = Date.now(); // if the canvas hasn't been updated... if (lastUpdate + cacheTimeout < now) { if (mirror) { context.scale(-1, 1); context.translate(width * -1, 0); } context.drawImage( this._video, // source x, y, width, height 0, 0, videoWidth, videoHeight, // dest x, y, width, height 0, 0, width, height, ); // context.resetTransform() doesn't work on Edge but the following should context.setTransform(1, 0, 0, 1, 0, 0); workspace.lastUpdate = now; } // each data type has it's own data cache, but the canvas is the same if (!cacheData[format]) { cacheData[format] = { lastUpdate: 0 }; } const formatCache = cacheData[format]; if (formatCache.lastUpdate + cacheTimeout < now) { if (format === VideoProvider.FORMAT_IMAGE_DATA) { formatCache.lastData = context.getImageData( 0, 0, width, height, ); } else if (format === VideoProvider.FORMAT_CANVAS) { // this will never change formatCache.lastUpdate = Infinity; formatCache.lastData = canvas; } else { log.error(`video io error - unimplemented format ${format}`); // cache the null result forever, don't log about it again.. formatCache.lastUpdate = Infinity; formatCache.lastData = null; } // rather than set to now, this data is as stale as it's canvas is formatCache.lastUpdate = Math.max( workspace.lastUpdate, formatCache.lastUpdate, ); } return formatCache.lastData; } /** * Method called when an error happens. Default implementation is just to log error. * * @abstract * @param {Error} error An error object from getUserMedia or other source of error. */ onError(error) { log.error('Unhandled video io device error', error); } /** * Create a video stream. * @private * @return {Promise} When video has been received, rejected if video is not received */ _setupVideo() { // We cache the result of this setup so that we can only ever have a single // video/getUserMedia request happen at a time. if (this._singleSetup) { return this._singleSetup; } this._singleSetup = requestVideoStream({ width: { min: 480, ideal: 640 }, height: { min: 360, ideal: 480 }, }) .then(stream => { this._video = document.createElement('video'); // Use the new srcObject API, falling back to createObjectURL try { this._video.srcObject = stream; } catch (error) { this._video.src = window.URL.createObjectURL(stream); } // Hint to the stream that it should load. A standard way to do this // is add the video tag to the DOM. Since this extension wants to // hide the video tag and instead render a sample of the stream into // the webgl rendered Scratch canvas, another hint like this one is // needed. this._video.play(); // Needed for Safari/Firefox, Chrome auto-plays. this._track = stream.getTracks()[0]; return this; }) .catch(error => { this._singleSetup = null; this.onError(error); }); return this._singleSetup; } get videoReady() { if (!this.enabled) { return false; } if (!this._video) { return false; } if (!this._track) { return false; } const { videoWidth, videoHeight } = this._video; if (typeof videoWidth !== 'number' || typeof videoHeight !== 'number') { return false; } if (videoWidth === 0 || videoHeight === 0) { return false; } return true; } /** * get an internal workspace for canvas/context/caches * this uses some document stuff to create a canvas and what not, probably needs abstraction * into the renderer layer? * @private * @return {object} A workspace for canvas/data storage. Internal format not documented intentionally */ _getWorkspace({ dimensions, mirror }) { let workspace = this._workspace.find( space => space.dimensions.join('-') === dimensions.join('-') && space.mirror === mirror, ); if (!workspace) { workspace = { dimensions, mirror, canvas: document.createElement('canvas'), lastUpdate: 0, cacheData: {}, }; workspace.canvas.width = dimensions[0]; workspace.canvas.height = dimensions[1]; workspace.context = workspace.canvas.getContext('2d'); this._workspace.push(workspace); } return workspace; } }
JavaScript
class ThrowErrorPolicy { handle(error, sourceString, localeCode, params) { throw error || new Error(`Error translating "${sourceString}"`); } }
JavaScript
class Stack extends bio.Struct { /** * Create a stack. * @constructor * @param {Buffer[]?} items - Stack items. */ constructor(items) { super(); this.items = items || []; } /** * Get length. * @returns {Number} */ get length() { return this.items.length; } /** * Set length. * @param {Number} value */ set length(value) { this.items.length = value; } /** * Instantiate a value-only iterator. * @returns {StackIterator} */ [Symbol.iterator]() { return this.items[Symbol.iterator](); } /** * Instantiate a value-only iterator. * @returns {StackIterator} */ values() { return this.items.values(); } /** * Instantiate a key and value iterator. * @returns {StackIterator} */ entries() { return this.items.entries(); } /** * Inspect the stack. * @returns {String} Human-readable stack. */ format() { return `<Stack: ${this.toString()}>`; } /** * Convert the stack to a string. * @returns {String} Human-readable stack. */ toString() { const out = []; for (const item of this.items) out.push(item.toString('hex')); return out.join(' '); } /** * Format the stack as bitcoind asm. * @param {Boolean?} decode - Attempt to decode hash types. * @returns {String} Human-readable script. */ toASM(decode) { const out = []; for (const item of this.items) out.push(common.toASM(item, decode)); return out.join(' '); } /** * Clone the stack. * @returns {Stack} Cloned stack. */ inject(stack) { this.items = stack.items.slice(); return this; } /** * Clear the stack. * @returns {Stack} */ clear() { this.items.length = 0; return this; } /** * Get a stack item by index. * @param {Number} index * @returns {Buffer|null} */ get(index) { if (index < 0) index += this.items.length; if (index < 0 || index >= this.items.length) return null; return this.items[index]; } /** * Pop a stack item. * @see Array#pop * @returns {Buffer|null} */ pop() { const item = this.items.pop(); return item || null; } /** * Shift a stack item. * @see Array#shift * @returns {Buffer|null} */ shift() { const item = this.items.shift(); return item || null; } /** * Remove an item. * @param {Number} index * @returns {Buffer} */ remove(index) { if (index < 0) index += this.items.length; if (index < 0 || index >= this.items.length) return null; const items = this.items.splice(index, 1); if (items.length === 0) return null; return items[0]; } /** * Set stack item at index. * @param {Number} index * @param {Buffer} value * @returns {Buffer} */ set(index, item) { if (index < 0) index += this.items.length; assert(Buffer.isBuffer(item)); assert(index >= 0 && index <= this.items.length); this.items[index] = item; return this; } /** * Push item onto stack. * @see Array#push * @param {Buffer} item * @returns {Number} Stack size. */ push(item) { assert(Buffer.isBuffer(item)); this.items.push(item); return this; } /** * Unshift item from stack. * @see Array#unshift * @param {Buffer} item * @returns {Number} */ unshift(item) { assert(Buffer.isBuffer(item)); this.items.unshift(item); return this; } /** * Insert an item. * @param {Number} index * @param {Buffer} item * @returns {Buffer} */ insert(index, item) { if (index < 0) index += this.items.length; assert(Buffer.isBuffer(item)); assert(index >= 0 && index <= this.items.length); this.items.splice(index, 0, item); return this; } /** * Erase stack items. * @param {Number} start * @param {Number} end * @returns {Buffer[]} */ erase(start, end) { if (start < 0) start = this.items.length + start; if (end < 0) end = this.items.length + end; this.items.splice(start, end - start); } /** * Swap stack values. * @param {Number} i1 - Index 1. * @param {Number} i2 - Index 2. */ swap(i1, i2) { if (i1 < 0) i1 = this.items.length + i1; if (i2 < 0) i2 = this.items.length + i2; const v1 = this.items[i1]; const v2 = this.items[i2]; this.items[i1] = v2; this.items[i2] = v1; } /* * Data */ getData(index) { return this.get(index); } popData() { return this.pop(); } shiftData() { return this.shift(); } removeData(index) { return this.remove(index); } setData(index, data) { return this.set(index, data); } pushData(data) { return this.push(data); } unshiftData(data) { return this.unshift(data); } insertData(index, data) { return this.insert(index, data); } /* * Length */ getLength(index) { const item = this.get(index); return item ? item.length : -1; } /* * String */ getString(index, enc) { const item = this.get(index); return item ? Stack.toString(item, enc) : null; } popString(enc) { const item = this.pop(); return item ? Stack.toString(item, enc) : null; } shiftString(enc) { const item = this.shift(); return item ? Stack.toString(item, enc) : null; } removeString(index, enc) { const item = this.remove(index); return item ? Stack.toString(item, enc) : null; } setString(index, str, enc) { return this.set(index, Stack.fromString(str, enc)); } pushString(str, enc) { return this.push(Stack.fromString(str, enc)); } unshiftString(str, enc) { return this.unshift(Stack.fromString(str, enc)); } insertString(index, str, enc) { return this.insert(index, Stack.fromString(str, enc)); } /* * Num */ getNum(index, minimal, limit) { const item = this.get(index); return item ? Stack.toNum(item, minimal, limit) : null; } popNum(minimal, limit) { const item = this.pop(); return item ? Stack.toNum(item, minimal, limit) : null; } shiftNum(minimal, limit) { const item = this.shift(); return item ? Stack.toNum(item, minimal, limit) : null; } removeNum(index, minimal, limit) { const item = this.remove(index); return item ? Stack.toNum(item, minimal, limit) : null; } setNum(index, num) { return this.set(index, Stack.fromNum(num)); } pushNum(num) { return this.push(Stack.fromNum(num)); } unshiftNum(num) { return this.unshift(Stack.fromNum(num)); } insertNum(index, num) { return this.insert(index, Stack.fromNum(num)); } /* * Int */ getInt(index, minimal, limit) { const item = this.get(index); return item ? Stack.toInt(item, minimal, limit) : -1; } popInt(minimal, limit) { const item = this.pop(); return item ? Stack.toInt(item, minimal, limit) : -1; } shiftInt(minimal, limit) { const item = this.shift(); return item ? Stack.toInt(item, minimal, limit) : -1; } removeInt(index, minimal, limit) { const item = this.remove(index); return item ? Stack.toInt(item, minimal, limit) : -1; } setInt(index, num) { return this.set(index, Stack.fromInt(num)); } pushInt(num) { return this.push(Stack.fromInt(num)); } unshiftInt(num) { return this.unshift(Stack.fromInt(num)); } insertInt(index, num) { return this.insert(index, Stack.fromInt(num)); } /* * Bool */ getBool(index) { const item = this.get(index); return item ? Stack.toBool(item) : false; } popBool() { const item = this.pop(); return item ? Stack.toBool(item) : false; } shiftBool() { const item = this.shift(); return item ? Stack.toBool(item) : false; } removeBool(index) { const item = this.remove(index); return item ? Stack.toBool(item) : false; } setBool(index, value) { return this.set(index, Stack.fromBool(value)); } pushBool(value) { return this.push(Stack.fromBool(value)); } unshiftBool(value) { return this.unshift(Stack.fromBool(value)); } insertBool(index, value) { return this.insert(index, Stack.fromBool(value)); } /** * Test an object to see if it is a Stack. * @param {Object} obj * @returns {Boolean} */ static isStack(obj) { return obj instanceof Stack; } /* * Encoding */ static toString(item, enc) { assert(Buffer.isBuffer(item)); return item.toString(enc || 'utf8'); } static fromString(str, enc) { assert(typeof str === 'string'); return Buffer.from(str, enc || 'utf8'); } static toNum(item, minimal, limit) { return ScriptNum.decode(item, minimal, limit); } static fromNum(num) { assert(ScriptNum.isScriptNum(num)); return num.encode(); } static toInt(item, minimal, limit) { const num = Stack.toNum(item, minimal, limit); return num.getInt(); } static fromInt(int) { assert(typeof int === 'number'); if (int >= -1 && int <= 16) return common.small[int + 1]; const num = ScriptNum.fromNumber(int); return Stack.fromNum(num); } static toBool(item) { assert(Buffer.isBuffer(item)); for (let i = 0; i < item.length; i++) { if (item[i] !== 0) { // Cannot be negative zero if (i === item.length - 1 && item[i] === 0x80) return false; return true; } } return false; } static fromBool(value) { assert(typeof value === 'boolean'); return Stack.fromInt(value ? 1 : 0); } }
JavaScript
class Calculator { constructor(currentInputLabelTextElement, previousInputLabelTextElement) { this.currentInputLabelTextElement = currentInputLabelTextElement this.previousInputLabelTextElement = previousInputLabelTextElement this.clear() } clear() { this.currentLabel = '0'; this.previousLabel = ''; this.method = undefined allclearButtons.style.backgroundColor = 'gainsboro' allclearButtons.innerText = 'AC' } halfClear(){ if(this.previousInputLabelTextElement.innerText != ''){ this.previousLabel = this.currentInputLabelTextElement.innerText; this.currentLabel = this.previousLabel + undefined; } allclearButtons.style.backgroundColor = "orange"; allclearButtons.innerText = 'C'; } appendNumber(number) { if (number === '.' && this.currentLabel.includes('.')) return this.currentLabel = this.currentLabel.toString() + number.toString(); } chooseMethod(method) { if (this.currentLabel === '') return if (this.previousLabel !== '') { this.compute() } this.method = method; this.previousLabel = this.currentLabel; this.currentLabel = ''; } compute() { let computation const prev = parseFloat(this.previousLabel) const current = parseFloat(this.currentLabel) if (isNaN(prev) || isNaN(current)) return switch (this.method) { case '+': computation = prev + current; break case '-': computation = prev - current; break case 'x': computation = prev * current; break case 'รท': computation = prev / current; break case 'ยฑ': computation = -Number(current); break case '%': computation = current / 100; break default: return } this.currentLabel = computation this.method = undefined this.previousLabel = '' } getDisplayNumber(number) { const floatNumber = parseFloat(number) if(isNaN(floatNumber)) return '' return floatNumber.toString() // const stringNumber = number.toString() // const integerDigits = parseFloat(stringNumber.split('.')[0]) // const decimalDigits = stringNumber.split('.')[1] // let integerDisplay // if (isNaN(integerDigits)){ // integerDisplay = '' // } else { // integerDisplay = integerDigits.toLocaleString('en', {maximumFractionDigits: 0}) // } // if (decimalDigits != null){ // return `${integerDisplay}.${decimalDigits}` // } else { // return integerDisplay // } } updateDisplay() { this.currentInputLabelTextElement.innerText = this.getDisplayNumber(this.currentLabel) if(this.method == "ยฑ"){ this.currentInputLabelTextElement.innerText = `-` + `${this.getDisplayNumber(this.currentLabel)}`; this.previousInputLabelTextElement.innerText = `Please press a number to get minus value` } else if(this.method == '%'){ this.currentInputLabelTextElement.innerText = `${this.getDisplayNumber(this.currentLabel)}%`; this.previousInputLabelTextElement.innerText = `Please press a number for its % value` } else if (this.method != null) { this.previousInputLabelTextElement.innerText = `${this.getDisplayNumber(this.previousLabel)} ${(this.method)}` } else { this.previousInputLabelTextElement.innerText = 'ย ' } } }
JavaScript
class SMA extends Indicator { constructor(input) { super(input); this.period = input.period; this.price = input.values; var genFn = (function* (period) { var list = new LinkedList(); var sum = 0; var counter = 1; var current = yield; var result; list.push(0); while (true) { if (counter < period) { counter++; list.push(current); sum = sum + current; } else { sum = sum - list.shift() + current; result = ((sum) / period); list.push(current); } current = yield result; } }); this.generator = genFn(this.period); this.generator.next(); this.result = []; this.price.forEach((tick) => { var result = this.generator.next(tick); if (result.value !== undefined) { this.result.push(this.format(result.value)); } }); } nextValue(price) { var result = this.generator.next(price).value; if (result != undefined) return this.format(result); } ; }
JavaScript
class EMA extends Indicator { constructor(input) { super(input); var period = input.period; var priceArray = input.values; var exponent = (2 / (period + 1)); var sma$$1; this.result = []; sma$$1 = new SMA({ period: period, values: [] }); var genFn = (function* () { var tick = yield; var prevEma; while (true) { if (prevEma !== undefined && tick !== undefined) { prevEma = ((tick - prevEma) * exponent) + prevEma; tick = yield prevEma; } else { tick = yield; prevEma = sma$$1.nextValue(tick); if (prevEma) tick = yield prevEma; } } }); this.generator = genFn(); this.generator.next(); this.generator.next(); priceArray.forEach((tick) => { var result = this.generator.next(tick); if (result.value != undefined) { this.result.push(this.format(result.value)); } }); } nextValue(price) { var result = this.generator.next(price).value; if (result != undefined) return this.format(result); } ; }
JavaScript
class MACD extends Indicator { constructor(input) { super(input); var oscillatorMAtype = input.SimpleMAOscillator ? SMA : EMA; var signalMAtype = input.SimpleMASignal ? SMA : EMA; var fastMAProducer = new oscillatorMAtype({ period: input.fastPeriod, values: [], format: (v) => { return v; } }); var slowMAProducer = new oscillatorMAtype({ period: input.slowPeriod, values: [], format: (v) => { return v; } }); var signalMAProducer = new signalMAtype({ period: input.signalPeriod, values: [], format: (v) => { return v; } }); var format = this.format; this.result = []; this.generator = (function* () { var index = 0; var tick; var MACD, signal, histogram, fast, slow; while (true) { if (index < input.slowPeriod) { tick = yield; fast = fastMAProducer.nextValue(tick); slow = slowMAProducer.nextValue(tick); index++; continue; } if (fast && slow) { MACD = fast - slow; signal = signalMAProducer.nextValue(MACD); } histogram = MACD - signal; tick = yield ({ //fast : fast, //slow : slow, MACD: format(MACD), signal: signal ? format(signal) : undefined, histogram: isNaN(histogram) ? undefined : format(histogram) }); fast = fastMAProducer.nextValue(tick); slow = slowMAProducer.nextValue(tick); } })(); this.generator.next(); input.values.forEach((tick) => { var result = this.generator.next(tick); if (result.value != undefined) { this.result.push(result.value); } }); } nextValue(price) { var result = this.generator.next(price).value; return result; } ; }
JavaScript
class RSI extends Indicator { constructor(input) { super(input); var period = input.period; var values = input.values; var GainProvider = new AverageGain({ period: period, values: [] }); var LossProvider = new AverageLoss({ period: period, values: [] }); let count = 1; this.generator = (function* (period) { var current = yield; var lastAvgGain, lastAvgLoss, RS, currentRSI; while (true) { lastAvgGain = GainProvider.nextValue(current); lastAvgLoss = LossProvider.nextValue(current); if (lastAvgGain && lastAvgLoss) { if (lastAvgLoss === 0) { currentRSI = 100; } else { RS = lastAvgGain / lastAvgLoss; currentRSI = parseFloat((100 - (100 / (1 + RS))).toFixed(2)); } } else if (lastAvgGain && !lastAvgLoss) { currentRSI = 100; } else if (lastAvgLoss && !lastAvgGain) { currentRSI = 0; } else if (count >= period) { //if no average gain and average loss after the RSI period currentRSI = 0; } count++; current = yield currentRSI; } })(period); this.generator.next(); this.result = []; values.forEach((tick) => { var result = this.generator.next(tick); if (result.value !== undefined) { this.result.push(result.value); } }); } ; nextValue(price) { return this.generator.next(price).value; } ; }
JavaScript
class FixedSizeLinkedList extends LinkedList { constructor(size, maintainHigh, maintainLow) { super(); this.size = size; this.maintainHigh = maintainHigh; this.maintainLow = maintainLow; this.periodHigh = 0; this.periodLow = Infinity; if (!size || typeof size !== 'number') { throw ('Size required and should be a number.'); } this._push = this.push; this.push = function (data) { this.add(data); }; } add(data) { if (this.length === this.size) { this.lastShift = this.shift(); this._push(data); //TODO: FInd a better way if (this.maintainHigh) if (this.lastShift == this.periodHigh) this.calculatePeriodHigh(); if (this.maintainLow) if (this.lastShift == this.periodLow) this.calculatePeriodLow(); } else { this._push(data); } //TODO: FInd a better way if (this.maintainHigh) if (this.periodHigh <= data) (this.periodHigh = data); if (this.maintainLow) if (this.periodLow >= data) (this.periodLow = data); } *iterator() { this.resetCursor(); while (this.next()) { yield this.current; } } calculatePeriodHigh() { this.resetCursor(); if (this.next()) this.periodHigh = this.current; while (this.next()) { if (this.periodHigh <= this.current) { this.periodHigh = this.current; } } } calculatePeriodLow() { this.resetCursor(); if (this.next()) this.periodLow = this.current; while (this.next()) { if (this.periodLow >= this.current) { this.periodLow = this.current; } } } }
JavaScript
class WilderSmoothing extends Indicator { constructor(input) { super(input); this.period = input.period; this.price = input.values; var genFn = (function* (period) { var list = new LinkedList(); var sum = 0; var counter = 1; var current = yield; var result = 0; while (true) { if (counter < period) { counter++; sum = sum + current; result = undefined; } else if (counter == period) { counter++; sum = sum + current; result = sum; } else { result = result - (result / period) + current; } current = yield result; } }); this.generator = genFn(this.period); this.generator.next(); this.result = []; this.price.forEach((tick) => { var result = this.generator.next(tick); if (result.value != undefined) { this.result.push(this.format(result.value)); } }); } nextValue(price) { var result = this.generator.next(price).value; if (result != undefined) return this.format(result); } ; }
JavaScript
class MDM extends Indicator { constructor(input) { super(input); var lows = input.low; var highs = input.high; var format = this.format; if (lows.length != highs.length) { throw ('Inputs(low,high) not of equal size'); } this.result = []; this.generator = (function* () { var minusDm; var current = yield; var last; while (true) { if (last) { let upMove = (current.high - last.high); let downMove = (last.low - current.low); minusDm = format((downMove > upMove && downMove > 0) ? downMove : 0); } last = current; current = yield minusDm; } })(); this.generator.next(); lows.forEach((tick, index) => { var result = this.generator.next({ high: highs[index], low: lows[index] }); if (result.value !== undefined) this.result.push(result.value); }); } ; static calculate(input) { Indicator.reverseInputs(input); var result = new MDM(input).result; if (input.reversedInput) { result.reverse(); } Indicator.reverseInputs(input); return result; } ; nextValue(price) { return this.generator.next(price).value; } ; }
JavaScript
class PDM extends Indicator { constructor(input) { super(input); var lows = input.low; var highs = input.high; var format = this.format; if (lows.length != highs.length) { throw ('Inputs(low,high) not of equal size'); } this.result = []; this.generator = (function* () { var plusDm; var current = yield; var last; while (true) { if (last) { let upMove = (current.high - last.high); let downMove = (last.low - current.low); plusDm = format((upMove > downMove && upMove > 0) ? upMove : 0); } last = current; current = yield plusDm; } })(); this.generator.next(); lows.forEach((tick, index) => { var result = this.generator.next({ high: highs[index], low: lows[index] }); if (result.value !== undefined) this.result.push(result.value); }); } ; static calculate(input) { Indicator.reverseInputs(input); var result = new PDM(input).result; if (input.reversedInput) { result.reverse(); } Indicator.reverseInputs(input); return result; } ; nextValue(price) { return this.generator.next(price).value; } ; }
JavaScript
class PSAR extends Indicator { constructor(input) { super(input); let highs = input.high || []; let lows = input.low || []; var genFn = function* (step, max) { let curr, extreme, sar, furthest; let up = true; let accel = step; let prev = yield; while (true) { if (curr) { sar = sar + accel * (extreme - sar); if (up) { sar = Math.min(sar, furthest.low, prev.low); if (curr.high > extreme) { extreme = curr.high; accel = Math.min(accel + step, max); } } else { sar = Math.max(sar, furthest.high, prev.high); if (curr.low < extreme) { extreme = curr.low; accel = Math.min(accel + step, max); } } if ((up && curr.low < sar) || (!up && curr.high > sar)) { accel = step; sar = extreme; up = !up; extreme = !up ? curr.low : curr.high; } } else { // Randomly setup start values? What is the trend on first tick?? sar = prev.low; extreme = prev.high; } furthest = prev; if (curr) prev = curr; curr = yield sar; } }; this.result = []; this.generator = genFn(input.step, input.max); this.generator.next(); lows.forEach((tick, index) => { var result = this.generator.next({ high: highs[index], low: lows[index], }); if (result.value !== undefined) { this.result.push(result.value); } }); } ; nextValue(input) { let nextResult = this.generator.next(input); if (nextResult.value !== undefined) return nextResult.value; } ; }
JavaScript
class ADL extends Indicator { constructor(input) { super(input); var highs = input.high; var lows = input.low; var closes = input.close; var volumes = input.volume; if (!((lows.length === highs.length) && (highs.length === closes.length) && (highs.length === volumes.length))) { throw ('Inputs(low,high, close, volumes) not of equal size'); } this.result = []; this.generator = (function* () { var result = 0; var tick; tick = yield; while (true) { let moneyFlowMultiplier = ((tick.close - tick.low) - (tick.high - tick.close)) / (tick.high - tick.low); let moneyFlowVolume = moneyFlowMultiplier * tick.volume; result = result + moneyFlowVolume; tick = yield Math.round(result); } })(); this.generator.next(); highs.forEach((tickHigh, index) => { var tickInput = { high: tickHigh, low: lows[index], close: closes[index], volume: volumes[index] }; var result = this.generator.next(tickInput); if (result.value != undefined) { this.result.push(result.value); } }); } ; nextValue(price) { return this.generator.next(price).value; } ; }
JavaScript
class TRIX extends Indicator { constructor(input) { super(input); let priceArray = input.values; let period = input.period; let format = this.format; let ema$$1 = new EMA({ period: period, values: [], format: (v) => { return v; } }); let emaOfema = new EMA({ period: period, values: [], format: (v) => { return v; } }); let emaOfemaOfema = new EMA({ period: period, values: [], format: (v) => { return v; } }); let trixROC = new ROC({ period: 1, values: [], format: (v) => { return v; } }); this.result = []; this.generator = (function* () { let tick = yield; while (true) { let initialema = ema$$1.nextValue(tick); let smoothedResult = initialema ? emaOfema.nextValue(initialema) : undefined; let doubleSmoothedResult = smoothedResult ? emaOfemaOfema.nextValue(smoothedResult) : undefined; let result = doubleSmoothedResult ? trixROC.nextValue(doubleSmoothedResult) : undefined; tick = yield result ? format(result) : undefined; } })(); this.generator.next(); priceArray.forEach((tick) => { let result = this.generator.next(tick); if (result.value !== undefined) { this.result.push(result.value); } }); } nextValue(price) { let nextResult = this.generator.next(price); if (nextResult.value !== undefined) return nextResult.value; } ; }
JavaScript
class Renko extends Indicator { constructor(input) { super(input); var format = this.format; let useATR = input.useATR; let brickSize = input.brickSize || 0; if (useATR) { let atrResult = atr(Object.assign({}, input)); brickSize = atrResult[atrResult.length - 1]; } this.result = new CandleList(); if (brickSize === 0) { console.error('Not enough data to calculate brickSize for renko when using ATR'); return; } let lastOpen = 0; let lastHigh = 0; let lastLow = Infinity; let lastClose = 0; let lastVolume = 0; let lastTimestamp = 0; this.generator = (function* () { let candleData = yield; while (true) { //Calculating first bar if (lastOpen === 0) { lastOpen = candleData.close; lastHigh = candleData.high; lastLow = candleData.low; lastClose = candleData.close; lastVolume = candleData.volume; lastTimestamp = candleData.timestamp; candleData = yield; continue; } let absoluteMovementFromClose = Math.abs(candleData.close - lastClose); let absoluteMovementFromOpen = Math.abs(candleData.close - lastOpen); if ((absoluteMovementFromClose >= brickSize) && (absoluteMovementFromOpen >= brickSize)) { let reference = absoluteMovementFromClose > absoluteMovementFromOpen ? lastOpen : lastClose; let calculated = { open: reference, high: lastHigh > candleData.high ? lastHigh : candleData.high, low: lastLow < candleData.Low ? lastLow : candleData.low, close: reference > candleData.close ? (reference - brickSize) : (reference + brickSize), volume: lastVolume + candleData.volume, timestamp: candleData.timestamp }; lastOpen = calculated.open; lastHigh = calculated.close; lastLow = calculated.close; lastClose = calculated.close; lastVolume = 0; candleData = yield calculated; } else { lastHigh = lastHigh > candleData.high ? lastHigh : candleData.high; lastLow = lastLow < candleData.Low ? lastLow : candleData.low; lastVolume = lastVolume + candleData.volume; lastTimestamp = candleData.timestamp; candleData = yield; } } })(); this.generator.next(); input.low.forEach((tick, index) => { var result = this.generator.next({ open: input.open[index], high: input.high[index], low: input.low[index], close: input.close[index], volume: input.volume[index], timestamp: input.timestamp[index] }); if (result.value) { this.result.open.push(result.value.open); this.result.high.push(result.value.high); this.result.low.push(result.value.low); this.result.close.push(result.value.close); this.result.volume.push(result.value.volume); this.result.timestamp.push(result.value.timestamp); } }); } nextValue(price) { console.error('Cannot calculate next value on Renko, Every value has to be recomputed for every change, use calcualte method'); return null; } ; }
JavaScript
class HeikinAshi extends Indicator { constructor(input) { super(input); var format = this.format; this.result = new CandleList(); let lastOpen = null; let lastHigh = 0; let lastLow = Infinity; let lastClose = 0; let lastVolume = 0; let lastTimestamp = 0; this.generator = (function* () { let candleData = yield; let calculated = null; while (true) { if (lastOpen === null) { lastOpen = (candleData.close + candleData.open) / 2; lastHigh = candleData.high; lastLow = candleData.low; lastClose = (candleData.close + candleData.open + candleData.high + candleData.low) / 4; lastVolume = (candleData.volume || 0); lastTimestamp = (candleData.timestamp || 0); calculated = { open: lastOpen, high: lastHigh, low: lastLow, close: lastClose, volume: candleData.volume || 0, timestamp: (candleData.timestamp || 0) }; } else { let newClose = (candleData.close + candleData.open + candleData.high + candleData.low) / 4; let newOpen = (lastOpen + lastClose) / 2; let newHigh = Math.max(newOpen, newClose, candleData.high); let newLow = Math.min(candleData.low, newOpen, newClose); calculated = { close: newClose, open: newOpen, high: newHigh, low: newLow, volume: (candleData.volume || 0), timestamp: (candleData.timestamp || 0) }; lastClose = newClose; lastOpen = newOpen; lastHigh = newHigh; lastLow = newLow; } candleData = yield calculated; } })(); this.generator.next(); input.low.forEach((tick, index) => { var result = this.generator.next({ open: input.open[index], high: input.high[index], low: input.low[index], close: input.close[index], volume: input.volume ? input.volume[index] : input.volume, timestamp: input.timestamp ? input.timestamp[index] : input.timestamp }); if (result.value) { this.result.open.push(result.value.open); this.result.high.push(result.value.high); this.result.low.push(result.value.low); this.result.close.push(result.value.close); this.result.volume.push(result.value.volume); this.result.timestamp.push(result.value.timestamp); } }); } nextValue(price) { var result = this.generator.next(price).value; return result; } ; }
JavaScript
class HTTPResponseError extends Error { constructor(response, ...args) { super(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args); this.response = response; } }
JavaScript
class AppRouter extends React.Component { render() { return ( <BrowserRouter> <Switch> <div> <Route path="/login" exact render={() => ( <LoginGuard> <Login /> </LoginGuard> )} /> <Route path="/game" render={() => ( <GameGuard> <GameRouter base={"/game"}/> </GameGuard> )} /> <Route path="/" exact render={() => <Redirect to={"/game"}/>}/> <Route path="/register" render={() => ( <RegisterGuard> <RegisterRouter base={"/register"}/> </RegisterGuard> )} /> <Route path="/ownprofile" render={() => ( <OwnProfileGuard> <OwnProfileRouter base={"/ownprofile"}/> </OwnProfileGuard> )} /> <Route path="/registeredusers" render={() => ( <RegisteredUsersGuard> <RegisteredUsersRouter base={"/registeredusers"}/> </RegisteredUsersGuard> )} /> <Route path="/ruserprofile" render={() => ( <RUserProfileGuard> <RUserProfileRouter base={"/ruserprofile"}/> </RUserProfileGuard> )} /> </div> </Switch> </BrowserRouter> ); } }
JavaScript
class Pet { constructor(name) { this.name = name; this.age = minAge; this.hunger = minHunger; this.fitness = maxFitness; this.child = children; // If player wants pet to have a child (empty at start) } growUp() { if (!this.isAlive) { throw new Error(errorMessage); } this.age += birthday; this.hunger += nomNoms; this.fitness -= heProtecc; } walkies() { if (!this.isAlive) { throw new Error(errorMessage); } else if (this.fitness + walked <= maxFitness) { this.fitness += walked; } else { this.fitness = maxFitness; } } feed() { if (!this.isAlive) { throw new Error(errorMessage); } else if (this.hunger - fed >= minHunger) { this.hunger -= fed; } else { this.hunger = minHunger; } } checkUp() { const bored = this.fitness <= heProtecc; // less than or equal to 3 const hungry = this.hunger >= nomNoms; // more than or equal to 5 const sadgePet = bored && hungry; if (!this.isAlive) { throw new Error(errorMessage); } else if (sadgePet) { return "I am hungry ๐Ÿฒ and I need a walk ๐Ÿ•โ€๐Ÿฆบ"; } else if (bored) { return "I need a walk ๐Ÿ•โ€๐Ÿฆบ"; } else if (hungry) { return "I am hungry ๐Ÿฒ"; } else if (!sadgePet) { return "I feel great! ๐Ÿ˜ธ"; } } get isAlive() { if ( this.age >= maxAge || this.hunger >= maxHunger || this.fitness <= minFitness ) { return false; } else { return true; } } haveaBaby(childName) { return children.push(childName); // if (childName !== Object) { // return "The child needs to be an object data type!"; // } else if (childName === Object) { } adoptChild(childName) { return children.push(childName); } }
JavaScript
class BabyPet extends Pet { constructor(name) { super(name); this.name = name; } }
JavaScript
class Value extends Record(DEFAULTS) { /** * Create a new `Value` with `attrs`. * * @param {Object|Value} attrs * @param {Object} options * @return {Value} */ static create(attrs = {}, options = {}) { if (Value.isValue(attrs)) { return attrs } if (isPlainObject(attrs)) { return Value.fromJSON(attrs) } throw new Error(`\`Value.create\` only accepts objects or values, but you passed it: ${attrs}`) } /** * Create a dictionary of settable value properties from `attrs`. * * @param {Object|Value} attrs * @return {Object} */ static createProperties(attrs = {}) { if (Value.isValue(attrs)) { return { data: attrs.data, decorations: attrs.decorations, schema: attrs.schema, } } if (isPlainObject(attrs)) { const props = {} if ('data' in attrs) props.data = Data.create(attrs.data) if ('decorations' in attrs) props.decorations = Range.createList(attrs.decorations) if ('schema' in attrs) props.schema = Schema.create(attrs.schema) return props } throw new Error(`\`Value.createProperties\` only accepts objects or values, but you passed it: ${attrs}`) } /** * Create a `Value` from a JSON `object`. * * @param {Object} object * @param {Object} options * @property {Boolean} normalize * @property {Array} plugins * @return {Value} */ static fromJSON(object, options = {}) { let { document = {}, selection = {}, schema = {}, } = object let data = new Map() document = Document.fromJSON(document) selection = Range.fromJSON(selection) schema = Schema.fromJSON(schema) // Allow plugins to set a default value for `data`. if (options.plugins) { for (const plugin of options.plugins) { if (plugin.data) data = data.merge(plugin.data) } } // Then merge in the `data` provided. if ('data' in object) { data = data.merge(object.data) } if (selection.isUnset) { const text = document.getFirstText() if (text) selection = selection.collapseToStartOf(text) } let value = new Value({ data, document, selection, schema, }) if (options.normalize !== false) { value = value.change({ save: false }).normalize().value } return value } /** * Alias `fromJS`. */ static fromJS = Value.fromJSON /** * Check if a `value` is a `Value`. * * @param {Any} value * @return {Boolean} */ static isValue(value) { return !!(value && value[MODEL_TYPES.VALUE]) } /** * Object. * * @return {String} */ get object() { return 'value' } get kind() { logger.deprecate('[email protected]', 'The `kind` property of Slate objects has been renamed to `object`.') return this.object } /** * Are there undoable events? * * @return {Boolean} */ get hasUndos() { return this.history.undos.size > 0 } /** * Are there redoable events? * * @return {Boolean} */ get hasRedos() { return this.history.redos.size > 0 } /** * Is the current selection blurred? * * @return {Boolean} */ get isBlurred() { return this.selection.isBlurred } /** * Is the current selection focused? * * @return {Boolean} */ get isFocused() { return this.selection.isFocused } /** * Is the current selection collapsed? * * @return {Boolean} */ get isCollapsed() { return this.selection.isCollapsed } /** * Is the current selection expanded? * * @return {Boolean} */ get isExpanded() { return this.selection.isExpanded } /** * Is the current selection backward? * * @return {Boolean} isBackward */ get isBackward() { return this.selection.isBackward } /** * Is the current selection forward? * * @return {Boolean} */ get isForward() { return this.selection.isForward } /** * Get the current start key. * * @return {String} */ get startKey() { return this.selection.startKey } /** * Get the current end key. * * @return {String} */ get endKey() { return this.selection.endKey } /** * Get the current start offset. * * @return {String} */ get startOffset() { return this.selection.startOffset } /** * Get the current end offset. * * @return {String} */ get endOffset() { return this.selection.endOffset } /** * Get the current anchor key. * * @return {String} */ get anchorKey() { return this.selection.anchorKey } /** * Get the current focus key. * * @return {String} */ get focusKey() { return this.selection.focusKey } /** * Get the current anchor offset. * * @return {String} */ get anchorOffset() { return this.selection.anchorOffset } /** * Get the current focus offset. * * @return {String} */ get focusOffset() { return this.selection.focusOffset } /** * Get the current start text node's closest block parent. * * @return {Block} */ get startBlock() { return this.startKey && this.document.getClosestBlock(this.startKey) } /** * Get the current end text node's closest block parent. * * @return {Block} */ get endBlock() { return this.endKey && this.document.getClosestBlock(this.endKey) } /** * Get the current anchor text node's closest block parent. * * @return {Block} */ get anchorBlock() { return this.anchorKey && this.document.getClosestBlock(this.anchorKey) } /** * Get the current focus text node's closest block parent. * * @return {Block} */ get focusBlock() { return this.focusKey && this.document.getClosestBlock(this.focusKey) } /** * Get the current start text node's closest inline parent. * * @return {Inline} */ get startInline() { return this.startKey && this.document.getClosestInline(this.startKey) } /** * Get the current end text node's closest inline parent. * * @return {Inline} */ get endInline() { return this.endKey && this.document.getClosestInline(this.endKey) } /** * Get the current anchor text node's closest inline parent. * * @return {Inline} */ get anchorInline() { return this.anchorKey && this.document.getClosestInline(this.anchorKey) } /** * Get the current focus text node's closest inline parent. * * @return {Inline} */ get focusInline() { return this.focusKey && this.document.getClosestInline(this.focusKey) } /** * Get the current start text node. * * @return {Text} */ get startText() { return this.startKey && this.document.getDescendant(this.startKey) } /** * Get the current end node. * * @return {Text} */ get endText() { return this.endKey && this.document.getDescendant(this.endKey) } /** * Get the current anchor node. * * @return {Text} */ get anchorText() { return this.anchorKey && this.document.getDescendant(this.anchorKey) } /** * Get the current focus node. * * @return {Text} */ get focusText() { return this.focusKey && this.document.getDescendant(this.focusKey) } /** * Get the next block node. * * @return {Block} */ get nextBlock() { return this.endKey && this.document.getNextBlock(this.endKey) } /** * Get the previous block node. * * @return {Block} */ get previousBlock() { return this.startKey && this.document.getPreviousBlock(this.startKey) } /** * Get the next inline node. * * @return {Inline} */ get nextInline() { return this.endKey && this.document.getNextInline(this.endKey) } /** * Get the previous inline node. * * @return {Inline} */ get previousInline() { return this.startKey && this.document.getPreviousInline(this.startKey) } /** * Get the next text node. * * @return {Text} */ get nextText() { return this.endKey && this.document.getNextText(this.endKey) } /** * Get the previous text node. * * @return {Text} */ get previousText() { return this.startKey && this.document.getPreviousText(this.startKey) } /** * Get the characters in the current selection. * * @return {List<Character>} */ get characters() { return this.selection.isUnset ? new List() : this.document.getCharactersAtRange(this.selection) } /** * Get the marks of the current selection. * * @return {Set<Mark>} */ get marks() { return this.selection.isUnset ? new Set() : this.selection.marks || this.document.getMarksAtRange(this.selection) } /** * Get the active marks of the current selection. * * @return {Set<Mark>} */ get activeMarks() { return this.selection.isUnset ? new Set() : this.selection.marks || this.document.getActiveMarksAtRange(this.selection) } /** * Get the block nodes in the current selection. * * @return {List<Block>} */ get blocks() { return this.selection.isUnset ? new List() : this.document.getBlocksAtRange(this.selection) } /** * Get the fragment of the current selection. * * @return {Document} */ get fragment() { return this.selection.isUnset ? Document.create() : this.document.getFragmentAtRange(this.selection) } /** * Get the inline nodes in the current selection. * * @return {List<Inline>} */ get inlines() { return this.selection.isUnset ? new List() : this.document.getInlinesAtRange(this.selection) } /** * Get the text nodes in the current selection. * * @return {List<Text>} */ get texts() { return this.selection.isUnset ? new List() : this.document.getTextsAtRange(this.selection) } /** * Check whether the selection is empty. * * @return {Boolean} */ get isEmpty() { if (this.isCollapsed) return true if (this.endOffset != 0 && this.startOffset != 0) return false return this.fragment.text.length == 0 } /** * Check whether the selection is collapsed in a void node. * * @return {Boolean} */ get isInVoid() { if (this.isExpanded) return false return this.document.hasVoidParent(this.startKey) } /** * Create a new `Change` with the current value as a starting point. * * @param {Object} attrs * @return {Change} */ change(attrs = {}) { const Change = require('./change').default return new Change({ ...attrs, value: this }) } /** * Return a JSON representation of the value. * * @param {Object} options * @return {Object} */ toJSON(options = {}) { const object = { object: this.object, document: this.document.toJSON(options), } if (options.preserveData) { object.data = this.data.toJSON() } if (options.preserveDecorations) { object.decorations = this.decorations ? this.decorations.toArray().map(d => d.toJSON()) : null } if (options.preserveHistory) { object.history = this.history.toJSON() } if (options.preserveSelection) { object.selection = this.selection.toJSON() } if (options.preserveSchema) { object.schema = this.schema.toJSON() } if (options.preserveSelection && !options.preserveKeys) { const { document, selection } = this object.selection.anchorPath = selection.isSet ? document.getPath(selection.anchorKey) : null object.selection.focusPath = selection.isSet ? document.getPath(selection.focusKey) : null delete object.selection.anchorKey delete object.selection.focusKey } return object } /** * Alias `toJS`. */ toJS(options) { return this.toJSON(options) } }
JavaScript
class Complex{ constructor(real, imaginary = 0){ this._x = real; this._y = imaginary; } abs(){ return Math.sqrt(this._x * this._x + this._y * this._y); } arg(){ return Math.atan2(this._y, this._x); } radius(){ return this.abs(); } theta(){ return this.arg(); } re(){ return this._x; } im(){ return this._y; } add(complex){ return new Complex(this._x + complex._x, this._y + complex._y); } sub(complex){ return new Complex(this._x - complex._x, this._y - complex._y); } mul(complex){ return new Complex( this._x * complex._x - this._y * complex._y, this._x * complex._y + this._y * complex._x ); } mulByScalar(scalar){ return new Complex(this._x * scalar, this._y * scalar); } inv(){ const radiusSquared = this._x * this._x + this._y * this._y; return new Complex(this._x / radiusSquared, -this._y / radiusSquared); } div(complex){ return this.mul(complex.inv()); } pow(exponent){ const r = this.abs() ** exponent; const theta = this.arg() * exponent; return new Complex(r * Math.cos(theta), r * Math.sin(theta)); } normalize(){ const r = this.abs(); return new Complex(this._x / r, this._y / r); } toString(){ const sign = this._y < 0 ? "-" : "+"; return this._x + sign + Math.abs(this._y) + "i"; } copy(){ return new Complex(this._x, this._y); } }
JavaScript
class PageComments extends React.Component { constructor(props) { super(props); this.state = { // desc order array comments: [], isLayoutTypeCrowiPlus: false, // for deleting comment commentToDelete: undefined, isDeleteConfirmModalShown: false, errorMessageForDeleting: undefined, }; this.init = this.init.bind(this); this.confirmToDeleteComment = this.confirmToDeleteComment.bind(this); this.deleteComment = this.deleteComment.bind(this); this.showDeleteConfirmModal = this.showDeleteConfirmModal.bind(this); this.closeDeleteConfirmModal = this.closeDeleteConfirmModal.bind(this); } componentWillMount() { const pageId = this.props.pageId; if (pageId) { this.init(); } } init() { if (!this.props.pageId) { return ; } const pageId = this.props.pageId; const layoutType = this.props.crowi.getConfig()['layoutType']; this.setState({isLayoutTypeCrowiPlus: 'crowi-plus' === layoutType}); // get data (desc order array) this.props.crowi.apiGet('/comments.get', {page_id: pageId}) .then(res => { if (res.ok) { this.setState({comments: res.comments}); } }).catch(err => { }); } confirmToDeleteComment(comment) { this.setState({commentToDelete: comment}); this.showDeleteConfirmModal(); } deleteComment() { const comment = this.state.commentToDelete; this.props.crowi.apiPost('/comments.remove', {comment_id: comment._id}) .then(res => { if (res.ok) { this.findAndSplice(comment); } this.closeDeleteConfirmModal(); }).catch(err => { this.setState({errorMessageForDeleting: err.message}); }); } findAndSplice(comment) { let comments = this.state.comments; const index = comments.indexOf(comment); if (index < 0) { return; } comments.splice(index, 1); this.setState({comments}); } showDeleteConfirmModal() { this.setState({isDeleteConfirmModalShown: true}); } closeDeleteConfirmModal() { this.setState({ commentToDelete: undefined, isDeleteConfirmModalShown: false, errorMessageForDeleting: undefined, }); } /** * generate Elements of Comment * * @param {any} comments Array of Comment Model Obj * * @memberOf PageComments */ generateCommentElements(comments) { return comments.map((comment) => { return ( <Comment key={comment._id} comment={comment} currentUserId={this.props.crowi.me} currentRevisionId={this.props.revisionId} deleteBtnClicked={this.confirmToDeleteComment} /> ); }); } render() { let currentComments = []; let newerComments = []; let olderComments = []; let comments = this.state.comments; if (this.state.isLayoutTypeCrowiPlus) { // replace with asc order array comments = comments.slice().reverse(); // non-destructive reverse } // divide by revisionId and createdAt const revisionId = this.props.revisionId; const revisionCreatedAt = this.props.revisionCreatedAt; comments.forEach((comment) => { if (comment.revision == revisionId) { currentComments.push(comment); } else if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) { newerComments.push(comment); } else { olderComments.push(comment); } }); // generate elements const currentElements = this.generateCommentElements(currentComments); const newerElements = this.generateCommentElements(newerComments); const olderElements = this.generateCommentElements(olderComments); // generate blocks const currentBlock = ( <div className="page-comments-list-current" id="page-comments-list-current"> {currentElements} </div> ); const newerBlock = ( <div className="page-comments-list-newer collapse" id="page-comments-list-newer"> {newerElements} </div> ); const olderBlock = ( <div className="page-comments-list-older collapse in" id="page-comments-list-older"> {olderElements} </div> ); // generate toggle elements const iconForNewer = (this.state.isLayoutTypeCrowiPlus) ? <i className="fa fa-angle-double-down"></i> : <i className="fa fa-angle-double-up"></i>; const toggleNewer = (newerElements.length === 0) ? <div></div> : ( <a className="page-comments-list-toggle-newer text-center" data-toggle="collapse" href="#page-comments-list-newer"> {iconForNewer} Comments for Newer Revision {iconForNewer} </a> ); const iconForOlder = (this.state.isLayoutTypeCrowiPlus) ? <i className="fa fa-angle-double-up"></i> : <i className="fa fa-angle-double-down"></i>; const toggleOlder = (olderElements.length === 0) ? <div></div> : ( <a className="page-comments-list-toggle-older text-center" data-toggle="collapse" href="#page-comments-list-older"> {iconForOlder} Comments for Older Revision {iconForOlder} </a> ); // layout blocks const commentsElements = (this.state.isLayoutTypeCrowiPlus) ? ( <div> {olderBlock} {toggleOlder} {currentBlock} {toggleNewer} {newerBlock} </div> ) : ( <div> {newerBlock} {toggleNewer} {currentBlock} {toggleOlder} {olderBlock} </div> ); return ( <div> {commentsElements} <DeleteCommentModal isShown={this.state.isDeleteConfirmModalShown} comment={this.state.commentToDelete} errorMessage={this.state.errorMessageForDeleting} cancel={this.closeDeleteConfirmModal} confirmedToDelete={this.deleteComment} /> </div> ); } }
JavaScript
class ButtonGroupPicker extends Component { constructor(props) { super(props); this.groupNameId = this.props.name || uniqueId('options'); this.errorMessageId = uniqueId('error-message'); this.handleOnChange = this.handleOnChange.bind(this); } getErrorMessageId() { const { error } = this.props; if (error) { return this.errorMessageId; } return undefined; } getContext() { const { multiple, size, value } = this.props; return { onChange: this.handleOnChange, values: value, type: multiple ? 'checkbox' : 'radio', name: this.groupNameId, ariaDescribedBy: this.getErrorMessageId(), size, }; } handleOnChange(event) { const { value: eventValue, checked } = event.target; const { value, multiple, onChange } = this.props; if (!multiple) { return onChange(eventValue); } if (checked && Array.isArray(value)) { return onChange(value.concat([eventValue])); } if (checked && !Array.isArray(value)) { return onChange([eventValue]); } return onChange(value.filter(valueId => valueId !== eventValue)); } render() { const { id, className, style, label, children, error, bottomHelpText, required, } = this.props; const context = this.getContext(); return ( <StyledContainer id={id} className={className} style={style}> <RenderIf isTrue={!!label}> <StyledLegend> <RequiredAsterisk required={required} /> {label} </StyledLegend> </RenderIf> <StyledButtonGroup> <Provider value={context}>{children}</Provider> </StyledButtonGroup> <RenderIf isTrue={!!bottomHelpText}> <StyledHelpText>{bottomHelpText}</StyledHelpText> </RenderIf> <RenderIf isTrue={!!error}> <StyledErrorText id={this.getErrorMessageId()}>{error}</StyledErrorText> </RenderIf> </StyledContainer> ); } }
JavaScript
class Overlay { /** * Create a Overlay. * @property {string} inputLabel The label of the job input which is to be * used as an overlay. The Input must specify exactly one file. You can * specify an image file in JPG or PNG formats, or an audio file (such as a * WAV, MP3, WMA or M4A file), or a video file. See https://aka.ms/mesformats * for the complete list of supported audio and video file formats. * @property {moment.duration} [start] The start position, with reference to * the input video, at which the overlay starts. The value should be in ISO * 8601 format. For example, PT05S to start the overlay at 5 seconds in to * the input video. If not specified the overlay starts from the beginning of * the input video. * @property {moment.duration} [end] The position in the input video at which * the overlay ends. The value should be in ISO 8601 duration format. For * example, PT30S to end the overlay at 30 seconds in to the input video. If * not specified the overlay will be applied until the end of the input video * if inputLoop is true. Else, if inputLoop is false, then overlay will last * as long as the duration of the overlay media. * @property {moment.duration} [fadeInDuration] The duration over which the * overlay fades in onto the input video. The value should be in ISO 8601 * duration format. If not specified the default behavior is to have no fade * in (same as PT0S). * @property {moment.duration} [fadeOutDuration] The duration over which the * overlay fades out of the input video. The value should be in ISO 8601 * duration format. If not specified the default behavior is to have no fade * out (same as PT0S). * @property {number} [audioGainLevel] The gain level of audio in the * overlay. The value should be in the range [0, 1.0]. The default is 1.0. * @property {string} odatatype Polymorphic Discriminator */ constructor() { } /** * Defines the metadata of Overlay * * @returns {object} metadata of Overlay * */ mapper() { return { required: false, serializedName: 'Overlay', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: '@odata.type', clientName: 'odatatype' }, uberParent: 'Overlay', className: 'Overlay', modelProperties: { inputLabel: { required: true, serializedName: 'inputLabel', type: { name: 'String' } }, start: { required: false, serializedName: 'start', type: { name: 'TimeSpan' } }, end: { required: false, serializedName: 'end', type: { name: 'TimeSpan' } }, fadeInDuration: { required: false, serializedName: 'fadeInDuration', type: { name: 'TimeSpan' } }, fadeOutDuration: { required: false, serializedName: 'fadeOutDuration', type: { name: 'TimeSpan' } }, audioGainLevel: { required: false, serializedName: 'audioGainLevel', type: { name: 'Number' } }, odatatype: { required: true, serializedName: '@odata\\.type', isPolymorphicDiscriminator: true, type: { name: 'String' } } } } }; } }
JavaScript
class GLContext { constructor(options = {}) { this._canvas = options.canvas || document.createElement('canvas'); this._context = options.context || this._canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false }); let gl = this._context; if (gl == null) { throw new Error("WebGL not supported"); } // Tell WebGL how to convert from clip space to pixels gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // float texture extension try { this._floatExt = gl.getExtension('OES_texture_float'); } catch (e) { console.warn("No support for OES_texture_float extension!"); } // highp this._highp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); this._encode = new Encode(this); } get canvas() { return this._canvas; } /** * @returns {WebGLRenderingContext} */ get context() { return this._context; } get hasFloat() { return this._floatExt != null; } /** * This is first input tensor */ get input0() { return this._input0; } /** * Binds the first tensor * @param tensor */ set input0(tensor) { this._input0 = tensor; let gl = this.context; gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tensor.texture.texture); } get input1() { return this._input1; } set input1(tensor) { this._input1 = tensor; let gl = this.context; gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, tensor.texture.texture); } get input2() { return this._input2; } set input2(tensor) { this._input2 = tensor; let gl = this.context; gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, tensor.texture.texture); } get output() { return this._output; } /** * Binds a Tensor to the output. * Exec depends on the correct binding of output * @param tensor The output tensor */ set output(tensor) { this._output = tensor; let gl = this.context; let M = tensor.shape[0]; let N = tensor.shape[1]; this.canvas.height = M; if (tensor.isOutput) { this.canvas.width = N / 4; gl.viewport(0, 0, N, M); } else { this.canvas.width = N / 4; gl.viewport(0, 0, N / 4, M); } if (!this.framebuffer) { this.framebuffer = this.framebuffer || gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tensor.texture.texture, /*level*/0); } /** * Returns the currently activated program * @returns {WebGLProgram} */ get program() { return this._program; } /** * Sets the active program * @param value {WebGLProgram} */ set program(value) { this._program = value; this.context.useProgram(value.program); } /** * Executes a program to encode a tensor to output texture * @param tensor */ encode(tensor) { let outTensor = new WebGLTensor(null, tensor.shape, this, {isOutput: true}); let program = this._encode; this.program = program; program.X = tensor; program.Z = outTensor; program.exec(); let M = tensor.shape[0]; let N = tensor.shape[1]; return this.readData(M, N); } /* Read data out as unsigned bytes */ readData(M, N) { let gl = this.context; // create destination buffer let rawbuffer = new ArrayBuffer(M * N * Float32Array.BYTES_PER_ELEMENT); // read the result into our buffer, as bytes let prod = new Uint8Array(rawbuffer); gl.readPixels(0, 0, N, M, gl.RGBA, gl.UNSIGNED_BYTE, prod); // return raw result bytes return new Float32Array(rawbuffer); // M x N }; }
JavaScript
class FlightSearch extends Component { constructor(props) { super(props); moment.locale(document.documentElement.lang || 'en'); this.state = { pickLocation: 5761, pickDate: moment().day(DEFAULT_PICKUP_DAY_FROM_NOW_OFFSET), pickTime: '1000', returnLocation: 5761, returnDate: moment().day( DEFAULT_PICKUP_DAY_FROM_NOW_OFFSET + DEFAULT_RETURN_DAY_OFFSET ), returnTime: '1000', age: '25+', promotion: '', syncLocation: false, overlayDate: moment().day(DEFAULT_PICKUP_DAY_FROM_NOW_OFFSET), overlayVisible: false, currentDateKey: '', }; } componentDidMount = async () => { // check access_token if (!this.props.access_token) { await this.props.fetchToken(); } // check locations if (_.isEmpty(this.props.locations)) { await this.props.fetchLocations(); } // update state if conditions already existed (usually from result page) if (!_.isEmpty(this.props.conditions)) { const { pickLocation, returnLocation, pickDate, returnDate, pickTime, returnTime, age, syncLocation, promotion, } = this.props.conditions; this.setState({ pickLocation, returnLocation, pickDate: moment(pickDate), returnDate: moment(returnDate), pickTime, returnTime, age, promotion, syncLocation, }); } }; componentWillReceiveProps(nextProps) { // refetch token before expiration if (this.props.access_token !== nextProps.access_token) { setTimeout(() => { this.props.fetchToken(); }, nextProps.expires_in * 1000); } } onInputChange = ({ target }) => { const value = target.type === 'checkbox' ? target.checked : target.value; this.setState({ [target.name]: value, }); // sync return location if necessary if (target.name === 'pickLocation' && this.state.syncLocation) { this.setState({ returnLocation: value, }); } // sync checkbox logic if (target.name === 'syncLocation') { if (!value) { this.setState({ returnLocation: this.state.pickLocation, syncLocation: true, }); } else { this.setState({ syncLocation: false, }); } } }; onHandleSubmit = () => { const { pickLocation, returnLocation, pickDate, returnDate, pickTime, returnTime, age, syncLocation, promotion, } = this.state; const conditions = { pickLocation, returnLocation, pickDate: pickDate.format('YYYY-MM-DD'), returnDate: returnDate.format('YYYY-MM-DD'), pickTime, returnTime, age, syncLocation: syncLocation.toString(), promotion, }; this.props.updateSearchConditions(conditions); this.props.router.push(`/result?${querystring.stringify(conditions)}`); }; onDateOverlayToggle = ({ focused }) => { if (focused) { this.setState({ overlayVisible: true, }); } else { $('body').removeClass('body-noscrolling'); this.setState({ overlayVisible: false, }); } }; onDateOverlayVisible = (date, dateKeyName) => { $('body').addClass('body-noscrolling'); this.setState({ currentDateKey: dateKeyName, overlayDate: this.state[dateKeyName], overlayVisible: true, }); }; onDateChange = date => { this.setState({ overlayDate: date, [this.state.currentDateKey]: date, overlayVisible: false, }); if ( this.state.currentDateKey === 'pickDate' && date.isAfter(this.state.returnDate) ) { this.setState({ returnDate: moment(date).add(DEFAULT_RETURN_DAY_OFFSET, 'days'), }); } }; isOutsideRange = day => { if (this.state.currentDateKey === 'returnDate') { return ( day.isBefore(this.state.pickDate) || day.isAfter(moment().add(DEFAULT_CALENDAR_RANGE_MONTHS, 'months')) ); } return ( day.isBefore(moment()) || day.isAfter(moment().add(DEFAULT_CALENDAR_RANGE_MONTHS, 'months')) ); }; isDayHighlighted = date => { if (this.state.currentDateKey === 'pickDate') return false; if (moment(date).isSame(moment(this.state.pickDate))) { return true; } }; renderForm() { return ( <div className="row"> <LocationDropdown name="pickLocation" labelText="ๅ–่ฝฆๅŸŽๅธ‚" value={this.state.pickLocation} onInputChange={this.onInputChange} locations={this.props.locations} syncLocation={this.state.syncLocation} /> <LocationDropdown name="returnLocation" labelText="่ฟ˜่ฝฆๅŸŽๅธ‚" value={this.state.returnLocation} onInputChange={this.onInputChange} locations={this.props.locations} isDisabled={this.state.syncLocation} /> <DateTimeDropdown dateSelectName="pickDate" timeSelectName="pickTime" labelText="ๅ–่ฝฆๆ—ฅๆœŸๅŠๆ—ถ้—ด" onInputChange={this.onInputChange} dateValue={this.state.pickDate} timeValue={this.state.pickTime} onDateChange={this.onDateChange} onTimeChange={this.onInputChange} syncLocation={this.state.syncLocation} onDateOverlayVisible={this.onDateOverlayVisible} /> <DateTimeDropdown dateSelectName="returnDate" timeSelectName="returnTime" labelText="่ฟ˜่ฝฆๆ—ฅๆœŸๅŠๆ—ถ้—ด" onInputChange={this.onInputChange} dateValue={this.state.returnDate} timeValue={this.state.returnTime} onDateChange={this.onDateChange} onTimeChange={this.onInputChange} syncLocation={this.state.syncLocation} onDateOverlayVisible={this.onDateOverlayVisible} isDisabled={this.state.syncLocation} /> {/* <AgeDropdown name="age" value={this.state.age} onInputChange={this.onInputChange} /> <div className="col-12 col-lg-6"> <div className="input-box-wrap"> <label className={classNames(styles.labelStyle, styles.labelPadding)} > ๆ‰“ๆŠ˜็ (้€‰ๅกซ) </label> <div className={styles.inputBox}> <div className={classNames(styles.divInInput, styles.selectWrap)}> <input className={styles.inputInWrap} name="promotion" onChange={this.onInputChange} type="text" value={this.state.promotion} /> </div> </div> </div> </div> */} <div className={classNames(styles.searchButton, 'col-12')}> <button className="btn btn-block red lighten-1 rounded-0" onClick={this.onHandleSubmit} > ๆœ็ดข </button> </div> </div> ); } render() { // const md = new MobileDetect(window.navigator.userAgent); if (_.isEmpty(this.props.locations)) { return <Loading />; } return ( <div className={styles.searchContainer}> <div className={classNames(styles.divInRow, 'col')}> <div className="row"> <div className="col"> <div className={styles.searchWrap}>{this.renderForm()}</div> <div className={styles.dateOverlayWrap}> <SingleDatePicker id={'dateInput'} date={this.state.overlayDate} focused={this.state.overlayVisible} initialVisibleMonth={() => this.state.overlayDate} onDateChange={this.onDateChange} isDayHighlighted={this.isDayHighlighted} onFocusChange={this.onDateOverlayToggle} withPortal={true} // orientation={ // md.mobile() ? VERTICAL_ORIENTATION : HORIZONTAL_ORIENTATION // } numberOfMonths={1} isOutsideRange={this.isOutsideRange} /> </div> </div> </div> </div> </div> ); } }
JavaScript
class DBPushService extends PushService { /** * Please use DBPushService,register() * * @param {AsyncSteps} as - async step interface * @param {Executor} executor - related Executor * @param {object} [options={}] - options * @param {string} [options.event_table=default] - events table * @param {string} [options.consumer_table=default] - consumers table * @param {integer} [options.sleep_min=100] - minimal sleep on lack of events * @param {integer} [options.sleep_max=3000] - maximal sleep on lack of events * @param {integer} [options.sleep_step=100] - sleep time increase on lack of events */ constructor( as, executor, options ) { super( as, executor, options ); _defaults( options, { sleep_min: 100, sleep_max: 3000, sleep_step: 100, event_table: DB_EVTTABLE, consumer_table: DB_EVTCONSUMERS, } ); const ccm = executor.ccm(); this._ccm = ccm; ccm.assertIface( '#db.evt', DB_IFACEVER ); const qb = ccm.db( 'evt' ).queryBuilder(); this._evt_table = qb.identifier( options.event_table ); this._consumer_table = qb.identifier( options.consumer_table ); this._worker_as = null; this._sleep_min = options.sleep_min; this._sleep_max = options.sleep_max; this._sleep_step = options.sleep_step; this._sleep_curr = this._sleep_min; this._sleep_prev = 0; } _close() { if ( this._worker_as ) { this._worker_as.cancel(); this._worker_as = null; } super._close(); } _recordLastId( as, ident, last_id ) { const db = this._ccm.db( 'evt' ); const qb = db.update( this._consumer_table ); qb .set( { last_evt_id: last_id, last_time: qb.helpers().now(), } ) .where( { ident, 'last_evt_id <=': last_id, } ) .execute( as ); } _pokeWorker() { if ( this._worker_as ) { return; } const was = $as(); // startup was.loop( ( as ) => as.add( ( as ) => { const db = this._ccm.db( 'evt' ); db.select( this._evt_table ) .get( 'last_id', 'MAX(id)' ) .execute( as ); as.add( ( as, res ) => { const state = as.state; state.last_id = `${res.rows[0][0] || 0}`; as.break(); } ); }, ( as, err ) => { if ( err !== 'LoopBreak' ) { this._onPushError( as, err ); as.success(); } } ) ); // main loop was.loop( ( as ) => as.add( ( as ) => { if ( !this._echannels.size ) { this._worker_as = null; as.break(); } const db = this._ccm.db( 'evt' ); const MAX_EVENTS = this.MAX_EVENTS; const xfer = db.newXfer( db.SERIALIZABLE ); xfer.select( this._evt_table, { result: true } ) .get( [ 'id', 'type', 'data', 'ts' ] ) .where( 'id >', as.state.last_id ) .order( 'id' ) .limit( MAX_EVENTS ); xfer.execute( as ); as.add( ( as, res ) => { const events = this._res2events( res[0].rows, db.helpers() ); const elen = events.length; if ( elen ) { this._onEvents( events ); as.state.last_id = events[events.length - 1].id; } if ( elen >= MAX_EVENTS ) { let curr = this._sleep_curr - this._sleep_step; if ( curr < this._sleep_min ) { curr = this._sleep_min; } this._sleep_curr = curr; this._sleep_prev = 0; } else { let curr; // only if previous sleep was not enough if ( this._sleep_prev === this._sleep_curr ) { curr = this._sleep_curr + this._sleep_step; if ( curr > this._sleep_max ) { curr = this._sleep_max; } this._sleep_curr = curr; } else { curr = this._sleep_curr; } as.waitExternal(); setTimeout( () => { if ( this._worker_as === was ) { as.success(); } }, curr ); this._sleep_prev = curr; } } ); }, ( as, err ) => { if ( err !== 'LoopBreak' ) { this._onPushError( as, err ); as.success(); } } ) ); was.execute(); this._worker_as = was; } }
JavaScript
class App extends Component { render() { let message = "US Senators 2019"; let appClass = "container"; let senatorsElem = this.props.senators; return ( <div className={appClass}> <h1>{message}</h1> <SenatorTable senators={this.props.senators} />; </div> ); } }
JavaScript
class VolumeControl extends Component { constructor(player, options){ super(player, options); // hide volume controls when they're not supported by the current tech if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ createEl() { return super.createEl('div', { className: 'vjs-volume-control vjs-control' }); } }
JavaScript
class Plugin extends PuppeteerExtraPlugin { constructor(opts = {}) { super(opts) } get name() { return 'stealth/evasions/media.codecs' } async onPageCreated(page) { await page.evaluateOnNewDocument(() => { try { /** * Input might look funky, we need to normalize it so e.g. whitespace isn't an issue for our spoofing. * * @example * video/webm; codecs="vp8, vorbis" * video/mp4; codecs="avc1.42E01E" * audio/x-m4a; * audio/ogg; codecs="vorbis" * @param {String} arg */ const parseInput = arg => { const [mime, codecStr] = arg.trim().split(';') let codecs = [] if (codecStr && codecStr.includes('codecs="')) { codecs = codecStr .trim() .replace(`codecs="`, '') .replace(`"`, '') .trim() .split(',') .filter(x => !!x) .map(x => x.trim()) } return { mime, codecStr, codecs } } /* global HTMLMediaElement */ const canPlayType = { // Make toString() native get(target, key) { // Mitigate Chromium bug (#130) if (typeof target[key] === 'function') { return target[key].bind(target) } return Reflect.get(target, key) }, // Intercept certain requests apply: function(target, ctx, args) { if (!args || !args.length) { return target.apply(ctx, args) } const { mime, codecs } = parseInput(args[0]) // This specific mp4 codec is missing in Chromium if (mime === 'video/mp4') { if (codecs.includes('avc1.42E01E')) { return 'probably' } } // This mimetype is only supported if no codecs are specified if (mime === 'audio/x-m4a' && !codecs.length) { return 'maybe' } // This mimetype is only supported if no codecs are specified if (mime === 'audio/aac' && !codecs.length) { return 'probably' } // Everything else as usual return target.apply(ctx, args) } } HTMLMediaElement.prototype.canPlayType = new Proxy( HTMLMediaElement.prototype.canPlayType, canPlayType ) } catch (err) {} }) } }
JavaScript
class SearchBar extends Component { constructor(props) { super(props); this.state = { searchText: (new URLSearchParams(props.location.search)).get("searchText") || "", searchOptions: [], activeOptions: [], }; } componentDidMount() { const {userID, location} = this.props; const {searchText} = this.state; const { good, issues } = validateSearchQuery(searchText); if (good && (new URLSearchParams(location.search)).get("autoSearch") && searchText) { this.handleSearch(); } axios .get(`/api/getAllSearchableSkills`) .then((res) => { if (res && Array.isArray(res.data)) { const skills = res.data; this.setState( { searchOptions: Array.isArray(skills) ? skills.sort((a, b) => stringCompare(a.name, b.name)) : [] }, () => this.updateSearchOptions() ); } }); } /** * Get the last term in a search string * @param {String} searchText * @returns Lowercase last term in a search string */ getLastTerm(searchText) { // Split string on "|", "&", "!", "*", "(", and ")"; then remove leading/trailing whitespace and remove empty terms const searchTerms = searchText .toLowerCase() .split(/[|*&!()]+/) .map((term) => term.trim()); const trimmedSearchTerms = searchTerms.filter( (term, index) => term || index === searchTerms.length - 1 ); const lastTerm = trimmedSearchTerms.length > 0 ? trimmedSearchTerms[trimmedSearchTerms.length - 1] : ''; return lastTerm; } /** * Update active search options to match new search text. */ updateSearchOptions() { const { searchText, searchOptions } = this.state; const lastTerm = this.getLastTerm(searchText); const MAX_TERMS_TO_RENDER = 1000; const activeOptions = searchOptions .filter((option) => option.name.toLowerCase().includes(lastTerm)) .sort((a, b) => a.name.length - b.name.length) .filter((option, index) => index < MAX_TERMS_TO_RENDER) .sort((a, b) => stringCompare(a.name, b.name)) .sort((a, b) => a.name.indexOf(lastTerm) - b.name.indexOf(lastTerm)) .map(option => (option.display_name && option.display_name.toLowerCase() == option.name) ? option.display_name : option.name); this.setState({ activeOptions }); } /** * Update the appropriate values upon getting new search text. * @param {String} searchText */ setSearchText(searchText) { const {location, history} = this.props; this.setState({searchText}, () => { const search = (new URLSearchParams(location.search)); search.set("searchText", searchText); history.replace({search: search.toString()}); this.updateSearchOptions(); }) } /** * Call the "handleSearch" prop function */ handleSearch() { const { handleSearch } = this.props; const { searchText } = this.state; handleSearch(searchText); } /** * Handle autocomplete select * @param {*} event * @param {*} newValue * @param {*} reason */ onSearchChange(event, newValue, reason) { if (reason === 'select-option') { // Handle yet another odd edge case caused by poor autocomplete behavior if (newValue === undefined) { const { searchText } = this.state; this.setState({ searchText: '' }, () => this.setSearchText(searchText)); return; } // Cut last search term and replace const { searchText } = this.state; const lastTerm = this.getLastTerm(searchText); if (!lastTerm || searchText.toLowerCase().lastIndexOf(lastTerm) == -1) { // Handle select from empty string this.setSearchText(searchText + newValue); } else { const otherText = searchText.substring(0, searchText.toLowerCase().lastIndexOf(lastTerm)); // The multiple setState calls are necessary to deal with a buggy Autocomplete edge case where selecting an option but not updating // state causes the option to fill the text field rather than the correct controlled value. this.setState({ searchText: otherText }, () => this.setSearchText(otherText + newValue) ); } } } /** * Handle typed input * @param {*} event * @param {*} newValue * @param {*} reason */ onSearchInputChange(event, newValue, reason) { if (reason === 'input') { this.setSearchText(newValue); } } render() { const { searchText, activeOptions } = this.state; const { classes, searchLabelText, searchButtonText } = this.props; const { good, issues } = validateSearchQuery(searchText); return ( <Toolbar className={classes.searchToolbar}> <Grid container justify="space-between" alignItems="center"> <SearchIcon /> <Autocomplete freeSolo disableClearable options={activeOptions} value={searchText} className={classes.searchField} onChange={(event, newValue, reason) => this.onSearchChange(event, newValue, reason) } onInputChange={(event, newValue, reason) => this.onSearchInputChange(event, newValue, reason) } renderInput={(params) => ( <TextField {...params} label={`${searchLabelText}${ good ? '' : ` --- Warning: ${issues.join(', ')}` }`} margin="normal" variant="outlined" type="search" error={!good} /> )} /> <Button variant="contained" color="primary" onClick={() => { this.handleSearch(); }} disabled={!good || !searchText} > {searchButtonText} </Button> </Grid> </Toolbar> ); } }
JavaScript
class ViewInputPortCollectionItem extends BaseViewCollectionItem { /////////////////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS /////////////////////////////////////////////////////////////////////////////////////// /** * Initializes the instance. * * @param {object} options Marionette.View options object; 'options.workflow' (Workflow) and 'options.workflowjob' (WorkflowJob) must also be provided */ initialize(options) { this._workflow = options.workflow; this._workflowJob = options.workflowjob; } /////////////////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS /////////////////////////////////////////////////////////////////////////////////////// /** * Handle delete. */ _handleButtonDelete() { Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__WORKFLOWBUILDER_REMOVE_INPUTPORT, {inputport: this.model, workflow: this._workflow, workflowjob: this._workflowJob}); } }
JavaScript
class Item { /** * The constructor function of the item class * * @param {object} cell the constant cell values * @param {string} type the item type represented as a string * @param {number} x realtive x position of this item * @param {number} y the relative y position of this item * @param {number} ingoing the amount of ingoing connections * @param {number} step the corresponding description step * @param {number} id the corresponding item id used for dialog handling */ constructor(cell, type, x, y, ingoing, step, id) { this.s = cell.s; this.type = type; this.cell = cell; this.x = cell.left + x * cell.horBuf; this.y = cell.top + y * cell.verBuf; this.step = step; this.id = id; this.hover = false; this.clicked = false; this.active = false; this.negativeActivation = false; this.connections = []; this.maxIngoingConnections = ingoing; this.currentActivatedConnecions = 0; switch (type) { case 'fst': case 'lst': case 'sav': case 'rec': this.r = (cell.width)/20; break; case 'glt': case 'gft': this.r = (cell.width)/30; break; case 'crs': this.r = (cell.width)/50; break; default: this.r = (cell.width)/10; } } /** * This function is responsible for drawing the item on the * drawing canvas */ draw() { const s = this.s; let size = this.r; let imgSize = 0.6 * this.r; if (this.active || (s.cellAnim.back && this.negativeActivation)) { size = this.r * 1.2; imgSize = 0.6 * this.r * 1.2; } this.s.fill(s.colors.lightgrey); if (this.type === 'gft' || this.type === 'glt') { this.s.fill(s.colors.grey); } this.s.noStroke(); if (this.active || (s.cellAnim.back && this.negativeActivation)) { s.fill(s.colors.detail); } else if (this.currentActivatedConnecions !== 0) { s.fill(s.colors.detail); } if (this.hover && !(this.type === 'fst' || this.type === 'lst' || this.type === 'crs' || this.type === 'gft' || this.type === 'glt')) { s.fill(s.colors.detaillight); s.cursor(s.HAND); } const layer = s.clickedBlock; const hasPrev = layer ? (layer.i !== 1) : false; const hasNext = layer ? (layer.i !== layer.layers) : false; if ((this.type === 'gft' && hasPrev) || (this.type === 'glt' && hasNext)) { const w = 0.05 * s.width; const h = 0.8 * w; s.noStroke(); if (this.active || (s.cellAnim.back && this.negativeActivation)) { s.fill(s.colors.detail); } else { s.fill(s.colors.darkgrey); } s.rect(this.x, this.y, w, h); s.noStroke(); s.fill(s.colors.white); const left = this.x - w/2; const top = this.y - h/2; for (let i = 0; i < 5; i++) { s.ellipse(left + (i+1) * w / 6, top + h / 3, w / (i === 0 || i === 2 ? 20 : 10)); } s.rect(left + (3) * w / 6, top + 2 * h / 3, w / (10), w / (10)); } else if (this.type === 'cel') { this.s.rect(this.x, this.y, size, size); } else { this.s.ellipse(this.x, this.y, size); } switch (this.type) { case 'rec': this.s.image(this.s.receive, this.x, this.y, imgSize*2, imgSize*2); break; case 'add': this.s.image(this.s.add, this.x, this.y, imgSize, imgSize); break; case 'sav': this.s.image(this.s.save, this.x, this.y, imgSize*2, imgSize*2); break; case 'los': this.s.image(this.s.forget, this.x, this.y, imgSize, imgSize); break; case 'cel': this.s.image(this.s.cellImage, this.x, this.y, imgSize, imgSize); break; case 'out': this.s.image(this.s.output, this.x, this.y, imgSize, imgSize); break; default: } if (this.hover && !(this.type === 'fst' || this.type === 'lst' || this.type === 'crs' || this.type === 'gft' || this.type === 'glt')) { s.textAlign(s.CENTER, s.CENTER); s.fill(0, 150); s.rect(s.mx, s.my + s.typography.tooltipoffset, 110, 30); s.fill(255); s.text(this.s.global.strings.lstmGates[this.id].title, s.mx, s.my + s.typography.tooltipoffset ); } s.stroke(s.colors.lightgrey); s.strokeWeight(2); s.line(s.detailProps.right, 0, s.detailProps.right, s.detailProps.height); } /** * This function increases the amount of active inputs by one, if the * maximum amount of input activtaions is reached this item will fire * an activation trigger in the next update cycle */ addActiveInput() { this.currentActivatedConnecions += 1; } /** * This function sets the negativeActivation parameter to true, meaning it * will be displayed as active in the backprop animation */ addNegativeInput() { this.negativeActivation = true; } /** * Removes the current activations */ deactivate() { this.active = false; this.negativeActivation = false; this.currentActivatedConnecions = 0; } /** * This funtion will send an activation call to all outgoing connections * if the item has enough activation inputs */ sendActivations() { const s = this.s; if (this.active && this.connections && this.connections.length > 0) { if (this.type === 'glt') { s.cellAnim.inputStep++; if (s.cellAnim.inputStep === this.s.props.training.values) { s.cellAnim.inputStep = 0; s.cellAnim.predictionStep++; if (s.cellAnim.predictionStep >= this.s.props.training.predictions) { s.cellAnim.predictionStep = 0; s.cellAnim.error = true; s.cellAnim.forward = false; this.s.props = {...this.s.props, ui: {...this.s.props.ui, state: [false, true, false]}}; } } } for (const c of this.connections) { if (c) { c.addActiveInput(); } } } } /** * This function makes sure that the item is always correctly labeled * active or inactive and gets called at the end of each update cycle */ updateActivation() { const s = this.s; if (this.active) { this.active = false; this.currentActivatedConnecions = 0; } else { if (this.currentActivatedConnecions >= this.maxIngoingConnections) { this.active = true; if (this.step >= 0) { this.s.props = {...this.s.props, ui: {...this.s.props.ui, lstmStep: this.step}}; } if (this.type === 'gft') { s.cellAnim.step = 0; } else { s.cellAnim.step++; } } } } /** * This function is called if the user has moved the mouse across the * canvas and checks if this item is being hovered over * * @param {number} x the x position of the mouse cursor * @param {number} y the y position of the mouse cursor */ mouseMoved(x, y) { if (this.s.dist(x, y, this.x, this.y) < this.r/2) { this.hover = true; } else { this.hover = false; } if (this.type === 'gft' || this.type === 'glt') { this.hover = false; } for (const c of this.connections) { c.hover = this.hover; } } /** * This function is called when the user clicks on the canvas and checks * if the current item is being clicked on * * @return {boolean} true, if this item is being clicked on */ checkClick() { if (this.hover) { this.s.clickedItem = this; const dialogs = [false, false, false, false, false, false]; dialogs[this.id] = true; this.s.props.actions.updateAppState( {...this.s.props.appState, cellDialog: dialogs} ); } return this.clicked = this.hover; } }
JavaScript
class PressableWithSecondaryInteraction extends Component { constructor(props) { super(props); this.callSecondaryInteractionWithMappedEvent = this.callSecondaryInteractionWithMappedEvent.bind(this); this.executeSecondaryInteractionOnContextMenu = this.executeSecondaryInteractionOnContextMenu.bind(this); } componentDidMount() { if (this.props.forwardedRef && _.isFunction(this.props.forwardedRef)) { this.props.forwardedRef(this.pressableRef); } this.pressableRef.addEventListener('contextmenu', this.executeSecondaryInteractionOnContextMenu); } componentWillUnmount() { this.pressableRef.removeEventListener('contextmenu', this.executeSecondaryInteractionOnContextMenu); } /** * @param {Object} e */ callSecondaryInteractionWithMappedEvent(e) { if ((e.nativeEvent.state !== State.ACTIVE) || hasHoverSupport()) { return; } // Map gesture event to normal Responder event const { absoluteX, absoluteY, locationX, locationY, } = e.nativeEvent; const mapEvent = { ...e, nativeEvent: { ...e.nativeEvent, pageX: absoluteX, pageY: absoluteY, x: locationX, y: locationY, }, }; this.props.onSecondaryInteraction(mapEvent); } /** * @param {contextmenu} e - A right-click MouseEvent. * https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event */ executeSecondaryInteractionOnContextMenu(e) { const selection = SelectionScraper.getAsMarkdown(); e.stopPropagation(); if (this.props.preventDefaultContentMenu) { e.preventDefault(); } this.props.onSecondaryInteraction(e, selection); } render() { const defaultPressableProps = _.omit(this.props, ['onSecondaryInteraction', 'children', 'onLongPress']); // On Web, Text does not support LongPress events thus manage inline mode with styling instead of using Text. return ( <LongPressGestureHandler onHandlerStateChange={this.callSecondaryInteractionWithMappedEvent}> <Pressable style={this.props.inline && styles.dInline} onPressIn={this.props.onPressIn} onPressOut={this.props.onPressOut} onPress={this.props.onPress} ref={el => this.pressableRef = el} // eslint-disable-next-line react/jsx-props-no-spreading {...defaultPressableProps} > {this.props.children} </Pressable> </LongPressGestureHandler> ); } }
JavaScript
class AzureFileShareConfiguration { /** * Create a AzureFileShareConfiguration. * @property {string} accountName The Azure Storage account name. * @property {string} azureFileUrl The Azure Files URL. This is of the form * 'https://{account}.file.core.windows.net/'. * @property {string} accountKey The Azure Storage account key. * @property {string} relativeMountPath The relative path on the compute node * where the file system will be mounted. All file systems are mounted * relative to the Batch mounts directory, accessible via the * AZ_BATCH_NODE_MOUNTS_DIR environment variable. * @property {string} [mountOptions] Additional command line options to pass * to the mount command. These are 'net use' options in Windows and 'mount' * options in Linux. */ constructor() { } /** * Defines the metadata of AzureFileShareConfiguration * * @returns {object} metadata of AzureFileShareConfiguration * */ mapper() { return { required: false, serializedName: 'AzureFileShareConfiguration', type: { name: 'Composite', className: 'AzureFileShareConfiguration', modelProperties: { accountName: { required: true, serializedName: 'accountName', type: { name: 'String' } }, azureFileUrl: { required: true, serializedName: 'azureFileUrl', type: { name: 'String' } }, accountKey: { required: true, serializedName: 'accountKey', type: { name: 'String' } }, relativeMountPath: { required: true, serializedName: 'relativeMountPath', type: { name: 'String' } }, mountOptions: { required: false, serializedName: 'mountOptions', type: { name: 'String' } } } } }; } }
JavaScript
class ElementHandler { constructor(variantNum) { this.variantNum = variantNum } element(element) { if (this.variantNum === 0) { // First variant if (element.tagName === "title") { element.setInnerContent("Super Cool Website") } else if (element.tagName === "h1") { element.setInnerContent("Hi! My name is Masaki Asanuma.") } else if (element.tagName === "p") { element.setInnerContent("I am an aspiring full-stack developer currently studying Computer Science at Georgia Tech!") } else if (element.tagName === "a") { element.setAttribute("href", "https://findtheinvisiblecow.com/") element.setInnerContent("My favorite website I discovered in quarantine") } } else { // Second Variant if (element.tagName === "title") { element.setInnerContent("Hey what's up") } else if (element.tagName === "h1") { element.setInnerContent("How are you doing?") } else if (element.tagName === "p") { element.setInnerContent("This take-home project is SO much more fun compared to the stressful algorithmic interviews. Thank you cloudflare for this opportunity!") } else if (element.tagName === "a") { element.setAttribute("href", "https://pointerpointer.com/") element.setInnerContent("Here's a pretty cool website") } } } }
JavaScript
class UserUpdateParameters { /** * Create a UserUpdateParameters. * @member {string} [state] Account state. Specifies whether the user is * active or not. Blocked users are unable to sign into the developer portal * or call any APIs of subscribed products. Default state is Active. Possible * values include: 'active', 'blocked'. Default value: 'active' . * @member {string} [note] Optional note about a user set by the * administrator. * @member {array} [identities] Collection of user identities. * @member {string} [email] Email address. Must not be empty and must be * unique within the service instance. * @member {string} [password] User Password. * @member {string} [firstName] First name. * @member {string} [lastName] Last name. */ constructor() { } /** * Defines the metadata of UserUpdateParameters * * @returns {object} metadata of UserUpdateParameters * */ mapper() { return { required: false, serializedName: 'UserUpdateParameters', type: { name: 'Composite', className: 'UserUpdateParameters', modelProperties: { state: { required: false, serializedName: 'properties.state', defaultValue: 'active', type: { name: 'Enum', allowedValues: [ 'active', 'blocked' ] } }, note: { required: false, serializedName: 'properties.note', type: { name: 'String' } }, identities: { required: false, readOnly: true, serializedName: 'properties.identities', type: { name: 'Sequence', element: { required: false, serializedName: 'UserIdentityContractElementType', type: { name: 'Composite', className: 'UserIdentityContract' } } } }, email: { required: false, serializedName: 'properties.email', constraints: { MaxLength: 254, MinLength: 1 }, type: { name: 'String' } }, password: { required: false, serializedName: 'properties.password', type: { name: 'String' } }, firstName: { required: false, serializedName: 'properties.firstName', constraints: { MaxLength: 100, MinLength: 1 }, type: { name: 'String' } }, lastName: { required: false, serializedName: 'properties.lastName', constraints: { MaxLength: 100, MinLength: 1 }, type: { name: 'String' } } } } }; } }
JavaScript
class AmiInfoProvider extends CustomResourceProvider { /** * Constructor for the AmiInfoProvider class. * * @param {Object} log - The global logger from the Lambda handler * @constructor */ constructor(log) { super(RESOURCE_TYPE, RESOURCE_SCHEMA); this._logger = log; } /** * Get the ResourceType that is provided by this CustomResourceProvider implementation. * * @returns {string} - The ResourceType that is provided by this CustomResourceProvider implementation. */ static get RESOURCE_TYPE() { return (RESOURCE_TYPE); } /** * For AMI information, 'Create' simply fetches the current AMI information and returns it. * * @param {Object} event - the CloudFormation Custom Resource Request event. * @param {Object} context - the Lambda invocation context. * @returns {Promise} - A Promise of the response from the ResponseURL and other data related to the response. */ async Create(event, context) { let result = await this.getAmiInfo(event); return this.sendResponse(event, context, result.responseStatus, result.responseData); } /** * Called when the Delete RequestType is specified, this is a non-operation for AMI information, * so SUCCESS is simply responded. * * @param {Object} event - the CloudFormation Custom Resource Request event. * @param {Object} context - the Lambda invocation context. * @returns {Promise} - A Promise of the response from the ResponseURL and other data related to the response. */ async Delete(event, context) { return this.sendResponse(event, context, SUCCESS, { PhysicalResourceId: event.PhysicalResourceId }); } /** * For AMI information, 'Update' simply fetches the current AMI information and returns it. * * @param {Object} event - the CloudFormation Custom Resource Request event * @param {Object} context - the Lambda invocation context * @returns {Promise} - A Promise of the response from the ResponseURL and other data related to the response. */ async Update(event, context) { let result = await this.getAmiInfo(event); return this.sendResponse(event, context, result.responseStatus, result.responseData); } /** * Utilizes either parameter store or describeImages to get the AMI ID specified * by architecture or instance type. * * @param {Object} event - the CloudFormation Custom Resource Request event * @returns {Object} - An object with the CloudFormation response status and data. * @private */ async getAmiInfo(event) { // Validate the EC2 instance type if provided let properties = event.ResourceProperties; let instanceTypeArchitecture = architectureLookup(properties.InstanceType); if (properties.InstanceType && !instanceTypeArchitecture) { let msg = `Unsupported InstanceType '${properties.InstanceType}'`; return { responseStatus: FAILED, responseData: { PhysicalResourceId: NOT_CREATED, Reason: msg }}; } // Default the LinuxVersion to 'Linux2' if not set let linuxVersion = properties.LinuxVersion || 'Linux2'; // Architecture is the overriding property and we default to 'HVM' if not provided let architecture = properties.Architecture || instanceTypeArchitecture; // Use describeImages for the GPU specialized image, and Parameter Store for all others. This is done // because the Parameter Store is more accurate and faster, but it does not have the GPU specialized // AMI info in it. let results = await (architecture == 'HVM_GPU' ? this.getGpuAmiViaDescribeImages(linuxVersion, properties.Region) : this.getAmiViaParameterStore(architecture, linuxVersion, properties.Region)); return results; } /** * Get the AMI ID for the specified architecture, Amazon Linux version and region. Utilizes the * latest image info that Amazon stores in the SSM Parameter Store. * * @param {string} architecture - The virtulization architecture. * @param {string} linuxVersion - The Amazon Linux version, will be either 'Linux' or 'Linux2' * @param {string} region - The AWS region to get the image for. * @returns {Object} - An object with the CloudFormation response status and data. */ async getAmiViaParameterStore(architecture, linuxVersion, region) { let amiPath = (linuxVersion === 'Linux' ? ARCH_TO_AMZN_AMI_PATH.get(architecture) : ARCH_TO_AMZN2_AMI_PATH.get(architecture)); if (!amiPath) { return { responseStatus: FAILED, responseData: { Reason: `Invalid Architecture '${architecture}'` }}; } let responseStatus = FAILED; let responseData = {}; try { // Use the SSM Parameter Store to fetch the latest Amazon Linux version, it is region specific this._logger.info({ message: 'Using SSM Parameter Store to get AMI ID', architecture, linuxVersion, region }); let savedAwsConfig = AWS.config; AWS.config = { region: region }; let ssm = new AWS.SSM(); AWS.config = savedAwsConfig; let params = { Names: [amiPath] }; let results = await ssm.getParameters(params).promise(); let amiId = results.Parameters[0].Value; responseData.PhysicalResourceId = amiId; responseData.Data = { Id: amiId }; responseStatus = SUCCESS; } catch(err) { responseData = { PhysicalResourceId: NOT_CREATED, Reason: err.message }; } return { responseStatus, responseData }; } /** * Get the GPU specialized AMI image ID for the specified Amazon Linux version and region. * Utilizes describeImages to get the matching image. * * @param {string} linuxVersion - The Amazon Linux version, will be either 'Linux' or 'Linux2' * @param {string} region - The AWS region to get the image for. * @returns {Object} - An object with the CloudFormation response status and data. */ async getGpuAmiViaDescribeImages(linuxVersion, region) { let amiPattern = (linuxVersion === 'Linux' ? ARCH_TO_AMZN_GPU_AMI_PATTERN : ARCH_TO_AMZN2_GPU_AMI_PATTERN); let params = { Filters: [{ Name: 'name', Values: [amiPattern] }], Owners: ['679593333241'] }; let responseStatus = FAILED; let responseData = {}; try { this._logger.info({ message: 'Using describeImages() to get GPU specialized AMI ID', linuxVersion, region }); let ec2 = new AWS.EC2({region: region}); let describeImagesResult = await ec2.describeImages(params).promise(); let images = describeImagesResult.Images; // Sort images by name in descending order. The names contain the AMI version, formatted as YYYY.MM.Ver. images.sort(function(x, y) { return y.Name.localeCompare(x.Name); }); for (let image of images) { responseData.PhysicalResourceId = image.ImageId; responseData.Data = { Id: image.ImageId }; responseStatus = SUCCESS; break; } } catch(err) { responseData = { PhysicalResourceId: NOT_CREATED, Reason: err.message }; } return { responseStatus, responseData }; } }
JavaScript
class ReportNotFoundError extends Error { constructor() { super('Record not found'); } }
JavaScript
class FormService { static getInstance() { return this.instance; } constructor() { if (!this.instance) { this.instance = this; this.formSettings = $.fn.form.settings; } return this.instance; } /** * Setup semantic-ui form callback with this service. * @param settings */ setService(settings) { settings.rules.isVisible = this.isVisible; settings.rules.notEmpty = settings.rules.empty; settings.rules.isEqual = this.isEqual; } /** * Visibility rule. * * @returns {boolean | jQuery} */ isVisible() { return $(this).is(':visible'); } isEqual(value, compare) { return parseInt(value) === parseInt(compare); } /** * Validate a field using our own or semantic-ui validation rule function. * * @param form Form containing the field. * @param fieldName Name of field * @param rule Rule to apply test. * @returns {*|boolean} */ validateField(form, fieldName, rule) { rule = this.normalizeRule(rule); const ruleFunction = this.getRuleFunction(this.getRuleName(rule)); if (ruleFunction) { const $field = this.getField(form, fieldName); if (!$field) { console.log('You are validating a field that does not exist: ', fieldName); return false; } const value = this.getFieldValue($field); const ancillary = this.getAncillaryValue(rule); return ruleFunction.call($field, value, ancillary); } else { console.log('this rule does not exist: '+this.getRuleName(rule)); return false; } } normalizeRule(rule) { if (typeof rule === 'string') { return {type: rule, value:null}; } return rule; } getDefaultSelector() { return $.fn.form.settings.selector.group; } getContainer($field, selector){ const $container = $field.closest(selector); if ($container.length > 1) { //radio button. return this.getContainer($container.parent(), selector); } else if ($container.length === 0) { return null; } return $container; } getField(form, identifier) { if(form.find('#' + identifier).length > 0 ) { return form.find('#' + identifier); } else if( form.find('[name="' + identifier +'"]').length > 0 ) { return form.find('[name="' + identifier +'"]'); } else if( form.find('[name="' + identifier +'[]"]').length > 0 ) { return form.find('[name="' + identifier +'[]"]'); } return false; } getFieldValue($field) { let value; if ($field.length > 1) { // radio button. value = $field.filter(':checked').val(); } else { value = $field.val(); } return value; } getRuleFunction(rule) { return this.formSettings.rules[rule]; } getAncillaryValue(rule) { //must have a rule.value property and must be a bracketed rule. if(!rule.value && !this.isBracketedRule(rule)) { return false; } return (rule.value === undefined || rule.value === null) ? rule.type.match(this.formSettings.regExp.bracket)[1] + '' : rule.value ; } getRuleName(rule) { if( this.isBracketedRule(rule) ) { return rule.type.replace(rule.type.match(this.formSettings.regExp.bracket)[0], ''); } return rule.type; } isBracketedRule(rule) { return (rule.type && rule.type.match(this.formSettings.regExp.bracket)); } }
JavaScript
class AnotherChange extends BaseChange { static get _impl_deltaClass() { return MockDelta; } }
JavaScript
class AnotherSnapshot extends BaseSnapshot { constructor(revNum, contents) { super(revNum, contents); Object.freeze(this); } static get _impl_changeClass() { return MockChange; } }
JavaScript
class DomImage extends Canvas { /** * * @param {external:Image|HTMLImageElement} image DOM Image object */ constructor(image) { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; canvas.getContext('2d').drawImage(image, 0, 0); super(canvas); this.image = image; } /** * @inheritDoc */ prepareBlank(width, height) { return new this.constructor(new Image(width, height)); } /** * @inheritDoc */ sync() { super.sync(); return new Promise(resolve => { this.image.onload = () => resolve(this); this.image.src = this.canvas.toDataURL(); }); } /** * @inheritDoc */ resize(width, height) { return this.sync().then(() => { return new Promise(resolve => { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; canvas.getContext('2d').drawImage(this.image, 0, 0, this.width, this.height, 0, 0, width, height); const image = new Image(width, height); image.onload = () => { const resized = new this.constructor(image); resolve(resized); }; image.src = canvas.toDataURL(); }); }); } }
JavaScript
class ShipModel { constructor(id, name) { this.id = id; this.name = name; } }
JavaScript
class Ship extends AbstractModel { constructor(id = null, alias = '', model = null, insuranceCost = null, localisation = '', note = '', todoList = []) { super(); // Auto generate id this.id = id; this.alias = alias; // An ships models' id reference. this.model = model; this.insuranceCost = insuranceCost; this.localisation = localisation; this.note = note; // A list of things to do this.todoList = todoList; } /** * Add a task at the todo list. * * @param {string} description A description of the task. */ addTask(description = '') { this.todoList.push({ description: description, done: false }); } /** * Display note (translate markdown to html). */ displayNote() { return converter.makeHtml(this.note); } /** * Count tasks done. */ countTasksDone() { var tasksDone = 0; for (var i = 0; i < this.todoList.length; i++) { if (this.todoList[i].done) { tasksDone++; } } return tasksDone; } }
JavaScript
class StandardGraph1 extends AbstractSubject { /** * @param {!VarsList} varsList the VarsList to collect data from * @param {!LabCanvas} graphCanvas the LabCanvas where the graph should appear * @param {!Element} div_controls the HTML div where controls should be added * @param {!Element} div_graph the HTML div where the graphCanvas is located * @param {!SimRunner} simRun the SimRunner controlling the overall app * @param {string=} displayStyle the CSS display style to use when adding controls */ constructor(varsList, graphCanvas, div_controls, div_graph, simRun, displayStyle) { super('GRAPH_LAYOUT'); /** @type {string} */ this.displayStyle = displayStyle || 'block'; /** @type {!LabCanvas} */ this.canvas = graphCanvas; simRun.addCanvas(graphCanvas); /** @type {!SimView} */ this.view = new SimView('X_Y_GRAPH_VIEW', new DoubleRect(0, 0, 1, 1)); this.view.setHorizAlign(HorizAlign.FULL); this.view.setVerticalAlign(VerticalAlign.FULL); graphCanvas.addView(this.view); /** @type {!DisplayList} */ this.displayList = this.view.getDisplayList(); /** @type {!GraphLine} */ this.line = new GraphLine('X_Y_GRAPH_LINE', varsList); this.line.setXVariable(0); this.line.setYVariable(1); this.line.setColor('lime'); this.view.addMemo(this.line); /** @type {!DisplayAxes} */ this.axes = CommonControls.makeAxes(this.view); var updateAxes = goog.bind(function(evt) { if (evt.nameEquals(GraphLine.en.X_VARIABLE)) { this.axes.setHorizName(this.line.getXVarName()); } if (evt.nameEquals(GraphLine.en.Y_VARIABLE)) { this.axes.setVerticalName(this.line.getYVarName()); } }, this); new GenericObserver(this.line, updateAxes, 'update axes names'); updateAxes(new GenericEvent(this.line, GraphLine.i18n.X_VARIABLE)); /** @type {!AutoScale} */ this.autoScale = new AutoScale('X_Y_AUTO_SCALE', this.line, this.view); this.autoScale.extraMargin = 0.05; /** @type {!DisplayGraph} */ this.displayGraph = new DisplayGraph(this.line); this.displayGraph.setScreenRect(this.view.getScreenRect()); // Use off-screen buffer because usually the autoScale doesn't change the area. this.displayGraph.setUseBuffer(true); this.displayList.prepend(this.displayGraph); // inform displayGraph when the screen rect changes. new GenericObserver(this.view, goog.bind(function(evt) { if (evt.nameEquals(LabView.SCREEN_RECT_CHANGED)) { this.displayGraph.setScreenRect(this.view.getScreenRect()); } }, this), 'resize DisplayGraph'); /** @type {!Array<!LabControl>} */ this.controls_ = []; /** @type {!Element} */ this.div_controls = div_controls; this.addControl(CommonControls.makePlaybackControls(simRun)); /** @type {!ParameterNumber} */ var pn = this.line.getParameterNumber(GraphLine.en.Y_VARIABLE); this.addControl(new ChoiceControl(pn, 'Y:')); pn = this.line.getParameterNumber(GraphLine.en.X_VARIABLE); this.addControl(new ChoiceControl(pn, 'X:')); this.addControl(new ButtonControl(GraphLine.i18n.CLEAR_GRAPH, goog.bind(this.line.reset, this.line))); /** @type {!ParameterString} */ var ps = this.line.getParameterString(GraphLine.en.GRAPH_COLOR); this.addControl(new ChoiceControl(ps, /*label=*/undefined, GraphColor.getChoices(), GraphColor.getValues())); pn = this.line.getParameterNumber(GraphLine.en.LINE_WIDTH); this.addControl(new NumericControl(pn)); ps = this.line.getParameterString(GraphLine.en.DRAWING_MODE); this.addControl(new ChoiceControl(ps)); /** SimController which pans the graph with no modifier keys pressed. * @type {!SimController} */ this.graphCtrl = new SimController(graphCanvas, /*eventHandler=*/null, /*panModifier=*/{alt:false, control:false, meta:false, shift:false}); var panzoom = CommonControls.makePanZoomControls(this.view, /*overlay=*/true, /*resetFunc=*/goog.bind(function() { this.autoScale.setActive(true); },this)); div_graph.appendChild(panzoom); /** @type {!ParameterBoolean} */ var pb = CommonControls.makeShowPanZoomParam(panzoom, this); this.addControl(new CheckBoxControl(pb)); }; /** @override */ toString() { return Util.ADVANCED ? '' : this.toStringShort().slice(0, -1) +', canvas: '+this.canvas.toStringShort() +', view: '+this.view.toStringShort() +', line: '+this.line.toStringShort() +', axes: '+this.axes.toStringShort() +', autoScale: '+this.autoScale.toStringShort() +', displayGraph: '+this.displayGraph.toStringShort() +', graphCtrl: '+this.graphCtrl.toStringShort() + super.toString(); }; /** @override */ getClassName() { return 'StandardGraph1'; }; /** @override */ getSubjects() { return [ this, this.line, this.view, this.autoScale ]; }; /** Add the control to the set of simulation controls. * @param {!LabControl} control * @return {!LabControl} the control that was passed in */ addControl(control) { var element = control.getElement(); element.style.display = this.displayStyle; this.div_controls.appendChild(element); this.controls_.push(control); return control; }; } // end class
JavaScript
class BuildingMdl { constructor(args) { this.building_id = args.building_id; this.name = args.name; this.num_class = args.num_class; this.longitude = args.longitude; this.latitude = args.latitude; this.exist = args.exist; } /** * [params returns an array the contains the valido * column names for the building table] * @type {Array} */ static get validColumns() { const params = [ 'building_id', 'name', 'num_class', 'latitude', 'longitude', 'exist', ]; return params; } /** * [processResult Method used for processing items * that are building objects] * @method processResult * @param {Array} data [is an array that represents different * building objects, normally obtained form the DB] * @return {Array} [An array containing all the building objects * normally from DB] */ static processResult(data) { this.result = []; data.forEach((res) => { this.result.push(new BuildingMdl(res)); }); return this.result; } /** * [validBuilding method used for validating a building id] * @method validBuilding * @param {Number} id [represents a building id] * @return {Promise} [returns diferent then undefined if found] */ static async validBuilding(id) { await db.get('building', 'building_id', `building_id = ${id}`) .then((results) => { this.result = results.length; }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } /** * [getAll method used for obtaining all the buildings * from the building table from the DB] * @method getAll * @return {Promise} [Returns an array containing all the building objects] */ static async getAll() { const condition = ''; await db.get('building', '*', condition) .then((results) => { this.result = BuildingMdl.processResult(results); }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } /** * [get Method used to retrieve building form the DB * on specified conditions and columns] * @method get * @param {[String]} columns [A string array the represents the columns from the * building table] * @param {Number} id [Number representing the id form building] * @param {[String]} condition [An array of strings that represents the specified conditions * for obtaining buildings form the building table] * @return {Promise} [returns the specified building or buildings] */ static async get(columns, id, condition) { let query = `building_id = ${id}`; if (condition) { query += condition; } await db.get('building', columns, query) .then((results) => { this.result = results; }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } /** * [save method used for saving a building object * into the building table in the DB] * @method save * @return {Promise} [if diferent then undefined there were no problems * saving into the DB] */ async save() { console.log(this); await db.insert('building', this) .then((results) => { this.result = results; return this.result; }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } /** * [update method used for updating a building object * from the DB on s specified id] * @method update * @param {Number} id [represents the id of a specified building] * @return {Promise} [if diferent then undefined, signifies it was succesfull] */ async update(id) { const condition = `building_id = ${id}`; await db.update('building', this, condition) .then((results) => { this.result = results; return this.result; }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } /** * [logicalDel method used for deleting a specified building * object from the DB logically, it makes exist = 0] * @method logicalDel * @param {Number} id [represents the id of a specified building] * @return {Promise} [if diferent then undefined, signifies it was succesfull] */ async logicalDel(id) { const condition = `building_id = ${id}`; await db.logicalDel('building', condition) .then((results) => { this.result = results; return this.result; }) .catch(e => console.error(`We have a error!(${e})`)); return this.result; } }
JavaScript
class Randomizer { constructor(node_id, node_resource, node_map, _playing_in_slot) { const _self = this; const AUTO_PLAY = true; const ONLY_USE_CONNECTED_SLOTS = false; this.get_element = function () { return this.html; }; this.remove_element = function() { this.html.remove(); }; this.play_forward_from = function(slot_idx){ slot_idx = safeInt(slot_idx); if ( this.slots_map.hasOwnProperty(slot_idx) ) { var next = this.slots_map[slot_idx]; play_node(next.id, next.slot); } else { handle_status(_CONSOLE_STATUS_CODE.END_EDGE, _self); } this.set_view_played(slot_idx); }; this.play_forward_randomly = function(){ var slots_count = -1; if ( ONLY_USE_CONNECTED_SLOTS !== true && this.node_resource.hasOwnProperty("data") && this.node_resource.data.hasOwnProperty("slots") ){ slots_count = safeInt( this.node_resource.data.slots ); } if ( slots_count < 0 ){ slots_count = Object.keys(this.slots_map).length; } var random_out_slot_idx = inclusiveRandInt(0, (slots_count - 1) ); this.play_forward_from(random_out_slot_idx); }; this.skip_play = function() { this.html.setAttribute('data-skipped', true); // Randomizes anyway this.play_forward_randomly(); }; this.set_view_played = function(slot_idx){ this.html.setAttribute('data-played', true); }; this.set_view_unplayed = function(){ this.html.setAttribute('data-played', false); }; this.step_back = function(){ this.set_view_unplayed(); }; this.proceed = function(){ // Randomly play one of the outgoing slots // whether we are handling skip, if (this.node_map.hasOwnProperty("skip") && this.node_map.skip == true){ this.skip_play(); // or auto-playing } else if ( AUTO_PLAY ) { this.play_forward_randomly(); } }; if ( node_id >= 0 ){ if ( typeof node_resource == 'object' && typeof node_map == 'object' ){ // Sort stuff this.node_id = node_id; this.node_resource = node_resource; this.node_map = node_map; this.slots_map = remap_connections_for_slots( (node_map || {}), node_id ); // Create the node html element this.html = create_node_base_html(node_id, node_resource); // ... and the children this.randomizer_button = create_element("button", node_resource.name); this.randomizer_button.addEventListener( _CLICK, this.play_forward_randomly.bind(_self) ); this.html.appendChild( this.randomizer_button ); } return this; } throw new Error("Unable to construct `Randomizer`"); } }
JavaScript
class StuffItemAdmin extends React.Component { render() { return ( <Table.Row> <Table.Cell>{this.props.stuff.name}</Table.Cell> <Table.Cell>{this.props.stuff.quantity}</Table.Cell> <Table.Cell>{this.props.stuff.condition}</Table.Cell> <Table.Cell>{this.props.stuff.owner}</Table.Cell> </Table.Row> ); } }
JavaScript
class Debouncer { constructor(connection) { this.connection = connection; this.interval_id = null; this.last_written = null; } /** * Internal method used for the event scheduler. */ interval_event() { if (this.last_written) { this.connection.send(JSON.stringify(this.last_written)); if (this.last_written.should_resend) { if (!this.last_written.should_resend()) { this.last_written = null; } } else { this.last_written = null; } } else { clearInterval(this.interval_id); this.interval_id = null; } } /** * Sends or schedules a message for sending. */ send(message) { if (this.interval_id == null) { this.connection.send(JSON.stringify(message)); const captured = this; this.interval_id = setInterval(function () { captured.interval_event(); }, 100); } else { this.last_written = message; } } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = { projects: [ { name: "Project 1", description: "Project 1 test des", }, { name: "Project 2", description: "Project 2 test des", }, ], }; this.handleSubmit = this.handleSubmit.bind(this); // any method using this keyword must bind // example: this.method = this.method.bind(this) } handleSubmit = (project) => { this.setState({ projects: [...this.state.projects, project], }); }; /* removeProject = (index) => { const { projects } = this.state; this.setState({ projects: projects.filter((project, i) => { return i !== index; }), }); }; */ render() { const { projects } = this.state; return ( <div className="App"> <div className="container-fluid"> <SideBar /> <CreateProjectForm handleSubmit={this.handleSubmit} /> <RowProjectCard projectData={projects} /> <Filter /> <UserProfile /> <UserInfo /> <UserProject /> </div> </div> ); } }
JavaScript
class Light { constructor(scene) { this.scene = scene; this.init(); } init() { // Ambient this.ambientLight = new THREE.AmbientLight(Config.ambientLight.color); this.ambientLight.visible = Config.ambientLight.enabled; // Point light this.pointLight = new THREE.PointLight(Config.pointLight.color, Config.pointLight.intensity, Config.pointLight.distance); this.pointLight.position.set(Config.pointLight.x, Config.pointLight.y, Config.pointLight.z); this.pointLight.visible = Config.pointLight.enabled; // Directional light this.directionalLight = new THREE.DirectionalLight(Config.directionalLight.color, Config.directionalLight.intensity); this.directionalLight.position.set(Config.directionalLight.x, Config.directionalLight.y, Config.directionalLight.z); this.directionalLight.visible = Config.directionalLight.enabled; // Shadow map this.directionalLight.castShadow = Config.shadow.enabled; this.directionalLight.shadow.bias = Config.shadow.bias; this.directionalLight.shadow.camera.near = Config.shadow.near; this.directionalLight.shadow.camera.far = Config.shadow.far; this.directionalLight.shadow.camera.left = Config.shadow.left; this.directionalLight.shadow.camera.right = Config.shadow.right; this.directionalLight.shadow.camera.top = Config.shadow.top; this.directionalLight.shadow.camera.bottom = Config.shadow.bottom; this.directionalLight.shadow.mapSize.width = Config.shadow.mapWidth; this.directionalLight.shadow.mapSize.height = Config.shadow.mapHeight; // Hemisphere light this.hemiLight = new THREE.HemisphereLight(Config.hemiLight.color, Config.hemiLight.groundColor, Config.hemiLight.intensity); this.hemiLight.position.set(Config.hemiLight.x, Config.hemiLight.y, Config.hemiLight.z); this.hemiLight.visible = Config.hemiLight.enabled; } place(lightName) { switch(lightName) { case 'ambient': this.scene.add(this.ambientLight); break; case 'directional': this.scene.add(this.directionalLight); break; case 'point': this.scene.add(this.pointLight); break; case 'hemi': this.scene.add(this.hemiLight); break; } } }
JavaScript
class AesEncryption { /** Creates a new AesEncryption object. * @param {String} [mode=cbc] Optional, the AES mode (cbc or cfb) * @param {Number} [size=128] Optional, the key size (128, 192 or 256) * @param {Number} [keyIterations=2048] * @throws {Error} if the mode is not supported or key size is invalid. */ constructor(mode, size,keyIterations) { mode = (mode === undefined) ? 'cbc' : mode.toLowerCase(); size = (size === undefined) ? 256 : size; keyIterations = (keyIterations === undefined) ? 2048 : keyIterations; if (!AES.Modes.hasOwnProperty(mode)) { throw Error(mode + ' is not supported!') } if (AES.Sizes.indexOf(size) === -1) { throw Error('Invalid key size!') } this._keyLen = size / 8; this._cipher = AES.Modes[mode].replace('size', size); this._masterKey = null; this.keyIterations = keyIterations; this.base64 = true; } /** * Encrypts data using a key or the supplied password. * * The password is not required if the master key has been set - * either with `randomKeyGen` or with `setMasterKey`. * If a password is supplied, it will be used to create a key with PBKDF2. * * @param {(Buffer|String)} data The plaintext. * @param {String} [password=null] Optional, the password. * @return {(Buffer|String)} Encrypted data (salt + iv + ciphertext + mac). */ encrypt(data, password) { const startTime = +(new Date()) const salt = randomBytes(saltLen); const iv = randomBytes(ivLen); try { const _keys = keys.call(this, salt, password); const aesKey = _keys[0], macKey = _keys[1]; const aes = cipher.call(this, aesKey, iv, AES.Encrypt); const ciphertext = Buffer.concat( [iv, aes.update(data), aes.final()] ); const mac = sign(ciphertext, macKey); let encrypted = Buffer.concat([salt, ciphertext, mac]); if (this.base64) { encrypted = encrypted.toString('base64'); } console.log("encrypt time: ",+(new Date()) - startTime) return encrypted; } catch (err) { this._errorHandler(err); return null; } } /** * Decrypts data using a key or the supplied password. * * The password is not required if the master key has been set - * either with `randomKeyGen` or with `setMasterKey`. * If a password is supplied, it will be used to create a key with PBKDF2. * * @param {(Buffer|String)} data The ciphertext. * @param {String} [password=null] Optional, the password. * @return {(Buffer|String)} Plaintext. */ decrypt(data, password) { try { const startTime = +(new Date()) if (this.base64) { data = Buffer.from(data, 'base64') } const salt = data.slice(0, saltLen); const iv = data.slice(saltLen, saltLen + ivLen); const ciphertext = data.slice(saltLen + ivLen, -macLen); const mac = data.slice(-macLen, data.length); const _keys = keys.call(this, salt, password); const aesKey = _keys[0], macKey = _keys[1]; verify(Buffer.concat([iv, ciphertext]), mac, macKey); const aes = cipher.call(this, aesKey, iv, AES.Decrypt); const plaintext = Buffer.concat( [aes.update(ciphertext), aes.final()] ); console.log("decrypt time: ",+(new Date()) - startTime) return plaintext.toString(); } catch (err) { this._errorHandler(err); return null; } } /** * Sets a new master key. * This key will be used to create the encryption and authentication keys. * * @param {(Buffer|String)} key The new master key. * @param {Boolean} [raw=false] Optional, expexts raw bytes (not base64-encoded). */ setMasterKey(key, raw) { try { key = (raw !== true) ? Buffer.from(key, 'base64') : key; if (!(key instanceof Buffer)) { throw Error('Key must be a Buffer!'); } this._masterKey = key; } catch (err) { this._errorHandler(err); } } /** * Returns the master key (or null if the key is not set). * * @param {Boolean} [raw=false] Optional, returns raw bytes (not base64-encoded). * @return {(Buffer|String)} The master key. */ getMasterKey(raw) { if (this._masterKey === null) { this._errorHandler(new Error('The key is not set!')); } else if (raw !== true) { return this._masterKey.toString('base64'); } return this._masterKey; } /** * Generates a new random key. * This key will be used to create the encryption and authentication keys. * * @param {Number} [keyLen=32] Optional, the key size. * @param {Boolean} [raw=false] Optional, returns raw bytes (not base64-encoded). * @return {(Buffer|String)} The new master key. */ randomKeyGen(keyLen, raw) { keyLen = (keyLen !== undefined) ? keyLen : 32; this._masterKey = randomBytes(keyLen); if (raw !== true) { return this._masterKey.toString('base64'); } return this._masterKey; } /** * Handles exceptions (prints the error message by default). */ _errorHandler(error) { console.log(error.message); } }
JavaScript
class InstanciaFilmeService { constructor(snackBar, http) { this.snackBar = snackBar; this.http = http; this.baseUrl = "http://localhost:8080/instancias"; } showMessage(msg, isError = false) { this.snackBar.open(msg, "Fechar", { duration: 3000, horizontalPosition: "center", verticalPosition: "top" }); } create(instancia) { return this.http.post(this.baseUrl, instancia).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["map"])((obj) => obj), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])(e => this.errorHandler(e))); } read() { return this.http.get(this.baseUrl).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["map"])((obj) => obj), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])(e => this.errorHandler(e))); } readById(id) { const url = `${this.baseUrl}/${id}`; return this.http.get(url).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["map"])((obj) => obj), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])(e => this.errorHandler(e))); } update(instancia) { const url = `${this.baseUrl}/${instancia.id}`; return this.http.put(url, instancia).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["map"])((obj) => obj), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])(e => this.errorHandler(e))); } deleteById(instancia) { const url = `${this.baseUrl}/${instancia.id}`; return this.http.delete(url).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["map"])((obj) => obj), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])(e => this.errorHandler(e))); } errorHandler(e) { console.log(e); this.showMessage('Algo deu errado :\\', true); return rxjs__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]; } stringToDate(dateStr) { dateStr = dateStr.slice(0, 10); let year = dateStr.split("-")[0], month = dateStr.split("-")[1], day = dateStr.split("-")[2]; let date = new Date(Number(year), Number(month), Number(day)); return date; } }
JavaScript
class CdkTreeNodeOutlet { /** * @param {?} viewContainer * @param {?=} _node */ constructor(viewContainer, _node) { this.viewContainer = viewContainer; this._node = _node; } }
JavaScript
class RaddecRelayUdp { /** * RaddecRelayUdp constructor * @param {Object} options The options as a JSON object. * @constructor */ constructor(options) { let self = this; options = options || {}; this.handleRaddec = options.raddecHandler; this.enableHandling = (typeof this.handleRaddec === 'function'); this.enableForwarding = DEFAULT_ENABLE_FORWARDING; if(options.hasOwnProperty('enableForwarding')) { this.enableForwarding = options.enableForwarding; } this.dnsRefreshMilliseconds = options.dnsRefreshMilliseconds || DEFAULT_DNS_REFRESH_MILLISECONDS; this.raddecEncodingOptions = options.raddecEncodingOptions || DEFAULT_RADDEC_ENCODING_OPTIONS; let sources = options.sources || DEFAULT_SOURCES; let targets = options.targets || DEFAULT_TARGETS; this.sources = []; sources.forEach(function(source) { source.port = source.port || DEFAULT_RADDEC_PORT; if(source.hasOwnProperty('address')) { self.sources.push(createRaddecListener(self, source.address, source.port)); } }); this.targets = []; targets.forEach(function(target) { target.port = target.port || DEFAULT_RADDEC_PORT; if(target.hasOwnProperty('address')) { self.targets.push(target); } }); let hasValidTargets = (this.targets.length > 0); this.enableForwarding &= hasValidTargets; this.resolvedHostnames = new Map(); this.client = dgram.createSocket({ type: 'udp4', lookup: lookup }); // Look up and resolve the given hostname (like dns.lookup() with memory). // TODO: support IPv6 and full set of options in future function lookup(hostname, options, callback) { let isLookupRequired = !self.resolvedHostnames.has(hostname); let isRefreshRequired = false; let resolution; if(!isLookupRequired) { resolution = self.resolvedHostnames.get(hostname); let elapsedTime = Date.now() - resolution.timestamp; isRefreshRequired = (elapsedTime > self.dnsRefreshMilliseconds); } if(isLookupRequired || isRefreshRequired) { dns.lookup(hostname, options, function(err, address, family) { if(err) { return callback(err); } resolution = { address: address, family: family, timestamp: Date.now() }; self.resolvedHostnames.set(hostname, resolution); return callback(null, address, family); }); } else { return callback(null, resolution.address, resolution.family); } } } /** * Relay the given raddec. * @param {Raddec} raddec The given Raddec instance. * @param {Array} targetIndices The optional indices of targets to relay to. */ relayRaddec(raddec, targetIndices) { let self = this; let raddecHex = raddec.encodeAsHexString(this.raddecEncodingOptions); let raddecBuffer = Buffer.from(raddecHex, 'hex'); let observeTargetIndices = Array.isArray(targetIndices); this.targets.forEach(function(target, targetIndex) { let ignoreTarget = false; if(observeTargetIndices && !targetIndices.includes(targetIndex)) { ignoreTarget = true; } if(!ignoreTarget) { self.client.send(raddecBuffer, target.port, target.address, function(err) { }); } }); } /** * Handle the given source raddec depending on the relay configuration. * @param {Raddec} raddec The given Raddec instance. */ handleSourceRaddec(raddec) { if(this.enableForwarding) { this.relayRaddec(raddec); } if(this.enableHandling) { this.handleRaddec(raddec); } } }
JavaScript
class Task { /** * Constructs a new <code>Task</code>. * Background operation started on the server. It&#39;s the client mission to check it on a regular basis. * @alias module:model/Task * @class */ constructor() { } /** * Constructs a <code>Task</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Task} obj Optional instance to populate. * @return {module:model/Task} The populated <code>Task</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Task(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('status')) { obj['status'] = ApiClient.convertToType(data['status'], 'Number'); } if (data.hasOwnProperty('label')) { obj['label'] = ApiClient.convertToType(data['label'], 'String'); } if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); } if (data.hasOwnProperty('userId')) { obj['userId'] = ApiClient.convertToType(data['userId'], 'String'); } if (data.hasOwnProperty('wsId')) { obj['wsId'] = ApiClient.convertToType(data['wsId'], 'String'); } if (data.hasOwnProperty('actionName')) { obj['actionName'] = ApiClient.convertToType(data['actionName'], 'String'); } if (data.hasOwnProperty('schedule')) { obj['schedule'] = TaskSchedule.constructFromObject(data['schedule']); } if (data.hasOwnProperty('parameters')) { obj['parameters'] = ApiClient.convertToType(data['parameters'], Object); } } return obj; } /** * @member {String} id */ id = undefined; /** * @member {Number} status */ status = undefined; /** * @member {String} label */ label = undefined; /** * @member {String} description */ description = undefined; /** * @member {String} userId */ userId = undefined; /** * @member {String} wsId */ wsId = undefined; /** * @member {String} actionName */ actionName = undefined; /** * @member {module:model/TaskSchedule} schedule */ schedule = undefined; /** * @member {Object} parameters */ parameters = undefined; }
JavaScript
class UIComponentPrototype extends Phaser.Events.EventEmitter { static get EVENT_STATE() { return _EVENT_STATE; } /** * @param {PhaserComps.UIComponents.UIComponentPrototype} parent * @param {String} key */ constructor(parent, key) { super(); /** * @type {String} */ this._lockId = null; /** * * @type {UIComponentPrototype} * @private */ this._parent = parent; /** * * @type {String} * @protected */ this._key = key; /** * * @type {PhaserComps.ComponentClip} * @protected */ this._clip = null; /** * * @type {Object<String>} * @private */ this._texts = {}; if (key && parent) { // sign on parents state update parent.on(_EVENT_STATE, this._onEventState, this); } this._clipUpdate(); } /** * @public * @method PhaserComps.UIComponents.UIComponentPrototype#appendClip * @description * Append a instance to this to control it. State setup will be processed immediately.<br> * Use only for root instance, child instances will be appended automatically depending on state of this. * @param {PhaserComps.ComponentClip} clip ComponentView instance to append */ appendClip(clip) { if (this._clip === clip) { return; } if (this._clip !== null) { this.removeClip(); } this._clip = clip; if (this._clip) { this.onClipAppend(this._clip); } this._clipProcess(); } /** @return {String} */ get lockId() { return this._lockId; } /** * @return {Phaser.Geom.Rectangle} */ get lockClipBounds() { return null; } // override /** @return {Phaser.GameObjects.GameObject|*} */ get lockClip() { return null; } // override /** @param {string} value */ set lockId(value) { if (this._lockId === value) { return; } if (this._lockId) { PhaserComps.UIManager.unregister(this); } this._lockId = value; if (this._lockId) { PhaserComps.UIManager.register(this); } } /** * Override this, if you want to do something, when new clip removed, * @method PhaserComps.UIComponents.UIComponentPrototype#onClipAppend * @protected * @param {PhaserComps.ComponentClip} clip */ onClipAppend(clip) { // override me } /** * @public * @method PhaserComps.UIComponents.UIComponentPrototype#removeClip * @protected */ removeClip() { this.onClipRemove(this._clip); this._clip = null; } /** * Override this, if you want to do something, when new clip removed, * like remove clip events listeners. * @method PhaserComps.UIComponents.UIComponentPrototype#onClipRemove * @protected * @param clip */ onClipRemove(clip) { // override me } /** * Call doState to setup new state, id is provided by [getStateId]{@link PhaserComps.UIComponents.UIComponentPrototype#getStateId} * @method PhaserComps.UIComponents.UIComponentPrototype#doState * @protected * @see #getStateId */ doState() { let stateId = this.getStateId(); this._setupState(stateId); } /** * Returns saved text by key, if it was set previously * @method PhaserComps.UIComponents.UIComponentPrototype#getText * @param {String} key * @returns {String|Array<String>} text value */ getText(key) { return this._texts[key]; } /** * Set text value to the textfield with provided key. * Text value is saved in the component's instance dictionary and will be set to the textField on every state change * @method PhaserComps.UIComponents.UIComponentPrototype#setText * @param {String} key TextField key * @param {String|Array<String>} text text string */ setText(key, text) { if (this._texts[key] === text) { return; } this._texts[key] = text; if (this._clip) { let textField = this._clip.getChildText(key); if (textField) { textField.text = text; } } } /** * @method PhaserComps.UIComponents.UIComponentPrototype#getStateId * @description * Current state id, used by [doState]{@link PhaserComps.UIComponents.UIComponentPrototype#doState} method * @returns {String} * @protected */ getStateId() { return "default"; } /** * Destroy ComponentPrototype and clip, if exists * @method PhaserComps.UIComponents.UIComponentPrototype#destroy * @protected * @param {Boolean} [fromScene=false] */ destroy(fromScene) { if (this._parent){ this._parent.removeListener(_EVENT_STATE, this._onEventState); } if (this._clip) { this._clip.destroy(fromScene); } super.destroy(); } /** * @method PhaserComps.UIComponents.UIComponentPrototype#_clipUpdate * @private */ _clipUpdate() { if (!this._key) { // parent is clip itself } else { if (this._parent._clip) { let clip = this._parent._clip.getChildClip(this._key); this.appendClip(clip); } else { this.appendClip(null); } } } /** * @method PhaserComps.UIComponents.UIComponentPrototype#_clipProcess * @private */ _clipProcess() { if (!this._clip) { return; } this.doState(); this.onClipProcess(); } /** * Override this, if you want to do something, when state or clip changes. * @method PhaserComps.UIComponents.UIComponentPrototype#onClipProcess * @protected * @override */ onClipProcess() { // override me } /** * @method PhaserComps.UIComponents.UIComponentPrototype#_setupState * @param {String} stateId state id to setup * @private */ _setupState(stateId) { if (this._clip) { this._clip.setState(stateId); // update textfields for (let textKey in this._texts) { let textField = this._clip.getChildText(textKey); if (textField) { textField.text = this._texts[textKey]; } } } this.emit(_EVENT_STATE); } /** * Parent state change listener * @method PhaserComps.UIComponents.UIComponentPrototype#_onEventState * @private */ _onEventState() { this._clipUpdate(); } }
JavaScript
class BottomChoiceSelection extends Component { constructor(props) { super(props); this.state = { animationTrack: new Animated.Value(0), modalHeight: 1000, unclickable: false }; } onClose() { this.setState({ unclickable: true }); // closing animation Animated.timing( this.state.animationTrack, { toValue: 0, duration: 200, useNativeDriver: true } ).start(() => { // then trigger onClose from the parent this.props.onClose(); this.setState({ unclickable: false }); }); } componentDidUpdate(prevProps) { if (this.props.isVisible && !prevProps.isVisible) { this.setState({ unclickable: true }); // enter animation Animated.timing( this.state.animationTrack, { toValue: 1, duration: 200, useNativeDriver: true } ).start(() => { this.setState({ unclickable: false }); }); } } render() { const { isVisible, backgroundColor = AYEZ_GREEN, title, buttons = [] } = this.props; const animatePosition = (this.state.animationTrack.interpolate({ inputRange: [ 0, 1 ], outputRange: [ this.state.modalHeight, 0 ] })); const buttonComponents = buttons.map(({ text, action, buttonColor, textColor }) => <BlockButton key={text} onPress={() => { action(); this.onClose() }} text={text.toUpperCase()} color={buttonColor || 'white'} style={{ marginTop: 10, marginBottom: 10 }} textStyle={{ color: (textColor || backgroundColor) }} /> ) if (!isVisible) { return null; } return ( <View style={{ position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, elevation: 1000 }} > <AnimatedTouchableOpacity onPress={this.onClose.bind(this)} style={{ opacity: this.state.animationTrack, backgroundColor: 'rgba(255, 255, 255, 0.8)', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0 }} disabled={this.state.unclickable} activeOpacity={1} /> <Animated.View style={{ backgroundColor, position: 'absolute', bottom: 0, left: 0, right: 0, paddingTop: 20, paddingLeft: 20, paddingRight: 20, paddingBottom: 30, transform: [ { translateY: animatePosition } ] }} onLayout={(event) => { const {x, y, width, height} = event.nativeEvent.layout; this.setState({ modalHeight: height }); }} > <AyezText bold color={'white'} style={{ textAlign: 'center', padding: 6, paddingRight: 10, paddingLeft: 10 }}>{title}</AyezText> {buttonComponents} </Animated.View> </View> ); } }
JavaScript
class Client extends SendStuff { // socket: Socket; // lobby: Lobby; // room: Room; // account: IAccount; // profile: IProfile; // halfpack: Buffer; // used internally in packet.ts // entity: PlayerEntity; ping; constructor(socket, type = 'tcp') { super(socket, type); this.type = type; this.socket = socket; this.lobby = null; // no lobby // these are the objects that contain all the meaningful data this.account = null; // account info this.profile = null; // gameplay info this.ping = -1; } // some events onJoinLobby(lobby) { this.sendJoinLobby(lobby); } onRejectLobby(lobby, reason) { if (!reason) reason = 'lobby is full!'; this.sendRejectLobby(lobby, reason); } onLeaveLobby(lobby) { this.sendKickLobby(lobby, 'you left the lobby!', false); } onKickLobby(lobby, reason, forced) { if (!reason) reason = ''; if (forced === null || forced === undefined) forced = true; this.sendKickLobby(lobby, reason, forced); } onPlay() { if (!this.profile) { if (!global.config.necessary_login) { var room = this.lobby.rooms.find(room => { return room.map.name === global.config.starting_room; }); } else { console.error('non-logged in player entering the playing state! if it\'s intentional, please disable config.necessary_login'); return -1; } } else if (this.profile) { // load the room from profile var room = this.lobby.rooms.find(room => { return room.map.name === this.profile.room; }); } room.addPlayer(this); this.sendPlay(this.lobby, room, this.entity.pos, this.entity.uuid); } onDisconnect() { this.save(); if (this.lobby !== null) this.lobby.kickPlayer(this, 'disconnected', true); } // preset functions below // this one saves everything save() { if (this.account !== null) { this.account.save(function (err) { if (err) { trace('Error while saving account: ' + err); } else { trace('Saved the account successfully'); } }); } if (this.profile !== null) { this.profile.save(function (err) { if (err) { trace('Error while saving profile: ' + err); } else { trace('Saved the profile successfully.'); } }); } } register(account) { this.account = account; this.profile = freshProfile(account); // this.save() returns a Promise this.save(); this.sendRegister('success'); } login(account) { this.account = account; Profile.findOne({ account_id: this.account._id }).then((profile) => { if (profile) { this.profile = profile; this.sendLogin('success'); } else { trace('Error: Couldn\'t find a profile with these credentials!'); } }); } }
JavaScript
class LottoSelectPanel extends Component { constructor(props) { super(props); this.keyUpHandle = this.keyUpHandle.bind(this); this.isModalDisplay = this.isModalDisplay.bind(this); } componentWillMount() { document.body.addEventListener('keyup', this.keyUpHandle, false); } componentWillUnmount() { document.body.removeEventListener('keyup', this.keyUpHandle, false); } keyUpHandle(event) { if (!this.isModalDisplay()) return; if (event.key === 'Escape') { window.location = "#"; return; } if (event.target.tabIndex < this.props.startNumber) return; if (event.key === 'Enter' || event.key === ' ') { this.clickDOM(event); return; } if (event.key.startsWith('Arrow')) { this.moveFocus(event); } } isModalDisplay() { return window.location.hash == "#" + this.props.modalId; } clickDOM(event) { if (event.target.tabIndex == this.props.buttonIndex) { this.props.handleSubmit(event); return; } const lottoNumber = Number(event.target.textContent); if (this.props.numbers[lottoNumber-this.props.indexOffset].disabled) return; this.props.onNumberSelected(lottoNumber); } moveFocus(event) { let lottoNumberIndex = 0; if (event.target.tabIndex == this.props.startNumber) { this.shiftFocus(lottoNumberIndex); // tab์„ ๋ˆ„๋ฅธ ๊ฒƒ๊ณผ ๊ฐ™์€ ํšจ๊ณผ return; } if (event.target.tabIndex == this.props.buttonIndex) { return; } const lottoNumber = Number(event.target.textContent); if (event.key === 'ArrowUp') { lottoNumberIndex = this.calcIndex(lottoNumber, this.addIndex, -COLUMN_COUNT_OF_LOTTO_NUMBER); } if (event.key === 'ArrowDown') { lottoNumberIndex = this.calcIndex(lottoNumber, this.addIndex, COLUMN_COUNT_OF_LOTTO_NUMBER); } if (event.key === 'ArrowLeft') { lottoNumberIndex = this.calcIndex(lottoNumber, this.addIndex, -1); } if (event.key === 'ArrowRight') { lottoNumberIndex = this.calcIndex(lottoNumber, this.addIndex, 1); } this.shiftFocus(lottoNumberIndex); } addIndex(index, number) { return index + number; } calcIndex(lottoNumber, method, targetNumber) { if (typeof method !== 'function') return; lottoNumber = method(lottoNumber, targetNumber); if (lottoNumber < this.props.startNumber || lottoNumber > this.props.endNumber) { lottoNumber = this.ceilCalc(lottoNumber); } while (lottoNumber < this.props.startNumber || lottoNumber > this.props.endNumber) { lottoNumber = method(lottoNumber, targetNumber); } return lottoNumber-this.props.indexOffset; } ceilCalc(lottoNumber) { if (lottoNumber < this.props.startNumber) { return lottoNumber += this.getCeilNumber(this.props.endNumber); } return lottoNumber -= this.getCeilNumber(this.props.endNumber); } // ํ•œ์ž๋ฆฌ ์•„๋ž˜์—์„œ ์˜ฌ๋ฆผ์„ ํ•œ๋‹ค. ex) 45 -> 50 getCeilNumber(number) { const numberArr = String(number).split(''); if (numberArr.length == 1) { return Math.ceil(number); } const _ceil = Number(numberArr[0]+numberArr[1])+9; return Number(String(_ceil).split('')[0]) * Math.pow(10, numberArr.length-1); } shiftFocus(index) { document.getElementById(this.props.modalId).getElementsByClassName('selectMode')[index].focus(); } getListRender() { return this.props.numbers.map((LNumber, index)=> { if (LNumber.number % COLUMN_COUNT_OF_LOTTO_NUMBER == 0) { return <LottoNumber key={index} number={LNumber.number} lastNumber={true} tabIndex={this.props.indexOffset + index + this.props.startNumber} //start selectMode={true} onSelected={this.props.onNumberSelected} selected={LNumber.selected} disabled={LNumber.disabled} /> } return <LottoNumber key={index} number={LNumber.number} tabIndex={this.props.indexOffset + index + this.props.startNumber} //start selectMode={true} onSelected={this.props.onNumberSelected} selected={LNumber.selected} disabled={LNumber.disabled} /> }) } render() { if (this.props.numbers.length == 0) return <div></div>; return( <div> {this.getListRender()} </div> ) } }
JavaScript
class Flag { constructor() { this.id = -1; } static set(id) { this.id = id; } static get() { return this.id; } }
JavaScript
class CommandoClient extends discord.Client { /** * Result of throttle function, returned when the command should be blocked * @typedef {object} ThrottleResult * @property {{ start: number, usages: number, timeout: NodeJS.Timeout }} throttle @property {number} remaining - remaining seconds */ /** * Throttles the command usage * @callback Throttle * @param {Command} command - Command to throttle * @param {User} user - The user that triggered the command * @returns {Promise<ThrottleResult?>} - Whether to throttle the use or allow the command to run */ /** * Updates the throttle database after command use * @callback ThrottleUse * @param {Command} command - Command to throttle * @param {User} user - The user that triggered the command * @returns {Promise<void>} */ /** * Options for a CommandoClient * @typedef {ClientOptions} CommandoClientOptions * @property {string} [commandPrefix=!] - Default command prefix * @property {number} [commandEditableDuration=30] - Time in seconds that command messages should be editable * @property {boolean} [nonCommandEditable=true] - Whether messages without commands can be edited to a command * @property {string|string[]|Set<string>} [owner] - ID of the bot owner's Discord user, or multiple IDs * @property {string} [invite] - Invite URL to the bot's support server * @property {boolean} [noErrorReply] - True if errors shouldn't send a message * (useful when using custom error handlers) * @property {boolean} [ignorePermissions] - True to not check for user permissions. * Useful when using custom inhibitors. * @property {Throttle} [throttle] - Used for custom throttling. * When object is returned, commando blocks the use of command. * @property {ThrottleUse} [throttleUse] - Used for custom throttling. * Called when the command is used,should increase the counter. */ /** * @param {CommandoClientOptions} [options] - Options for the client */ constructor(options = {}) { if(typeof options.commandPrefix === 'undefined') options.commandPrefix = '!'; if(options.commandPrefix === null) options.commandPrefix = ''; if(typeof options.commandEditableDuration === 'undefined') options.commandEditableDuration = 30; if(typeof options.nonCommandEditable === 'undefined') options.nonCommandEditable = true; super(options); /** * The client's command registry * @type {CommandoRegistry} */ this.registry = new CommandoRegistry(this); /** * The client's command dispatcher * @type {CommandDispatcher} */ this.dispatcher = new CommandDispatcher(this, this.registry); /** * The client's setting provider * @type {?SettingProvider} */ this.provider = null; /** * Shortcut to use setting provider methods for the global settings * @type {GuildSettingsHelper} */ this.settings = new GuildSettingsHelper(this, null); /** * Internal global command prefix, controlled by the {@link CommandoClient#commandPrefix} getter/setter * @type {?string} * @private */ this._commandPrefix = null; // Set up command handling const msgErr = err => { this.emit('error', err); }; this.on('messageCreate', message => { this.dispatcher.handleMessage(message).catch(msgErr); }); this.on('messageUpdate', (oldMessage, newMessage) => { this.dispatcher.handleMessage(newMessage, oldMessage).catch(msgErr); }); // eslint-disable-next-line this.on('interactionCreate', async (/** @type {CommandInteraction | AutocompleteInteraction} */ int) => { if(int.isButton()) return; const command = this.registry.resolveFromInteraction(int.commandName); if(!command) { throw new TypeError( `Command ${int.commandName} from interaction not found. Make sure that only Commando is registering commands.` ); } if(int.isAutocomplete()) { const ind = int.options.data.findIndex(data => data.focused); const arg = command.argsCollector.args[ind]; const res = arg.autocomplete ? await arg.autocomplete(int) : await arg.type.autocomplete(int); if(res && Array.isArray(res)) { await int.respond(res); } } else { const ctx = Context.extend(int); if(!command.argsCollector) return command.run(ctx); var opts = {}; for(var i = 0; i < command.argsCollector.args.length; i++) { const src = int.options.data[i]; var value; switch(src.type) { case 'STRING': case 'INTEGER': case 'BOOLEAN': case 'NUMBER': value = src.value; break; case 'SUB_COMMAND': case 'SUB_COMMAND_GROUP': value = src; break; case 'USER': value = this.users.resolve(src.user || src.member); break; case 'CHANNEL': value = this.channels.resolve(src.channel); break; case 'ROLE': value = src.role; break; case 'MENTIONABLE': value = src.user || src.member || src.role; break; } opts[command.argsCollector.args[i].key] = command.argsCollector.args[i].commandConvert ? command.argsCollector.args[i].commandConvert(value, src) : command.argsCollector.args[i].type.commandConvert ? command.argsCollector.args[i].type.commandConvert(value, src) : value; } command.run(ctx, opts, false, null); } }); // Fetch the owner(s) if(options.owner) { this.once('ready', () => { if(options.owner instanceof Array || options.owner instanceof Set) { for(const owner of options.owner) { this.users.fetch(owner).catch(err => { this.emit('warn', `Unable to fetch owner ${owner}.`); this.emit('error', err); }); } } else { this.users.fetch(options.owner).catch(err => { this.emit('warn', `Unable to fetch owner ${options.owner}.`); this.emit('error', err); }); } }); } } async login(token) { var res = await super.login(token); this.registry.rest.setToken(token); return res; } /** * Global command prefix. An empty string indicates that there is no default prefix, and only mentions will be used. * Setting to `null` means that the default prefix from {@link CommandoClient#options} will be used instead. * @type {string} * @emits {@link CommandoClient#commandPrefixChange} */ get commandPrefix() { if(typeof this._commandPrefix === 'undefined' || this._commandPrefix === null) return this.options.commandPrefix; return this._commandPrefix; } set commandPrefix(prefix) { this._commandPrefix = prefix; this.emit('commandPrefixChange', null, this._commandPrefix); } /** * Owners of the bot, set by the {@link CommandoClientOptions#owner} option * <info>If you simply need to check if a user is an owner of the bot, please instead use * {@link CommandoClient#isOwner}.</info> * @type {?Array<User>} * @readonly */ get owners() { if(!this.options.owner) return null; if(typeof this.options.owner === 'string') return [this.users.cache.get(this.options.owner)]; const owners = []; for(const owner of this.options.owner) owners.push(this.users.cache.get(owner)); return owners; } /** * Checks whether a user is an owner of the bot (in {@link CommandoClientOptions#owner}) * @param {UserResolvable} user - User to check for ownership * @return {boolean} */ isOwner(user) { if(!this.options.owner) return false; user = this.users.resolve(user); if(!user) throw new RangeError('Unable to resolve user.'); if(typeof this.options.owner === 'string') return user.id === this.options.owner; if(this.options.owner instanceof Array) return this.options.owner.includes(user.id); if(this.options.owner instanceof Set) return this.options.owner.has(user.id); throw new RangeError('The client\'s "owner" option is an unknown value.'); } /** * Sets the setting provider to use, and initialises it once the client is ready * @param {SettingProvider|Promise<SettingProvider>} provider Provider to use * @return {Promise<void>} */ async setProvider(provider) { const newProvider = await provider; this.provider = newProvider; if(this.readyTimestamp) { this.emit('debug', `Provider set to ${newProvider.constructor.name} - initialising...`); await newProvider.init(this); this.emit('debug', 'Provider finished initialisation.'); return undefined; } this.emit('debug', `Provider set to ${newProvider.constructor.name} - will initialise once ready.`); await new Promise(resolve => { this.once('ready', () => { this.emit('debug', `Initialising provider...`); resolve(newProvider.init(this)); }); }); /** * Emitted upon the client's provider finishing initialisation * @event CommandoClient#providerReady * @param {SettingProvider} provider - Provider that was initialised */ this.emit('providerReady', provider); this.emit('debug', 'Provider finished initialisation.'); return undefined; } /** * Destroys the client and clears up memory. * @returns {Promise<void>} */ async destroy() { await super.destroy(); if(this.provider) await this.provider.destroy(); } }
JavaScript
class IconView extends View { /** * @inheritDoc */ constructor() { super(); const bind = this.bindTemplate; /** * The SVG source of the icon. * * @observable * @member {String} #content */ this.set( 'content', '' ); /** * This attribute specifies the boundaries to which the * icon content should stretch. * * @observable * @default '0 0 16 16' * @member {String} #viewBox */ this.set( 'viewBox', '0 0 16 16' ); this.setTemplate( { tag: 'svg', ns: 'http://www.w3.org/2000/svg', attributes: { class: [ 'ck', 'ck-icon', 'ck-gitlab-icon' ], viewBox: bind.to( 'viewBox' ) } } ); } /** * @inheritDoc */ render() { super.render(); this._updateXMLContent(); this.on( 'change:content', () => { this._updateXMLContent(); } ); } /** * Updates the {@link #element} with the value of {@link #content}. * * @private */ _updateXMLContent() { this.element.innerHTML = ''; const useElement = document.createElementNS( 'http://www.w3.org/2000/svg', 'use' ); useElement.setAttributeNS( 'http://www.w3.org/1999/xlink', 'href', `${ GITLAB_SVGS_PATH }#${ getMappedIconSpriteId( this.content.id ) }` ); this.element.appendChild( useElement ); } }
JavaScript
class MessageBox extends LitElement { static get properties() { return { message: { type: String }, reply: { type: Object } }; } constructor() { super(); this.message = ''; } static get styles() { return sharedStyles; } render() { return html` ${this.reply ? html` <div class="message-box" id="reply-box"> <h3>replying to:</h3> <h4>${this.reply.text}</h4> </div> ` : ''} <div class="message-box" @keyup=${this.shortcutListener}> <fc-input type="text" id="message-box" class="text-input" value=${this.message} @change="${this.updateMessage}" contenteditable="" ></fc-input> <button id="submit-button" @click=${this.sendMessage} class="common-button" > <span class="icon">โžค</span> </button> </div> `; } // shortcut for sending on enter key. shortcutListener(e) { if (e.key === 'Enter') { this.sendMessage(); } } // listens for message user is typing. updateMessage(e) { this.message = e.target.value; } // removing spaces, checking if the message is not empty, and handel each case if its a reply or a regular message. sendMessage() { let msg = this.message.trim(); let reply = this.reply; if (!msg) { return false; } if (reply) { // Emit reply to server emitReply(msg, reply); this.dispatchEvent(new CustomEvent('chatReply', { detail: undefined })); this.message = ''; } else { // Emit message to server emitMessage(msg); this.message = ''; } } }
JavaScript
class ThisMemoryScope extends memoryScope_1.MemoryScope { constructor() { super(scopePath_1.ScopePath.THIS); } getMemory(dc) { if (!dc.activeDialog) { throw new Error(`ThisMemoryScope.getMemory: no active dialog found.`); } return dc.activeDialog.state; } setMemory(dc, memory) { if (memory == undefined) { throw new Error(`ThisMemoryScope.setMemory: undefined memory object passed in.`); } if (!dc.activeDialog) { throw new Error(`ThisMemoryScope.setMemory: no active dialog found.`); } dc.activeDialog.state = memory; } }
JavaScript
class DurationPicker extends Component { style = {}; state = { style: { hour: {}, minutes: {}, seconds: {} }, data: { hour: 0, minutes: 0, seconds: 0 } }; selection = false; constructor() { super(); var durationstyle = Constant.numericInputStyle; //hide arrows durationstyle["btn"].visibility = "hidden"; //highlight when focused durationstyle["input:focus"] = { "border": "1px solid #1e88e5" }; //modify margin durationstyle["input"] = { "margin": "5px", "paddingRight": '3ex', "boxSizing": 'border-box' }; durationstyle["btnUp"] = { top: 2, bottom: '50%', borderRadius: '2px 2px 0 0', borderWidth: '1px 1px 0 1px', marginTop: '4px', marginRight: '4px' }; durationstyle["btnDown"] = { top: '50%', bottom: 2, borderRadius: '0 0 2px 2px', borderWidth: '0 1px 1px 1px', marginBottom: '4px', marginRight: '4px' } this.style = { hour: JSON.parse(JSON.stringify(durationstyle)), minutes: JSON.parse(JSON.stringify(durationstyle)), seconds: JSON.parse(JSON.stringify(durationstyle)) }; this.onFocus = this.onFocus.bind(this); this.onBlur = this.onBlur.bind(this); } componentDidMount() { if (this.props.style && Object.keys(this.props.style).length !== 0) { this.style = this.props.style; } this.setState({ style: this.style, data: { hour: this.props.hour, minutes: this.props.minutes, seconds: this.props.seconds } }); } componentDidUpdate() { } onFocus(type) { if (!this.selection) { this.selection = true; switch (type) { case 'hour': this.style.hour["btn"].visibility = "visible"; break; case 'minutes': this.style.minutes["btn"].visibility = "visible"; break; case 'seconds': this.style.seconds["btn"].visibility = "visible"; break; default: break; } if (typeof this.props.onUpdateValue === 'function') { this.props.onUpdateValue(this.props.name, { style: this.style, data: { hour: this.props.hour, minutes: this.props.minutes, seconds: this.props.seconds } }); } } } onBlur(type) { this.selection = false; switch (type) { case 'hour': this.style.hour["btn"].visibility = "hidden"; break; case 'minutes': this.style.minutes["btn"].visibility = "hidden"; break; case 'seconds': this.style.seconds["btn"].visibility = "hidden"; break; default: break; } if (typeof this.props.onUpdateValue === 'function') { this.props.onUpdateValue(this.props.name, { style: this.style, data: { hour: this.refs.hour.state.value, minutes: this.refs.minutes.state.value, seconds: this.refs.seconds.state.value } }); } } onChange(valueAsNumber, valueAsString, input) { if (typeof this.props.onChange === 'function') { this.props.onChange(this.props.name, { hour: this.refs.hour.state.value, minutes: this.refs.minutes.state.value, seconds: this.refs.seconds.state.value }); } } render() { return <div className={this.props.className + " durationpicker-container form-control"}> <NumericInput ref='hour' onBlur={() => this.onBlur('hour')} onSelect={() => this.onFocus('hour')} min={0} max={24} value={this.props.hour} style={this.state.style.hour} onChange={(numericVal,strVal,input) => this.onChange(numericVal,strVal,input) } />h <NumericInput ref='minutes' onBlur={() => this.onBlur('minutes')} onSelect={() => this.onFocus('minutes')} min={0} max={60} value={this.props.minutes} style={this.state.style.minutes} onChange={(numericVal,strVal,input) => this.onChange(numericVal,strVal,input)} />m <NumericInput ref='seconds' onBlur={() => this.onBlur('seconds')} onSelect={() => this.onFocus('seconds')} min={0} max={60} value={this.props.seconds} style={this.state.style.seconds} onChange={(numericVal,strVal,input) => this.onChange(numericVal,strVal,input)} />s </div> } }
JavaScript
class MSTeamsService { /** * @function * @name createTeam * @param {*} payload * @returns */ async createTeam (payload) { try { const { authorization, teamName, teamMembers } = payload // Get access token from AD to start team creation process const { accessToken } = await msTeamUtils.getGraphToken(authorization) if (accessToken) { // This user const adminCreationPromises = teamMembers.filter(p => p.role === 'admin') .map(p => msTeamUtils.getTeamsProfile(accessToken, p.userId) .then(response => response.id)) // Admin team profile ids const admins = await Promise.all(adminCreationPromises) const group = await msTeamUtils.createGroup(accessToken, teamName, admins) if (!group) { logger.error('MSTeamsService:createTeam: Error, Failed to create group', { group }) throw new CustomError('Failed to create group', STATUS_CODES.INTERNAL_SERVER_ERROR) } // After creation of group, it needs some time to sync data // If tried before timeout, will return 404 error await generalUtils.wait(2 * 60 * 1000) const teamReqResponse = await msTeamUtils.createTeam(accessToken, group.id) if (!teamReqResponse) { logger.error('MSTeamsService:createTeam: Error, No response received after teams creation') throw CustomError('No response received after teams creation', STATUS_CODES.INTERNAL_SERVER_ERROR) } // If status code is not 200, 201 or 202, then team creation will be failed if (teamReqResponse.statusCode !== STATUS_CODES.OK && teamReqResponse.statusCode !== STATUS_CODES.CREATED && teamReqResponse.statusCode !== STATUS_CODES.ACCEPTED) { logger.error('MSTeamsService:createTeam: Error, Error while creating team ', { error: teamReqResponse.body }) throw new CustomError('Error while creating team', teamReqResponse.statusCode) } try { // Get teams profile for members to add const teamProfiles = await Promise .all(teamMembers .filter(p => p.role === 'member') .map(async p => { return await msTeamUtils .getTeamsProfile(accessToken, p.userId).then(response => response.id) })) const promises = teamProfiles.map(async id => await msTeamUtils.addMembers(accessToken, group.id, id)) const addedMembers = await Promise.all(promises) console.log('MSTeamsService:createTeam: Members added to team ', addedMembers) return { message: 'Team created successfully' } } catch (error) { console.log('MSTeamsService:createTeam: Error while adding members to team ', error.message) throw new CustomError('Error while adding members to team', STATUS_CODES.INTERNAL_SERVER_ERROR) } } else { logger.error('No response received/Error while fetching access token') throw new CustomError('No response received/Error while fetching access token', STATUS_CODES.INTERNAL_SERVER_ERROR) } } catch (error) { throw new CustomError(error.message, error.statusCode || STATUS_CODES.INTERNAL_SERVER_ERROR) } } }