language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class MatTabLink extends _MatTabLinkBase {
/**
* @param {?} tabNavBar
* @param {?} elementRef
* @param {?} globalRippleOptions
* @param {?} tabIndex
* @param {?} focusMonitor
* @param {?} _document
* @param {?=} animationMode
*/
constructor(tabNavBar, elementRef, globalRippleOptions, tabIndex, focusMonitor, _document, animationMode) {
super(tabNavBar, elementRef, globalRippleOptions, tabIndex, focusMonitor, animationMode);
this._foundation = new MatInkBarFoundation(elementRef, _document);
this._foundation.init();
}
/**
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
this._foundation.destroy();
}
} |
JavaScript | class Set {
constructor() {
this.set = [];
}
add(element) {
if (this.set.includes(element)) {
return false;
} else {
this.set.push(element);
return true;
}
}
clear() {
this.set = [];
}
contains() {
return this.set.include(element) ? true : false;
}
isEmpty() {
return this.set.length == 0 ? true : false;
}
size() {
return this.set.length;
}
} |
JavaScript | class RandomTimer extends Timer {
/** @default 1 */
static defaultMinPeriod = 1
/** @default 2 */
static defaultMaxPeriod = 2
/** @default undefined */
static defaultPeriod = undefined
/**
* @arg {Object} config - Config
* @arg {float} config.minPeriod - Minimum period
* @arg {float} config.maxPeriod - Maximum period
* @arg {float} config.period - Current period
* @arg {float} config.time - Current time
*/
constructor(config = {}) {
super(config)
initFromConfig(this, config, RandomTimer, "minPeriod", "maxPeriod", "period")
if (this.period === undefined)
this.reset()
}
/** */
reset() {
this.period = Math.randomInRange(this.minPeriod, this.maxPeriod)
this.time = 0
return this
}
} |
JavaScript | class MessageManager extends CachedManager {
constructor(channel, iterable) {
super(channel.client, Message, iterable);
/**
* The channel that the messages belong to
* @type {TextBasedChannels}
*/
this.channel = channel;
}
/**
* The cache of Messages
* @type {Collection<Snowflake, Message>}
* @name MessageManager#cache
*/
_add(data, cache) {
return super._add(data, cache);
}
/**
* Data that can be resolved to a Message object. This can be:
* * A Message
* * A Snowflake
* @typedef {Message|Snowflake} MessageResolvable
*/
/**
* Options used to fetch a message.
* @typedef {BaseFetchOptions} FetchMessageOptions
* @property {MessageResolvable} [message] The message to fetch
*/
/**
* Options used to fetch multiple messages.
* @typedef {Object} FetchMessagesOptions
* @property {number} [limit] The maximum number of messages to return
* @property {Snowflake} [before] Consider only messages before this id
* @property {Snowflake} [after] Consider only messages after this id
* @property {Snowflake} [around] Consider only messages around this id
* @property {boolean} [cache] Whether to cache the fetched messages
*/
/**
* Fetches message(s) from a channel.
* <info>The returned Collection does not contain reaction users of the messages if they were not cached.
* Those need to be fetched separately in such a case.</info>
* @param {MessageResolvable|FetchMessageOptions|FetchMessagesOptions} [options] Options for fetching message(s)
* @returns {Promise<Message|Collection<Snowflake, Message>>}
* @example
* // Fetch a message
* channel.messages.fetch('99539446449315840')
* .then(message => console.log(message.content))
* .catch(console.error);
* @example
* // Fetch a maximum of 10 messages without caching
* channel.messages.fetch({ limit: 10, cache: false })
* .then(messages => console.log(`Received ${messages.size} messages`))
* .catch(console.error);
* @example
* // Fetch a maximum of 10 messages without caching around a message id
* channel.messages.fetch({ limit: 10, cache: false, around: '99539446449315840' })
* .then(messages => console.log(`Received ${messages.size} messages`))
* .catch(console.error);
* @example
* // Fetch messages and filter by a user id
* channel.messages.fetch()
* .then(messages => console.log(`${messages.filter(m => m.author.id === '84484653687267328').size} messages`))
* .catch(console.error);
*/
fetch(options) {
if (!options) return this._fetchMany();
const { message, cache, force } = options;
const resolvedMessage = this.resolveId(message ?? options);
if (resolvedMessage) return this._fetchSingle({ message: resolvedMessage, cache, force });
return this._fetchMany(options);
}
async _fetchSingle({ message, cache, force = false }) {
if (!force) {
const existing = this.cache.get(message);
if (existing && !existing.partial) return existing;
}
const data = await this.client.rest.get(Routes.channelMessage(this.channel.id, message));
return this._add(data, cache);
}
async _fetchMany(options = {}) {
const data = await this.client.rest.get(Routes.channelMessages(this.channel.id), {
query: makeURLSearchParams(options),
});
return data.reduce((_data, message) => _data.set(message.id, this._add(message, options.cache)), new Collection());
}
/**
* Fetches the pinned messages of this channel and returns a collection of them.
* <info>The returned Collection does not contain any reaction data of the messages.
* Those need to be fetched separately.</info>
* @param {boolean} [cache=true] Whether to cache the message(s)
* @returns {Promise<Collection<Snowflake, Message>>}
* @example
* // Get pinned messages
* channel.messages.fetchPinned()
* .then(messages => console.log(`Received ${messages.size} messages`))
* .catch(console.error);
*/
async fetchPinned(cache = true) {
const data = await this.client.rest.get(Routes.channelPins(this.channel.id));
const messages = new Collection();
for (const message of data) messages.set(message.id, this._add(message, cache));
return messages;
}
/**
* Resolves a {@link MessageResolvable} to a {@link Message} object.
* @method resolve
* @memberof MessageManager
* @instance
* @param {MessageResolvable} message The message resolvable to resolve
* @returns {?Message}
*/
/**
* Resolves a {@link MessageResolvable} to a {@link Message} id.
* @method resolveId
* @memberof MessageManager
* @instance
* @param {MessageResolvable} message The message resolvable to resolve
* @returns {?Snowflake}
*/
/**
* Edits a message, even if it's not cached.
* @param {MessageResolvable} message The message to edit
* @param {string|MessageEditOptions|MessagePayload} options The options to edit the message
* @returns {Promise<Message>}
*/
async edit(message, options) {
const messageId = this.resolveId(message);
if (!messageId) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
const { body, files } = await (options instanceof MessagePayload
? options
: MessagePayload.create(message instanceof Message ? message : this, options)
)
.resolveBody()
.resolveFiles();
const d = await this.client.rest.patch(Routes.channelMessage(this.channel.id, messageId), { body, files });
const existing = this.cache.get(messageId);
if (existing) {
const clone = existing._clone();
clone._patch(d);
return clone;
}
return this._add(d);
}
/**
* Publishes a message in an announcement channel to all channels following it, even if it's not cached.
* @param {MessageResolvable} message The message to publish
* @returns {Promise<Message>}
*/
async crosspost(message) {
message = this.resolveId(message);
if (!message) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
const data = await this.client.rest.post(Routes.channelMessageCrosspost(this.channel.id, message));
return this.cache.get(data.id) ?? this._add(data);
}
/**
* Pins a message to the channel's pinned messages, even if it's not cached.
* @param {MessageResolvable} message The message to pin
* @param {string} [reason] Reason for pinning
* @returns {Promise<void>}
*/
async pin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
}
/**
* Unpins a message from the channel's pinned messages, even if it's not cached.
* @param {MessageResolvable} message The message to unpin
* @param {string} [reason] Reason for unpinning
* @returns {Promise<void>}
*/
async unpin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
}
/**
* Adds a reaction to a message, even if it's not cached.
* @param {MessageResolvable} message The message to react to
* @param {EmojiIdentifierResolvable} emoji The emoji to react with
* @returns {Promise<void>}
*/
async react(message, emoji) {
message = this.resolveId(message);
if (!message) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
emoji = Util.resolvePartialEmoji(emoji);
if (!emoji) throw new TypeError('EMOJI_TYPE', 'emoji', 'EmojiIdentifierResolvable');
const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
: encodeURIComponent(emoji.name);
await this.client.rest.put(Routes.channelMessageOwnReaction(this.channel.id, message, emojiId));
}
/**
* Deletes a message, even if it's not cached.
* @param {MessageResolvable} message The message to delete
* @returns {Promise<void>}
*/
async delete(message) {
message = this.resolveId(message);
if (!message) throw new TypeError('INVALID_TYPE', 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelMessage(this.channel.id, message));
}
} |
JavaScript | class Alchemist {
constructor (element) {
this.setElement(element)
}
static isQuerySelector (element) {
return typeof element === 'string'
}
static fromQuerySelector (element) {
return document.querySelector(element)
}
static isSizzle (element) {
return typeof element === 'function'
}
static fromSizzle (element) {
return element.get(0)
}
static isTemplate (element) {
return is.element(element)
}
static fromTemplate (element) {
return element.content
}
static isFragment (element) {
return is.fragment(element) && element.hasChildNodes()
}
static fromFragment (element) {
return element.firstElementChild
}
static asElement (element) {
let waterfall = [
Alchemist.fromQuerySelector,
Alchemist.fromSizzle,
Alchemist.fromTemplate,
Alchemist.fromFragment
]
let result = as.decomposed(waterfall, element)
// element is already provided
if (result && is.element(result)) {
return result
}
}
setElement (element) {
this.element = Alchemist.asElement(element)
return this
}
getElement () {
return this.element
}
} |
JavaScript | class PipelineScheduleAllOf {
/**
* Constructs a new <code>PipelineScheduleAllOf</code>.
* A Pipelines schedule.
* @alias module:model/PipelineScheduleAllOf
*/
constructor() {
PipelineScheduleAllOf.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>PipelineScheduleAllOf</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/PipelineScheduleAllOf} obj Optional instance to populate.
* @return {module:model/PipelineScheduleAllOf} The populated <code>PipelineScheduleAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PipelineScheduleAllOf();
if (data.hasOwnProperty('uuid')) {
obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String');
}
if (data.hasOwnProperty('enabled')) {
obj['enabled'] = ApiClient.convertToType(data['enabled'], 'Boolean');
}
if (data.hasOwnProperty('target')) {
obj['target'] = PipelineTarget.constructFromObject(data['target']);
}
if (data.hasOwnProperty('selector')) {
obj['selector'] = PipelineSelector.constructFromObject(data['selector']);
}
if (data.hasOwnProperty('cron_pattern')) {
obj['cron_pattern'] = ApiClient.convertToType(data['cron_pattern'], 'String');
}
if (data.hasOwnProperty('created_on')) {
obj['created_on'] = ApiClient.convertToType(data['created_on'], 'Date');
}
if (data.hasOwnProperty('updated_on')) {
obj['updated_on'] = ApiClient.convertToType(data['updated_on'], 'Date');
}
}
return obj;
}
} |
JavaScript | class Dijkstra extends Path {
constructor(toX, toY, passableCallback, options) {
super(toX, toY, passableCallback, options);
this._computed = {};
this._todo = [];
this._add(toX, toY, null);
}
/**
* Compute a path from a given point
* @see ROT.Path#compute
*/
compute(fromX, fromY, callback) {
let key = fromX + "," + fromY;
if (!(key in this._computed)) {
this._compute(fromX, fromY);
}
if (!(key in this._computed)) {
return;
}
let item = this._computed[key];
while (item) {
callback(item.x, item.y);
item = item.prev;
}
}
/**
* Compute a non-cached value
*/
_compute(fromX, fromY) {
while (this._todo.length) {
let item = this._todo.shift();
if (item.x == fromX && item.y == fromY) {
return;
}
let neighbors = this._getNeighbors(item.x, item.y);
for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i];
let x = neighbor[0];
let y = neighbor[1];
let id = x + "," + y;
if (id in this._computed) {
continue;
} /* already done */
this._add(x, y, item);
}
}
}
_add(x, y, prev) {
let obj = {
x: x,
y: y,
prev: prev
};
this._computed[x + "," + y] = obj;
this._todo.push(obj);
}
} |
JavaScript | class HelloApp extends React.Component {
render() {
// Relay will materialize this prop based on the
// result of the query in the next component.
var {hello} = this.props.greetings;
return <h1>{hello}</h1>;
}
} |
JavaScript | class HelloRoute extends Relay.Route {
static routeName = 'Hello'; // A unique name
static queries = {
// Here, we compose your Relay container's
// 'greetings' fragment into the 'greetings'
// field at the root of the GraphQL schema.
greetings: (Component) => Relay.QL`
query GreetingsQuery {
greetings {
${Component.getFragment('greetings')},
},
}
`,
};
} |
JavaScript | class Peer{
constructor(config){
this.config = config;
this.filepath = path.join(this.config.getHomeDir(),".peers");
this.DISCOVERY_PORT = process.env.DISCOVERY_PORT || this.config.get("DISCOVERY_PORT");
this.NETWORK_KEY = process.env.NETWORK_KEY || this.config.get("NETWORK_KEY");
this.P2P_PORT = process.env.P2P_PORT || this.config.get("P2P_PORT");
this.peers = {};
this.sockets = {};
this.publicip = null;
this.nodeid = null;
/*
this.unknown_peers = [];
//this._load();
var env_peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
for(var i in env_peers){
var peer_url;
var peer_id;
if(env_peers[i].indexOf("@") > -1){
peer_url = env_peers[i].split("@")[0];
peer_id = env_peers[i].split("@")[1];
}else{
peer_url = env_peer[i];
peer_id = "";
}
var u = url.parse(peer_url,true);
var p = {hostname:u.hostname, port:u.port, status:-1, id:peer_id, failed:0};
this.unknown_peers.push(p);
}*/
//this.checkinterval = setInterval(this._checkPeers,1000*60*10);
//this._checkPeers();
}
setConfig(config){
this.config = config;
}
/*
_load(){
if(fs.existsSync(this.filepath)){
var speers = fs.readFileSync(this.filepath,'utf8');
this.peers = JSON.parse(speers);
}
}
*/
_save(){
fs.writeFileSync(this.filepath,JSON.stringify(this.peers,undefined,'\t'),'utf8');
}
_geturl(peer){
return "ws://" + peer.hostname + ":" + peer.port;
}
/*
_startPeer(peer){
const socket = new Websocket(this._geturl(peer));
this._messageHandler(socket);
socket.on('open', () => {
console.log('opened peer ' + peer.host);
});
socket.on('err',(err) =>{
console.log('socket error ' + peer.host + '. ' + err);
if(peer.id && peer.id !== ""){
this.setFail();
}
});
socket.on('close',(code, reason) => {
console.log('closed peer ' + peer.host + '. (' + code + ' : ' + reason + ')');
this._deleteSocket(socket);
});
}
_deleteSocket(socket){
for(var i in this.sockets){
if(sockets[i] === socket){
this.setStatus(this.sockets[i].id,-1,true);
delete sockets[i];
return;
}
}
}
_messageHandler(socket) {
//triggered by a send function
socket.on('message', message => {
const data = JSON.parse(message);
switch (data.type) {
case MESSAGE_TYPES.id:
//this._setStartPeer(data.peer, socket);
break;
case MESSAGE_TYPES.chain:
this.blockchain.replaceChain(data.chain);
break;
case MESSAGE_TYPES.transaction:
this.transactionPool.updateOrAddTransaction(data.transaction);
break;
case MESSAGE_TYPES.clearTransactions:
this.transactionPool.clear();
break;
}
})
}
_setStartPeer(peer,socket){
peer.status = 0;
peer.failed = 0;
this.setPeer(peer,true);
sockets[peer.id] = socket;
}*/
/*
_checkPeers(){
Object.keys(this.peers).forEach(function(key){
var peer = this.peers[key];
tcpscan.run({host:peer.hostname,port:peer.port}).then(
() => {
if(peer.status == -1){
this.setStatus(peer.id, 0);
}
},
()=>{
if(peer.failed >= 3) {
delete this.peers[peer.id];
}
else this.setFail(peer);
}
);
});
var unknown_peers = this.unknown_peers;
for(var i = 0; i < unknown_peers.length; i++){
var peer = unknown_peers[i];
tcpscan.run({host:peer.hostname,port:peer.port}).then(
() => {
if(peer.status == -1){
peer.status = 0;
}
},
()=>{
if(peer.failed >= 3) {
unknown_peers.splice(i,1);
i--;
}
else peer.failed++;
}
);
}
this._save();
}
*/
listen(){
var parent = this;
publicIp.v4()
.then(ip => {
parent.publicip = ip;
console.log('[' + (new Date()).toLocaleString()+'] public ip is ' + parent.publicip);
var nodeidfile = path.join(parent.config.getHomeDir(),".nodeid");
if(fs.existsSync(nodeidfile)){
parent.nodeid = fs.readFileSync(nodeidfile,'utf8');
}else{
parent.nodeid = parent.publicip + ":" + parent.P2P_PORT + "@" + parent.nodeid;
fs.writeFileSync(nodeidfile,parent.nodeid,'utf8');
}
parent.nodeid = parent.nodeid.trim();
parent.discovery_config = defaults({
id:parent.nodeid,
maxConnections:50,
//whitelist:this.getPeerIps(),
keepExistingConnections: false
});
parent.sw = Swarm(parent.discovery_config);
console.log('[' + (new Date()).toLocaleString()+'] start node ' + parent.nodeid);
parent.sw.listen(parent.DISCOVERY_PORT);
console.log('[' + (new Date()).toLocaleString()+'] peer Listening to discovery port : ' + parent.DISCOVERY_PORT);
parent.sw.join(parent.NETWORK_KEY);
console.log('[' + (new Date()).toLocaleString()+'] peer Join network : ' + parent.NETWORK_KEY);
parent.sw.on("connection",function(conn, info){
var host = info.host;
var id = info.id.toString();
if(parent.nodeid == id) return;
console.log('[' + (new Date()).toLocaleString()+ '] peer Connected peer from '+ id + '(' + host + ')');
parent.setPeer({"id":id,"host":host,"port":info.port,"type":info.type},true);
/*
var port = parent.P2P_PORT;
tcpscan.run({host:host,port:port}).then(
() => {
var p = {hostname:host, port:port, status:-1, id:id, failed:0};
if(!parent.existPeer(p)){
if(Object.keys(parent.peers).length < 50){
p.status = 0;
parent.setPeer(p, true);
console.log('[' + (new Date()).toLocaleString()+"] peer Added peer " + id + "(" + host + ")");
}else{
console.log('[' + (new Date()).toLocaleString()+"] peer Peers is full. so skip this peer " + id + "(" + host + ")");
}
}else{
console.log('[' + (new Date()).toLocaleString()+"] peer Aleady exist peer " + id + "(" + host +")");
}
},
() => {
console.log('[' + (new Date()).toLocaleString()+'] peer Peer ' + host + ' is no listen ' + port + ' port.');
//parent.setPeer(p);
}
);*/
});
parent.sw.on('connection-closed',function(conn, info){
if(info.initiator == false || info.channel == null || (info.channel.toString() != parent.NETWORK_KEY)) return;
publicIp.v4()
.then(ip => {
//console.log('[' + (new Date()).toLocaleString()+'] peer closed ip : ' + ip);
if(info.host.indexOf(ip) > -1 && parent.DISCOVERY_PORT == info.port) return;
if (info.id != null && parent.peers[info.id.toString()]){
//delete parent.peers[info.id.toString()];
//console.log('[' + (new Date()).toLocaleString()+'] peer Closed : ' + JSON.stringify(info));
console.log('[' + (new Date()).toLocaleString()+'] peer Closed discovery peer from ' + info.host);
}
});
});
});
}
/*
addConnection(socket){
this._messageHandler(socket);
socket.send(JSON.stringify({
type: MESSAGE_TYPES.id,
peer: {hosstname:ip.address(), port:this.config.get('P2P_PORT'), id:this.nodeid}
}));
}*/
existPeer(peer){
//var purl = "ws://" + peer.hostname + ":" + peer.port;
if(this.peers[peer.id]) return true;
else return false;
}
setPeers(peer_list, is_save=false){
if(peer_list.length == 0) return;
for(var i in peer_list){
this.setPeer(peer_list[i]);
}
if(is_save) this._save();
}
setStatus(id, status, is_save=false){
if(!this.peers[id]) return null;
this.peers[id].status = status;
if(is_save) this._save();
}
setPeer(peer, is_save = false){
if(!peer.id || peer.id == ""){
this.unknown_peers.push(peer);
}
this.peers[peer.id] = peer;
if(is_save) this._save();
}
setFail(peer, is_save=false){
this.peers[peer.id].failed++;
this.peers[peer.id].status = -1;
if(is_save) this._save();
}
getPeerInfo(id){
return this.peers[id];
}
getPeerInfoByUrl(purl){
var u = url.parse(purl,true);
for(var id in this.peers){
if(this.peers[id].hostname == u.hostname && this.peers[id].port == u.port){
return this.peers[id];
}
}
return null;
}
getPeerUrl(id){
return this._geturl(this.peers[id]);
}
getPeerIps(){
var ips = [];
for(var id in this.peers){
ips.push(this.peers[id].hostname);
}
}
getUrls(){
var urls = [];
for(var id in this.peers){
urls.push(this._geturl(peers[id]));
}
return urls;
}
getPeers(){
return this.peers;
}
getStatus(){
return {"connecting":this.sw.connecting,"queued":this.sw.queued,"connected":this.sw.connected,"peer_count":this.peers.length}
}
/*
sockets(){
return this.sockets;
}*/
} |
JavaScript | class BaseAction {
/**
* Constructor.
*
* @param {String} method
* @param {Object} params
* @param {Executor} executor
* @param {*} DestinationType
* @param {Boolean} returnsArray
*/
constructor(method, params, executor, DestinationType, returnsArray) {
this[P_METHOD] = method;
this[P_PARAMS] = params;
this[P_EXECUTOR] = executor;
this[P_DESTINATION_TYPE] = DestinationType;
this[P_RETURNS_ARRAY] = returnsArray;
}
/**
* Gets the destination type.
*
* @returns {*}
*/
get destinationType() {
return this[P_DESTINATION_TYPE];
}
/**
* Gets a value indicating whether the action returns an array.
*
* @returns {Boolean}
*/
get returnsArray() {
return this[P_RETURNS_ARRAY];
}
/**
* Gets the params for the rpc call.
*
* @returns {Object}
*/
get params() {
return this[P_PARAMS];
}
/**
* Changes a single param of the params object.
*
* @param {String} name
* @param {*} value
* @returns {BaseAction}
*/
changeParam(name, value) {
this[P_PARAMS][name] = value;
return this;
}
/**
* Gets the method.
*
* @returns {*}
*/
get method() {
return this[P_METHOD];
}
get destinationType() {
return this[P_DESTINATION_TYPE];
}
get returnsArray() {
return this[P_RETURNS_ARRAY];
}
/**
* Executes the current action and returns the raw result.
*
* @returns {Promise}
*/
async execute() {
return this[P_EXECUTOR].execute(this);
}
/**
* Gets a flag indicating whether the current action is valid.
*
* @returns {boolean}
*/
isValid() {
return true;
}
} |
JavaScript | class Util {
constructor() {
throw new Error('The Util class may not be instantiated');
}
/**
* Sets default properties on an object that aren't already specified.
* @param {Object} def Default properties
* @param {Object} given Object to assign defaults to
* @returns {Object}
* @private
*/
static mergeDefault(def, given) {
if (!given) return def;
for (const key in def) {
if (!has(given, key) || given[key] === undefined) {
given[key] = def[key];
} else if (given[key] === Object(given[key])) {
given[key] = Util.mergeDefault(def[key], given[key]);
}
}
return given;
}
/**
* Data that can be resolved to give a Buffer. This can be:
* * A Buffer
* * The path to a local file
* * A URL
* @typedef {string|Buffer} BufferResolvable
*/
/**
* @external Stream
* @see {@link https://nodejs.org/api/stream.html}
*/
/**
* Resolves a BufferResolvable to a Buffer or a Stream.
* @param {BufferResolvable|Stream} resource The buffer or stream resolvable to resolve
* @returns {Promise<Buffer|Stream>}
*/
static async resolveBuffer(resource) {
if (Buffer.isBuffer(resource)) return resource;
if (resource instanceof stream.Readable) return resource;
if (typeof resource === 'string') {
if (/^https?:\/\//.test(resource)) {
const res = await fetch(resource);
return res.body;
}
return new Promise((resolve, reject) => {
const file = path.resolve(resource);
fs.stat(file, (err, stats) => {
if (err) return reject(err);
if (!stats.isFile()) return reject(new Error('FILE_NOT_FOUND', file));
return resolve(fs.createReadStream(file));
});
});
}
throw new TypeError('REQ_RESOURCE_TYPE');
}
/**
* Options for sending message
* @typedef {Object} MessageOptions
* @property {string} [mode] Parsing
* mode,This can be:
* * MarkdownV2
* * Markdown
* * HTML
* @property {boolean} [silent=false]
* Whether to disable notification
* while sending message
* @property {Array} [entities] Array
* of special entities that appear in
* message text, which can be specified
* instead of parse_mode ({@link http
* ://core.telegram.org/bot
* /api#messageentity})
* @property {boolean} [embedLink
* =true] Whether to enable links
* preview or not
* @property {number} [reply] If the
* message is a reply, ID of the
* original message
* @property {boolean} [force] Pass
* true,if the message should be sent
* even if the specified replied-to
* message is not found
* @property {ReplyMarkup} [markup]
* Reply markups
* @property {...*} [others] Other
* options for specific method
*/
static parseOptions(options = {}) {
const defaults = {
silent: false,
embedLinks: true,
force: true,
};
options = Util.mergeDefault(defaults, options);
const { embedLinks, silent, force, mode, reply, markup, ...others } = options;
const body = {
disable_web_page_preview: !embedLinks,
disable_notification: silent,
allow_sending_without_reply: force,
};
if (mode) body.parse_mode = mode;
if (reply) body.reply_to_message_id = reply;
if (markup) body.reply_markup = markup;
return { ...body, ...others };
}
static isPlainObject(obj) {
if (Buffer.isBuffer(obj)) return false;
if (obj instanceof stream.Readable) return false;
if (typeof obj === 'object') return true;
return false;
}
/**
* Type of message. This can be:
* * text
* * photo
* * audio
* * video
* * vudeoNote
* * voice
* * animation
* * sticker
* * contact
* * document
* * dice
* * poll
* * location
* @typedef {string} MessageTypes
*/
static messageTypes(msg) {
const Types = [
'text',
'photo',
'audio',
'video',
'videoNote',
'voice',
'animation',
'sticker',
'contact',
'document',
'dice',
'poll',
'location',
];
return Types.filter(type => {
if (type === 'text' && msg.content) return type;
// eslint-disable-next-line
if (Object.prototype.hasOwnProperty(msg, type)) return type;
return null;
})[0];
}
static isDoubleArray(array) {
return Array.isArray(array[0]);
}
} |
JavaScript | class Crypt {
/**
* @param {object} options - Options for the cryptographic functions.
*/
constructor (options) {
/**
* The key used for the chiper and dechiper.
*
* @type {Buffer}
*/
this.key = options.key ? Buffer.from(options.key) : Buffer.from("tKYit86jnt6J8TN6b7h96TBHR6UN9h3s");
/**
* The algorithm used for encryption.
*
* @type {string}
*/
this.algorithm = options.algorithm || "aes-256-cbc";
/**
* The salt used for hashes.
*
* @type {Buffer}
*/
this.salt = this.key.subarray(0, 15);
}
/**
* Encrypts a string.
*
* @param {string} string - The string to encrypt.
* @returns {string} The encrypted value.
*/
encrypt (string) {
const iv = randomBytes(16);
const chiper = createCipheriv(this.algorithm, this.key, iv);
const crypted = Buffer.concat([
Buffer.from(chiper.update(string)),
chiper.final()
]);
return this.atob(JSON.stringify({
iv: iv.toString("hex"),
data: crypted.toString("hex")
}));
}
/**
* Decrypts a string.
*
* @param {string} string - The encoded string to decrypt.
* @returns {string} The decrypted value.
*/
decrypt (string) {
let data = this.btoa(string);
data = JSON.parse(data);
data = {
iv: Buffer.from(data.iv, "hex"),
data: Buffer.from(data.data, "hex")
};
const dechiper = createDecipheriv(this.algorithm, this.key, data.iv);
const decrypted = Buffer.concat([
dechiper.update(data.data),
dechiper.final()
]);
return decrypted.toString();
}
/**
* Hashes a string with SHA512.
*
* @param {string} string - String to be hashed.
* @returns {string} The hash.
*/
hash (string) {
return pbkdf2Sync(Buffer.from(string), this.salt, 100, 64, "sha512").toString("hex");
}
/**
* Encodes a string to hexadecimal.
*
* @param {string} string - String to encode.
* @returns {string} Encoded string.
*/
atob (string) {
return Buffer.from(string).toString("hex");
}
/**
* Decodes a string from hexadecimal.
*
* @param {string} string - String to decode.
* @returns {string} Decoded string/
*/
btoa (string) {
return Buffer.from(string, "hex").toString();
}
} |
JavaScript | class happeoCustomWidget extends LitElement {
static get properties() {
return {
uniqueId: { type: String },
mode: { type: String },
user: { state: true },
};
}
connectedCallback() {
super.connectedCallback();
this.doInit();
}
async doInit() {
// Init API
const widgetApi = await widgetSDK.api.init(this.uniqueId);
// Do stuff
this.user = await widgetApi.getCurrentUser();
console.log("I am all good and ready to go!", this.user);
}
render() {
return html`
<div class="wrapper">
<h1>
Happeo custom widget ${this.mode === "edit" ? "[edit mode]" : ""}
</h1>
<p>
${(this.user && html`Hi, ${this.user.name.fullName}!`) ||
html`initializing...`}
</p>
<p>Useful resources</p>
<ul>
<li>
<p>
<a
href="https://github.com/happeo/custom-widget-templates"
target="_blank"
>Custom widget templates</a
>
</p>
</li>
<li>
<p>
<a href="https://github.com/happeo/widgets-sdk" target="_blank"
>Widget SDK</a
>
</p>
</li>
<li>
<p>
<a href="https://uikit.happeo.com/" target="_blank"
>Happeo UI kit</a
>
</p>
</li>
</ul>
</div>
`;
}
static styles = css`
.wrapper {
position: relative;
}
p {
font-size: 16px;
}
h1,
p + p {
margin-top: 4px;
}
`;
} |
JavaScript | class Group extends APIObject {
_parse(data) {
/**
* MangaDex Group ID
* @type {Number}
*/
this.id = data.id;
/**
* Viewcount (Web Parsing)
* @type {String}
*/
this.views = data.views ? parseInt(data.views.replace(/\D/g, "")) : undefined;
/**
* Group language code (Web Parsing)
* @type {String}
*/
this.language = data.language ? data.language.toUpperCase(): undefined;
/**
* Group description (Web Parsing)
* @type {String}
*/
this.description = data.description ? data.description.replace(/<\s*br\s*\/>/gmi, ""): undefined; // Removes <br />
/**
* Followers (Web Parsing)
* @type {String}
*/
this.followers = data.followers ? parseInt(data.followers.replace(/\D/g, "")) : undefined;
/**
* Number of chapters uploaded (Web Parsing)
* @type {String}
*/
this.uploads = data.uploads ? parseInt(data.uploads.replace(/\D/g, "")) : undefined;
/**
* Official Group Name (Web Parsing)
* @type {String}
*/
this.title = data.title;
/**
* Official Group Links (Web Parsing)
* Website, Discord, IRC, and Email
* @type {Object}
*/
this.links = {};
if (data.website) this.links.website = data.website;
if (data.discord) this.links.discord = data.discord;
if (data.irc) this.links.irc = data.irc;
if(data.email) this.links.email = data.email;
/**
* Leader User Object (Web Parsing)
* Contains ID only, use fill() for full data.
* @type {User}
*/
this.leader = data.leader ? new User(parseInt(data.leader)) : undefined;
/**
* Array of members (Web Parsing)
* @type {Array<User>}
*/
this.members = [];
if (data.members) for (let i of data.members) this.members.push(new User(i));
}
fill(id) {
const web = "https://mangadex.org/group/";
if (!id) id = this.id;
return new Promise((resolve, reject) => {
if (!id) reject("No id specified or found.");
Util.getMatches(web + id.toString(), {
"title": /<span class=["']mx-1["']>(.*?)<\/span>/gmi,
"language": /<span class=["']mx-1["']>.*?<\/span>\s*?<span[^>]+flag-(\w{2})["']/gmi,
"views": /Stats:[\D\n]+([\d,]+)<\/li>[\D\n]+[\d,]+<\/li>[\D\n]+[\d,]+<\/li>/gmi,
"followers": /Stats:[\D\n]+[\d,]+<\/li>[\D\n]+([\d,]+)<\/li>[\D\n]+[\d,]+<\/li>/gmi,
"uploads": /Stats:[\D\n]+[\d,]+<\/li>[\D\n]+[\d,]+<\/li>[\D\n]+([\d,]+)<\/li>/gmi,
"website": /Links:[\d\D\n]+<a target=["']_blank["'] href=["']([^<>\s]+)["']><span[^<>]+title=["']Website["']/gmi,
"discord": /Links:[\d\D\n]+<a target=["']_blank["'] href=["']([^<>\s]+)["']><span[^<>]+title=["']Discord["']/gmi,
"irc": /Links:[\d\D\n]+<a target=["']_blank["'] href=["']([^<>\s]+)["']><span[^<>]+title=["']IRC["']/gmi,
"email": /Links:[\d\D\n]+<a target=["']_blank["'] href=["']([^<>\s]+)["']><span[^<>]+title=["']Email["']/gmi,
"description": /Description[\w\W\n]+<div class=["']card-body["']>([\w\W\n]+)<\/div>\s*?<\/div>\s*?<ul/gmi,
"leader": /Leader:[\w\W]*?href=["']\/user\/(\d+)\/.+["']>/gmi,
"members": /<li[^>]+><span[^>]+><\/span>\s?<a[^\/]+\/user\/(\d+)\/[^"']+["']>[^>]+><\/li>/gmi
}).then(matches => {
this._parse({...matches, id: id});
resolve(this);
}).catch(reject);
});
}
/**
* Executes Group.search() then executes fill() with the most relevent user.
* @param {String} query Quicksearch query like a name or description
*/
fillByQuery(query) {
return new Promise((resolve, reject) => {
Group.search(query).then((res)=>{
if (res.length == 0) reject("No Group Found");
else this.fill(parseInt(res[0])).then(resolve).catch(reject);
}).catch(reject);
});
}
/**
* Gets full MangaDex HTTPS link.
* @param {"id"|"flag"} property A property in this object
* Unknown properties defaults to MangaDex's homepage
* @returns {String} String with link
*/
getFullURL(property) {
const homepage = "https://mangadex.org";
switch(property) {
default:
return homepage;
case "id":
return homepage + "/group/" + this.id.toString();
case "flag":
return homepage + "/images/flags/" + this.language.toLowerCase() + ".png";
}
}
/**
* MangaDex group quicksearch
* @param {String} query Quicksearch query like a name or description
*/
static search(query) {
const regex = /<td><a href=["']\/group\/(\d+)\/[^"'\/<>]+["']>/gmi;
return Util.quickSearch(query, regex);
}
} |
JavaScript | class CustomButton extends Component {
//Render the elements
render() {
return(
<Button onClick={this.props.handleShow} bsStyle={this.props.color} className="pull-right">{this.props.name}</Button>
);
}
} |
JavaScript | class Registry {
constructor({ chainInfo, metadata, chainTypes }) {
createMetadata.clear();
const registry = new TypeRegistry();
registry.setChainProperties(
registry.createType(
'ChainProperties',
chainInfo.properties,
),
);
registry.setKnownTypes({
types: chainTypes || types,
});
registry.register(getSpecTypes(registry, chainInfo.name, chainInfo.specName, chainInfo.specVersion));
registry.setMetadata(createMetadata(registry, metadata));
/* eslint-disable no-underscore-dangle */
this._registry = registry;
this._metadata = metadata;
this._chainInfo = chainInfo;
}
get registry() {
return this._registry;
}
get metadata() {
return this._metadata;
}
get chainInfo() {
return this._chainInfo;
}
} |
JavaScript | class XRCoordinateSystem {
constructor(display, type, cartographicCoordinates=null){
this._display = display
this._type = type
this._cartographicCoordinates = cartographicCoordinates
}
get cartographicCoordinates(){ return this._cartographicCoordinates }
get type(){ return this._type }
get _poseModelMatrix(){
switch(this._type){
case XRCoordinateSystem.HEAD_MODEL:
return this._display._headPose.poseModelMatrix
case XRCoordinateSystem.EYE_LEVEL:
return this._display._eyeLevelPose.poseModelMatrix
case XRCoordinateSystem.TRACKER:
return this._display._trackerPoseModelMatrix
case XRCoordinateSystem.GEOSPATIAL:
throw 'This polyfill does not yet handle geospatial coordinate systems'
default:
throw 'Unknown coordinate system type: ' + this._type
}
}
getCoordinates(position=[0,0,0], orientation=[0,0,0,1]){
return new XRCoordinates(this._display, this, position, orientation)
}
getTransformTo(otherCoordinateSystem){
let out = new Float32Array([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
])
// apply inverse of other system's poseModelMatrix to the identity matrix
let inverse = new Float32Array(16)
MatrixMath.mat4_invert(inverse, otherCoordinateSystem._poseModelMatrix)
MatrixMath.mat4_multiply(out, inverse, out)
// apply this system's poseModelMatrix
MatrixMath.mat4_multiply(out, this._poseModelMatrix, out)
return out
}
} |
JavaScript | class CodeSplit {
/**
* The optional name to be used when called by Mix.
* Defaults to the class name.
*
* @return {String|Array}
*/
name() {
return ['split', 'codeSplit'];
}
/**
* All dependencies that should be installed by Mix.
*
* @return {Array}
*/
dependencies() {
return ['laravel-js-str'];
}
/** Run The Split Command via a specific mix method **/
register(via, folder, to, ...parameters) {
CollectFiles(folder).map(file => str(file).afterLast(file, '/').toString())
.filter(file => file !== null && typeof file !== "undefined")
.forEach(
file => typeof parameters === 'undefined'
? via(path.resolve(Mix.paths.rootPath, `${folder}/${file}`), path.resolve(Mix.paths.rootPath, (`${to}/${file}`)))
: via(path.resolve(Mix.paths.rootPath, `${folder}/${file}`), path.resolve(Mix.paths.rootPath, (`${to}/${file}`)), ...parameters)
);
}
} |
JavaScript | class GvDatePicker extends LitElement {
static get properties () {
return {
range: { type: Boolean },
label: { type: String },
time: { type: Boolean },
value: { type: Array, reflect: true },
min: { type: Number },
max: { type: Number },
distanceFromNow: { type: Number },
disabledDates: { type: Array },
format: { type: String },
invalid: { type: Boolean, reflect: true },
valid: { type: Boolean, reflect: true },
_hoveredDate: { type: String, attribute: false },
_open: { type: Boolean, attribute: false },
_month: { type: String, attribute: false },
_year: { type: String, attribute: false },
_monthPlus: { type: String, attribute: false },
_yearPlus: { type: Number, attribute: false },
_mode: { type: String, attribute: false },
_from: { type: Number, attribute: false },
_to: { type: Number, attribute: false },
_min: { type: Number, attribute: false },
_max: { type: Number, attribute: false },
_distance: { type: Number, attribute: false },
};
}
static get styles () {
return [
// language=CSS
css`
:host {
box-sizing: border-box;
display: inline-block;
margin: 0.2rem;
--gv-input-icon--bgc: transparent;
--gv-icon--s: 20px;
--date-picker-hover--bgc: var(--gv-date-picker-hover--bgc, var(--gv-theme-color-light, #86c3d0));
--date-picker-hover--c: var(--gv-date-picker-hover--c, var(--gv-theme-font-color-dark, #262626));
--date-picker-selected--bgc: var(--gv-date-picker-selected--bgc, var(--gv-theme-color, #5A7684));
--date-picker-selected--c: var(--gv-date-picker-selected--c, var(--gv-theme-font-color-light, #FFFFFF));
}
.box {
display: inline-block;
width: 100%;
}
gv-input {
width: 160px;
--gv-icon--s: 16px;
margin: 0;
}
.time gv-input {
width: 205px
}
:not(.range) gv-input {
width: 100%;
}
.range gv-input {
--gv-input--bds: none;
--gv-input--bdw: 0;
}
.time .range-input gv-input {
width: 150px;
}
.range-input gv-input {
width: 120px;
}
.range.hasFrom.open gv-input:first-of-type, .range.hasFrom.open .box-icon:first-of-type {
border-bottom: 1px solid var(--gv-date-picker-selected--bgc, var(--gv-theme-color, #5A7684));
}
.range.hasTo.open gv-input:last-of-type, .range.hasTo.open .box-icon:not(.box-icon-calendar) {
border-bottom: 1px solid var(--gv-date-picker-selected--bgc, var(--gv-theme-color, #5A7684));
}
.range-input {
position: relative;
z-index: 10;
border: var(--gv-input--bdw, 1px) var(--gv-input--bds, solid) var(--gv-input--bdc, var(--gv-theme-neutral-color-dark, #D9D9D9));
border-radius: 4px;
margin: 0.2rem;
display: flex;
}
.box-icon {
display: flex;
justify-content: center;
align-items: center;
}
.box-icon-calendar {
--gv-icon--s: 16px;
padding: 0 6px;
}
.box-icon-arrow,
.box-icon-calendar {
--gv-icon--c: var(--gv-theme-neutral-color-darker);
}
.box-icon-clear {
--gv-icon--s: 16px;
padding-right: 6px;
width: 22px;
}
.box-icon-clear gv-icon {
cursor: pointer;
}
.box.open .calendar {
visibility: visible;
opacity: 1;
-webkit-transform: -webkit-translateY(0%);
transform: translateY(0%);
z-index: 100;
}
.calendar {
background-color: var(--gv-theme-neutral-color-lightest, #FFFFFF);
color: var(--gv-theme-font-color, #262626);
margin: 0.2rem;
position: absolute;
box-shadow: 0 0 0 1px var(--gv-theme-neutral-color, #F5F5F5), 0 1px 3px var(--gv-theme-neutral-color-dark, #BFBFBF);
border-radius: 2px;
display: flex;
cursor: pointer;
visibility: hidden;
opacity: 0;
-webkit-transform: -webkit-translateY(-2em);
transform: translateY(-2em);
-webkit-transition: -webkit-transform 150ms ease-in-out, opacity 150ms ease-in-out;
-moz-transition: all 150ms ease-in-out;
-ms-transition: all 150ms ease-in-out;
-o-transition: all 150ms ease-in-out;
overflow: auto;
position: absolute;
}
:host([invalid]) .range-input {
border-left: 5px solid #a94442;
padding-left: 0;
}
:host([invalid]) .box-icon-calendar {
padding-left: 2px;
}
`,
];
}
constructor () {
super();
this._id = 'gv-id';
this.range = false;
this.time = false;
this.format = 'dd/MM/yyyy';
const format = i18n('gv-date-picker.format');
if (format !== 'unknown') {
this.format = format;
}
this.timeFormat = 'HH:mm';
this.handleClick = this._onClick.bind(this);
this.handleDocumentClick = this._onDocumentClick.bind(this);
this.disabledDates = [];
}
connectedCallback () {
super.connectedCallback();
this.addEventListener('click', this.handleClick);
document.addEventListener('click', this.handleDocumentClick);
this.getLocale().then((locale) => {
this._year = format(new Date().getTime(), 'yyyy', { locale });
this._month = format(new Date().getTime(), 'MM', { locale });
});
}
disconnectedCallback () {
clearInterval(this._distanceTimer);
this.removeEventListener('click', this.handleClick);
document.removeEventListener('click', this.handleDocumentClick);
super.disconnectedCallback();
}
set min (value) {
this._min = parseInt(value / 1000, 10);
}
set max (value) {
this._max = parseInt(value / 1000, 10);
}
set distanceFromNow (value) {
this._distance = value;
this._max = parseInt(Date.now() / 1000, 10);
this._min = parseInt((Date.now() - value) / 1000, 10);
if (this._from && this._from < this._min) {
this._from = this._min;
}
}
_onClick (e) {
e.preventDefault();
e.stopPropagation();
}
_onDocumentClick (e) {
this._open = false;
this.performUpdate();
}
_onFocus (mode) {
this._open = true;
if (this.time && this.range) {
this._mode = mode;
}
this.performUpdate();
}
async getLocale () {
const lang = getLanguage();
if (!lang) {
return locales.en;
}
if (!locales[lang]) {
try {
const locale = await import(`date-fns/locale/${lang}/index.js`);
locales[lang] = locale.default;
}
catch (e) {
console.error(`[Error] cannot load locale ${lang}`, e);
}
}
return locales[lang];
}
get dateFromPlaceholder () {
if (this.range) {
return i18n('gv-date-picker.startDate');
}
return this.getFormat();
}
get dateToPlaceholder () {
if (this.range) {
return i18n('gv-date-picker.endDate');
}
return this.getFormat();
}
get icon () {
return this._from != null || this._to != null ? 'code:error' : 'general:calendar';
}
get hasContent () {
return this._from != null || this._to != null;
}
_onClear () {
this.invalid = false;
this.value = null;
this.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
dispatchCustomEvent(this, 'input', this.value);
}
render () {
const classes = {
box: true,
open: this._open,
range: this.range,
time: this.time,
hasFrom: this.hasFrom(),
hasTo: this.hasTo(),
};
return html`
<div class="${classMap(classes)}">
${this.range ? html`
${this.label ? html`<label for=${this._id} title="${this.label}">${this.label}</label>` : ''}
<div class="range-input">
<div class="box-icon box-icon-calendar"><gv-icon shape=general:calendar></gv-icon></div>
<gv-input
id="${this._id}"
@focus="${this._onFocus.bind(this, 'from')}"
@blur="${this._onBlurForm}"
@gv-input:submit="${this._onBlurForm}"
.value="${until(this.getFormattedDate(this._from))}"
.placeholder="${this.dateFromPlaceholder}"
></gv-input>
<div class="box-icon box-icon-arrow"><gv-icon shape="navigation:arrow-right"></gv-icon></div>
<gv-input
.placeholder="${this.dateToPlaceholder}"
@focus="${this._onFocus.bind(this, 'to')}"
@blur="${this._onBlurTo}"
@gv-input:submit="${this._onBlurTo}"
.value="${until(this.getFormattedDate(this._to))}"></gv-input>
<div class="box-icon box-icon-clear">${this.hasContent ? html`<gv-icon class="link" @click=${this._onClear} shape=code:error></gv-icon>` : ''}</div>
`
: html`
<gv-input
id="${this._id}"
icon="general:calendar"
clearable
.label="${this.label}"
@focus="${this._onFocus.bind(this, null)}"
@blur="${this._onBlurForm}"
?invalid="${this.invalid}"
@gv-input:submit="${this._onBlurForm}"
@gv-input:clear="${this._onClear}"
.placeholder="${this.dateToPlaceholder}"
.value="${until(this.getFormattedDate(this._from))}"></gv-input></div>
`}
<span class="calendar">
${this.range ? html`
${this.hasFrom() ? html`<gv-date-picker-calendar
.disabledDates="${this.disabledDates}"
.min="${this._min}"
.max="${this._max}"
?time="${this.time}"
?prev="${true}"
?next="${this.time}"
?range="${this.range && !this.time}"
.month="${this._month}"
.year="${this._year}"
.hoveredDate="${this._hoveredDate}"
.dateTo="${this._to}"
.dateFrom="${this._from}"
.locale="${until(this.getLocale())}"
@gv-date-picker-calendar:month-mode="${this._onMonthMode}"
@gv-date-picker-calendar:year-mode="${this._onYearMode}"
@gv-date-picker-calendar:month-changed="${this._onMonthChanged}"
@gv-date-picker-calendar:year-changed="${this._onYearChanged}"
@hovered-date-changed="${this.hoveredDateChanged}"
@date-to-changed="${this.dateToChanged}"
@date-from-changed="${this.dateFromChanged}">
</gv-date-picker-calendar>` : ''}
${this.hasTo() ? html`<gv-date-picker-calendar
.disabledDates="${this.disabledDates}"
.min="${this._min}"
.max="${this._max}"
?time="${this.time}"
?prev="${this.time}"
?next="${true}"
?range="${this.range && !this.time}"
.month="${this._monthPlus}"
.year="${this._yearPlus}"
.hoveredDate="${this._hoveredDate}"
.dateTo="${this._to}"
.dateFrom="${this._from}"
.locale="${until(this.getLocale())}"
@gv-date-picker-calendar:month-mode="${this._onMonthMode}"
@gv-date-picker-calendar:year-mode="${this._onYearMode}"
@gv-date-picker-calendar:month-changed="${this._onMonthChanged}"
@gv-date-picker-calendar:year-changed="${this._onYearChanged}"
@hovered-date-changed="${this.hoveredDateChanged}"
@date-to-changed="${this.dateToChanged}"
@date-from-changed="${this.dateFromChanged}">
</gv-date-picker-calendar>` : ''}
` : html`
<gv-date-picker-calendar
.disabledDates="${this.disabledDates}"
.min="${this._min}"
.max="${this._max}"
?time="${this.time}"
?prev="${true}"
?next="${true}"
?range="${this.range}"
.month="${this._month}"
.year="${this._year}"
.hoveredDate="${this._hoveredDate}"
.dateTo="${this._to}"
.dateFrom="${this._from}"
.locale="${until(this.getLocale())}"
@hovered-date-changed="${this.hoveredDateChanged}"
@date-to-changed="${this.dateToChanged}"
@date-from-changed="${this.dateFromChanged}">
</gv-date-picker-calendar>
`}
</span>
</div>`;
}
hasFrom () {
return this._mode == null || this._mode === 'from';
}
hasTo () {
return this._mode == null || this._mode === 'to';
}
firstUpdated () {
if (this.time && this.range) {
this._mode = 'from';
}
if (this._distance) {
this._distanceTimer = setInterval(() => {
this.distanceFromNow = this._distance;
}, 30000);
}
}
monthChanged (month, year) {
if (year && month) {
const add = (this.time && this.range) ? 0 : 1;
const monthPlus = `0${((month % 12) + add)}`;
this._monthPlus = monthPlus.substring(monthPlus.length - 2);
if (this._monthPlus === '01') {
this._yearPlus = parseInt(year, 10) + add;
}
else {
this._yearPlus = parseInt(year, 10);
}
}
}
updated (properties) {
if (properties.has('_month') || properties.has('_year')) {
this.monthChanged(this._month, this._year);
}
if (properties.has('value')) {
if (this.value == null || (this.value.filter && this.value.filter((v) => v != null).length === 0)) {
this._from = null;
this._to = null;
}
else {
if (this.range) {
this._from = this.value && this.value.length > 0 ? this.value[0] / 1000 : null;
this._to = this.value && this.value.length > 1 ? this.value[1] / 1000 : null;
}
else {
this._from = this.value / 1000;
}
}
}
}
_onMonthChanged ({ detail }) {
this._month = detail.month;
this._year = detail.year;
this._hoveredDate = null;
if (!(this.range && this.time)) {
this._mode = null;
}
}
_onYearChanged ({ detail }) {
this._year = detail.year;
}
_onMonthMode ({ detail }) {
if (this.time && this.range) {
this._month = detail.month;
this._year = detail.year;
}
}
_onYearMode ({ detail }) {
if (this.time && this.range) {
this._month = detail.month;
this._year = detail.year;
}
}
_onBlurForm ({ target }) {
const value = target.value;
if (value) {
const date = this.parseValue(value);
if (date && !isNaN(date)) {
this._month = (getMonth(date) + 1).toString();
this._year = (getYear(date)).toString();
this._from = date.getTime() / 1000;
// if (this.time) {
// this._hour = date.getHours().toString();
// this._minute = date.getHours().toString();
// }
this.invalid = isInvalid(this._from, this._min, this._max, !this.time);
}
}
}
_onBlurTo ({ target }) {
const value = target.value;
if (value) {
const date = this.parseValue(value);
if (date && !isNaN(date)) {
this._month = (getMonth(date) + 1).toString();
this._year = (getYear(date)).toString();
this._to = date.getTime() / 1000;
this.invalid = isInvalid(this._to, this._min, this._max, !this.time);
}
}
}
hoveredDateChanged ({ detail }) {
this._hoveredDate = detail.value;
}
dateFromChanged ({ detail }) {
if (this.time && this.range) {
if (this._mode === 'from') {
this._from = detail.value;
const inputs = this.shadowRoot.querySelectorAll('.range-input gv-input');
inputs[inputs.length - 1].focus();
setTimeout(() => (this._mode = 'to'), 0);
}
else {
this._to = detail.value;
this._open = false;
if (this._to < this._from) {
const tmp = this._to;
this._to = this._from;
this._from = tmp;
}
}
}
else if (!this.range) {
this._from = detail.value;
this._open = false;
}
else {
this._from = detail.value;
}
if (this._distance) {
this.distanceFromNow = this._distance;
}
if (this.range) {
this.value = [this._from * 1000, this._to * 1000];
this.invalid = isInvalid(this._to, this._min, this._max, !this.time) || isInvalid(this._from, this._min, this._max, !this.time) || this._to === this._form;
}
else {
this.value = this._from * 1000;
this.invalid = isInvalid(this._from, this._min, this._max, !this.time);
}
this.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
dispatchCustomEvent(this, 'input', this.value);
}
dateToChanged ({ detail }) {
if (this._distance) {
this.distanceFromNow = this._distance;
}
this._to = detail.value;
if (this._to) {
this._open = false;
this.value = [this._from * 1000, this._to * 1000];
this.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
dispatchCustomEvent(this, 'input', this.value);
}
}
getFormat () {
return this.time ? `${this.format} ${this.timeFormat}` : this.format;
}
async getFormattedDate (date) {
if (date) {
const locale = await this.getLocale();
return format(new Date(date * 1000), this.getFormat(), locale);
}
return '';
}
parseValue (value) {
if (value) {
return parse(value, this.getFormat(), new Date());
}
return '';
}
} |
JavaScript | class JSONItemHelper extends BaseHelper {
/**
* The constructor for a helper that manages JSON artifacts.
*
* @constructs JSONItemHelper
*
* @param {BaseREST} restApi - The REST API object managed by this helper.
* @param {BaseFS} fsApi - The FS object managed by this helper.
* @param {String} artifactName - The name of the "artifact type" managed by this helper.
* @param {String} [classification] - Optional classification of the artifact type - defaults to artifactName
*/
constructor (restApi, fsApi, artifactName, classification) {
super(restApi, fsApi, artifactName, classification);
}
/**
* Determines if the artifact directory exists locally.
*
* @returns {boolean}
*/
doesDirectoryExist(context, opts) {
const dir = this._fsApi.getPath(context, opts);
return fs.existsSync(dir);
}
/**
* Get the name to be displayed for the given item.
*
* @param {Object} item - The item for which to get the name.
*
* @returns {String} The name to be displayed for the given item.
*/
getName (item) {
// Display the ID of the artifact, or the name if the ID doesn't exist.
if (item.id) {
return item.id;
}
return item.name;
}
/**
* Get the name to be displayed for the given item.
* Path by default, fallback to id then name
*
* Don't fallback to getName since that may have been overwritten to call
* this method, which could then cause infinite recursion
*
* @param {Object} item - The item for which to get the name.
*
* @returns {String} The name to be displayed for the given item.
*/
getPathName (item) {
if (item.path)
return item.path;
else if (item.hierarchicalPath)
return item.hierarchicalPath;
else if (item.id) {
return item.id;
}
return item.name;
}
/**
* Get the item on the local file system with the given name.
*
* @param {Object} context The API context to be used by the get operation.
* @param {String} name - The name of the item.
* @param {Object} opts - The options to be used to get the item.
*
* @returns {Q.Promise} A promise to get the item on the local file system with the given name.
*
* @resolves {Object} The item on the local file system with the given name.
*/
getLocalItem (context, name, opts) {
// Return the FS object's promise to get the local item with the given name.
return this._fsApi.getItem(context, name, opts);
}
/**
* Get the items on the local file system.
*
* @param {Object} context The API context to be used by the get operation.
* @param {Object} opts - The options to be used to get the items.
*
* @returns {Q.Promise} A promise to get the items on the local file system.
*
* @resolves {Array} The items on the local file system.
*/
getLocalItems (context, opts) {
// Return the FS object's promise to get the local items.
return this._fsApi.getItems(context, opts);
}
/**
* Get the specified item on the remote content hub.
*
* @param {Object} context The API context to be used by the get operation.
* @param {String} id The id of the item to retrieve
* @param {Object} opts - The options to be used to get the items.
*
* @returns {Q.Promise} A promise to get the items on the remote content hub.
*
* @resolves {Array} The items on the remote content hub.
*/
getRemoteItem (context, id, opts) {
// Return the REST object's promise to get the remote item.
return this._restApi.getItem(context, id, opts);
}
/**
* Create the given item on the remote content hub.
*
* @param {Object} context The API context to be used by the create operation.
* @param {Object} item - The item to be created.
* @param {Object} opts - The options to be used for the create operation.
*
* @returns {Q.Promise} A promise to create the given item on the remote content hub.
*
* @resolves {Object} The item that was created.
*/
createRemoteItem (context, item, opts) {
// Return the REST object's promise to create the remote item.
return this._restApi.createItem(context, item, opts);
}
/**
* Push the local item with the given name to the remote content hub.
*
* Note: The remote item will be created if it does not exist, otherwise the remote item will be updated.
*
* @param {Object} context The API context to be used for this operation.
* @param {String} name - The name of the item to be pushed.
* @param {Object} opts - The options to be used for the push operation.
*
* @returns {Q.Promise} A promise to push the local item with the given name to the remote content hub.
*
* @resolves {Object} The item that was pushed.
*/
pushItem (context, name, opts) {
// Return the promise to to get the local item and upload it to the content hub.
const helper = this;
let errorInfo = name;
return helper._fsApi.getItem(context, name, opts)
.then(function (item) {
errorInfo = item;
// Check whether the item should be uploaded.
if (helper.canPushItem(item)) {
// Save the original file name, in case the result of the push is saved to a file with a different name.
return helper._uploadItem(context, item, utils.cloneOpts(opts, {originalPushFileName: name}));
} else {
// Add a log entry if we try to push an item that can't be pushed.
helper.getLogger(context).info(i18n.__("cannot_push_item" , {name: name}));
}
})
.catch(function (err) {
// Only emit the error event if it hasn't already been emitted and we won't be doing a retry.
if (!err.emitted && !err.retry) {
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pushed-error", err, {
id: errorInfo["id"],
name: errorInfo["name"],
path: (errorInfo["path"] || name["path"] || name)
});
}
}
throw err;
});
}
/**
* Push the items in the current manifest from the local file system to the remote content hub.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The options to be used for the push operations.
*
* @returns {Q.Promise} A promise to push the local items to the remote content hub.
*
* @resolves {Array} The items that were pushed.
*/
pushManifestItems (context, opts) {
// Get the names (actually the proxy items) from the current manifest and push them to the content hub.
const helper = this;
return helper.getManifestItems(context, opts)
.then(function (items) {
return helper._pushNameList(context, items, opts);
});
}
/**
* Push all items from the local file system to the remote content hub.
*
* Note: The remote items will be created if they do not exist, otherwise the remote items will be updated.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for the push operation.
*
* @returns {Q.Promise} A promise to push the local items to the remote content hub.
*
* @resolves {Array} The items that were pushed.
*/
pushAllItems (context, opts) {
// Return the promise to get the list of local item names and push those items to the content hub.
const helper = this;
return helper._listLocalItemNames(context, opts)
.then(function (names) {
return helper._pushNameList(context, names, opts);
});
}
/**
* Push any modified items from the local file system to the remote content hub.
*
* Note: The remote items will be created if they do not exist, otherwise the remote items will be updated.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for the push operation.
*
* @returns {Q.Promise} A promise to push the modified local items to the remote content hub.
*
* @resolves {Array} The modified items that were pushed.
*/
pushModifiedItems (context, opts) {
// Return the promise to to get the list of modified local item names and push those items to the content hub.
const helper = this;
return helper._listModifiedLocalItemNames(context, [helper.NEW, helper.MODIFIED], opts)
.then(function (names) {
return helper._pushNameList(context, names, opts);
});
}
makeEmittedObject(context, item, opts) {
return {id: item.id, name: item.name, path: item.path};
}
/**
* Pull the item with the given id from the remote content hub to the local file system.
*
* Note: The local item will be created if it does not exist, otherwise the local item will be overwritten.
*
* @param {Object} context The API context to be used for this operation.
* @param {String} id - The ID of the item to be pulled.
* @param {Object} opts - The options to be used for the pull operation.
*
* @returns {Q.Promise} A promise to pull the remote item to the local file system.
*
* @resolves {Array} The item that was pulled.
*/
pullItem (context, id, opts) {
// Return the promise to get the remote item and save it on the local file system.
const helper = this;
return helper.getRemoteItem(context, id, opts)
.then(function (item) {
// Check whether the item should be saved to file.
if (helper.canPullItem(item, context, opts)) {
return helper._fsApi.saveItem(context, item, opts);
} else {
// If the item returned by the service cannot be pulled, add a log entry.
helper.getLogger(context).info(i18n.__("cannot_pull_item" , {name: helper.getName(item)}));
}
})
.then(function (item) {
if (item) {
// Use the event emitter to indicate that the item was successfully pulled.
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pulled", helper.makeEmittedObject(context, item, opts));
emitter.emit("post-process", item);
}
}
return item;
})
.catch(function (err) {
// Use the event emitter to indicate that there was an error pulling the item.
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pulled-error", err, id);
}
throw err;
});
}
/**
* Pull the items in the current manifest from the remote content hub to the local file system.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The options to be used for the pull operations.
*
* @returns {Q.Promise} A promise to pull the remote items to the local file system.
*
* @resolves {Array} The items that were pulled.
*/
pullManifestItems (context, opts) {
// Get the names (actually the proxy items) from the current manifest and pull them from the content hub.
const helper = this;
return helper.getManifestItems(context, opts)
.then(function (items) {
return helper._pullItemList(context, items, opts);
});
}
/**
* Pull all items from the remote content hub to the local file system.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The options to be used for the pull operations.
*
* @returns {Q.Promise} A promise to pull the remote items to the local file system.
*
* @resolves {Array} The items that were pulled.
*/
pullAllItems (context, opts) {
// Keep track of the error count.
context.pullErrorCount = 0;
const deletions = options.getRelevantOption(context, opts, "deletions");
let allFSItems;
if (deletions) {
allFSItems = this._listLocalItemNames(context, opts);
}
// Get the timestamp to set before we call the REST API.
const timestamp = new Date().toISOString();
// Pull a "chunk" of remote items and and then recursively pull any remaining chunks.
const helper = this;
const listFn = helper._getRemoteListFunction(context, opts);
const handleChunkFn = helper._pullItemsChunk.bind(helper);
// After the promise has been resolved, update the last pull timestamp.
return helper.recursiveGetItems(context, listFn, handleChunkFn, opts)
.then(function (items) {
const filterPath = options.getRelevantOption(context, opts, "filterPath");
// Only update the last pull timestamp if there were no errors and items are not being filtered by path.
if ((context.pullErrorCount === 0) && !filterPath) {
helper._setLastPullTimestamps(context, timestamp, opts);
}
const emitter = helper.getEventEmitter(context);
if (deletions && emitter) {
return allFSItems.then(function (values) {
const pulledIDs = items.map(function (item) {
return item.id;
});
values.forEach(function (item) {
if (pulledIDs.indexOf(item.id) === -1) {
emitter.emit("local-only", item);
}
});
return items;
});
} else {
return items;
}
})
.finally(function () {
delete context.pullErrorCount;
});
}
/**
* Returns a function to be used for the list remote items functionality. The returned function should accept a single opts argument.
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The options to be used for the pull operations.
* @return the function to call to list remote items.
* @private
*/
_getRemoteListFunction (context, opts) {
// Use getRemoteItems() as the list function, so that all artifacts will be pulled.
return this.getRemoteItems.bind(this, context);
}
/**
* Given an array of items, filter those that are modified based on the flags.
* @param context
* @param items
* @param flags
* @param opts
* @private
*/
_filterRemoteModified (context, items, flags, opts) {
const helper = this;
const dir = helper._fsApi.getPath(context, opts);
return items.filter(function (item) {
try {
const itemPath = helper._fsApi.getItemPath(context, item, opts);
return hashes.isRemoteModified(context, flags, item, dir, itemPath, undefined, opts);
} catch (err) {
utils.logErrors(context, i18n.__("error_filtering_remote_items"), err);
}
});
}
/**
* Returns a function to be used for the modified list remote items functionality. The returned function should accept a single opts argument.
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The options to be used for the pull operations.
* @return the function to call to list modified remote items.
* @private
*/
_getRemoteModifiedListFunction (context, flags, opts) {
// Use getModifiedRemoteItems() as the list function, so that all modified artifacts will be pulled.
return this.getModifiedRemoteItems.bind(this, context, flags);
}
/**
* Pull any modified items from the remote content hub to the local file system.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for the pull operations.
*
* @returns {Q.Promise} A promise to pull the modified remote items to the local file system.
*
* @resolves {Array} The modified items that were pulled.
*/
pullModifiedItems (context, opts) {
// Keep track of the error count.
context.pullErrorCount = 0;
// Get the timestamp to set before we call the REST API.
const timestamp = new Date().toISOString();
// Pull a "chunk" of modified remote items and and then recursively pull any remaining chunks.
const helper = this;
const listFn = helper._getRemoteModifiedListFunction(context, [helper.NEW, helper.MODIFIED], opts);
const handleChunkFn = helper._pullItemsChunk.bind(helper);
// After the promise has been resolved, update the last pull timestamp.
return helper.recursiveGetItems(context, listFn, handleChunkFn, opts)
.then(function (items) {
const filterPath = options.getRelevantOption(context, opts, "filterPath");
// Only update the last pull timestamp if there were no errors and items are not being filtered by path.
if ((context.pullErrorCount === 0) && !filterPath) {
helper._setLastPullTimestamps(context, timestamp, opts);
}
return items;
})
.finally(function () {
delete context.pullErrorCount;
});
}
/**
* Get the timestamp for the last "similar" pull operation.
*
* @example "2017-01-16T22:30:05.928Z"
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The API options to be used for this operation.
*
* @returns {Object} The timestamp for the last "similar" pull operation, or undefined.
*/
getLastPullTimestamp(context, opts) {
const timestamps = this._getLastPullTimestamps(context, opts);
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
if (readyOnly) {
// A ready-only pull operation will use the ready timestamp.
return timestamps["ready"];
} else if (draftOnly) {
// A draft-only pull operation will use the draft timestamp.
return timestamps["draft"];
} else {
// A ready-and-draft pull operation will use the older timestamp to make sure all modified items are pulled.
return utils.getOldestTimestamp([timestamps["draft"], timestamps["ready"]]);
}
}
/**
* Get the timestamp data for the last pull operation, converting to the new draft/ready format if needed.
*
* @example {"draft": "2017-01-16T22:30:05.928Z", "ready": "2017-01-16T22:30:05.928Z"}
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts The API options to be used for this operation.
*
* @returns {Object} The last pull timestamp data.
*/
_getLastPullTimestamps(context, opts) {
const dir = this._fsApi.getDir(context, opts);
const timestamps = hashes.getLastPullTimestamp(context, dir, opts);
if (typeof timestamps === "string") {
// Convert from a single timestamp value to the new draft/ready format.
return {"draft": timestamps, "ready": timestamps};
} else {
// Return the existing data, or an empty object if there is no existing data.
return timestamps || {};
}
}
/**
* Set the timestamp data for the last pull operation.
*
* @param {Object} context The API context to be used for this operation.
* @param {Date} timestamp The current timestamp to be used.
* @param {Object} opts The API options to be used for this operation.
*/
_setLastPullTimestamps(context, timestamp, opts) {
const pullTimestamps = this._getLastPullTimestamps(context, opts);
// Store separate pull timestamps for draft and ready.
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
if (!draftOnly) {
// Store the ready timestamp if the operation is not draft only.
pullTimestamps["ready"] = timestamp;
}
if (!readyOnly) {
// Store the draft timestamp if the operation is not ready only.
pullTimestamps["draft"] = timestamp;
}
const dir = this._fsApi.getDir(context, opts);
hashes.setLastPullTimestamp(context, dir, pullTimestamps, opts);
}
/**
* Updates the manifest with results of a list operation.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} itemList The list of items to be added to the manifest.
* @param {Object} opts - The options to be used for the list operation.
*/
_updateManifest (context, itemList, opts) {
manifests.updateManifestSection(context, this.getArtifactName(), itemList, opts);
}
/**
* Updates the deletions manifest with results of a list operation.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} itemList The list of items to be added to the deletions manifest.
* @param {Object} opts - The options to be used for the list operation.
*/
_updateDeletionsManifest (context, itemList, opts) {
manifests.updateDeletionsManifestSection(context, this.getArtifactName(), itemList, opts);
}
/**
* Lists all local items.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for the push operation.
*
* @returns {Q.Promise} - A promise that resolves with an array of the names of
* all items that exist on the file system.
*/
_listLocalItemNames (context, opts) {
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
const helper = this;
if (readyOnly || draftOnly) {
// Make sure the proxy items contain the status.
opts = utils.cloneOpts(opts);
if (!opts["additionalItemProperties"]) {
opts["additionalItemProperties"] = [];
}
opts["additionalItemProperties"].push("status");
}
return this._fsApi.listNames(context, opts)
.then(function (itemList) {
// Filter the item list based on the ready and draft options.
if (readyOnly) {
// Filter out any items that are not ready.
itemList = itemList.filter(function (item) {
return (helper.getStatus(context, item, opts) === "ready");
});
} else if (draftOnly) {
// Filter out any items that are not draft.
itemList = itemList.filter(function (item) {
return (helper.getStatus(context, item, opts) === "draft");
});
}
return itemList;
});
}
/**
* Lists all local items.
* This function serves as an entry point for the list command and should not be internally called otherwise.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for the push operation.
*
* @returns {Q.Promise} - A promise that resolves with an array of the names of
* all items that exist on the file system.
*/
listLocalItemNames (context, opts) {
const helper = this;
return this._listLocalItemNames(context, opts)
.then(function (itemList) {
helper._updateManifest(context, itemList, opts);
return itemList;
});
}
/**
* Get an array of names for all items on the file system which have been modified since being pushed/pulled.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} flags An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
* @param {Object} opts The options to be used for the push operation.
*
* @returns {Q.Promise} A promise that resolves with an array of names for all items on the file system which have
* been modified since being pushed/pulled.
*/
_listModifiedLocalItemNames (context, flags, opts) {
const helper = this;
const fsObject = this._fsApi;
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
if (readyOnly || draftOnly) {
// Make sure the proxy items contain the status.
opts = utils.cloneOpts(opts);
if (!opts["additionalItemProperties"]) {
opts["additionalItemProperties"] = [];
}
opts["additionalItemProperties"].push("status");
}
const dir = fsObject.getPath(context, opts);
return fsObject.listNames(context, opts)
.then(function (itemNames) {
// Filter the item list based on the ready and draft options.
if (readyOnly) {
// Filter out any items that are not ready.
itemNames = itemNames.filter(function (item) {
return (helper.getStatus(context, item, opts) === "ready");
});
} else if (draftOnly) {
// Filter out any items that are not draft.
itemNames = itemNames.filter(function (item) {
return (helper.getStatus(context, item, opts) === "draft");
});
}
const results = itemNames.filter(function (itemName) {
if (itemName.id) {
const itemPath = fsObject.getItemPath(context, itemName, opts);
return hashes.isLocalModified(context, flags, dir, itemPath, undefined, opts);
} else {
helper.getLogger(context).info(i18n.__("file_skipped" , {path: itemName.path}));
return false;
}
});
if (flags.indexOf(helper.DELETED) !== -1) {
return helper.listLocalDeletedNames(context, opts)
.then(function (items) {
items.forEach(function (item) {
results.push(item);
});
return results;
});
} else {
return results;
}
});
}
/**
* Get an array of names for all items on the file system which have been modified since being pushed/pulled.
* This function serves as an entry point for the list command and should not be internally called otherwise.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} flags An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
* @param {Object} opts The options to be used for the push operation.
*
* @returns {Q.Promise} A promise that resolves with an array of names for all items on the file system which have
* been modified since being pushed/pulled.
*/
listModifiedLocalItemNames (context, flags, opts) {
const helper = this;
return this._listModifiedLocalItemNames(context, flags, opts)
.then(function(itemList) {
helper._updateManifest(context, itemList, opts);
return itemList;
});
}
listLocalDeletedNames (context, opts) {
const fsObject = this._fsApi;
const deferred = Q.defer();
const dir = fsObject.getPath(context, opts);
const extension = fsObject.getExtension();
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
deferred.resolve(hashes.listFiles(context, dir, opts)
.filter(function (item) {
let stat = undefined;
try {
stat = fs.statSync(dir + item.path);
} catch (ignore) {
// ignore this error we're testing to see if a file exists
}
return !stat;
})
.filter(function (item) {
// Filter the item list based on the ready and draft options.
const draft = item.id && (item.id.indexOf(":") >= 0);
if ((readyOnly && draft) || (draftOnly && !draft)) {
// Filter out any items that do not match the specified option.
return false;
} else {
return true;
}
})
.filter(function (item) {
return item.path.endsWith(extension);
})
.map(function (item) {
return {
id: item.id,
path: item.path.replace(extension, "")
};
}));
return deferred.promise;
}
_makeListItemResult (context, item, opts) {
return {
id: item.id,
name: item.name
};
}
/**
* Get a list of the names of all remote items.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of the names of all remote items.
*/
_listRemoteItemNames (context, opts) {
// Recursively call restApi.getItems() to retrieve all of the remote items.
const helper = this;
const listFn = helper._getRemoteListFunction(context, opts);
const handleChunkFn = helper._listItemChunk.bind(helper);
// Get the first chunk of remote items, and then recursively retrieve any additional chunks.
return helper.recursiveGetItems(context, listFn, handleChunkFn, opts)
.then(function (items) {
// Turn the resulting list of items (metadata) into a list of item names.
return items.map(function (item) {
return helper._makeListItemResult(context, item, opts);
});
});
}
/**
* Get a list of the names of all remote items.
* This function serves as an entry point for the list command and should not be internally called otherwise.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of the names of all remote items.
*/
listRemoteItemNames (context, opts) {
const helper = this;
return this._listRemoteItemNames(context, opts)
.then(function(itemList) {
helper._updateManifest(context, itemList, opts);
return itemList;
});
}
/**
* Get a list of the items that have been modified.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} flags - An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of all remote items that were modified since being pushed/pulled.
*/
getModifiedRemoteItems (context, flags, opts) {
const helper = this;
return helper._restApi.getModifiedItems(context, helper.getLastPullTimestamp(context, opts), opts)
.then(function (items) {
return helper._filterRemoteModified(context, items, flags, opts);
});
}
/**
* Get a list of the names of all remote items that have been modified.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} flags - An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of the names of all remote items that were modified since being
* pushed/pulled.
*/
_listModifiedRemoteItemNames (context, flags, opts) {
const helper = this;
const listFn = helper._getRemoteModifiedListFunction(context, flags, opts);
const handleChunkFn = helper._listItemChunk.bind(helper);
return helper.recursiveGetItems(context, listFn, handleChunkFn, opts)
.then(function (items) {
const results = items.map(function (item) {
return helper._makeListItemResult(context, item, opts);
});
if (flags.indexOf(helper.DELETED) !== -1) {
return helper.listRemoteDeletedNames(context, opts)
.then(function (items) {
items.forEach(function (item) {
results.push(item);
});
return results;
});
} else {
return results;
}
});
}
/**
* Get a list of the names of all remote items that have been modified.
* This function serves as an entry point for the list command and should not be internally called otherwise.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} flags - An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of the names of all remote items that were modified since being
* pushed/pulled.
*/
listModifiedRemoteItemNames (context, flags, opts) {
const helper = this;
return this._listModifiedRemoteItemNames(context, flags, opts)
.then(function(itemList) {
helper._updateManifest(context, itemList, opts);
return itemList;
});
}
/**
* Get a list of the names of all remote items that have been deleted.
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} opts - The options to be used for this operation.
*
* @returns {Q.Promise} - A promise for an array of the names of all remote items that were deleted since being
* pushed/pulled.
*/
listRemoteDeletedNames (context, opts) {
const deferred = Q.defer();
const dir = this._fsApi.getDir(context, opts);
const extension = this._fsApi.getExtension();
this._listRemoteItemNames(context, opts)
.then(function (remoteItems) {
deferred.resolve(
hashes.listFiles(context, dir, opts)
.filter(function (item) {
return item.path.endsWith(extension);
})
.map(function (item) {
return {
id: item.id,
path: item.path.replace(extension, "")
};
})
.filter(function (item) {
return (remoteItems.indexOf(item.path) === -1);
})
);
})
.catch(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
/**
* Gets a remote item by path.
*
* @param {Object} context The API context to be used for this operation.
* @param {String} path The path of the item to find.
* @param {Object} opts The options to be used for the operation.
*
* @returns {Q.Promise} A promise for the item to find.
*/
getRemoteItemByPath (context, path, opts) {
return this._restApi.getItemByPath(context, path, opts);
}
/**
* Determine whether the given item can be pulled.
*
* @param {Object} item The item to be pulled.
* @param {Object} context The API context to be used by the pull operation.
* @param {Object} opts The options to be used to pull the items.
*
* @returns {Boolean} A return value of true indicates that the item can be pulled. A return value of false
* indicates that the item cannot be pulled.
*/
canPullItem (item, context, opts) {
let retVal = super.canPullItem(item, context, opts);
if (retVal) {
// Do not pull system items unless the system option was specified.
retVal = (!item.isSystem || (options.getRelevantOption(context, opts, "allowSystemArtifacts") === true));
}
return retVal;
}
addIgnoreKeys (ignoreKeys, segments) {
const segment = segments.splice(0, 1)[0];
if (segments.length > 0) {
if (!ignoreKeys[segment]) {
ignoreKeys[segment] = {};
}
this.addIgnoreKeys(ignoreKeys[segment], segments);
} else {
ignoreKeys[segment] = undefined;
}
}
/**
* Return a set of extra keys to be ignored for this artifact type. This should be used to return a list
* of synthetic fields per artifact type.
*
* @return {Array} the names of the JSON elements to be ignored.
*/
getExtraIgnoreKeys() {
return [];
}
/**
* Return the keys that can be ignored as they can contain unimportant differences in artifacts of this type.
*
* @returns {Object} the ignore keys for this artifact type.
*/
getIgnoreKeys () {
const ignoreKeys = {};
["rev",
"created", "creator", "creatorId",
"lastModified", "lastModifier", "lastModifierId",
"systemModified",
"links", "types", "categories", "publishing", "hierarchicalPath"
].forEach(function (key) {
ignoreKeys[key] = undefined;
});
const self = this;
self.getExtraIgnoreKeys().forEach(function (key) {
self.addIgnoreKeys(ignoreKeys, key.split("/"));
});
return ignoreKeys;
}
/**
* Determine whether a push conflict between the provided localItem and remoteItem can be ignored.
*
* @param context The API context to be used for this operation.
* @param localItem The local item being pushed.
* @param remoteItem The remote item.
* @param opts The options for this operation.
* @returns {boolean}
*/
canIgnoreConflict (context, localItem, remoteItem, opts) {
const diffs = utils.compare(localItem, remoteItem, this.getIgnoreKeys());
return (diffs.added.length === 0 && diffs.removed.length === 0 && diffs.changed.length === 0);
}
/**
* Executes a compare operation between two local directories, two tenants, or a local directory and a tenant.
*
* @param context The API context to be used for this operation.
* @param opts The options for this operation.
*
* @returns {*}
*/
compare (context, target, source, opts) {
const self = this;
const targetIsUrl = utils.isValidApiUrl(target);
const sourceIsUrl = utils.isValidApiUrl(source);
const targetOpts = utils.cloneOpts(opts);
const sourceOpts = utils.cloneOpts(opts);
let targetListFunction;
let targetGetItemFunction;
if (targetIsUrl) {
targetOpts["x-ibm-dx-tenant-base-url"] = target;
if (context.readManifest) {
targetListFunction = self.getManifestItems.bind(self);
} else {
targetListFunction = self._wrapRemoteListFunction.bind(self, self._listRemoteItemNames.bind(self));
}
targetGetItemFunction = self._wrapRemoteItemFunction.bind(self, function (context, item, opts) {
return self.getRemoteItem(context, item.id, opts);
});
} else {
targetOpts.workingDir = target;
if (context.readManifest) {
targetListFunction = self.getManifestItems.bind(self);
} else {
targetListFunction = self._wrapLocalListFunction.bind(self, self._listLocalItemNames.bind(self));
}
targetGetItemFunction = self._wrapLocalItemFunction.bind(self, self.getLocalItem.bind(self));
}
let sourceListFunction;
let sourceGetItemFunction;
if (sourceIsUrl) {
sourceOpts["x-ibm-dx-tenant-base-url"] = source;
if (context.readManifest) {
sourceListFunction = self.getManifestItems.bind(self);
} else {
sourceListFunction = self._wrapRemoteListFunction.bind(self, self._listRemoteItemNames.bind(self));
}
sourceGetItemFunction = self._wrapRemoteItemFunction.bind(self, function (context, item, opts) {
return self.getRemoteItem(context, item.id, opts);
});
} else {
sourceOpts.workingDir = source;
if (context.readManifest) {
sourceListFunction = self.getManifestItems.bind(self);
} else {
sourceListFunction = self._wrapLocalListFunction.bind(self, self._listLocalItemNames.bind(self));
}
sourceGetItemFunction = self._wrapLocalItemFunction.bind(self, self.getLocalItem.bind(self));
}
const emitter = self.getEventEmitter(context);
const diffItems = {
diffCount: 0,
totalCount: 0
};
const handleRemovedItem = function (context, item, opts) {
// Add the item to the deletions manifest.
self._updateDeletionsManifest(context, [item], opts);
// Increment both the total items counter and diff counter.
diffItems.totalCount++;
diffItems.diffCount++;
// Emit a "removed" event for the target item.
if (emitter) {
emitter.emit("removed", {artifactName: self.getArtifactName(), item: item});
}
};
const handleAddedItem = function (context, item, opts) {
// Add the item to the manifest.
self._updateManifest(context, [item], opts);
// Increment both the total items counter and diff counter.
diffItems.totalCount++;
diffItems.diffCount++;
// Emit an "added" event for the source item.
if (emitter) {
emitter.emit("added", {artifactName: self.getArtifactName(), item: item});
}
};
const handleDifferentItem = function (context, object, diffs, opts) {
self._updateManifest(context, [object], opts);
// Increment both the total items counter and diff counter.
diffItems.totalCount++;
diffItems.diffCount++;
// Emit a "diff" event for the source item.
if (emitter) {
const item = self.makeEmittedObject(context, object, opts);
emitter.emit("diff", {artifactName: self.getArtifactName(), item: item, diffs: diffs});
}
};
const handleEqualItem = function (context, object, opts) {
// Increment the total items counter.
diffItems.totalCount++;
};
const handleMissingItem = function (context, object, opts) {
// Don't count the missing items, since no comparison was done.
};
return targetListFunction(context, targetOpts)
.then(function (unfilteredTargetItems) {
const targetItems = unfilteredTargetItems.filter(function (item) {
return self.canCompareItem(item, targetOpts);
});
return sourceListFunction(context, sourceOpts)
.then(function (unfilteredSourceItems) {
const sourceItems = unfilteredSourceItems.filter(function (item) {
return self.canCompareItem(item, sourceOpts);
});
const targetIds = targetItems.map(function (item) {
return item.id;
});
const sourceIds = sourceItems.map(function (item) {
return item.id;
});
const promises = [];
targetItems.forEach(function (targetItem) {
if (sourceIds.indexOf(targetItem.id) === -1) {
// The target id exists but the source id does not. The item has been removed.
handleRemovedItem(context, targetItem, opts);
}
});
const ignoreKeys = self.getIgnoreKeys();
sourceItems.forEach(function (sourceItem) {
if (targetIds.indexOf(sourceItem.id) === -1) {
// The source id exists but the target id does not. The item has been added.
handleAddedItem(context, sourceItem, opts);
} else {
// Both the source and target ids exist, so get the complete objects for comparison.
const deferredCompare = Q.defer();
promises.push(deferredCompare.promise);
targetGetItemFunction(context, sourceItem, targetOpts)
.then(function (targetObject) {
sourceGetItemFunction(context, sourceItem, sourceOpts)
.then(function (sourceObject) {
if (targetObject && sourceObject) {
// Both the target and source objects exist. Compare them.
const diffs = utils.compare(sourceObject, targetObject, ignoreKeys);
if (diffs.added.length > 0 || diffs.changed.length > 0 || diffs.removed.length > 0) {
// The objects are different.
handleDifferentItem(context, sourceObject, diffs, opts);
} else {
// The objects are equal.
handleEqualItem(context, sourceObject, opts);
}
} else if (targetObject) {
// The object exists in target but not source. It has been removed.
handleRemovedItem(context, targetObject, opts);
} else if (sourceObject) {
// The object exists in source but not target. It has been added.
handleAddedItem(context, sourceObject, opts);
} else {
// Neither the target nor source object exists. It is missing.
handleMissingItem(context, sourceItem, opts);
}
deferredCompare.resolve(true);
})
.catch(function (err) {
deferredCompare.reject(err);
});
})
.catch(function (err) {
deferredCompare.reject(err);
});
}
});
return Q.allSettled(promises)
.then(function () {
return diffItems;
});
});
});
}
/**
* Completes the push operation for the provided item.
*
* @param context The API context to be used for this operation.
* @param item The item that was pushed.
* @param opts The options for this operation.
*
* @returns {*}
*
* @private
*/
_pushComplete (context, item, opts) {
const emitter = this.getEventEmitter(context);
if (emitter) {
emitter.emit("pushed", this.makeEmittedObject(context, item, opts));
}
const rewriteOnPush = options.getRelevantOption(context, opts, "rewriteOnPush");
if (rewriteOnPush) {
return this._fsApi.saveItem(context, item, opts);
} else {
return item;
}
}
/**
*
* @param {Object} context The API context to be used for this operation.
* @param {Object} item
* @param {Object} opts
*
* @returns {Q.Promise}
*
* @private
*/
_uploadItem (context, item, opts) {
let promise;
let logError;
const isUpdate = item.id && item.rev;
if (isUpdate) {
promise = this._restApi.updateItem(context, item, opts);
logError = i18n.__("push_error_updating_item");
} else {
// No ID, so it has to be created
promise = this._restApi.createItem(context, item, opts);
logError = i18n.__("push_error_creating_item");
}
const helper = this;
return promise
.then(function (item) {
return helper._pushComplete(context, item, opts);
})
.catch(function (err) {
const name = opts.originalPushFileName || helper.getName(item);
const heading = logError + JSON.stringify(name);
// Determine whether the push of this item should be retried.
if (err.retry) {
// Add a retry entry to the helper.
const retryProperties = {};
retryProperties[BaseHelper.RETRY_PUSH_ITEM_NAME] = name;
retryProperties[BaseHelper.RETRY_PUSH_ITEM_ERROR] = err;
retryProperties[BaseHelper.RETRY_PUSH_ITEM_HEADING] = heading;
helper.addRetryPushProperties(context, retryProperties);
// Rethrow the error to propogate it back to the caller. Otherwise the caller won't know to retry.
throw(err);
} else {
const ignoreConflict = Q.defer();
let remoteItemPromise;
// Ignore a conflict (409) if the contents only differ in unimportant ways.
if (isUpdate && err.statusCode === 409) {
remoteItemPromise = helper.getRemoteItem(context, item.id, opts);
remoteItemPromise
.then(function (remoteItem) {
ignoreConflict.resolve(helper.canIgnoreConflict(context, item, remoteItem, opts));
})
.catch(function (remoteItemErr) {
ignoreConflict.reject(err);
});
} else {
ignoreConflict.resolve(false);
}
return ignoreConflict.promise.then(function (canIgnore) {
if (canIgnore) {
utils.logWarnings(context, i18n.__("push_warning_ignore_conflict", {name: item.name}));
return helper._pushComplete(context, item, opts);
} else {
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pushed-error", err, {id: item.id, name: item.name, path: (item.path || name.path || name)});
}
err.emitted = true;
utils.logErrors(context, heading, err);
const saveFileOnConflict = options.getRelevantOption(context, opts, "saveFileOnConflict");
if (saveFileOnConflict && isUpdate && err.statusCode === 409) {
if (!remoteItemPromise) {
remoteItemPromise = helper.getRemoteItem(context, item.id, opts);
}
return remoteItemPromise
.then(function (item) {
return helper._fsApi.saveItem(context, item, utils.cloneOpts(opts, {conflict: true}));
})
.catch(function (error) {
// Log a warning if there was an error getting the conflicting item or saving it.
utils.logWarnings(context, error.toString());
})
.finally(function () {
// throw the original err for conflict
throw(err);
});
} else {
throw(err);
}
}
});
}
});
}
/**
* Push the items with the given names.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} names - The names of the items to be pushed.
* @param {Object} opts - The options to be used for the push operations.
*
* @returns {Q.Promise} A promise for the items that were pushed.
*
* @protected
*/
_pushNameList (context, names, opts) {
const deferred = Q.defer();
const helper = this;
const concurrentLimit = options.getRelevantOption(context, opts, "concurrent-limit", helper.getArtifactName());
const pushedItems = [];
const pushItems = function (names, opts) {
const results = utils.throttledAll(context, names.map(function (name) {
return function () {
return helper.pushItem(context, name, opts);
};
}), concurrentLimit);
results
.then(function (promises) {
promises
.filter(function (promise) {
return (promise.state === 'fulfilled');
})
.forEach(function (promise) {
if (promise.value) {
pushedItems.push(promise.value);
}
});
// Check to see if a retry is required.
const retryItems = helper.getRetryPushProperty(context, BaseHelper.RETRY_PUSH_ITEMS);
if (retryItems && retryItems.length > 0) {
// There are items to retry, so check to see whether any push operations were successful.
const itemCount = helper.getRetryPushProperty(context, BaseHelper.RETRY_PUSH_ITEM_COUNT);
if (retryItems.length < itemCount) {
// At least one push operation was successful, so proceed with the retry.
const names = [];
retryItems.forEach(function (item) {
// Add each retry item to the list of items to be pushed.
const name = item[BaseHelper.RETRY_PUSH_ITEM_NAME];
names.push(name);
// Log a warning that the push of this item will be retried.
const error = item[BaseHelper.RETRY_PUSH_ITEM_ERROR];
utils.logRetryInfo(context, i18n.__("pushed_item_retry", {
name: name.id || name,
message: error.log ? error.log : error.message
}));
});
// Initialize the retry values and then push the items in the list.
helper.initializeRetryPush(context, names);
pushItems(names, opts);
} else {
// There were no successful push operations, so do not retry again.
retryItems.forEach(function (item) {
// Emit a "pushed-error" event for each unpushed item, and log the error.
const name = item[BaseHelper.RETRY_PUSH_ITEM_NAME];
const error = item[BaseHelper.RETRY_PUSH_ITEM_ERROR];
const heading = item[BaseHelper.RETRY_PUSH_ITEM_HEADING];
delete error.retry;
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pushed-error", error, name);
}
utils.logErrors(context, heading, error);
});
// Resolve the promise with the list of any items that were successfully pushed.
deferred.resolve(pushedItems);
}
} else {
// There were no items to retry, so resolve the promise with the list pushed items.
deferred.resolve(pushedItems);
}
});
};
// Retry is only available if it is enabled for this helper.
if (this.isRetryPushEnabled()) {
// Initialize the retry state on the context.
context.retryPush = {};
helper.initializeRetryPush(context, names);
// Add the filter for determining whether a failed push should be retried.
context.filterRetryPush = this.filterRetryPush.bind(this);
}
// Push the items in the list.
pushItems(names, opts);
// Return the promise that will eventually be resolved in the pushItems function.
return deferred.promise
.then(function (itemList) {
helper._updateManifest(context, itemList, opts);
return itemList;
})
.finally(function () {
// Once the promise has been settled, remove the retry push state from the context.
delete context.retryPush;
delete context.filterRetryPush;
});
}
/**
* Pull the given items.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} items - The items to be pulled.
* @param {Object} opts - The options to be used for this operations.
*
* @returns {Q.Promise} A promise for the items that were pulled.
*
* @protected
*/
_pullItemList (context, items, opts) {
const deferred = Q.defer();
const helper = this;
// Create an array of functions, one function for each item being pulled.
const functions = items.map(function (item) {
return function () {
return helper.pullItem(context, item.id, opts);
};
});
// Pull the items in the list, throttling the concurrent requests to the defined limit for this artifact type.
const concurrentLimit = options.getRelevantOption(context, opts, "concurrent-limit", helper.getArtifactName());
utils.throttledAll(context, functions, concurrentLimit)
.then(function (promises) {
const pulledItems = [];
promises.forEach(function (promise) {
if ((promise.state === 'fulfilled') && promise.value) {
pulledItems.push(promise.value);
}
});
// Resolve the promise with the list of pulled items.
deferred.resolve(pulledItems);
});
// Return the promise that will eventually be resolved with the pulled items.
return deferred.promise;
}
/**
* Filter the given list of items before completing the pull operation.
*
* @param {Object} context The API context to be used for this operation.
* @param {Array} itemList The items to be pulled.
* @param {Object} opts The options to be used for this operations.
*
* @returns {Array} The filtered list of items.
*
* @protected
*/
_pullFilter (context, itemList, opts) {
// Filter the item list based on the ready and draft options.
const readyOnly = options.getRelevantOption(context, opts, "filterReady");
const draftOnly = options.getRelevantOption(context, opts, "filterDraft");
const helper = this;
if (readyOnly) {
// Filter out any items that are not ready.
itemList = itemList.filter(function (item) {
return (helper.getStatus(context, item, opts) === "ready");
});
} else if (draftOnly) {
// Filter out any items that are not draft.
itemList = itemList.filter(function (item) {
return (helper.getStatus(context, item, opts) === "draft");
});
}
// Filter the list to exclude any items that should not be saved to file.
itemList = itemList.filter(function (item) {
const canPullItem = helper.canPullItem(item, context, opts);
if (!canPullItem) {
// This item cannot be pulled, so add a log entry.
helper.getLogger(context).info(i18n.__("cannot_pull_item", {name: helper.getName(item)}));
}
return canPullItem;
});
return itemList;
}
_pullItemsChunk (context, listFn, opts) {
let items = [];
const deferred = Q.defer();
const helper = this;
listFn(opts)
.then(function (itemList) {
// Keep track of the original number of items in the chunk.
const chunkSize = itemList.length;
// Filter the items before saving them to the local file system.
itemList = helper._pullFilter(context, itemList, opts);
const promises = itemList.map(function (item) {
// make the emitted object before calling saveItem which prunes important data from the object!
const obj = helper.makeEmittedObject(context, item, opts);
return helper._fsApi.saveItem(context, item, opts)
.then(function () {
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pulled", obj);
}
return item;
});
});
return Q.allSettled(promises)
.then(function (promises) {
items = [];
const manifestList = [];
promises.forEach(function (promise, index) {
if (promise.state === "fulfilled") {
items.push(promise.value);
manifestList.push(promise.value);
} else {
items.push(promise.reason);
const emitter = helper.getEventEmitter(context);
if (emitter) {
emitter.emit("pulled-error", promise.reason, itemList[index].id);
}
context.pullErrorCount++;
}
});
// Append the resulting itemList to the manifest if writing/updating a manifest.
helper._updateManifest(context, manifestList, opts);
deferred.resolve({length: chunkSize, items: items});
});
})
.catch(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
} |
JavaScript | class RestorableDroppedDatabase extends models['ProxyResource'] {
/**
* Create a RestorableDroppedDatabase.
* @property {string} [location] The geo-location where the resource lives
* @property {string} [databaseName] The name of the database
* @property {string} [edition] The edition of the database
* @property {string} [maxSizeBytes] The max size in bytes of the database
* @property {string} [serviceLevelObjective] The service level objective
* name of the database
* @property {string} [elasticPoolName] The elastic pool name of the database
* @property {date} [creationDate] The creation date of the database (ISO8601
* format)
* @property {date} [deletionDate] The deletion date of the database (ISO8601
* format)
* @property {date} [earliestRestoreDate] The earliest restore date of the
* database (ISO8601 format)
*/
constructor() {
super();
}
/**
* Defines the metadata of RestorableDroppedDatabase
*
* @returns {object} metadata of RestorableDroppedDatabase
*
*/
mapper() {
return {
required: false,
serializedName: 'RestorableDroppedDatabase',
type: {
name: 'Composite',
className: 'RestorableDroppedDatabase',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
readOnly: true,
serializedName: 'location',
type: {
name: 'String'
}
},
databaseName: {
required: false,
readOnly: true,
serializedName: 'properties.databaseName',
type: {
name: 'String'
}
},
edition: {
required: false,
readOnly: true,
serializedName: 'properties.edition',
type: {
name: 'String'
}
},
maxSizeBytes: {
required: false,
readOnly: true,
serializedName: 'properties.maxSizeBytes',
type: {
name: 'String'
}
},
serviceLevelObjective: {
required: false,
readOnly: true,
serializedName: 'properties.serviceLevelObjective',
type: {
name: 'String'
}
},
elasticPoolName: {
required: false,
readOnly: true,
serializedName: 'properties.elasticPoolName',
type: {
name: 'String'
}
},
creationDate: {
required: false,
readOnly: true,
serializedName: 'properties.creationDate',
type: {
name: 'DateTime'
}
},
deletionDate: {
required: false,
readOnly: true,
serializedName: 'properties.deletionDate',
type: {
name: 'DateTime'
}
},
earliestRestoreDate: {
required: false,
readOnly: true,
serializedName: 'properties.earliestRestoreDate',
type: {
name: 'DateTime'
}
}
}
}
};
}
} |
JavaScript | class AppSamuraiBanner extends Component {
constructor() {
super();
this.handleSizeChange = this.handleSizeChange.bind(this);
this.handleAdFailedToLoad = this.handleAdFailedToLoad.bind(this);
this.state = {
style: {},
};
}
componentDidMount() {
this.loadBanner();
}
loadBanner() {
UIManager.dispatchViewManagerCommand(
findNodeHandle(this._bannerView),
UIManager.getViewManagerConfig('RNASBannerView').Commands.loadBanner,
null,
);
}
handleSizeChange(event) {
const { height, width } = event.nativeEvent;
this.setState({ style: { width, height } });
if (this.props.onSizeChange) {
this.props.onSizeChange({ width, height });
}
}
handleAdFailedToLoad(event) {
if (this.props.onAdFailedToLoad) {
// this.props.onAdFailedToLoad(createErrorFromErrorData(event.nativeEvent.error));
}
}
render() {
return (
<RNASBannerView
{...this.props}
style={[this.props.style, this.state.style]}
onSizeChange={this.handleSizeChange}
onAdFailedToLoad={this.handleAdFailedToLoad}
ref={el => (this._bannerView = el)}
/>
);
}
} |
JavaScript | class BpxLibSurfaceFire {
/**
* Calculate the distance given the velocity and elapsed time.
*
* @param rate Velocity
* @param time Elapsed time
* @return Distance traveled
*/
static distance(rate, time) {
return rate * time;
}
/**
* Calculate the `effective wind speed` of a combined slope-plus-wind spread rate coefficient.
*
* The `effective` wind speed is the theoretical wind speed that yields the same
* spread rate coefficient as the combined slope-plus-wind spread rate coefficient.
*
* @param phiew The sum of the slope and wind coefficients.
* @param windB Fuel bed wind factor B.
* @param windI Fuel bed wind factor I.
* @return The effective wind speed for the slope-plus-wind coefficient (ft+1 min-1).
*/
static effectiveWindSpeed(phiew, windB, windI) {
let ews = 0;
if ( phiew > 0 && windB > 0 && windI > 0) {
const a = phiew * windI;
const b = 1.0 / windB;
ews = Math.pow(a, b);
}
return ews;
}
/**
* Calculate the effective wind speed (ft+1 min-1) from the length-to-width ratio.
*
* This uses Anderson's (1983) equation.
*
* @param lwr The fire ellipse length-to-width ratio (ratio).
* @return The effective wind speed (ft+1 min-1).
*/
static effectiveWindSpeedFromLwr(lwr) {
return 88 * ( 4 * (lwr - 1) );
}
/**
* Calculate the maximum effective wind speed limit
* as per Rothermel (1972) equation 86 on page 33.
*
* @param rxi Fire reaction intensity (btu+1 ft-2 min-1).
* @return The maximum effective wind speed limit (ft+1 min-1).
*/
// static effectiveWindSpeedLimit(rxi) {
// return 0.9 * rxi;
// }
/**
* Calculate the fire heading direction (degrees clockwise from north).
*
* @param upslopeFromNorth Upslope direction (degrees clockwise from north).
* @param headingFromUpslope Fire heading direction (degrees clockwise from the upslope direction).
* @return The fire heading direction (degrees clockwise from north).
*/
// static headingFromNorth(upslopeFromNorth, headingFromUpslope) {
// return compass.constrain(upslopeFromNorth + headingFromUpslope);
// }
/**
* Calculate the fireline intensity (btu+1 ft-1 s-1) from spread rate,
* reaction intensity, and residence time.
*
* @param ros The fire spread rate (ft+1 min-1).
* @param rxi The reaction intensity (btu+1 ft-2 min-1).
* @param taur The flame residence time (min+1)
* @return The fireline intensity (btu+1 ft-1 s-1).
*/
static firelineIntensity(ros, rxi, taur) {
return ros * rxi * taur / 60;
}
/**
* Calculate the fireline intensity (btu+1 ft-1 s-1) from flame length.
*
* @param flame The flame length (ft+1).
* @return The fireline intensity (btu+1 ft-1 s-1).
*/
static fliFromFlameLength(flame) {
return (flame <= 0) ? 0 : Math.pow((flame / 0.45), (1 / 0.46));
}
/**
* Calculate Byram's (1959) flame length (ft+1) given a fireline intensity.
*
* @param fli Fireline intensity (btu+1 ft-1 s-1).
* @return Byram's (1959) flame length (ft+1).
*/
static flameLength(fli) {
return (fli <= 0) ? 0 : (0.45 * Math.pow(fli, 0.46));
}
/**
* Calculate the fire ellipse length-to-width ratio from the
* effective wind speed (ft+1 min-1).
*
* This uses Anderson's (1983) equation.
*
* @param effectiveWindSpeed The effective wind speed (ft+1 min-1).
* @return The fire ellipse length-to-width ratio (ratio).
*/
static lengthToWidthRatio(effectiveWindSpeed) {
// Wind speed MUST be in miles per hour
return 1 + 0.25 * (effectiveWindSpeed / 88);
}
/**
* Calculate the wind-slope coefficient (phiEw = phiW + phiS)
* from the individual slope (phiS) and wind (phiW) coefficients.
*
* @param phiW Rothermel (1972) wind coefficient `phiW` (ratio)
* @param phiS Rothermel (1972) slope coefficient `phiS` (ratio)
* @return Rothermel's (1972) wind-slope coefficient `phiEw` (ratio).
*/
static phiEw(phiW, phiS) {
return phiW + phiS;
}
/**
* Calculate the wind-slope coefficient (phiEw = phiW + phiS)
* from the no-wind, no-slope spread rate and an actual spread rate.
*
* There are 3 ways to calculate the wind-slope coefficient `phiEw`:
* - from `phiS` and `phiW`: see phiEw(phiS,phiW)
* - from `ros0` and `rosHead`: see phiEwInferred(ros0,rosHead)
* - from `ews`, `windB`, and `windK`: see phiEwFromEws(ews, windB, windK)
*
* @param ros0 No-wind, no-slope spread rate (ft+1 min-1).
* @param rosHead The actual spread rate (ft+1 min-1) at the fire head
* (possibly under cross-slope wind conditions).
* @return Rothermel's (1972) wind-slope coefficient `phiEw` (ratio).
*/
static phiEwInferred(ros0, rosHead) {
return (ros0 <= 0) ? 0 : ((rosHead / ros0) - 1);
}
/**
* Calculate the wind-slope coefficient (phiEw = phiW + phiS)
* from the effective wind speed.
*
* There are 3 ways to calculate the wind-slope coefficient `phiEw`:
* - from `phiS` and `phiW`: see phiEw(phiS,phiW)
* - from `ros0` and `rosHead`: see phiEwInferred(ros0,rosHead)
* - from `ews`, `windB`, and `windK`: see phiEwFromEws(ews, windB, windK)
*
* @param ews The theoretical wind speed that produces
* the same spread rate coefficient as the current slope-wind combination.
* @param windB
* @param windK
* @return Rothermel's (1972) wind-slope coefficient `phiEw` (ratio).
*/
// static phiEwFromEws(ews, windB, windK) {
// return (ews <= 0) ? 0 : (windK * Math.pow(ews, windB));
// }
/** Calculate the fire spread rate slope coefficient (ratio).
*
* This returns Rothermel's (1972) `phiS' as per equation 51 (p 24, 26).
*
* @param slopeRatio Slope steepness ratio (vertical rise / horizontal reach).
* @param slopeK Fuel Bed slope factor.
* @return The fire spread rate slope coefficient (ratio).
*/
static phiS(slopeRatio, slopeK) {
return slopeK * slopeRatio * slopeRatio;
}
/** Calculate the fire spread rate wind coefficient (ratio).
*
* This returns Rothermel's (1972) `phiW' as per equation 47 (p 23, 26).
*
* @param midflameWind Wind speed at midflame height (ft+1 min-1).
* @param windB Fuel Bed wind factor `B`.
* @param windK Fuel Bed wind factor `K`.
* @return The fire spread rate wind coefficient (ratio).
*/
static phiW(midflameWind, windB, windK) {
return (midflameWind <= 0) ? 0 : windK * Math.pow(midflameWind, windB);
}
static rosArithmetic(cover1, ros1, ros2) {
return (cover1 * ros1) + ((1-cover1) * ros2);
}
static rosExpectedMOCK(cover1, ros1, ros2) {
return 0.5 * ( BpxLibSurfaceFire.rosArithmetic(cover1, ros1, ros2)
+ BpxLibSurfaceFire.rosHarmonic(cover1, ros1, ros2) );
}
static rosHarmonic(cover1, ros1, ros2) {
return (1 / ( (cover1 / ros1) + ((1-cover1) / ros2) ));
}
/**
* Calculate the maximum fire spread rate under slope & wind conditions.
*
* @param ros0 No-wind, no-slope spread rate (ft+1 min-1).
* @param phiEw Rothermel's (1972) `phiEw` wind-slope coefficient (ratio).
* @return The maximum fire spread rate (ft+1 min-1).
*/
static rosMax(ros0, phiEw) {
return ros0 * (1 + phiEw);
}
/**
* Calculate the maximum fire spread rate under cross-slope wind conditions.
*
* If the wind is blowing up-slope (or, if there is no slope, or if there is no wind),
* then spreadRateMaximumUpSlopeWind() == spreadRateMaximumCrossSlopeWind().
*
* @param ros0 No-wind, no-slope spread rate (ft+1 min-1).
* @param spreadDirVectorRate Additional spread reate (ft+1 min-1)
* along the cross-slope vector of maximum spread.
* @return The maximum fire spread rate (ft+1 min-1).
*/
static rosMaxCrossSlopeWind(ros0, spreadDirVectorRate ) {
return ros0 + spreadDirVectorRate;
}
/**
* Calculate the maximum spread rate after applying the effective wind speed limit.
*
* If the effective wind speed does not exceed the limit,
* then spreadRateMaximumCrossSlopeWind() == spreadRateMaximumEffectiveWindSpeedLimitApplied().
*
* @param ros0 The no-wind, no-slope spread rate (ft+1 min-1).
* @param phiEwLimited Rothermel's (1972) `phiEw` wind-slope coefficient (ratio)
* AFTER applying the effective wind speed limit.
*/
// static rosMaxEwslApplied(ros0, phiEwLimited) {
// return ros0 * (1 + phiEwLimited);
// }
/**
* Calculate the maximum spread rate after applying the effective wind speed upper limit.
*
* If the spread rate exceeds the effective wind speed
* AND the effective wind speed exceeds 1 mph, then the
* spread rate is reduced back to the effective wind speed.
*
* @param rosMax The fire maximum spread rate (ft+1 min-1)
* @param ews The effective wind speed (ft+1 min-1).
* @return The maximum spread rate (ft+1 min-1) after applying any effective wind speed limit.
*/
static rosMaxRosLimitApplied(rosMax, ews) {
return (rosMax > ews && ews > 88) ? ews : rosMax;
}
/**
* Calculate the scorch height (ft+1) estimated from Byram's fireline
* intensity, wind speed, and air temperature.
*
* @param fli Byram's fireline intensity (btu+1 ft-1 s-1).
* @param windSpeed Wind speed (ft+1 min-1).
* @param airTemp (oF).
* @return The scorch height (ft+1).
*/
static scorchHt(fli, windSpeed, airTemp) {
const mph = windSpeed / 88;
return ( fli <= 0) ? 0
: (63 / (140 - airTemp)) *
Math.pow(fli, 1.166667) /
Math.sqrt(fli + (mph * mph * mph));
}
/**
* Calculate the scorch height (ft+1) estimated from flame length,
* wind speed, and air temperature.
*
* @param flame Flame length (ft+1).
* @param windSpeed Wind speed (ft+1 min-1).
* @param airTemp (oF).
* @return The scorch height (ft+1)
*/
static scorchHtFromFlame(flame, windSpeed, airTemp) {
const fli = BpxLibSurfaceFire.fliFromFlameLength(flame);
return BpxLibSurfaceFire.scorchHt(fli, windSpeed, airTemp);
}
/**
* Calculate the direction of maximum spread as degrees clockwise from up-slope.
*
* @param xComp Vector x-component returned by spreadDirectionXComponent()
* @param yComp Vector y-component as returned by spreadDirectionYComponent().
* @param rosv Spread rate in the vector of maximum spread (ft+1 min-1).
* @return The direction of maximum fire spread (degrees from upslope)
*/
static spreadDirFromUpslope(xComp, yComp, rosv) {
const pi = Math.PI;
const al = (rosv <= 0) ? 0 : (Math.asin(Math.abs(yComp) / rosv));
const radians = (xComp >= 0)
? ( (yComp >= 0) ? (al) : (pi + pi - al) )
: ( (yComp >= 0) ? (pi - al) : (pi + al) );
const degrees = radians * 180 / pi;
return degrees;
}
/**
* Calculate the slope contribution to the spread rate.
*
* @param ros0 No-wind, no-wlope fire spread rate (ft+1 min-1)
* @param phiS Slope coefficient (factor)
* @return The slope contribution to the fire spread rate (ft+1 min-1)
*/
static spreadDirSlopeRate(ros0, phiS) {
return ros0 * phiS;
}
/**
* Calculate the wind contribution to the spread rate.
*
* @param ros0 No-wind, no-wlope fire spread rate (ft+1 min-1)
* @param phiW Wind coefficient (factor)
* @return The wind contribution to the fire spread rate (ft+1 min-1)
*/
static spreadDirWindRate(ros0, phiW) {
return ros0 * phiW;
}
/**
* Calculate the additional spread rate (ft+1 min-1) in the direction of maximum
* spread under cross-slope wind condtions.
*
* @param xComp Vector x-component returned by spreadDirXComp()
* @param yComp Vector y-component as returned by spreadDirYComp().
* @return Cross wind - cross slope spread rate (ft+1 min-1)
*/
static spreadDirVectorRate(xComp, yComp) {
return Math.sqrt(xComp * xComp + yComp * yComp);
}
/**
* Calculate the x-component of the spread rate vector under cross-slope wind conditions.
*
* @param windRate
* @param slopeRate
* @param windHdgAzUp Wind heading in degrees clockwise from the up-slope direction.
*/
static spreadDirXComp(windRate, slopeRate, windHdgAzUp) {
const radians = windHdgAzUp * Math.PI / 180;
return slopeRate + windRate * Math.cos( radians );
}
/**
* Calculate the y-component of the spread rate vector under cross-slope wind conditions.
*
* @param windRate
* @param windHdgAzUp Wind heading in degrees clockwise from the up-slope direction.
*/
static spreadDirYComp(windRate, windHdgAzUp) {
const radians = windHdgAzUp * Math.PI / 180;
return windRate * Math.sin( radians );
}
/**
* Calculates the midflame wind speed required to attain a target fire spread rate.
*
* @param rosTarget Target fire spread rate (ft+1 min-1)
* @param ros0 The fuel bed no-wind, no-slope fire spread rate (ft+1 min-1)
* @param windB The fuel bed wind factor B
* @param windK The fuel bed wind factor K
* @param phiS The fuel bed slope coefficient (phi slope)
* @return The midflame wind speed (ft+1 min-1) required to attain the target fire spread rate.
*/
// static windSpeedAtRosTarget(rosTarget, ros0, windB, windK, phiS) {
// if (ros0 <= 0 || windK <= 0) {
// return 0;
// }
// const numerator = (rosTarget / ros0) - 1 - phiS;
// const term = numerator / windK;
// return Math.pow(term, (1/windB));
// }
/**
* Calculates the midflame wind speed required to attain a target fire spread rate.
*
* @param rosTarget Target fire spread rate (ft+1 min-1)
* @param ros0 The fuel bed no-wind, no-slope fire spread rate (ft+1 min-1)
* @param beta The fuel bed packing ratio
* @param bedSavr The fuel bed characteristic surface area-to-volume ratio (ft-1)
* @param slopeRatio The fuel bed slope (ratio)
* @return The midflame wind speed (ft+1 min-1) required to attain the target fire spread rate.
*/
// static windSpeedAtRosTarget2(rosTarget, ros0, beta, bedSavr, slopeRatio) {
// const windB = BpxLibFuelBed.windB(bedSavr);
// const windC = BpxLibFuelBed.windC(bedSavr);
// const windE = BpxLibFuelBed.windE(bedSavr);
// const betaOpt = BpxLibFuelBed.beto(bedSavr);
// const betaRatio = beta / betaOpt;
// const windK = BpxLibFuelBed.windK(betaRatio, windE, windC);
// const slopeK = BpxLibFuelBed.slopeK(beta);
// const phiS = BpxLibSurfaceFire.phiS(slopeRatio, slopeK);
// return BpxLibSurfaceFire.windSpeedAtRosTarget(rosTarget, ros0, windB, windK, phiS);
// }
} |
JavaScript | class GroupMember {
/**
* @typedef {Object} Location
* @property {Date} location.updatedAt - The date when the location was last updated.
* @property {number} location.longitude - The location longitude.
* @property {number} location.latitude - The location latitude.
*/
/**
* Create a GroupMember.
* @param {Object} props
* @param {BSON.ObjectId} props.userId - The ID of the member.
* @param {string} props.displayName - The member's name to be displayed on the group.
* @param {string} props.deviceName - The name of the member's device to be used in the group.
* @param {Location} [props.location] - The member's location.
*/
constructor({ userId, displayName, deviceName, location }) {
this.userId = userId;
this.displayName = displayName;
this.deviceName = deviceName;
if (location)
this.location = location;
}
// To use a class as an object type, define the object schema on the static property 'schema'.
static schema = {
name: 'GroupMember',
embedded: true,
properties: {
userId: 'objectId',
displayName: 'string',
deviceName: 'string',
location: 'Location?'
}
};
} |
JavaScript | class DefaultStateEvaluator {
constructor(arweave, executionContextModifiers = []) {
this.arweave = arweave;
this.executionContextModifiers = executionContextModifiers;
this.logger = _smartweave_1.LoggerFactory.INST.create('DefaultStateEvaluator');
this.transactionStateCache = new _smartweave_1.MemCache();
this.tagsParser = new _smartweave_1.TagsParser();
}
async eval(executionContext, currentTx) {
return this.doReadState(executionContext.sortedInteractions, new _smartweave_1.EvalStateResult(executionContext.contractDefinition.initState, {}), executionContext, currentTx);
}
async doReadState(missingInteractions, baseState, executionContext, currentTx) {
const stateEvaluationBenchmark = _smartweave_1.Benchmark.measure();
const { ignoreExceptions, stackTrace, internalWrites } = executionContext.evaluationOptions;
const { contract, contractDefinition, sortedInteractions } = executionContext;
let currentState = baseState.state;
let validity = (0, _smartweave_1.deepCopy)(baseState.validity);
this.logger.info(`Evaluating state for ${executionContext.contractDefinition.txId} [${missingInteractions.length} non-cached of ${executionContext.sortedInteractions.length} all]`);
this.logger.debug('Base state:', baseState.state);
let lastEvaluatedInteraction = null;
let errorMessage = null;
for (const missingInteraction of missingInteractions) {
const singleInteractionBenchmark = _smartweave_1.Benchmark.measure();
const interactionTx = missingInteraction.node;
this.logger.debug(`[${contractDefinition.txId}][${missingInteraction.node.id}][${missingInteraction.node.block.height}]: ${missingInteractions.indexOf(missingInteraction) + 1}/${missingInteractions.length} [of all:${sortedInteractions.length}]`);
const state = await this.onNextIteration(interactionTx, executionContext);
const isInteractWrite = this.tagsParser.isInteractWrite(missingInteraction, contractDefinition.txId);
this.logger.debug('interactWrite?:', isInteractWrite);
// other contract makes write ("writing contract") on THIS contract
if (isInteractWrite && internalWrites) {
// evaluating txId of the contract that is writing on THIS contract
const writingContractTxId = this.tagsParser.getContractTag(missingInteraction);
this.logger.debug('Loading writing contract', writingContractTxId);
const interactionCall = contract
.getCallStack()
.addInteractionData({ interaction: null, interactionTx, currentTx });
// creating a Contract instance for the "writing" contract
const writingContract = executionContext.smartweave.contract(writingContractTxId, executionContext.contract, interactionTx);
this.logger.debug('Reading state of the calling contract', interactionTx.block.height);
/**
Reading the state of the writing contract.
This in turn will cause the state of THIS contract to be
updated in cache - see {@link ContractHandlerApi.assignWrite}
*/
await writingContract.readState(interactionTx.block.height, [
...(currentTx || []),
{
contractTxId: contractDefinition.txId,
interactionTxId: missingInteraction.node.id
}
]);
// loading latest state of THIS contract from cache
const newState = await this.latestAvailableState(contractDefinition.txId, interactionTx.block.height);
this.logger.debug('New state:', {
height: interactionTx.block.height,
newState,
txId: contractDefinition.txId
});
if (newState !== null) {
currentState = (0, _smartweave_1.deepCopy)(newState.cachedValue.state);
validity[interactionTx.id] = newState.cachedValue.validity[interactionTx.id];
}
else {
validity[interactionTx.id] = false;
}
lastEvaluatedInteraction = interactionTx;
interactionCall.update({
cacheHit: false,
intermediaryCacheHit: false,
outputState: stackTrace.saveState ? currentState : undefined,
executionTime: singleInteractionBenchmark.elapsed(true),
valid: validity[interactionTx.id],
errorMessage: errorMessage
});
this.logger.debug('New state after internal write', { contractTxId: contractDefinition.txId, newState });
}
else {
// "direct" interaction with this contract - "standard" processing
const inputTag = this.tagsParser.getInputTag(missingInteraction, executionContext.contractDefinition.txId);
if (!inputTag) {
this.logger.error(`Skipping tx - Input tag not found for ${interactionTx.id}`);
continue;
}
const input = this.parseInput(inputTag);
if (!input) {
this.logger.error(`Skipping tx - invalid Input tag - ${interactionTx.id}`);
continue;
}
const interaction = {
input,
caller: interactionTx.owner.address
};
let intermediaryCacheHit = false;
const interactionData = {
interaction,
interactionTx,
currentTx
};
this.logger.debug('Interaction:', interaction);
const interactionCall = contract.getCallStack().addInteractionData(interactionData);
if (state !== null) {
this.logger.debug('Found in intermediary cache');
intermediaryCacheHit = true;
currentState = state.state;
validity = state.validity;
}
else {
const result = await executionContext.handler.handle(executionContext, new _smartweave_1.EvalStateResult(currentState, validity), interactionData);
errorMessage = result.errorMessage;
this.logResult(result, interactionTx, executionContext);
if (result.type === 'exception' && ignoreExceptions !== true) {
throw new Error(`Exception while processing ${JSON.stringify(interaction)}:\n${result.errorMessage}`);
}
validity[interactionTx.id] = result.type === 'ok';
currentState = result.state;
// cannot simply take last element of the missingInteractions
// as there is no certainty that it has been evaluated (e.g. issues with input tag).
lastEvaluatedInteraction = interactionTx;
this.logger.debug('Interaction evaluation', singleInteractionBenchmark.elapsed());
}
interactionCall.update({
cacheHit: false,
intermediaryCacheHit,
outputState: stackTrace.saveState ? currentState : undefined,
executionTime: singleInteractionBenchmark.elapsed(true),
valid: validity[interactionTx.id],
errorMessage: errorMessage
});
}
await this.onStateUpdate(interactionTx, executionContext, new _smartweave_1.EvalStateResult(currentState, validity));
// I'm really NOT a fan of this "modify" feature, but I don't have idea how to better
// implement the "evolve" feature
for (const { modify } of this.executionContextModifiers) {
executionContext = await modify(currentState, executionContext);
}
}
this.logger.debug('State evaluation total:', stateEvaluationBenchmark.elapsed());
const evalStateResult = new _smartweave_1.EvalStateResult(currentState, validity);
// state could have been full retrieved from cache
// or there were no interactions below requested block height
if (lastEvaluatedInteraction !== null) {
await this.onStateEvaluated(lastEvaluatedInteraction, executionContext, evalStateResult);
}
return evalStateResult;
}
logResult(result, currentTx, executionContext) {
if (result.type === 'exception') {
this.logger.error(`Executing of interaction: [${executionContext.contractDefinition.srcTxId} -> ${currentTx.id}] threw exception:`, `${result.errorMessage}`);
}
if (result.type === 'error') {
this.logger.warn(`Executing of interaction: [${executionContext.contractDefinition.srcTxId} -> ${currentTx.id}] returned error:`, result.errorMessage);
}
}
parseInput(inputTag) {
try {
return JSON.parse(inputTag.value);
}
catch (e) {
this.logger.error(e);
return null;
}
}
async onStateUpdate(currentInteraction, executionContext, state) {
if (executionContext.evaluationOptions.fcpOptimization && !currentInteraction.dry) {
this.transactionStateCache.put(`${executionContext.contractDefinition.txId}|${currentInteraction.id}`, (0, _smartweave_1.deepCopy)(state));
}
}
async onNextIteration(currentInteraction, executionContext) {
const cacheKey = `${executionContext.contractDefinition.txId}|${currentInteraction.id}`;
const cachedState = this.transactionStateCache.get(cacheKey);
if (cachedState == null) {
return null;
}
else {
return (0, _smartweave_1.deepCopy)(cachedState);
}
}
onContractCall(currentInteraction, executionContext, state) {
return Promise.resolve(undefined);
}
onStateEvaluated(lastInteraction, executionContext, state) {
return Promise.resolve(undefined);
}
async latestAvailableState(contractTxId, blockHeight) {
return null;
}
onInternalWriteStateUpdate(currentInteraction, contractTxId, state) {
return Promise.resolve(undefined);
}
} |
JavaScript | class PassageComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
passageIndex: 0,
passageCount: 0,
buttonText: "Next",
selectedValues: [],
completed: false,
correct: "init"
}
}
componentDidMount() {
this.getPassages();
}
componentDidUpdate(prevProps) {
if (prevProps.lessonId !== this.props.lessonId) {
this.getPassages();
}
}
/**
* Get a human readable version of the text structure for display
* @param {*} textStructure
*/
getTssHuman(textStructure) {
switch (textStructure) {
case 'COMPARISON':
return "Comparison";
case 'CAUSE_EFFECT':
return "Cause & Effect";
case 'SEQUENCE':
return "Sequence"
case 'DESCRIPTION':
return "Description"
default:
return "Description"
}
}
//Get a passage given a lessonId
getPassages = () => {
// read all entities
fetch("http://localhost:8080/get-passages?id=" + this.props.lessonId, {
"method": "GET",
})
.then(response => response.json())
.then(response => {
this.setState({
passages: response
});
this.setState({
passageCount: this.state.passages.length
});
console.log("Loaded " + this.state.passageCount + " passages from the server for the lesson.");
})
.catch(err => {
console.log(err);
});
};
saveAnswer(passageId) {
fetch("http://localhost:8080/save-answer", {
"method": "POST",
"headers": {
"content-type": "application/json",
"accept": "application/json"
},
"body": JSON.stringify({
passageId: passageId,
answerText: "",
studentAnswers: this.state.selectedValues
})
})
.then(response => response.json())
.then(response => {
console.log("Finished resolving");
this.handleNext(response);
});
}
handleNext(answer) {
this.setState({
correct: answer.correct
})
if (answer.correct === false) {
console.log("Answer Incorrect", answer.correct, this.state.correct);
this.setState({
correct: "init"
})
return;
}
if (this.state.passageIndex + 1 < this.state.passageCount - 1) {
this.setState({ passageIndex: this.state.passageIndex + 1 });
} else if (this.state.passageIndex + 1 === this.state.passageCount - 1) {
this.setState({
passageIndex: this.state.passageIndex + 1,
buttonText: "Finish Lesson"
});
} else {
console.log("Lesson complete");
const isCompleted = true;
this.setState({
completed: isCompleted
})
this.props.onCompleted({isCompleted});
}
var selectedAnswers = []
this.setState({ selectedValues: selectedAnswers });
}
handleChange = (val) => {
var selectedAnswers = [];
val.forEach(function (item, index) {
selectedAnswers.push(item);
});
this.setState({ selectedValues: selectedAnswers });
console.log(selectedAnswers);
}
render() {
if (!this.state || !this.state.passages) {
if (!this.props.lessonId) {
return <div>Loading Passage...</div>
} else {
return <div> Loading Passages for Lesson {this.props.lessonId}</div>
}
}
return (
<Container>
<Card bg="dark" text="white">
<Card.Body>
<Card.Title>Passage - {this.getTssHuman(this.state.passages[this.state.passageIndex].textStructure)} </Card.Title>
<Card.Text>
{this.state.passages[this.state.passageIndex].passageText}
</Card.Text>
</Card.Body>
</Card>
<br />
<Card bg="dark" text="white" >
<Card.Body>
<Card.Title>Question Prompt</Card.Title>
<h4>{this.state.passages[this.state.passageIndex].questionText}</h4>
<Form onSubmit={this.handleSubmitAnswer} className="passage-question">
<Col>
<ToggleButtonGroup
vertical
value={this.state.selectedValues}
onChange={this.handleChange}
type="checkbox" >
<ToggleButton value={"answerA"}>{this.state.passages[this.state.passageIndex].answerAText} </ToggleButton>
<ToggleButton value={"answerB"}>{this.state.passages[this.state.passageIndex].answerBText} </ToggleButton>
<ToggleButton value={"answerC"}>{this.state.passages[this.state.passageIndex].answerCText} </ToggleButton>
<ToggleButton value={"answerD"}>{this.state.passages[this.state.passageIndex].answerDText} </ToggleButton>
<ToggleButton value={"answerE"}>{this.state.passages[this.state.passageIndex].answerEText} </ToggleButton>
</ToggleButtonGroup>
</Col>
</Form>
</Card.Body>
<PassageFeedback
passageId={this.state.passages[this.state.passageIndex].id}
correct={this.state.correct}
/>
</Card>
<br />
<Button
variant="info"
onClick={() => {this.saveAnswer(this.state.passages[this.state.passageIndex].id)} }
>{this.state.buttonText}</Button>
</Container>
);
}
} |
JavaScript | class CachingProxy {
constructor(cacheOptions) {
this.cacheEnabled = cacheOptions.enabled;
this.ttl = cacheOptions.ttl || 600000; // 10 minutes by default
// Internal objects for data storing
this.cache = {};
this.promises = {};
}
/**
* Check that result is present in the cache and is up to date or send request otherwise.
*/
cacheRequest(func, funcName, funcScope) {
return cacheRequest(func, funcName, funcScope, this);
}
/**
* Wrap request to prevent multiple calls with same params when request is waiting for response.
*/
proxyfy(func, funcName, funcScope) {
if (!this.promises[funcName]) {
this.promises[funcName] = {};
}
const promiseKeeper = this.promises[funcName];
return callOnce(func, promiseKeeper, funcScope);
}
proxyfyWithCache(func, funcName, funcScope) {
let proxyfied = this.proxyfy(func, funcName, funcScope);
return this.cacheRequest(proxyfied, funcName, funcScope);
}
_isExpired(cacheObject) {
if (cacheObject) {
let object_age = Date.now() - cacheObject.timestamp;
return !(cacheObject.timestamp && object_age < this.ttl);
} else {
return true;
}
}
} |
JavaScript | class Chart {
/**
* lchart v0.1 WARNING: Not compatible with versions below v0.1
* @param {Array<{name:String,points:Array<{x:Number, y:Number}>,configs:{lineColor:String, pointFillColor:String}}>} datas
* @param {Object} [picConfigs]
* @param {{left:Number, right:Number, up:Number, down:Number}} [picConfigs.padding]
* @param {{width:Number, height:Number}} [picConfigs.size] pic size
* @param {String} [picConfigs.font] exp. "15px Georgia"
* @param {{background:String ,title:String, titleX:String, titleY:String, coordinate:String, grid:String}} [picConfigs.color]
* @param {{title:String, titleX:String, titleY:String, divideX:Number, divideY:Number}} [picConfigs.label]
* @param {Boolean} [picConfigs.xDateMode] x-coordinate is date etc... divited evenly, point.x must be [1, 2, 3, ...] or [3, 5, 6, ...] etc...
* @param {Array<String>} [picConfigs.xDateLabel] when xDateMode = true, show xDateLabel at x-coordinate instead of x value, length must contains all data's point.x
* for example: line1 point.x [1, 2, 3, 4, 5] line2 point.x [2, 4, 6, 7, 8]
* xDateLabel should be like ["day1", "day2", "day3", "day4", "day5", "day6", "day7", "day8"] contains 1-8
* the reason that I don't use Date() directly is x-coordinate can be other things like team numbers, seasons, years...
*/
constructor(datas, picConfigs = {}) {
// lines count should be no more than 8
this.defaultLineColor = ["#E74C3C", "#3498DB", "#9B59B6", "#2ECC71", "#F1C40F", "#34495E", "#95A5A6", "#1ABC9C"];
this.defaultPointColor = ["#C0392B", "#2980B9", "#8E44AD", "#27AE60", "#F39C12", "#2C3E50", "#7F8C8D", "#16A085"];
if (datas.length <= 1) this.lines = [new Line(datas.pop(), { lineColor: "#111", pointFillColor: "#000" })];
else this.lines = datas.map((data, index) => {
const lineColor = this.defaultLineColor[index] || this.randomColor();
const pointFillColor = this.defaultPointColor[index] || lineColor;
return new Line(data, { lineColor, pointFillColor });
});
// padding
this.padding = {};
if (!picConfigs.padding) picConfigs.padding = {};
this.padding.left = picConfigs.padding.left || 50;
this.padding.right = picConfigs.padding.right || (this.lines.length > 1) ? 150 : 50;
this.padding.up = picConfigs.padding.up || 50;
this.padding.down = picConfigs.padding.down || 50;
// size
this.size = {};
if (!picConfigs.size) picConfigs.size = {};
this.size.width = picConfigs.size.width || 800;
this.size.height = picConfigs.size.height || 600;
// font
this.font = picConfigs.font || "15px Georgia";
// color
this.color = {};
if (!picConfigs.color) picConfigs.color = {};
this.color.background = picConfigs.color.background || "white";
this.color.title = picConfigs.color.title || "#000";
this.color.titleX = picConfigs.color.titleX || "#000";
this.color.titleY = picConfigs.color.titleY || "#000";
this.color.coordinate = picConfigs.color.coordinate || "#000";
this.color.grid = picConfigs.color.grid || "#999";
// labels
this.label = {};
if (!picConfigs.label) picConfigs.label = {};
this.label.title = picConfigs.label.title || "";
this.label.titleX = picConfigs.label.titleX || "";
this.label.titleY = picConfigs.label.titleY || "";
// how many segments are the coordinates divided into, it may be changed by getDatasRange()
this.label.divideX = picConfigs.label.divideX || 10;
this.label.divideY = picConfigs.label.divideY || 10;
// xDateMode
this.xDateMode = picConfigs.xDateMode || false;
this.xDateLabel = picConfigs.xDateLabel || null;
// draw zone
/*
-123-in-pic----------------------------------------------------------------
1 | | |
2 | up padding | |
3 | (title) | |
|---------^---------------------------------------------------------------|
| | | |
| left | | right |
| (y-coor 3 data zone | padding |
| dinate) 2 | (legend) |
| 1 | |
|---------+1-2-3-in-data--------------------------------------->----------|
| | | |
| | down | |
| | (x-coordinate) | |
---------------------------------------------------------------------------
*/
this.zone = {};
// data zone
this.zone.data = {};
this.zone.data.width = this.size.width - this.padding.left - this.padding.right;
this.zone.data.height = this.size.height - this.padding.up - this.padding.down;
this.zone.data.originX = this.padding.left;
this.zone.data.originY = this.size.height - this.padding.down;
// left zone
this.zone.left = {};
this.zone.left.width = this.padding.left;
this.zone.left.height = this.zone.data.height;
// down zone
this.zone.down = {};
this.zone.down.width = this.zone.data.width;
this.zone.down.height = this.padding.down;
// dataRange
this.dataRange = this.getCoordinatesRanges();
// Calculate how many pixels equal to 1
this.dataInterval = this.getDataInterval();
// initCtx
this.canvas = createCanvas(this.size.width, this.size.height);
this.ctx = this.canvas.getContext('2d');
}
randomColor() {
var color = "#";
for (var i = 0; i < 6; i++) color += parseInt(Math.random() * 16).toString(16);
return color;
}
getSuitableRange(min, max, divideCount) {
const interval = (max - min) / divideCount;
const digit = Math.floor(Math.log10(interval)) + 1;
const fixedInterval = Math.pow(10, digit);
let fixedMin = (min >= 0) ? (min - (min % fixedInterval)) : (min - (min % fixedInterval) - fixedInterval);
let fixedMax = (max > 0) ? (max - (max % fixedInterval) + fixedInterval) : (max - (max % fixedInterval));
// Avoid accuracy problems
const mul = Math.pow(10, -digit);
if (fixedMin.toString().length > 10) fixedMin = Math.round((fixedMin + Number.EPSILON) * mul) / mul;
if (fixedMax.toString().length > 10) fixedMax = Math.round((fixedMax + Number.EPSILON) * mul) / mul;
const fixedDivideCount = Math.round((fixedMax - fixedMin) / fixedInterval);
return { min: fixedMin, max: fixedMax, divideCount: fixedDivideCount };
}
getDataRange(data) {
let xmin = data[0].x;
let xmax = data[0].x;
let ymin = data[0].y;
let ymax = data[0].y;
data.map((point) => {
if (point.x > xmax) xmax = point.x;
if (point.x < xmin) xmin = point.x;
if (point.y > ymax) ymax = point.y;
if (point.y < ymin) ymin = point.y;
});
return { xmin, xmax, ymin, ymax };
}
getCoordinatesRanges() {
const ranges = this.lines.map((line) => {
return this.getDataRange(line.points);
})
let xmin = ranges[0].xmin;
let xmax = ranges[0].xmax;
let ymin = ranges[0].ymin;
let ymax = ranges[0].ymax;
ranges.map((range) => {
if (range.xmax > xmax) xmax = range.xmax;
if (range.xmin < xmin) xmin = range.xmin;
if (range.ymax > ymax) ymax = range.ymax;
if (range.ymin < ymin) ymin = range.ymin;
});
const suitableX = (this.xDateMode) ? { min: xmin, max: xmax, divideCount: this.label.divideX } : this.getSuitableRange(xmin, xmax, this.label.divideX);
this.label.divideX = suitableX.divideCount;
const suitableY = this.getSuitableRange(ymin, ymax, this.label.divideY);
this.label.divideY = suitableY.divideCount;
return { xmin: suitableX.min, xmax: suitableX.max, ymin: suitableY.min, ymax: suitableY.max };
}
getDataInterval() {
const widthInterval = this.zone.data.width / (this.dataRange.xmax - this.dataRange.xmin);
const heightInterval = this.zone.data.height / (this.dataRange.ymax - this.dataRange.ymin);
return { widthInterval, heightInterval };
}
drawCoordinates() {
this.ctx.beginPath();
this.ctx.strokeStyle = this.color.coordinate;
this.ctx.lineWidth = 1;
this.ctx.moveTo(this.zone.data.originX, this.zone.data.originY);
this.ctx.lineTo(this.zone.data.originX, this.padding.up);
this.ctx.moveTo(this.zone.data.originX, this.zone.data.originY);
this.ctx.lineTo(this.zone.data.originX + this.zone.data.width, this.zone.data.originY);
this.ctx.stroke();
}
// accuary fix
accAdd(arg1, arg2) {
let r1, r2;
try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
const m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
}
accDiv(arg1, arg2) {
let t1 = 0, t2 = 0, r1, r2;
try { t1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
try { t2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return (r1 / r2) * Math.pow(10, t2 - t1);
}
drawUp() {
// title
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.fillStyle = this.color.title;
// min label at origin
this.ctx.textAlign = "center";
this.ctx.fillText(this.label.title, Math.floor(this.size.width / 2), Math.floor(this.padding.up / 2));
this.ctx.stroke();
}
drawRight() {
// legend
// ----------------
// | right padding|
// | name O|
// | anothername O|
// | |
// ----------------
const fontHeight = 20;
const circleX = this.size.width - 10;
let circleY = this.padding.up + fontHeight;
const colors = [];
const names = [];
this.lines.map((line) => {
colors.push(line.lineColor);
names.push(line.name);
})
this.ctx.textAlign = "right";
for (let i = 0; i < colors.length; i++) {
this.ctx.beginPath();
this.ctx.fillStyle = colors[i];
this.ctx.arc(circleX, circleY, 10, 0, 2 * Math.PI);
this.ctx.fill();
this.ctx.fillText(names[i], circleX - 20, circleY + 5);
circleY += fontHeight
}
this.ctx.stroke();
}
drawLeft() {
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.strokeStyle = this.color.grid;
this.ctx.fillStyle = this.color.titleY;
// min label at origin
this.ctx.textAlign = "center";
const intervalY = this.accDiv(this.accAdd(this.dataRange.ymax, -this.dataRange.ymin), this.label.divideY);
const fontWidth = 5;
let nowY = this.dataRange.ymin;
for (let i = 0; i <= this.label.divideY; i++) {
const y = Math.ceil(this.size.height - this.dataInterval.heightInterval * i * intervalY - this.padding.down);
const text = nowY.toString();
this.ctx.moveTo(this.zone.data.originX, y);
this.ctx.lineTo(this.zone.data.originX + this.zone.data.width, y);
this.ctx.textAlign = "right";
this.ctx.fillText(text, this.zone.data.originX - fontWidth * text.length, y);
nowY = this.accAdd(nowY, intervalY);
}
this.ctx.stroke();
// titleY
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.fillStyle = this.color.titleY;
this.ctx.fillText(this.label.titleY, this.zone.data.originX, this.padding.up - 20);
this.ctx.stroke();
}
drawBottom() {
if (this.xDateMode && this.xDateLabel) {
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.strokeStyle = this.color.grid;
this.ctx.fillStyle = this.color.titleX;
// min label at origin
this.ctx.textAlign = "center";
const intervalX = this.accAdd(this.dataRange.xmax, -this.dataRange.xmin) / this.label.divideX;
const fontHeight = 20;
let nowX = this.dataRange.xmin;
for (let i = 0; i <= this.label.divideX; i++) {
const x = Math.ceil(this.padding.left + this.dataInterval.widthInterval * i * intervalX);
let labelIndex = (this.label.divideX <= 1) ? (this.xDateLabel.length - 1) * i : Math.floor(this.xDateLabel.length / this.label.divideX * i);
if (labelIndex >= this.xDateLabel.length) labelIndex = this.xDateLabel.length - 1;
const text = this.xDateLabel[labelIndex];
this.ctx.textAlign = "center";
this.ctx.fillText(text, x, this.zone.data.originY + fontHeight);
nowX = this.accAdd(nowX, intervalX);
}
this.ctx.stroke();
// titleX
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.fillStyle = this.color.titleX;
this.ctx.fillText(this.label.titleX, this.zone.data.originX + this.zone.data.width + 5, this.zone.data.originY - 10);
this.ctx.stroke();
}
else {
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.strokeStyle = this.color.grid;
this.ctx.fillStyle = this.color.titleX;
// min label at origin
this.ctx.textAlign = "center";
const intervalX = this.accAdd(this.dataRange.xmax, -this.dataRange.xmin) / this.label.divideX;
const fontHeight = 20;
let nowX = this.dataRange.xmin;
for (let i = 0; i <= this.label.divideX; i++) {
const x = Math.ceil(this.padding.left + this.dataInterval.widthInterval * i * intervalX);
const text = nowX.toString();
this.ctx.moveTo(x, this.zone.data.originY);
this.ctx.lineTo(x, this.padding.up);
this.ctx.textAlign = "center";
this.ctx.fillText(text, x, this.zone.data.originY + fontHeight);
nowX = this.accAdd(nowX, intervalX);
}
this.ctx.stroke();
// titleX
this.ctx.beginPath();
this.ctx.font = this.font;
this.ctx.fillStyle = this.color.titleX;
this.ctx.fillText(this.label.titleX, this.zone.data.originX + this.zone.data.width + 5, this.zone.data.originY - 10);
this.ctx.stroke();
}
}
setBackground() {
this.ctx.rect(0, 0, this.size.width, this.size.height);
this.ctx.fillStyle = this.color.background;
this.ctx.fill();
}
data2Point(points) {
// true point in pic
return points.map((point) => {
const x = Math.ceil(this.dataInterval.widthInterval * (point.x - this.dataRange.xmin) + this.padding.left);
const y = Math.ceil(this.size.height - this.dataInterval.heightInterval * (point.y - this.dataRange.ymin) - this.padding.down);
return { x, y };
});
}
/**
* @param {Line} line
*/
drawLine(line) {
const drawPoints = this.data2Point(line.points);
this.ctx.beginPath();
this.ctx.moveTo(drawPoints[0].x, drawPoints[0].y);
drawPoints.map((point) => {
this.ctx.lineWidth = 2;
this.ctx.lineTo(point.x, point.y);
this.ctx.strokeStyle = line.lineColor;
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.fillStyle = line.pointFillColor;
this.ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(point.x, point.y);
});
this.ctx.stroke();
}
drawLines() {
this.lines.map((line) => {
this.drawLine(line);
})
}
draw() {
this.setBackground();
this.drawUp();
this.drawCoordinates();
this.drawLeft();
if (this.lines.length > 1) this.drawRight();
this.drawBottom();
this.drawLines();
// data:image/png;base64,#picdata#
return this.canvas.toDataURL();
// return this;
}
} |
JavaScript | class NoMatch extends React.Component{
render(){
return(
<div>
No Pages Not Found
</div>
)
}
} |
JavaScript | class HttpClient {
constructor(directoryUrl, accountKey) {
this.directoryUrl = directoryUrl;
this.accountKey = accountKey;
this.directory = null;
this.jwk = null;
}
/**
* HTTP request
*
* @param {string} url HTTP URL
* @param {string} method HTTP method
* @param {object} [opts] Request options
* @returns {Promise<object>} HTTP response
*/
async request(url, method, opts = {}) {
opts.url = url;
opts.method = method;
opts.validateStatus = null;
/* Headers */
if (typeof opts.headers === 'undefined') {
opts.headers = {};
}
opts.headers['Content-Type'] = 'application/jose+json';
/* Request */
debug(`HTTP request: ${method} ${url}`);
const resp = await axios.request(opts);
debug(`RESP ${resp.status} ${method} ${url}`);
return resp;
}
/**
* Ensure provider directory exists
*
* https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#directory
*
* @returns {Promise}
*/
async getDirectory() {
if (!this.directory) {
const resp = await this.request(this.directoryUrl, 'get');
this.directory = resp.data;
}
}
/**
* Get JSON Web Key
*
* @returns {Promise<object>} {e, kty, n}
*/
async getJwk() {
if (this.jwk) {
return this.jwk;
}
const exponent = await forge.getPublicExponent(this.accountKey);
const modulus = await forge.getModulus(this.accountKey);
this.jwk = {
e: util.b64encode(exponent),
kty: 'RSA',
n: util.b64encode(modulus)
};
return this.jwk;
}
/**
* Get nonce from directory API endpoint
*
* https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#getting-a-nonce
*
* @returns {Promise<string>} nonce
*/
async getNonce() {
const url = await this.getResourceUrl('newNonce');
const resp = await this.request(url, 'head');
if (!resp.headers['replay-nonce']) {
throw new Error('Failed to get nonce from ACME provider');
}
return resp.headers['replay-nonce'];
}
/**
* Get URL for a directory resource
*
* @param {string} resource API resource name
* @returns {Promise<string>} URL
*/
async getResourceUrl(resource) {
await this.getDirectory();
if (!this.directory[resource]) {
throw new Error(`Could not resolve URL for API resource: "${resource}"`);
}
return this.directory[resource];
}
/**
* Create signed HTTP request body
*
* @param {string} url Request URL
* @param {object} payload Request payload
* @param {string} [nonce] Request nonce
* @returns {Promise<object>} Signed HTTP request body
*/
async createSignedBody(url, payload, nonce = null, kid = null) {
/* JWS header */
const header = {
url,
alg: 'RS256'
};
if (nonce) {
debug(`Using nonce: ${nonce}`);
header.nonce = nonce;
}
/* KID or JWK */
if (kid) {
header.kid = kid;
}
else {
header.jwk = await this.getJwk();
}
/* Request payload */
const result = {
payload: util.b64encode(JSON.stringify(payload)),
protected: util.b64encode(JSON.stringify(header))
};
/* Signature */
const signer = crypto.createSign('RSA-SHA256').update(`${result.protected}.${result.payload}`, 'utf8');
result.signature = util.b64escape(signer.sign(this.accountKey, 'base64'));
return result;
}
/**
* Signed HTTP request
*
* https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#request-authentication
*
* @param {string} url Request URL
* @param {string} method HTTP method
* @param {object} payload Request payload
* @param {string} [kid] KID
* @returns {Promise<object>} HTTP response
*/
async signedRequest(url, method, payload, kid = null) {
const nonce = await this.getNonce();
const data = await this.createSignedBody(url, payload, nonce, kid);
return this.request(url, method, { data });
}
} |
JavaScript | class DefaultHasManyThroughRepository {
constructor(getTargetRepository, getThroughRepository, getTargetConstraintFromThroughModels, getTargetKeys, getThroughConstraintFromSource, getTargetIds, getThroughConstraintFromTarget) {
this.getTargetRepository = getTargetRepository;
this.getThroughRepository = getThroughRepository;
this.getTargetConstraintFromThroughModels = getTargetConstraintFromThroughModels;
this.getTargetKeys = getTargetKeys;
this.getThroughConstraintFromSource = getThroughConstraintFromSource;
this.getTargetIds = getTargetIds;
this.getThroughConstraintFromTarget = getThroughConstraintFromTarget;
}
async create(targetModelData, options) {
const targetRepository = await this.getTargetRepository();
const targetInstance = await targetRepository.create(targetModelData, options);
await this.link(targetInstance.getId(), options);
return targetInstance;
}
async find(filter, options) {
const targetRepository = await this.getTargetRepository();
const throughRepository = await this.getThroughRepository();
const sourceConstraint = this.getThroughConstraintFromSource();
const throughInstances = await throughRepository.find(__1.constrainFilter(undefined, sourceConstraint), options === null || options === void 0 ? void 0 : options.throughOptions);
const targetConstraint = this.getTargetConstraintFromThroughModels(throughInstances);
return targetRepository.find(__1.constrainFilter(filter, targetConstraint), options);
}
async delete(where, options) {
const targetRepository = await this.getTargetRepository();
const throughRepository = await this.getThroughRepository();
const sourceConstraint = this.getThroughConstraintFromSource();
const throughInstances = await throughRepository.find(__1.constrainFilter(undefined, sourceConstraint), options === null || options === void 0 ? void 0 : options.throughOptions);
if (where) {
// only delete related through models
// TODO(Agnes): this performance can be improved by only fetching related data
// TODO: add target ids to the `where` constraint
const targets = await targetRepository.find({ where });
const targetIds = this.getTargetIds(targets);
if (targetIds.length > 0) {
const targetConstraint = this.getThroughConstraintFromTarget(targetIds);
const constraints = { ...targetConstraint, ...sourceConstraint };
await throughRepository.deleteAll(__1.constrainDataObject({}, constraints), options === null || options === void 0 ? void 0 : options.throughOptions);
}
}
else {
// otherwise, delete through models that relate to the sourceId
const targetFkValues = this.getTargetKeys(throughInstances);
// delete through instances that have the targets that are going to be deleted
const throughFkConstraint = this.getThroughConstraintFromTarget(targetFkValues);
await throughRepository.deleteAll(__1.constrainWhereOr({}, [sourceConstraint, throughFkConstraint]));
}
// delete target(s)
const targetConstraint = this.getTargetConstraintFromThroughModels(throughInstances);
return targetRepository.deleteAll(__1.constrainWhere(where, targetConstraint), options);
}
// only allows patch target instances for now
async patch(dataObject, where, options) {
const targetRepository = await this.getTargetRepository();
const throughRepository = await this.getThroughRepository();
const sourceConstraint = this.getThroughConstraintFromSource();
const throughInstances = await throughRepository.find(__1.constrainFilter(undefined, sourceConstraint), options === null || options === void 0 ? void 0 : options.throughOptions);
const targetConstraint = this.getTargetConstraintFromThroughModels(throughInstances);
return targetRepository.updateAll(__1.constrainDataObject(dataObject, targetConstraint), __1.constrainWhere(where, targetConstraint), options);
}
async link(targetId, options) {
var _a;
const throughRepository = await this.getThroughRepository();
const sourceConstraint = this.getThroughConstraintFromSource();
const targetConstraint = this.getThroughConstraintFromTarget([targetId]);
const constraints = { ...targetConstraint, ...sourceConstraint };
await throughRepository.create(__1.constrainDataObject((_a = options === null || options === void 0 ? void 0 : options.throughData) !== null && _a !== void 0 ? _a : {}, constraints), options === null || options === void 0 ? void 0 : options.throughOptions);
}
async unlink(targetId, options) {
const throughRepository = await this.getThroughRepository();
const sourceConstraint = this.getThroughConstraintFromSource();
const targetConstraint = this.getThroughConstraintFromTarget([targetId]);
const constraints = { ...targetConstraint, ...sourceConstraint };
await throughRepository.deleteAll(__1.constrainDataObject({}, constraints), options === null || options === void 0 ? void 0 : options.throughOptions);
}
} |
JavaScript | class Grid {
/**
* Create a new grid
*
* @param {number} width
* @param {number} height
* @param {number[][]} cells
*/
constructor(width, height, cells = null) {
this.width = width;
this.height = height;
this.cells = cells || Array2D.create(width, height, 0);
this.events = new EventEmitter();
}
/**
* Create a new Grid from a JSON string
*
* @param jsonObject {object} JSON object
* @return {Grid}
*/
static fromJSON(jsonObject) {
const { width, height, cells } = jsonObject;
return new Grid(width, height, cells);
}
/**
* Serializes to a JSON object
* @return {{cells: number[][], width: number, height: number}}
*/
toJSON() {
return {
width: this.width,
height: this.height,
cells: Array2D.clone(this.cells),
};
}
copy(grid) {
this.width = grid.width;
this.height = grid.height;
this.replace(grid.cells);
}
/**
* Retrieves the value at (x,y)
*
* @param {number} x
* @param {number} y
* @return {number}
*/
get(x, y) {
return this.cells[y][x];
}
/**
* Set the value at (x, y)
*
* @fires Grid.events#update
*
* @param {number} x
* @param {number} y
* @param {number} value
*/
set(x, y, value) {
this.cells[y][x] = value;
/**
* Update event.
*
* Argument is an array of updated cells. Each updated cell is represented
* by an array with three elements: [x, y, value]
*
* @event Grid.events#update
* @type {[[number, number, number]]}
*/
this.events.emit('update', [[x, y, value]]);
}
/**
* Backwards compatibility function that maps (x, y) to a single index in a flat array
* @deprecated
* @param x {number}
* @param y {number}
* @return {number}
*/
offset(x, y) {
return y * this.width + x;
}
replace(cells) {
Array2D.copy(cells, this.cells);
this.events.emit('update', this.allCells());
}
/**
* Returns true if (x, y) are valid coordinates within the grid's bounds.
*
* @param {number} x
* @param {number} y
* @return {boolean}
*/
isValidCoords(x, y) {
return x >= 0 && y >= 0 && x < this.width && y < this.height;
}
/**
* Returns all cells, represented as [x, y, value] arrays.
*
* @return {[[number, number, number]]}
*/
allCells() {
return Array2D.items(this.cells);
}
/**
* Get cells adjacent to the cell at (i, j).
*
* Each cell is represented by an array of the form [i, j, value]
* A cell has at most four adjacent cells, which share one side
* (diagonals are not adjacent).
*
* @param {number} i
* @param {number} j
* @return {[[number, number, number]]}
*/
adjacentCells(i, j) {
return [[i, j - 1], [i + 1, j], [i, j + 1], [i - 1, j]]
.filter(([x, y]) => this.isValidCoords(x, y))
.map(([x, y]) => [x, y, this.get(x, y)]);
}
/**
* Returns the cells around the cell at (i, j).
*
* Each cells returned is represented as an array [i, j, value].
* Cells "around" are those reachable by no less than <distance> steps in
* any direction, including diagonals.
*
* @param {number} i
* @param {number} j
* @param {number} distance
* @return {[[number, number, number]]}
*/
nearbyCells(i, j, distance = 1) {
const coords = [];
// Top
for (let x = i - distance; x < i + distance; x += 1) {
coords.push([x, j - distance]);
}
// Right
for (let y = j - distance; y < j + distance; y += 1) {
coords.push([i + distance, y]);
}
// Bottom
for (let x = i + distance; x > i - distance; x -= 1) {
coords.push([x, j + distance]);
}
// Left
for (let y = j + distance; y > j - distance; y -= 1) {
coords.push([i - distance, y]);
}
return coords
.filter(([x, y]) => this.isValidCoords(x, y))
.map(([x, y]) => [x, y, this.get(x, y)]);
}
stepDistance(x1, y1, x2, y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
} |
JavaScript | class Consumer extends Component {
render() {
return this.props.children(this.context);
}
} |
JavaScript | class bySquare {
constructor(client) {
this.client = client;
}
/**
* Returns a list of relevant points of interest for a given area.
*
* @param {Object} params
* @param {Double} params.north latitude north of bounding box - required
* @param {Double} params.west longitude west of bounding box - required
* @param {Double} params.south latitude south of bounding box - required
* @param {Double} params.east longitude east of bounding box - required
* @return {Promise.<Response,ResponseError>} a Promise
*
* Find relevant points of interest within an area in Barcelona
*
* ```js
* amadeus.referenceData.locations.pointsOfInterest.bySquare.get({
* north: 41.397158,
* west: 2.160873,
* south: 41.394582,
* east: 2.177181
* });
* ```
*/
get(params = {}) {
return this.client.get('/v1/reference-data/locations/pois/by-square', params);
}
} |
JavaScript | class CategoryModel extends Model {
constructor(dataStructure) {
super(dataStructure);
}
validate(dataStructure) {
return SideCatProps.checkPropTypes(
CategoryModel.Structure,
dataStructure,
this.constructor.name
);
}
serialize() {
return Object.assign({}, Model.prototype.serialize.call(this), {
children: this.serializeChildren(this.dataStructure.children)
});
}
serializeChildren(children) {
if (!children) {
return null;
}
return children.map((child) => {
return Object.assign({}, Model.prototype.serialize.call(child), {
children: this.serializeChildren(child.dataStructure.children)
});
});
}
} |
JavaScript | class ProfilePhoto extends React.Component {
constructor() {
super(...arguments);
_defineProperty(this, "state", {
src: this.props.imageSrc || ''
});
_defineProperty(this, "handleError", event => {
const {
fallbackImageSrc
} = this.props;
if (fallbackImageSrc) {
this.setState({
src: fallbackImageSrc
});
}
});
}
componentDidUpdate(prevProps) {
const {
imageSrc
} = this.props;
if (imageSrc !== prevProps.imageSrc) {
this.setState({
src: imageSrc
});
}
}
render() {
const {
src
} = this.state;
const {
cx,
fallbackImageSrc,
inline,
macro,
large,
small,
size,
square,
styles,
title,
theme
} = this.props;
const {
unit
} = theme;
return React.createElement("div", {
className: cx(inline && styles.inline, styles.regular, macro && styles.macro, large && styles.large, small && styles.small, !!size && size > 0 && {
height: size * unit,
maxHeight: size * unit,
maxWidth: size * unit,
width: size * unit
})
}, React.createElement("img", {
className: cx(styles.image, styles.regular, !square && styles.roundedImage, macro && styles.macro, large && styles.large, small && styles.small, !!size && size > 0 && {
height: size * unit,
maxHeight: size * unit,
maxWidth: size * unit,
width: size * unit
}),
src: src,
alt: title,
title: title,
onError: fallbackImageSrc ? this.handleError : undefined
}));
}
} |
JavaScript | class Event extends Component {
render() {
const {data} = this.props
//console.log(data)
//const numLines = 3
return (
<div className="ui-event">
<h2 className="fm">{data.title}</h2>
{data.subheadline !== "" &&
<h3 className="fm">{data.subheadline}</h3>
}
<time className="fm" dateTime="2018-07-07">{moment(data.date).format('LL')}</time>
{/* {data.texte !== null &&
<Truncate clamp={numLines} className="texte ">
<div
dangerouslySetInnerHTML={{ __html: data.texte.childMarkdownRemark.html }} />
</Truncate>
} */}
{data.peoples !== "" &&
<Peoples length={data.peoples.length} data={data.peoples} />
}
<div className="bottom">
<div className="eventType fs">{data.eventType}</div>
</div>
</div>
);
}
} |
JavaScript | class Qektors {
/**
* @param {Object} options - `width` must be explicitly defined!
*/
constructor (options) {
if (!(options && typeof options === 'object')) this._complain(E_OPTIONS, '', 0)
const opts = { ...Qektors.options, ...options }
if (!(opts.width >= 1)) this._complain(E_OPTIONS)
if (typeof opts.Ctr !== 'function') this._complain('bad \'Ctr\' option')
this._Ctr = opts.Ctr
this._iTop = 0
this._width = opts.width
this.total = 0
this.isLocked = false
this.next = null
this._raw = [new this._Ctr(this._width)] // So, valid index is never 0!
this._isTyped = (this._raw.buffer && this._raw.buffer instanceof ArrayBuffer) || false
}
/**
* Internal error emitter.
* @param {string} msg - error message.
* @param {string=} locus - empty means constructor.
* @param {string|number} extras - for `extras` property or 0 for generating TypeError.
* @protected
*/
_complain (msg, locus, extras = undefined) {
const error = new (extras === 0 ? TypeError : Error)(
ME + (locus ? '.' + locus : '()') + ': ' + msg)
if (extras) error.extras = extras
throw error
}
// Those read-only properties are documented in class description above.
get Ctr () {
return this._Ctr
}
get isTyped () {
return this._isTyped
}
get size () {
return this._iTop
}
get strict () {
return false
}
get top () {
const { _iTop } = this
return _iTop === 0 ? undefined : this._raw[_iTop]
}
get topIndex () {
return this._iTop
}
get volume () {
return this._raw.length - 1
}
get width () {
return this._width
}
/**
* Retrieve an existing entry by its index.
* @param {number} index
* @returns {undefined|*}
*/
// $ /*
at (index) {
if (index === 0) return undefined
const entry = this._raw[index]
return entry && entry[0] === 0 ? undefined : entry
} // $ /* */
// $ at (index) {
// $ const t0 = getTime()
// $ let entry
// $ if (index !== 0) {
// $ entry = this._raw[index]
// $ entry = entry && entry[0] === 0 ? undefined : entry
// $ }
// $ ++N.at, T.at += getTime() - t0
// $ return entry
// $ }
/**
* Delete all entries, but do not release allocated memory.
* @returns {Qektors}
*/
clear () {
// $ const t0 = getTime()
const { _raw } = this
for (let i = this._iTop; i > 0; --i) _raw[i][0] = 0
this._iTop = 0
// $ ++N.clear, T.clear += getTime() - t0
return this
}
/**
* Mark the top entry as deleted.
* @returns {number} remaining entries count.
*/
delete () {
// $ const t0 = getTime()
let { _iTop } = this
if (_iTop > 0) {
this._raw[_iTop][0] = 0
this._iTop = --_iTop
}
// $ ++N.delete, T.delete += getTime() - t0
return _iTop
}
/**
* Ensure that entry with given `key` exists (allocate if necessary).
* @param {number} key
* @returns {number} entry index.
*/
grant (key) {
// $ const t0 = getTime()
let index = this.indexOf(key), entry
if (index === 0) {
const { _iTop, _raw } = this
if ((index = _iTop + 1) === _raw.length) {
_raw.push(entry = new this._Ctr(this._width))
} else {
entry = _raw[index]
}
entry[0] = key
this._iTop = index
}
// $ ++N.grant, T.grant += getTime() - t0
return index
}
/**
* Get index of entry with given `key`.
* @param {number} key
* @returns {number} 0 if not found.
*/
indexOf (key) {
// $ const t0 = getTime()
let { _iTop, _raw } = this
while (_iTop !== 0 && _raw[_iTop][0] !== key) --_iTop
// $ ++N.indexOf, T.indexOf += getTime() - t0
return _iTop
}
/**
* Similar to Array.prototype.map().
* @param {function(*,*,*):*} cb
* @returns {[]}
*/
map (cb) {
// $ const t0 = getTime()
const res = [], { _raw, _iTop } = this
for (let i = 1; i <= _iTop; ++i) {
res.push(cb(_raw[i], i, this))
}
// $ ++N.map, T.map += getTime() - t0
return res
}
/**
* Add an entry of `values` to the end of collection.
* @param {...number} values
* @returns {number} new topIndex
*/
push (...values) {
// $ const t0 = getTime()
let { _iTop, _raw } = this, entry
if (++_iTop === _raw.length) {
_raw.push(entry = new this._Ctr(this._width))
} else {
entry = _raw[_iTop]
}
for (let i = values.length; --i >= 0;) entry[i] = values[i]
this._iTop = _iTop
// $ ++N.push, T.push += getTime() - t0
return _iTop
}
} |
JavaScript | class GenomeReader {
constructor (registrar, info) {
this.registrar = registrar
this.info = info
const n = config.CachingFetcher.dbName
this.fetcher = new CachingFetcher(n, info.name)
this.kstore = new KeyStore(n)
this.readers = this.info.tracks.reduce((a,t) => {
if (t.type === 'ChunkedGff3') {
a[t.name] = new ChunkedGff3FileReader(this.fetcher, t.name, t.chunkSize, info, info.url + "models/")
}
else if (t.type === "ChunkedVcf") {
a[t.name] = new ChunkedVcfFileReader(this.fetcher, t.name, t.chunkSize, info, info.url )
}
return a
}, {})
this.readyp = this.checkTimestamp()
}
// -------------------------------------------------------------------------------
// Compares the timestamp of the cached info for this genome against the timestamp
// of the info we just loaded. If they differ, drop all cached data for this genome,
// then save the new info.
// Returns a promise that resolves when all that is done.
checkTimestamp () {
return this.kstore.get(this.info.name + '::INFO').then(cinfo => {
if (!cinfo || cinfo.timestamp != this.info.timestamp) {
return this.fetcher.clearNamespace().then(() => {
return this.kstore.set(this.info.name+'::INFO', this.info)
})
}
})
}
// Returns a promise that resolves when the genome is ready to start reading
ready () {
return this.readyp
}
} |
JavaScript | class FileInput extends React.Component {
constructor(...args) {
super(...args);
this.state = {inputDisplay: '', inputKey: 0};
this.onChange = this.onChange.bind(this);
this.onChooseClick = this.onChooseClick.bind(this);
this.onClearClick = this.onClearClick.bind(this);
}
render() {
const className = getClassName(
'react-ui-file-input',
this.props.className
);
return (
<div className={className}>
{this.renderHiddenInput()}
{this.renderChooseButton()}
{this.renderClearButton()}
{this.renderInput()}
</div>
);
}
renderHiddenInput() {
const style = {display: 'none'};
return (
<input
disabled={this.props.disabled}
key={this.state.inputKey}
name={this.props.name}
onChange={this.onChange}
ref="fileInput"
style={style}
type="file" />
);
}
renderChooseButton() {
const className = getClassName(
'react-ui-file-input-choose',
this.props.chooseClassName
);
return this.props.showChooseButton ? (
<button
className={className}
disabled={this.props.disabled}
onClick={this.onChooseClick}
type="button">
{this.props.chooseText}
</button>
) : null;
}
renderClearButton() {
const className = getClassName(
'react-ui-file-input-clear',
this.props.clearClassName
);
return this.props.showClearButton ? (
<button
className={className}
disabled={this.props.disabled}
onClick={this.onClearClick}
type="button">
{this.props.clearText}
</button>
) : null;
}
renderInput() {
const className = getClassName(
'react-ui-file-input-input',
this.props.inputClassName
);
return this.props.showInput ? (
<input
className={className}
disabled={this.props.disabled}
onClick={this.onChooseClick}
placeholder={this.props.placeholder}
readOnly={true}
type="text"
value={this.state.inputDisplay} />
) : null;
}
onChange(evt) {
const inputDisplay = evt.target.value.split('\\').pop();
this.props.onChange(evt, inputDisplay);
this.setState({inputDisplay});
}
onChooseClick(evt) {
evt.preventDefault();
this.props.onChooseClick(evt);
this.refs.fileInput.click();
}
onClearClick(evt) {
evt.preventDefault();
this.props.onClearClick(evt);
this.clear();
}
clear() {
this.setState({
inputDisplay: '',
inputKey: this.state.inputKey + 1
});
}
} |
JavaScript | class TimeDataSet {
/**
* This constructor will create you an empty instance
*/
constructor () {
this.startTime = null;
this.endTime = null;
this.timeIngored = null;
this.isBooked = null;
this.setTimeIngnored(false);
this.setTimeBooked(false);
this.description = '';
}
/**
* This method will set the description of this instance
*
* @param {String} data
*/
setDescription (data) {
this.description = data;
}
/**
* This function will return you the description
*/
getDescription () {
return this.description;
}
/**
* Should we ignore the entry?
* @param {boolean} isIgnored
*/
setTimeIngnored(isIgnored) {
this.timeIngored = isIgnored;
}
/**
* Set if this is already booked
* @param {boolean} isBooked
*/
setTimeBooked(isBooked) {
this.isBooked = isBooked;
}
/**
* Should the dataset be counted
*/
isGettingCounted() {
return (!this.timeIngored);
}
/**
* Is this already booked
* @returns {boolean}
*/
isAlreadyBooked() {
return this.isBooked;
}
/**
* This method will return you a human readable version of you date
*
* @param {Int32Array} value
*/
convertToTime (value) {
if (value === null) {
return '';
}
let date = new Date(value);
let time = String(date.getHours()).padStart(2, '0') + ':';
time += String(date.getMinutes()).padStart(2, '0');
return time;
}
/**
* This method will set the start date for this container
*
* @param {Date} dateTime;
*/
setStartTime (dateTime) {
this.startTime = dateTime.getTime();
}
/**
* This method will get you the raw start date of this container
*/
getRawStartTime () {
return this.startTime;
}
/**
* This method will get you the start date of this container
*/
getStartTime () {
return this.convertToTime(this.startTime);
}
/**
* Get the start date as real date
* @returns {Date}
*/
getStartDate() {
return new Date(this.getRawStartTime());
}
/**
* This method will get you the raw end date of this container
*/
getRawEndTime () {
return this.endTime;
}
/**
* This method will set the end date for this container
* @param {Date} dateTime
*/
setEndTime (dateTime) {
this.endTime = dateTime.getTime();
}
/**
* This method will return you the current end time set in the container
*/
getEndTime () {
return this.convertToTime(this.endTime);
}
/**
* Get the end date as real date
* @returns {Date}
*/
getEndDate() {
return new Date(this.getRawEndTime());
}
/**
* This method will return you the work time for this data set
*/
getWorkTime () {
var returnInt = 0;
if (this.startTime === null || this.endTime === null) {
return returnInt;
}
returnInt = this.endTime - this.startTime;
return returnInt;
}
/**
* This method will return you a well formated time ready to display
*/
getFormatedTime () {
return TimeFormatter.toHumanReadable(this.getWorkTime());
}
/**
* This method will get you a saveable dataset as object
*/
getSaveableDataSet () {
var data = {};
data['startTime'] = this.startTime;
data['endTime'] = this.endTime;
data['counted'] = this.isGettingCounted();
data['booked'] = this.isAlreadyBooked();
data['description'] = this.description;
return data;
}
/**
* This method will fill this container with the data of an object
*
* @param {Object} data
*/
fromJson (data) {
if (data.startTime === undefined || data.endTime === undefined) {
return;
}
this.startTime = data.startTime;
this.endTime = data.endTime;
if (data.counted !== undefined) {
this.setTimeIngnored(!data.counted);
}
if (data.booked !== undefined) {
this.setTimeBooked(data.booked);
}
if (data.description !== undefined) {
this.description = data.description;
}
}
} |
JavaScript | class Server {
/** @type {string} */
@serialize(qtypes.QString, 'Host')
host;
@serialize(qtypes.QUInt, 'Port')
port = 6667;
@serialize(qtypes.QString, 'Password')
password = '';
@serialize(qtypes.QBool, 'UseSSL')
useSSL = false;
@serialize(qtypes.QBool, 'UseProxy')
useProxy = false;
@serialize(qtypes.QInt, 'ProxyType')
proxyType = 0;
@serialize(qtypes.QString, 'ProxyHost')
proxyHost = '';
@serialize(qtypes.QUInt, 'ProxyPort')
proxyPort = 8080;
@serialize(qtypes.QString, 'ProxyUser')
proxyUser = '';
@serialize(qtypes.QString, 'ProxyPass')
proxyPass = '';
@serialize(qtypes.QBool)
sslVerify = false;
@serialize(qtypes.QInt)
sslVersion = 0;
constructor(args) {
Object.assign(this, args);
}
} |
JavaScript | class Network extends EventEmitter {
/** @type {number} */
@serialize(qtypes.QUserType.get('NetworkId'), 'NetworkId')
get networkId() {
return this.id;
}
/** @type {number} */
set networkId(value) {
this.id = value;
}
/** @type {string} */
@serialize(qtypes.QString, 'NetworkName')
get networkName() {
return this.name;
}
/** @type {string} */
set networkName(value) {
this.name = value;
}
/** @type {number} */
@serialize(qtypes.QUserType.get('IdentityId'), 'Identity')
identityId;
/** @type {string} */
@setter(toStr)
@serialize(qtypes.QByteArray, 'CodecForServer')
codecForServer = null;
/** @type {string} */
@setter(toStr)
@serialize(qtypes.QByteArray, 'CodecForEncoding')
codecForEncoding = null;
/** @type {string} */
@setter(toStr)
@serialize(qtypes.QByteArray, 'CodecForDecoding')
codecForDecoding = null;
@serialize(qtypes.QList.of(Server), 'ServerList')
ServerList = [];
@serialize(qtypes.QBool, 'UseRandomServer')
useRandomServer = false;
@serialize(qtypes.QStringList, 'Perform')
perform = [];
@serialize(qtypes.QBool, 'UseAutoIdentify')
useAutoIdentify = false;
@serialize(qtypes.QString, 'AutoIdentifyService')
autoIdentifyService = 'NickServ';
@serialize(qtypes.QString, 'AutoIdentifyPassword')
autoIdentifyPassword = '';
@serialize(qtypes.QBool, 'UseSasl')
useSasl = false;
@serialize(qtypes.QString, 'SaslAccount')
saslAccount = '';
@serialize(qtypes.QString, 'SaslPassword')
saslPassword = '';
@serialize(qtypes.QBool, 'UseAutoReconnect')
useAutoReconnect = true;
@serialize(qtypes.QUInt, 'AutoReconnectInterval')
autoReconnectInterval = 60;
@serialize(qtypes.QUInt, 'AutoReconnectRetries')
autoReconnectRetries = 20;
@serialize(qtypes.QBool, 'UnlimitedReconnectRetries')
unlimitedReconnectRetries = false;
@serialize(qtypes.QBool, 'RejoinChannels')
rejoinChannels = true;
@serialize(qtypes.QBool, 'UseCustomMessageRate')
useCustomMessageRate = false;
@serialize(qtypes.QBool, 'UnlimitedMessageRate')
unlimitedMessageRate = false;
@serialize(qtypes.QUInt, 'MessageRateDelay')
msgRateMessageDelay = 2200;
@serialize(qtypes.QUInt, 'MessageRateBurstSize')
msgRateBurstSize = 5;
/** @type {string} */
set myNick(value) {
this.nick = value;
}
/** @type {string} */
get myNick() {
return this._nick;
}
/** @type {string} */
set nick(value) {
this._nick = value;
this.nickRegex = value.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
/** @type {string} */
get nick() {
return this._nick;
}
/** @type {boolean} */
set isConnected(connected) {
connected = Boolean(connected);
if (this.statusBuffer) {
this.statusBuffer.isActive = connected;
}
this._isConnected = connected;
}
/** @type {boolean} */
get isConnected() {
return this._isConnected;
}
constructor(id, name = null) {
super();
this._isConnected = false;
this._nick = null;
this.id = typeof id === 'number' ? id : -1;
/** @type {IRCBufferCollection} */
this.buffers = new IRCBufferCollection();
/** @type {Map<String, IRCUser>} */
this.users = new Map;
/** @type {boolean} */
this.open = false;
/** @type {number} */
this.connectionState = ConnectionStates.DISCONNECTED;
/** @type {number} */
this.latency = 0;
/** @type {?IRCBuffer} */
this.statusBuffer = null;
this.nickRegex = null;
this.name = name;
}
getUser(nick) {
return this.users.get(nick);
}
/**
* Add given user to the network
* @param {IRCUser} user
*/
addUser(user) {
this.users.set(user.nick, user);
}
/**
* Returns `true` if the specified nick/{@link IRCUser} exists in the network, `false` otherwise
* @param {string|IRCUser} nick
* @returns {boolean}
*/
hasUser(nick) {
return this.users.has(typeof nick.nick === 'string' ? nick.nick : nick);
}
/**
* Replace `oldNick` by `newNick` in current network and buffers
* @param {string} oldNick
* @param {string} newNick
*/
renameUser(oldNick, newNick) {
const user = this.users.get(oldNick);
if (user) {
user.nick = newNick;
this.users.set(newNick, user);
this.users.delete(oldNick);
for (let buffer of this.buffers.values()) {
if (buffer.isChannel && buffer.hasUser(oldNick)) {
buffer.updateUserMaps(oldNick);
}
}
}
}
/**
* Delete the user identified by `nick` from the network and buffers
* @param {string} nick
* @returns {number[]} list of buffer ids that has been deactivated
*/
deleteUser(nick) {
const ids = [];
for (let buffer of this.buffers.values()) {
if (buffer.isChannel) {
if (buffer.hasUser(nick)) {
buffer.removeUser(nick);
if (this.nick && this.nick.toLowerCase() === nick.toLowerCase()) {
buffer.isActive = false;
ids.push(buffer.id);
}
}
} else if (buffer.name === nick) {
buffer.isActive = false;
ids.push(buffer.id);
}
}
this.users.delete(nick);
return ids;
}
/**
* @param {IRCUser[]} userlist
*/
updateUsers(userlist) {
this.users.clear();
if (Array.isArray(userlist) && userlist.length> 0) {
for (let user of userlist) {
this.users.set(user.nick, user);
}
}
}
/**
* Get the {IRCBuffer} corresponding to specified id or name
* @param {number|string} bufferId
*/
getBuffer(bufferId) {
return this.buffers.get(bufferId);
}
/**
* Returns `true` if a buffer exists with corresponding id or name
* @param {number|string} bufferId
*/
hasBuffer(bufferId) {
return this.buffers.has(bufferId);
}
/**
* This method is used internally by update method
* @protected
* @param {Object} uac
*/
@serialize(qtypes.QMap, 'IrcUsersAndChannels')
set ircUsersAndChannels(uac) {
// Create IRCUsers and attach them to network
for (let user of Object.values(uac.users)) {
this.addUser(new IRCUser(user));
}
// If there is a buffer corresponding to a nick, activate the buffer
for (let buffer of this.buffers.values()) {
if (!buffer.isChannel && !buffer.isStatusBuffer && this.hasUser(buffer.name)) {
buffer.isActive = true;
}
}
// Attach channels to network
let channel, nick, user;
for (let key of Object.keys(uac.channels)) {
channel = this.getBuffer(key);
// Then attach users to channels
for (nick in uac.channels[key].UserModes) {
user = this.getUser(nick);
if (user) {
channel.addUser(user, uac.channels[key].UserModes[nick]);
} else {
logger('User %s have not been found on server', nick);
}
}
}
}
update(data) {
Object.assign(this, data);
}
toString() {
return `<Network ${this.id} ${this.name}>`;
}
} |
JavaScript | class NetworkCollection extends Map {
/**
* Add an empty {@linkNetwork} identified by `networkId` to the collection
* @param {number} networkId
* @returns {module:network.Network}
*/
add(networkId) {
networkId = parseInt(networkId, 10);
const network = new Network(networkId);
this.set(networkId, network);
return network;
}
/**
* Returns {@link IRCBuffer} corresponding to given `bufferId`, or `undefined` otherwise
* @param {number} bufferId
* @returns {?IRCBuffer}
*/
getBuffer(bufferId) {
if (typeof bufferId !== 'number') return undefined;
let buffer;
for (let network of this.values()) {
buffer = network.buffers.get(bufferId);
if (buffer) return buffer;
}
return undefined;
}
/**
* Delete the {@link IRCBuffer} object identified by `bufferId` from the networks
* @param {number} bufferId
*/
deleteBuffer(bufferId) {
if (typeof bufferId !== 'number') {
logger('deleteBuffer:%O is not a number', bufferId);
return;
}
const buffer = this.getBuffer(bufferId);
if (buffer) {
this.get(buffer.network).buffers.delete(bufferId);
}
}
/**
* Yields all buffers of all networks
*/
*buffers() {
for (let network of this.values()) {
for (let buffer of network.buffers.values()) {
yield buffer;
}
}
}
/**
* Returns `true` if buffer identified by `bufferId` exists
* @param {number} bufferId
*/
hasBuffer(bufferId) {
if (typeof bufferId !== 'number') {
logger('hasBuffer:%O is not a number', bufferId);
return false;
}
for (let network of this.values()) {
if (network.hasBuffer(bufferId)) return true;
}
return false;
}
} |
JavaScript | class PrivatednsClient extends AbstractClient {
constructor(credential, region, profile) {
super("privatedns.tencentcloudapi.com", "2020-10-28", credential, region, profile);
}
/**
* This API is used to get the private domain information.
* @param {DescribePrivateZoneRequest} req
* @param {function(string, DescribePrivateZoneResponse):void} cb
* @public
*/
DescribePrivateZone(req, cb) {
let resp = new DescribePrivateZoneResponse();
this.request("DescribePrivateZone", req, resp, cb);
}
/**
* This API is used to modify a DNS record for a private domain.
* @param {ModifyPrivateZoneRecordRequest} req
* @param {function(string, ModifyPrivateZoneRecordResponse):void} cb
* @public
*/
ModifyPrivateZoneRecord(req, cb) {
let resp = new ModifyPrivateZoneRecordResponse();
this.request("ModifyPrivateZoneRecord", req, resp, cb);
}
/**
* This API is used to get the list of records for a private domain.
* @param {DescribePrivateZoneRecordListRequest} req
* @param {function(string, DescribePrivateZoneRecordListResponse):void} cb
* @public
*/
DescribePrivateZoneRecordList(req, cb) {
let resp = new DescribePrivateZoneRecordListResponse();
this.request("DescribePrivateZoneRecordList", req, resp, cb);
}
/**
* This API is used to query the Private DNS activation status.
* @param {DescribePrivateZoneServiceRequest} req
* @param {function(string, DescribePrivateZoneServiceResponse):void} cb
* @public
*/
DescribePrivateZoneService(req, cb) {
let resp = new DescribePrivateZoneServiceResponse();
this.request("DescribePrivateZoneService", req, resp, cb);
}
/**
* This API is used to get the list of operation logs.
* @param {DescribeAuditLogRequest} req
* @param {function(string, DescribeAuditLogResponse):void} cb
* @public
*/
DescribeAuditLog(req, cb) {
let resp = new DescribeAuditLogResponse();
this.request("DescribeAuditLog", req, resp, cb);
}
/**
* This API is used to add a DNS record for a private domain.
* @param {CreatePrivateZoneRecordRequest} req
* @param {function(string, CreatePrivateZoneRecordResponse):void} cb
* @public
*/
CreatePrivateZoneRecord(req, cb) {
let resp = new CreatePrivateZoneRecordResponse();
this.request("CreatePrivateZoneRecord", req, resp, cb);
}
/**
* This API is used to create a private domain.
* @param {CreatePrivateZoneRequest} req
* @param {function(string, CreatePrivateZoneResponse):void} cb
* @public
*/
CreatePrivateZone(req, cb) {
let resp = new CreatePrivateZoneResponse();
this.request("CreatePrivateZone", req, resp, cb);
}
/**
* This API is used to get the list of private domains.
* @param {DescribePrivateZoneListRequest} req
* @param {function(string, DescribePrivateZoneListResponse):void} cb
* @public
*/
DescribePrivateZoneList(req, cb) {
let resp = new DescribePrivateZoneListResponse();
this.request("DescribePrivateZoneList", req, resp, cb);
}
/**
* This API is used to modify a private domain.
* @param {ModifyPrivateZoneRequest} req
* @param {function(string, ModifyPrivateZoneResponse):void} cb
* @public
*/
ModifyPrivateZone(req, cb) {
let resp = new ModifyPrivateZoneResponse();
this.request("ModifyPrivateZone", req, resp, cb);
}
/**
* This API is used to activate the Private DNS service.
* @param {SubscribePrivateZoneServiceRequest} req
* @param {function(string, SubscribePrivateZoneServiceResponse):void} cb
* @public
*/
SubscribePrivateZoneService(req, cb) {
let resp = new SubscribePrivateZoneServiceResponse();
this.request("SubscribePrivateZoneService", req, resp, cb);
}
/**
* This API is used to get the overview of private DNS records.
* @param {DescribeDashboardRequest} req
* @param {function(string, DescribeDashboardResponse):void} cb
* @public
*/
DescribeDashboard(req, cb) {
let resp = new DescribeDashboardResponse();
this.request("DescribeDashboard", req, resp, cb);
}
/**
* This API is used to modify the VPC associated with a private domain.
* @param {ModifyPrivateZoneVpcRequest} req
* @param {function(string, ModifyPrivateZoneVpcResponse):void} cb
* @public
*/
ModifyPrivateZoneVpc(req, cb) {
let resp = new ModifyPrivateZoneVpcResponse();
this.request("ModifyPrivateZoneVpc", req, resp, cb);
}
/**
* This API is used to get the DNS request volume of a private domain.
* @param {DescribeRequestDataRequest} req
* @param {function(string, DescribeRequestDataResponse):void} cb
* @public
*/
DescribeRequestData(req, cb) {
let resp = new DescribeRequestDataResponse();
this.request("DescribeRequestData", req, resp, cb);
}
/**
* This API is used to delete a DNS record for a private domain.
* @param {DeletePrivateZoneRecordRequest} req
* @param {function(string, DeletePrivateZoneRecordResponse):void} cb
* @public
*/
DeletePrivateZoneRecord(req, cb) {
let resp = new DeletePrivateZoneRecordResponse();
this.request("DeletePrivateZoneRecord", req, resp, cb);
}
/**
* This API is used to delete a private domain and stop DNS.
* @param {DeletePrivateZoneRequest} req
* @param {function(string, DeletePrivateZoneResponse):void} cb
* @public
*/
DeletePrivateZone(req, cb) {
let resp = new DeletePrivateZoneResponse();
this.request("DeletePrivateZone", req, resp, cb);
}
/**
* This API is used to get the list of Private DNS accounts.
* @param {DescribePrivateDNSAccountListRequest} req
* @param {function(string, DescribePrivateDNSAccountListResponse):void} cb
* @public
*/
DescribePrivateDNSAccountList(req, cb) {
let resp = new DescribePrivateDNSAccountListResponse();
this.request("DescribePrivateDNSAccountList", req, resp, cb);
}
} |
JavaScript | class Scope extends EventEmitter {
static persistenceTm = 1;// if > 0, will wait 'persistenceTm' ms before destroy when dispose reach 0
static Store = null;
static scopeRef = function scopeRef( path ) {
this.path = path;
};
static scopes = allScopes;// all active scopes
/**
* get a parsed reference list from stateMap
* @param _ref
* @returns {{storeId, path, alias: *, ref: *}}
*/
static stateMapToRefList( sm, state = {}, _refs = [], actions = {}, path = "" ) {
let applier;
Object.keys(sm).forEach(
key => {
let cpath = path ? path + '.' + key : key;
sm[key] instanceof Scope.scopeRef ?
_refs.push(sm[key].path + ':' + cpath) :
(sm[key] && sm[key] instanceof Function) ?
key === "$apply" ?
applier = sm[key] :
actions[key] = sm[key] :
(sm[key] && sm[key].prototype instanceof Scope.Store) ?
_refs.push(sm[key].as(cpath)) :
//key === "$actions" ?
//Object.assign(actions, sm[key]) :
state[cpath] = sm[key]
//: this.stateMapToRefList(sm[key], _refs, path + '.' + key)
}
)
return applier;
}
static getScope( scopes ) {
let skey = is.array(scopes) ? scopes.sort(( a, b ) => {
if ( a.firstname < b.firstname ) return -1;
if ( a.firstname > b.firstname ) return 1;
return 0;
}).join('+') : scopes;
return allScopes[skey] = allScopes[skey] || new Scope({}, { id: skey });
};
/**
* Init an RS scope
*
* @param storesMap {Object} Object with the initial stores definition / instances
* @param config {Object} Scope config
* {
* parent {scope} @optional parent scope
* upperScope {scope} @optional parent (hirarchicly) scope
*
* id {string} @optional id ( if this id exist storesMap will be merge on the 'id'
* scope)
* key {string} @optional key of the scope ( if no id is set, the scope id will be (parent.id+'>'+key)
* incrementId {bool} @optional true to add a suffix id, if the provided key or id globally exist
*
* keyMap {Object} @optional
*
* state {Object} @optional initial state by store alias
* data {Object} @optional initial data by store alias
*
* rootEmitter {bool} @optional true to not being destabilized by parent
* boundedActions {array | regexp} @optional list or regexp of actions not propagated to the parent
* autoDestroy {true | false | 'inherit'}
* persistenceTm {number) if > 0, will wait 'persistenceTm' ms before destroy when
* dispose reach 0 autoDestroy {bool} will trigger retain & dispose after start
* }
* @returns {Scope}
*/
constructor( storesMap, {
parent,
upperScope,
key,
keyMap = parent && parent.keyMap || {},
id,
snapshot,
state,
data,
incrementId = !!key,
persistenceTm,
autoDestroy,
rootEmitter,
boundedActions
} = {} ) {
super();
let _ = {
keyPID: (upperScope && upperScope._id || parent && parent._id || shortid.generate()),
key,
incrementId,
baseId: id
};
// generate / set this scope id
id = id || key && (_.keyPID + '>' + key);
_.isLocalId = !id;
id = id || ("_____" + shortid.generate());
if ( keyMap[id] && incrementId ) {// generate key id
let i = -1;
while ( keyMap[id + '[' + (++i) + ']'] ) ;
id = id + '[' + i + ']';
}
keyMap[id] = true;
this.keyMap = keyMap;
if ( allScopes[id] ) {// réuse existing scope
this._id = id;
if ( _.baseId ) {// specified id should merge over existing
allScopes[id].register(storesMap);
}
//console.log('recycle scope !!', id);
return allScopes[id]
}
// register this scope in the static Scope.scopes
allScopes[id] = this;
this._id = id;
this._rev = 0;
this._ = _;
this.actions = {};
this.stores = {};
this.state = {};
this.data = {};
this.parent = parent;
if ( autoDestroy == 'inherit' )
autoDestroy = parent && parent._autoDestroy;
this._autoDestroy = autoDestroy;
_.persistenceTm = persistenceTm || this.constructor.persistenceTm;
if ( parent && parent.dead )
throw new Error("Can't use a dead scope as parent !");
__proto__push(this, 'actions', parent);
__proto__push(this, 'stores', parent);
__proto__push(this, 'state', parent);
__proto__push(this, 'data', parent);
this.sources = [];
_.childScopes = [];
_.childScopesList = [];
_.unStableChilds = 0;
_.seenChilds = 0;
_._listening = {};
_._scope = {};
_._mixed = [];
_._mixedList = [];
_.followers = [];
this.__retains = { all: 0 };
this.__locks = { all: 1 };
// todo
_._boundedActions = is.array(boundedActions)
? { test: boundedActions.includes.bind(boundedActions) }
: boundedActions;
// register to the parent scope
if ( parent ) {
parent.retain("isMyParent");
if ( !rootEmitter ) {
!parent._stable && this.wait("waitingParent");
parent.on(_._parentList = {
'stable' : s => this.release("waitingParent"),
'unstable': s => this.wait("waitingParent"),
'update' : s => this._propag()
});
}
else {
parent.on(_._parentList = {
'update': s => this._propag()
});
}
// this.register(parent.__scope, state, data);
}
// restore snapshots
snapshot && this.restore(snapshot);
// register this scope stores
this.register(storesMap, state, data);
this.__locks.all--;
this._stable = !this.__locks.all;
if ( parent ) {
parent._addChild(this);
}
if ( autoDestroy )
setTimeout(
tm => {
this.retain("autoDestroy");
this.dispose("autoDestroy");
}
)
}
/**
*
* Mount the stores in storesList, in this scope or in its parents or mixed scopes
*
* @param storeIdList {string|storeRef} Store name, Array of Store names, or Rescope
* store ref from Store::as or Store:as
* @param state
* @param data
* @returns {Scope}
*/
mount( storeIdList, snapshot, state, data ) {
if ( is.array(storeIdList) ) {
storeIdList.forEach(storeId => this._mount(storeId, snapshot, state, data));
}
else {
this._mount(...arguments);
}
return this;
}
_mount( id, snapshot, state, data ) {
let ref, _ = this._;
ref = this.parseRef(id)
if ( id == "$parent" ) return;
if ( !_._scope[ref.storeId] ) {//ask mixed || parent
if ( _._mixed.reduceRight(( mounted, ctx ) => (mounted || ctx._mount(id, snapshot, state, data)), false) ||
!this.parent )
return;
return this.parent._mount(...arguments);
}
else {
let store = _._scope[ref.storeId], taskQueue = [];
if ( Scope.isStoreClass(store) ) {
_._scope[ref.storeId] = new store(this, {
//snapshot,
name: ref.storeId,
state,
data
}, taskQueue);
while ( taskQueue.length ) taskQueue.shift()();
}
else if ( Scope.isScopeClass(store) ) {
store = _._scope[ref.storeId] = new store({ $parent: this }, {
key : ref.storeId,
incrementId: true,
upperScope : this
});
if ( ref.path.length > 1 )
_._scope[ref.storeId].mount(ref.path.slice(1).join('.'), snapshot, state, data)
}
if ( Scope.isStore(store) ) {
if ( state !== undefined && data === undefined )
store.setState(state);
else if ( state !== undefined )
store.state = state;
if ( data !== undefined )
store.push(data);
}
if ( Scope.isScope(store) ) {
if ( state !== undefined )
store.setState(state);
if ( ref.path.length > 1 )
store._mount(ref.path.slice(1).join('.'))
}
this._watchStore(ref.storeId);
}
return _._scope[ref.storeId];
}
resetKeys() {
for ( let key in this.keyMap )
if ( this.keyMap.hasOwnProperty(key) )
delete this.keyMap[key];
}
/**
* Register stores in storesMap & link them in the protos
* @param storesMap
* @param state
* @param data
*/
register( storesMap, state = {}, data = {} ) {
this.relink(storesMap, this, false, false);
Object.keys(storesMap).forEach(
id => {
if ( id === "$parent" ) return;
if ( !Scope.isScopable(storesMap[id]) )
return console.warn("RS: ", this._id, ", can't register not scopable object :", id);
if ( storesMap[id].singleton || (is.fn(storesMap[id]) && (state[id] || data[id])) ) {
this._mount(id, undefined, state[id], data[id])
}
else if ( state[id] || data[id] ) {
if ( data[id] ) {
if ( state[id] )
this.stores[id].state = state[id];
this.stores[id].push(data[id]);
}
else if ( state[id] ) {
this.stores[id].setState(state[id]);
}
}
else {
this._watchStore(id);
}
}
)
}
/**
* Map srcCtx store's on targetCtx headers proto's
* @param srcCtx
* @param targetCtx
* @param state
* @param data
*/
relink( srcCtx, targetCtx = this, external, force ) {
let _ = this._, me = this;
Object.keys(srcCtx)
.forEach(
id => {
let hotReloading, actions, activeActions;
// same store def : ignore
if ( !force && targetCtx._._scope[id] === srcCtx[id] ||
targetCtx._._scope[id] && (targetCtx._._scope[id].constructor === srcCtx[id]) )
return;
// hot switch
if ( !force && targetCtx._._scope[id] ) {
if ( !external && !is.fn(targetCtx._._scope[id]) ) {// mounted store
targetCtx._._scope[id].__proto__ = srcCtx[id].prototype;
targetCtx._._scope[id].__onHotReloaded
&& targetCtx._._scope[id].__onHotReloaded(srcCtx[id]);
}
else if ( !external && is.fn(targetCtx._._scope[id]) )
targetCtx._._scope[id] = srcCtx[id];
}
else if ( !force && !external )
_._scope[id] = srcCtx[id];
// map the store id
Object.defineProperty(
targetCtx._.stores.prototype,
id,
{
enumerable : true,
configurable: true,
get : () => _._scope[id]
}
);
activeActions = targetCtx._.actions.prototype;
// not mapping hierarchic scopes
if ( id !== "$parent" ) {
// map state & data
Object.defineProperty(
targetCtx._.state.prototype,
id,
{
enumerable : true,
configurable: true,
get : () => (_._scope[id] && _._scope[id].state),
set : ( v ) => (this._mount(id, undefined, v))
}
);
Object.defineProperty(
targetCtx._.data.prototype,
id,
{
enumerable : true,
configurable: true,
get : () => (_._scope[id] && _._scope[id].data),
set : ( v ) => (this._mount(id, undefined, undefined, v))
}
);
// action mapping
actions = srcCtx[id] instanceof Scope.Store
? srcCtx[id].constructor.actions
: srcCtx[id].actions;
if ( Scope.isScopeClass(_._scope[id]) )
this._mount(id);
if ( Scope.isScope(_._scope[id]) ) {// map hierarchic scopes
if ( activeActions[id] )
console.warn("RS : Sub scope actions is mapped over an existing function !", id);
activeActions[id] = _._scope[id].actions;
}
else if ( !Scope.isStore(_._scope[id]) && !Scope.isStoreClass(_._scope[id]) )
return;
actions &&
this._mapActions(actions, activeActions, id)
}
else {
activeActions[id] = srcCtx[id].actions;
}
// remount the store if it was hot reloaded
if ( hotReloading )
this._mount(id, null, hotReloading);
}
)
}
/**
* Map & bounds actions from stores
* todo : unmap actions
* @param actions
* @param target
* @param storeId
* @private
*/
_mapActions( actions, target, storeId ) {
for ( let act in actions ) {
if ( actions.hasOwnProperty(act) ) {
if ( is.object(actions[act]) ) {// hirarchised actions
if ( target[act] && !is.object(target[act]) )
console.warn("RS : Actions namespace is mapped over an existing function !", storeId, act);
target[act] = target[act] || { __targetStores: 0 };
this._mapActions(actions[act], target[act]);
target[act].__targetStores++;
}
else if ( target.hasOwnProperty(act) )
target[act].__targetStores++;
else {
if ( is.object(target[act]) )
console.warn("RS : Action is mapped over existing namespace !", storeId, act);
target[act] = this.dispatch.bind(this, act);
target[act].__targetStores = 1;
}
}
}
}
/**
* Make this scope watching the local store 'id'
* @param id
* @returns {boolean}
* @private
*/
_watchStore( id ) {
let _ = this._;
if ( !_._listening[id] && !is.fn(_._scope[id]) ) {
!_._scope[id]._autoDestroy && _._scope[id].retain("scoped");
!_._scope[id].isStable() && this.wait(id);
_._scope[id].on(
_._listening[id] = {
'destroy' : s => {
delete _._listening[id];
_._scope[id] = _._scope[id].constructor;
},
'update' : s => this.propag(),
'stable' : s => this.release(id),
'unstable': s => this.wait(id)
});
}
return true;
}
/**
* Mix targetCtx on this scope
* Mixed scope parents are NOT mapped
* @param targetCtx
*/
mixin( targetCtx ) {
let parent = this.parent,
lists,
_ = this._;
_._mixed.push(targetCtx);
targetCtx.retain("mixedTo");
if ( !targetCtx._stable )
this.wait(targetCtx._id);
_._mixedList.push(lists = {
'stable' : s => this.release(targetCtx._id),
'unstable': s => this.wait(targetCtx._id),
'update' : s => this._propag()
});
targetCtx.on(lists);
// reset protos
// push new proto with parent
__proto__push(this, 'actions', parent);
__proto__push(this, 'stores', parent);
__proto__push(this, 'state', parent);
__proto__push(this, 'data', parent);
// bind local accessors in the new proto
this.relink(_._scope, this, false, true);
_._mixed.forEach(
ctx => {
// push protos
__proto__push(this, 'actions');
__proto__push(this, 'stores');
__proto__push(this, 'state');
__proto__push(this, 'data');
this.stores.__origin = "mixed " + ctx._id;
// write mixed accessors
ctx.relink(ctx._._scope, this, true, true)
}
)
}
/**
* Bind stores from this scope, his parents or mixed scopes to obj
*
* @param target {React.Component|Store|function}
* @param key {string} stores keys to bind updates
* @param as
* @param setInitial {boolean} false to not propag initial value (default : true)
*/
bind( target, key, as, setInitial = true, revMap = {} ) {
let lastRevs, data, refKeys;
if ( key && !is.array(key) )
key = [key];
if ( as === false || as === true ) {
setInitial = as;
as = null;
}
refKeys = key
.map(id => (is.string(id) ? id : id.name))
.map(id => (this.parseRef(id)));
this._.followers.push(
[
target,
key,
as || undefined,
lastRevs = refKeys.reduce(( revs, ref ) => {
revs[ref.storeId] = revs[ref.storeId] || {
rev : 0,
refs: []
};
revs[ref.storeId].refs.push(ref);
return revs;
}, revMap)
]);
this.mount(key);
this.retainStores(Object.keys(lastRevs), 'listeners');
if ( setInitial && this._stable ) {
data = this.getUpdates(lastRevs);
if ( !data ) return this;
if ( typeof target != "function" ) {
if ( as ) target.setState({ [as]: data });
else target.setState(data);
}
else {
target(data);
}
}
return this;
}
/**
* Un bind this scope off the given component-keys
* @param target
* @param key
* @returns {Array.<*>}
*/
unBind( target, key, as ) {
let followers = this._.followers,
i = followers && followers.length;
while ( followers && i-- )
if ( followers[i][0] === target &&
('' + followers[i][1]) == ('' + key) &&
followers[i][2] == as ) {
this.disposeStores(Object.keys(followers[i][3]), 'listeners');
return followers.splice(i, 1);
}
}
/**
* Mount the stores in storeIdList from this scope, its parents and mixed scope
* Bind them to 'to'
* Hook 'to' so it will auto unbind on 'destroy' or 'componentWillUnmount'
* @param target
* @param storeIdList
* @param bind
* @returns {Object} Initial outputs of the stores in 'storesList'
*/
map( target, storeIdList, bind = true, revMap ) {
let Store = this.constructor.Store;
storeIdList = is.array(storeIdList) ? storeIdList : [storeIdList];
let refList = storeIdList.map(this.parseRef);
this.mount(storeIdList);
if ( bind && target instanceof Store ) {
Store.map(target, storeIdList, this, this, false)
}
else if ( bind ) {
this.bind(target, storeIdList, undefined, false);
let mixedCWUnmount,
unMountKey = target.isReactComponent ? "componentWillUnmount" : "destroy";
if ( target.hasOwnProperty(unMountKey) ) {
mixedCWUnmount = target[unMountKey];
}
target[unMountKey] = ( ...argz ) => {
delete target[unMountKey];
if ( mixedCWUnmount )
target[unMountKey] = mixedCWUnmount;
this.unBind(target, storeIdList);
return target[unMountKey] && target[unMountKey](...argz);
}
}
return revMap && this.getUpdates(revMap)
|| refList.reduce(( data, ref ) => {
walknSet(data, ref.alias || ref.path, this.retrieve(ref.path))
return data;
}, {});
}
/**
* Get current data value from json path
* @param path
* @returns {string|*}
*/
retrieve( path = "" ) {
path = is.string(path) ? path.split('.') : path;
return path &&
this.stores[path[0]] &&
this.stores[path[0]].retrieve &&
this.stores[path[0]].retrieve(path.slice(1));
}
/**
* Restore all nodes in a jsonPath
* @param path
* @returns {string|*}
*/
restoreRefPath( path = "" ) {
path = is.string(path) ? path.split('.') : path;
let obj, i = 0, cScope = this;
while ( i < path.length ) {
obj = cScope.stores[path[i]];
if ( Scope.isScopeClass(obj)
||
Scope.isStoreClass(obj) ) {
cScope.mount(path[0]);
obj = cScope.stores[path[i]];
}
if ( Scope.isScope(obj) ) {
cScope = obj;
i++;
}
else if ( Scope.isStore(obj) ) {
obj.restore();
break;
}
else {
break;
}
}
}
/**
* Get target store from json path
* @param path
* @returns {string|*}
*/
retrieveStore( path = "" ) {
path = is.string(path) ? path.split('.') : path;
return path
&& path.length
&& (
path.length != 1 && this.stores[path[0]].retrieveStore
? this.stores[path[0]].retrieveStore(path.slice(1))
: path.length == 1 && this.stores[path[0]]
);
}
/**
* Get or update stores revisions in 'storesRevMap'
* @param storesRevMap
* @param local
* @returns {{}}
*/
getStoresRevs( storesRevMap = {}, local ) {
let ctx = this._._scope;
if ( !storesRevMap ) {
storesRevMap = {};
}
Object.keys(ctx).forEach(
id => {
if ( id == "$parent" ) return;
if ( !is.fn(ctx[id])
) {
storesRevMap[id] = ctx[id]._rev;
}
else if ( !storesRevMap.hasOwnProperty(id) )
storesRevMap[id] = false
}
);
if ( !local ) {
this._._mixed.reduce(( updated, ctx ) => (ctx.getStoresRevs(storesRevMap), storesRevMap), storesRevMap);
this.parent && this.parent.getStoresRevs(storesRevMap);
}
return storesRevMap;
}
/**
* Recursively get all stores revs
* @param childs
* @returns {Array}
* @private
*/
_getRevMap( storesRevMap = {} ) {
let ctx = this._._scope;
Object.keys(ctx).forEach(
id => {
if ( id === "$parent" || storesRevMap[id] ) return;
storesRevMap[id] = { rev: ctx[id]._rev, refs: [] };
});
this._._mixed.reduceRight(
( storesRevMap, ctx ) => (ctx._getRevMap(storesRevMap)), storesRevMap);
this.parent && this.parent._getRevMap(storesRevMap);
return storesRevMap;
}
/**
* Get updated output basing storesRevMap's revisions.
* If a store in 'storesRevMap' was updated; add it to 'output' & update storesRevMap
* @param storesRevMap
* @param output
* @param updated
* @returns {*|{}}
*/
getRefsUpdates( refs, revMap, output ) {
revMap = revMap || refs
.map(id => (is.string(id) ? id : id.name))
.map(id => (this.parseRef(id)))
.reduce(( revs, ref ) => {
revs[ref.storeId] = revs[ref.storeId] || {
rev : 0,
refs: []
};
revs[ref.storeId].refs.push(ref);
return revs;
}, {});
return this.getUpdates(revMap, output)
}
/**
* Get or update output basing storesRevMap's revisions.
* If a store in 'storesRevMap' was updated; add it to 'output' & update storesRevMap
* @param storesRevMap
* @param output
* @param updated
* @returns {*|{}}
*/
getUpdates( storesRevMap, output, updated ) {
output = output || {};
storesRevMap = storesRevMap || this._getRevMap();
Object.keys(storesRevMap).forEach(
id => {
let store = this.stores[id];
storesRevMap[id] = storesRevMap[id] || { rev: 0, refs: [] };
if ( store && is.fn(store) ) {
updated = true;
output[id] = undefined;
}
else if ( store && store._rev > storesRevMap[id].rev ) {
storesRevMap[id].rev = store._rev;
updated = true;
storesRevMap[id].refs.forEach(
ref => {
output[ref.alias] = this.retrieve(ref.path)
}
)
}
}
)
return updated && output;
}
/**
* Recursively get all child scopes
* @param childs
* @returns {Array}
* @private
*/
_getAllChilds( childs = [] ) {
childs.push(...this._.childScopes);
this._.childScopes.forEach(
ctx => {
ctx._getAllChilds(childs);
}
);
return childs;
}
/**
* Serialize all active stores state & data in every childs & mixed scopes
*
* Scopes without key or id are ignored
* @param output
* @returns {{}}
*/
serialize( cfg = {}, output = {} ) {
let ctx = this._._scope,
{ baseId, key, keyPID, incrementId } = this._,
{
alias,
parentAlias,
} = cfg,
sid = key
? (parentAlias || keyPID) + '>' + key
: alias || parentAlias && (parentAlias + '/' + baseId) || this._id;
//alias = alias || baseId;
return this.serialize_ex(cfg, output, sid, alias, ["$parent"])
}
serialize_ex( cfg = {}, output = {}, sid, alias, exclude ) {
let _ = this._,
ctx = _._scope,
{ incrementId } = _,
{
withChilds = true,
withMixed = true,
norefs,
} = cfg;
if ( keyWalknGet(output, sid) ) {
if ( !incrementId )// done
return output;
else if ( incrementId ) {// generate key id
let i = -1;
while ( keyWalknGet(output, sid + '[' + (++i) + ']') ) ;
sid = sid + '[' + i + ']';
}
}
keyWalknSet(output, sid, {});
Object.keys(ctx).forEach(
id => {
if ( exclude.includes(id) || Scope.isStoreClass(ctx[id]) || Scope.isScopeClass(ctx[id]) )
return;
ctx[id].serialize({ ...cfg, parentAlias: sid }, output);
}
)
withChilds && _.childScopes.forEach(
ctx => {
!ctx._.isLocalId && ctx.serialize({
withChild : true,
withParents: false,
parentAlias: sid,
withMixed,
norefs,
}, output);
}
);
withMixed && _._mixed.forEach(
ctx => {
!ctx._.isLocalId && ctx.serialize({
withChild : false,
withParents: false,
withMixed,
norefs
}, output);
}
);
if ( alias ) {
output = Object.keys(output)
.reduce(
( h, k ) => (
h[k === this._id
? alias
: k] = output[k],
h
),
{}
)
}
return output;
}
/**
* Restore state & data from the serialize fn
* @param snapshot
* @param force
*/
restore( snapshot, cfg = {}, force = is.bool(cfg) && cfg ) {
let ctx = this._._scope, snap;
if ( snapshot && cfg && cfg.alias && cfg.alias != this._id ) {
snap = {
...snapshot,
[this._id]: snapshot[cfg.alias]
}
delete snap[cfg.alias];
snapshot = snap;
}
snapshot = snapshot
&& keyWalknGet(snapshot, this._id)
|| this.takeSnapshotByKey(this._id);
if ( !snapshot )
return;
this._.snapshot = { ...snapshot };
snap = snapshot['/'];
snapshot['/'] = { ...snap };
snap && Object.keys(snap).forEach(
name => {
if ( name == "$parent" ) return;
if ( ctx[name] ) {
if ( force && !is.fn(ctx[name]) )
ctx[name].destroy();
this._mount(name);// quiet
}
}
)
this._._mixed.forEach(
ctx => {
!ctx._.isLocalId && ctx.restore(undefined, force);
}
);
this._.childScopes.forEach(
ctx => {
!ctx._.isLocalId && ctx.restore(undefined, force);
}
);
}
getSnapshotByKey( key, local ) {
// only have the local snap
if ( this._.snapshot && key.startsWith(this._id) ) {
let obj = keyWalknGet(this._.snapshot, key.substr(this._id.length))
return obj;
}
else {
let ret = !local
&& this.parent
&& this.parent.getSnapshotByKey(key)
||
this.stores.$parent
&& this.stores.$parent.getSnapshotByKey(key);
return ret;
}
}
getSnapshotByKeyExt( snapshot, key, local ) {
// only have the local snap
if ( snapshot ) {
let obj = keyWalknGet(snapshot, key)
return obj;
}
}
takeSnapshotByKey( key, local ) {
if ( this._.snapshot && key.startsWith(this._id) ) {
let obj = keyWalknGet(this._.snapshot, key.substr(this._id.length))
if ( obj ) {
this.deleteSnapshotByKey(key, true);
}
return obj;
}
else {
let ret = !local
&& this.parent
&& this.parent.takeSnapshotByKey(key)
||
this.stores.$parent
&& this.stores.$parent.takeSnapshotByKey(key);
return ret;
}
}
deleteSnapshotByKey( key, local ) {
if ( this._.snapshot && key.startsWith(this._id) ) {
let obj = keyWalknGet(this._.snapshot, key.substr(this._id.length).replace(/^(.*[\>|\/])[^\>|\/]+$/ig, '$1'))
if ( obj )
delete obj[key.replace(/^.*[\>|\/]([^\>|\/]+)$/ig, '$1')]
}
return !local
&& this.parent
&& this.parent.deleteSnapshotByKey(key)
||
this.stores.$parent
&& this.stores.$parent.deleteSnapshotByKey(key);
}
setState( pState ) {
Object.keys(pState)
.forEach(k => (this.state[k] = pState[k]))
}
/**
* get a parsed reference
* @param _ref
* @returns {{storeId, path, alias: *, ref: *}}
*/
parseRef( _ref ) {
if ( typeof _ref !== 'string' ) {// @todo : rm this
this.register({ [_ref.name]: _ref.store });
_ref = _ref.name;
}
let ref = _ref.split(':');
ref[0] = ref[0].split('.');
return {
storeId: ref[0][0],
path : ref[0],
alias : ref[1] || ref[0][ref[0].length - 1],
ref : _ref
};
}
/**
* Dispatch an action to the top parent & mixed scopes, in all stores
* todo
* @param action
* @param data
* @returns {Scope}
*/
dispatch( action, ...argz ) {
if ( this.dead ) {
console.warn("Dispatch was called on a dead scope, check you're async functions in this stack...", (new Error()).stack);
return;
}
let bActs = this._._boundedActions;
for ( let storeId in this._._scope ) {
if ( storeId === "$parent" ) continue;
if ( !is.fn(this._._scope[storeId]) )
this._._scope[storeId].trigger(action, ...argz);
}
if ( bActs && bActs.test(action) )
return this;
this._._mixed.forEach(( ctx ) => (ctx.dispatch(action, ...argz)));
this.parent && this.parent.dispatch(action, ...argz);
return this;
}
trigger() {
this.dispatch(...arguments);
}
/**
* once('stable', cb)
* @param obj {React.Component|Store|function)
* @param key {string} optional key where to map the public state
*/
then( cb ) {
if ( !this._stable )
return this.once('stable', e => this.then(cb));
return cb(this.data);
}
onceStableTree( cb ) {
if ( this._.unStableChilds )
return this.once('stableTree', e => this.onceStableTree(cb));
return cb(this.data);
}
/**
* Call retain on the scoped stores basing the given list
*
* @param stores
* @param reason
*/
retainStores( stores = [], reason ) {
stores.forEach(
id => (this.stores[id] && this.stores[id].retain && this.stores[id].retain(reason))
)
}
/**
* Call retain on the scoped stores
*
* @param stores
* @param reason
*/
disposeStores( stores = [], reason ) {
stores.forEach(
id => (this.stores[id] && this.stores[id].dispose && this.stores[id].dispose(reason))
)
}
/**
* Keep the scope unstable until release is called
* @param reason
*/
wait( reason ) {
//console.log("wait", reason);
this._stable && !this.__locks.all && this.emit("unstable", this);
this._stable = false;
this.__locks.all++;
if ( reason ) {
this.__locks[reason] = this.__locks[reason] || 0;
this.__locks[reason]++;
}
}
/**
* Stabilize the scope if no more locks remain (wait fn)
* @param reason
*/
release( reason ) {
if ( reason ) {
if ( this.__locks[reason] == 0 )
console.error("Release more than locking !", reason);
this.__locks[reason] = this.__locks[reason] || 0;
this.__locks[reason]--;
}
if ( !reason && this.__locks.all == 0 )
console.error("Release more than locking !");
this.__locks.all--;
if ( !this.__locks.all ) {
if ( this._.stabilizerTM )
return;
this._.stabilizerTM && clearTimeout(this._.stabilizerTM);
this._.stabilizerTM = setTimeout(
e => {
this._.stabilizerTM = null;
if ( this.__locks.all )
return;
this._.propagTM && clearTimeout(this._.propagTM);
this._rev++;
this._stable = true;
this.emit("stable", this);
!this.dead && this._propag();// stability can induce destroy
}
);
}
}
/**
* Propag stores updates basing theirs last updates
* todo : data fps?
*/
propag() {
this._.propagTM && clearTimeout(this._.propagTM);
this._.propagTM = setTimeout(
e => {
this._.propagTM = null;
this._propag()
}, 2
);
}
_propag() {
if ( this._.followers.length )
this._.followers.forEach(( { 0: obj, 1: key, 2: as, 3: lastRevs, 3: remaps } ) => {
let data = this.getUpdates(lastRevs);
if ( !data ) return;
if ( typeof obj != "function" ) {
//console.log("setState ",obj, Object.keys(data))
if ( as ) obj.setState({ [as]: data });
else obj.setState(data);
}
else {
obj(data, lastRevs && { ...lastRevs } || "no revs");
}
// lastRevs &&
// key.forEach(id => (lastRevs[id] = this.stores[id] &&
// this.stores[id]._rev || 0));
});
this.emit("update", this.getUpdates());
}
/**
* is stable
* @returns bool
*/
isStable() {
return this._stable;
}
/**
* is stable tree
* @returns bool
*/
isStableTree() {
return !this._.unStableChilds;
}
/**
* Register children
* @param scope
* @private
*/
_addChild( scope ) {
this._.childScopes.push(scope);
this._.seenChilds++;
let lists = {
'stable' : s => {
this._.unStableChilds--;
if ( !this._.unStableChilds )
this.emit("stableTree", this)
},
'unstable' : s => {
this._.unStableChilds++;
if ( 1 == this._.unStableChilds )
this.emit("unstableTree", this)
},
'stableTree' : s => {
this._.unStableChilds--;
if ( !this._.unStableChilds )
this.emit("stableTree", this)
},
'unstableTree': s => {
this._.unStableChilds++;
if ( 1 == this._.unStableChilds )
this.emit("unstableTree", this)
},
'destroy' : ctx => {
if ( ctx._.unStableChilds )
this._.unStableChilds--;
if ( !ctx.isStable() )
this._.unStableChilds--;
if ( !this._.unStableChilds )
this.emit("stableTree", this)
}
},
wasStable = this._.unStableChilds;
!scope.isStable() && this._.unStableChilds++;
scope._.unStableChilds && this._.unStableChilds++;
this._.childScopesList.push(lists);
if ( !wasStable && this._.unStableChilds )
this.emit("unstableTree", this);
scope.on(lists);
}
_rmChild( ctx ) {
let i = this._.childScopes.indexOf(ctx),
wasStable = this._.unStableChilds;
if ( i != -1 ) {
this._.childScopes.splice(i, 1);
!ctx.isStable() && this._.unStableChilds--;
ctx._.unStableChilds && this._.unStableChilds--;
ctx.un(this._.childScopesList.splice(i, 1)[0]);
if ( wasStable && !this._.unStableChilds )
this.emit("stableTree")
}
}
retain( reason ) {
this.__retains.all++;
//console.log("retain", this._id, reason);
if ( reason ) {
this.__retains[reason] = this.__retains[reason] || 0;
this.__retains[reason]++;
}
}
dispose( reason ) {
//console.log("dispose", this._id, reason);
if ( reason ) {
if ( !this.__retains[reason] )
throw new Error("Dispose more than retaining : " + reason);
this.__retains[reason]--;
}
if ( !this.__retains.all )
throw new Error("Dispose more than retaining !");
this.__retains.all--;
if ( !this.__retains.all ) {
//console.log("dispose do destroy ", this._id, this._persistenceTm);
if ( this._.persistenceTm ) {
this._.destroyTM && clearTimeout(this._.destroyTM);
this._.destroyTM = setTimeout(
e => {
this.then(s => {
!this.__retains.all && !this.dead && this.destroy()
});
},
this._.persistenceTm
);
}
else {
this.then(s =>
(!this.__retains.all && !this.dead && this.destroy())
);
}
}
}
/**
* order destroy of local stores
*/
destroy() {
let ctx = this._._scope;
[...this._.childScopes].map(scope => scope.destroy())
for ( let key in ctx )
if ( !is.fn(ctx[key]) ) {
if ( key == "$parent" ) continue;
!ctx[key]._autoDestroy && ctx[key].dispose("scoped");
}
this._.stabilizerTM && clearTimeout(this._.stabilizerTM);
this._.propagTM && clearTimeout(this._.propagTM);
Object.keys(
this._._listening
).forEach(
id => ((id !== "$parent") && this._._scope[id].removeListener(this._._listening[id]))
);
while ( this._._mixedList.length ) {
this._._mixed[0].removeListener(this._._mixedList.shift());
this._._mixed.shift().dispose("mixedTo");
}
[...this._.followers].map(follower => this.unBind(...follower));
if ( this._._parentList ) {
this.parent._rmChild(this);
this.parent.removeListener(this._._parentList);
this.parent.dispose("isMyParent");
this._._parentList = null;
}
this.dead = true;
delete allScopes[this._id];
this.emit("destroy", this);
}
} |
JavaScript | class Handler {
constructor() {
/**
* Absolute path used for the modules database
* @type {string}
* @readonly
*/
this.dbPath = path.join(__dirname, "..", "data", "modules.json");
/**
* Absolute path to the presumed working directory
* @type {string}
* @readonly
*/
this.workingDirectory = path.join(__dirname, "..");
/**
* The amount of subfolders to trim from the beginning of paths
* @type {string}
* @readonly
*/
this.folderLevels = this.workingDirectory.split(path.sep).length;
// Determine whether the modules database exists prior to using low()
const generating = !fse.pathExistsSync(this.dbPath);
/**
* Modules database via lowdb
*/
this.modules = low(new FileSync(this.dbPath));
// Handle modules that were configured to be disabled by default
// All modules not present in the modules database are implicitly enabled (and will be added upon load)
if (generating) {
for (const trimmedPath of disabledModules) {
const resolvedPath = Handler.resolvePath(path.join(this.workingDirectory, trimmedPath));
if (!resolvedPath.success) continue;
// Putting the path in an array prevents periods from being interpreted as traversing the db
if (!this.modules.has([trimmedPath]).value()) this.modules.set([trimmedPath], false).write();
}
log.info("A database of enabled modules has been generated at ./data/modules.json");
}
}
/**
* @param {string} filePath
*/
static resolvePath(filePath) {
if (!filePath) return new Response({ message: "Required parameters weren't supplied", success: false });
const obj = {};
try {
obj.value = require.resolve(filePath);
} catch (error) {
obj.error = error;
obj.success = false;
if (error.code === "MODULE_NOT_FOUND") {
obj.code = error.code;
obj.message = `Path "${filePath}" couldn't be resolved, module not found`;
log.warn("[resolvePath]", obj.message, error);
} else {
obj.message = "Error while resolving file path";
log.error("[resolvePath]", error);
}
}
if (has(obj, "value") && isString(obj.value)) {
obj.success = true;
obj.message = "Path successfully resolved";
} else if (!has(obj, "error")) {
obj.success = false;
obj.message = "Something went wrong while resolving path, but didn't result in an error";
}
return new Response(obj);
}
/**
* @param {string} filePath
*/
trimPath(filePath) {
if (!filePath) return "";
const splitPath = filePath.split(path.sep);
if (!filePath.startsWith(this.workingDirectory)) return splitPath.join(path.posix.sep);
return drop(splitPath, this.folderLevels).join(path.posix.sep);
}
/**
* @param {BaseConstruct} construct
* @param {?string} [filePath=null]
*/
unloadModule(construct, filePath = null) {
if (!construct) return new Response({ message: "Required parameters weren't supplied", success: false });
if (construct instanceof BaseConstruct === false) return new Response({ message: "Construct provided wasn't a construct", success: false });
let target = null, cache = false, blocks = false, ids = [];
if (filePath) {
const resolvedPath = Handler.resolvePath(filePath);
if (resolvedPath.success && !resolvedPath.error) {
target = resolvedPath.value;
if (has(require.cache, target)) {
delete require.cache[target];
cache = true;
}
} else {
return resolvedPath;
}
}
if (construct.idsByPath.has(target)) {
ids = construct.idsByPath.get(target);
for (const id of ids) {
if (!construct.cache.has(id)) continue;
construct.unload(construct.cache.get(id));
}
blocks = true;
}
const obj = {
success: true,
value: filePath,
};
if (blocks || cache) {
obj.message = `Unloaded ${cache ? `"${target}" from the cache` : ""}${cache && blocks ? " and " : ""}${blocks ? (target ? `${ids.length} ${ids.length === 1 ? "block" : "blocks"} mapped to that path` : "all anonymous blocks") : ""} from the ${construct.name}`;
} else {
obj.message = `Didn't unload anything as "${target}" wasn't cached nor mapped to any blocks`;
}
return new Response(obj);
}
/**
* @param {BaseConstruct} construct
* @param {[string]} filePaths
* @param {?string} [directoryPath=null]
*/
unloadMultipleModules(construct, filePaths, directoryPath = null) {
if (!construct || !filePaths) return new Response({ message: "Required parameters weren't supplied", success: false });
if (!filePaths.length) return new Response({ message: `Unloaded 0/0 modules (No modules to unload, skipped)`, success: true });
let successes = 0;
const resolvedPaths = [];
for (const filePath of filePaths) {
const result = this.unloadModule(construct, filePath);
if (result.success && !result.error) ++successes;
if (result.value) resolvedPaths.push(result.value);
}
return new Response({
message: `Unloaded ${successes}/${filePaths.length} modules${directoryPath ? ` in "${directoryPath}"` : ""}`,
success: true,
value: resolvedPaths,
});
}
/**
* @param {BaseConstruct} construct
* @param {BaseBlock|[BaseBlock]} mod
* @param {?string} [filePath=null]
* @param {?string} [trimmedPath=null]
*/
loadModule(construct, mod, filePath = null, trimmedPath = null) {
if (!construct || !mod) return new Response({ message: "Required parameters weren't supplied", success: false });
if (construct instanceof BaseConstruct === false) return new Response({ message: "Construct provided wasn't a construct", success: false });
if (isArray(mod)) {
for (const block of mod) {
construct.load(block, filePath, trimmedPath);
}
return new Response({
message: `Loaded ${mod.length} ${mod.length === 1 ? "block" : "blocks"} from ${!filePath ? "code anonymously" : filePath}`,
success: true,
value: filePath,
});
} else {
construct.load(mod, filePath, trimmedPath);
return new Response({
message: `Loaded 1 block from ${!filePath ? "code anonymously" : `"${filePath}"`}`,
success: true,
value: filePath,
});
}
}
/**
* @param {BaseConstruct} construct
* @param {string} filePath
* @param {boolean} [respectDisabled=false]
*/
requireModule(construct, filePath, respectDisabled = false) {
if (!construct || !filePath) return new Response({ message: "Required parameters weren't supplied", success: false });
if (construct instanceof BaseConstruct === false) return new Response({ message: "Construct provided wasn't a construct", success: false });
const resolvedPath = Handler.resolvePath(filePath);
if (!resolvedPath.success || resolvedPath.error) return resolvedPath;
const trimmedPath = this.trimPath(resolvedPath.value);
// Putting the path in an array prevents periods from being interpreted as traversing the db
if (!this.modules.has([trimmedPath]).value()) {
this.modules.set([trimmedPath], true).write();
} else if (respectDisabled && !this.modules.get([trimmedPath]).value()) {
log.debug(`Skipping disabled module "${resolvedPath.value}"`);
return new Response({ message: `Module "${resolvedPath.value}" was disabled`, success: true });
}
let mod;
try {
mod = require(resolvedPath.value);
} catch (error) {
log.error("[requireModule]", error);
return new Response({ message: "Error while requiring module", success: false, error: error });
}
if (isNil(mod)) return new Response({ message: `Something went wrong while requiring module "${resolvedPath.value}" but didn't result in an error`, success: false });
// The use of cloneDeep prevents the require.cache from being affected by changes to the module
return this.loadModule(construct, cloneDeep(mod), resolvedPath.value, trimmedPath);
}
/**
* @param {BaseConstruct} construct
* @param {[string]} filePaths
* @param {boolean} [respectDisabled=false]
* @param {?string} [directoryPath=null]
*/
requireMultipleModules(construct, filePaths, respectDisabled = false, directoryPath = null) {
if (!construct || !filePaths) return new Response({ message: "Required parameters weren't supplied", success: false });
if (!filePaths.length) return new Response({ message: `Loaded 0/0 modules (No modules to require, skipped)`, success: true });
let successes = 0, disabled = 0;
const resolvedPaths = [];
for (const filePath of filePaths) {
const result = this.requireModule(construct, filePath, respectDisabled);
if (result.success && !result.error) {
if (!result.value) {
++disabled;
} else {
++successes;
resolvedPaths.push(result.value);
}
}
}
return new Response({
message: `Loaded ${successes}/${filePaths.length - disabled} modules${disabled ? ` (${disabled} disabled)` : ""}${directoryPath ? ` in "${directoryPath}"` : ""}`,
success: true,
value: resolvedPaths,
});
}
/**
* @param {string} directoryPath
*/
static async searchDirectory(directoryPath) {
if (!directoryPath) return new Response({ message: "Required parameters weren't supplied", success: false });
const filePaths = await filehound.create().paths(directoryPath).ext(".js").find().catch(error => {
log.error(error);
return new Response({ message: "Error while attempting to search directory", success: false, error: error });
});
if (isNil(filePaths)) return new Response({ message: "Something went wrong while searching directory but didn't result in an error", success: false });
if (!filePaths.length) return new Response({ message: `No files found in "${directoryPath}", skipping`, success: true, value: null });
return new Response({
message: `Found ${filePaths.length} ${!filePaths.length ? "file" : "files"} under "${directoryPath}"`,
success: true,
value: filePaths.map(filePath => path.join("..", filePath)),
});
}
/**
* @param {BaseConstruct} construct
* @param {string} directoryPath
* @param {boolean} [respectDisabled=false]
*/
async requireDirectory(construct, directoryPath, respectDisabled = false) {
if (!construct || !directoryPath) return new Response({ message: "Required parameters weren't supplied", success: false });
if (construct instanceof BaseConstruct === false) return new Response({ message: "Construct provided wasn't a construct", success: false });
const result = await Handler.searchDirectory(directoryPath);
if (!result.value || !result.success) return result;
return this.requireMultipleModules(construct, result.value, respectDisabled, directoryPath);
}
/**
* @param {BaseConstruct} construct
* @param {string} directoryPath
*/
async unloadDirectory(construct, directoryPath) {
if (!construct || !directoryPath) return new Response({ message: "Required parameters weren't supplied", success: false });
if (construct instanceof BaseConstruct === false) return new Response({ message: "Construct provided wasn't a construct", success: false });
const result = await Handler.searchDirectory(directoryPath);
if (!result.value || !result.success) return result;
return this.unloadMultipleModules(construct, result.value, directoryPath);
}
} |
JavaScript | class SchemaVersion {
/**
* @param {number} major
* @param {number} minor
* @param {number} patch
*
* @throws {InvalidSchemaVersion}
*/
constructor(major = 1, minor = 0, patch = 0) {
this.major = toInteger(major);
this.minor = toInteger(minor);
this.patch = toInteger(patch);
this.version = `${major}-${minor}-${patch}`;
if (!VALID_PATTERN.test(this.version)) {
throw new InvalidSchemaVersion(
`SchemaVersion [${this.version}] is invalid. It must match the pattern [${VALID_PATTERN}].`,
);
}
Object.freeze(this);
}
/**
* @param {string} version - A valid SchemaVersion as a string, e.g. 1-0-0
*
* @returns {SchemaVersion}
*
* @throws {InvalidSchemaVersion}
*/
static fromString(version = '1-0-0') {
const matches = `${version}`.match(VALID_PATTERN);
if (matches === null) {
throw new InvalidSchemaVersion(
`SchemaVersion [${version}] is invalid. It must match the pattern [${VALID_PATTERN}].`,
);
}
return new SchemaVersion(matches[1], matches[2], matches[3]);
}
/**
* @returns {string}
*/
toString() {
return this.version;
}
/**
* @returns {string}
*/
toJSON() {
return this.version;
}
/**
* @returns {string}
*/
valueOf() {
return this.version;
}
/**
* @returns {number}
*/
getMajor() {
return this.major;
}
/**
* @returns {number}
*/
getMinor() {
return this.minor;
}
/**
* @returns {number}
*/
getPatch() {
return this.patch;
}
} |
JavaScript | class SortHeader extends Component {
static defaultProps = {
};
render() {
const { options, onChange, value, className } = this.props;
// <i class="fas fa-arrow-up"></i>
// <i class="fas fa-sort-down"></i>
const token = value.split("_");
const key = token[0];
const isUp = token[1] === "up";
const items = options.map(e => {
let icon;
if (e === key) {
if (isUp) {
icon = <i className="fas fa-arrow-up"></i>;
} else {
icon = <i className="fas fa-arrow-down"></i>;
}
}
const next = `${e}_${(isUp ? "down" : "up")}`;
return (<div key={e} className="sort-item" onClick={() => onChange(next)}> {icon} {e} </div>)
})
return (<div className={classNames("sort-header", className)}>{items}</div>)
}
} |
JavaScript | class LoggingService {
constructor() {
}
log() {
if (appSettingsObject.logEnabled === true) {
console.log("LOGSERVICE:", ...arguments);
}
}
} |
JavaScript | class MatSelectSearchComponent {
/**
* @param {?} matSelect
* @param {?} changeDetectorRef
* @param {?} _viewportRuler
* @param {?=} matOption
*/
constructor(matSelect, changeDetectorRef, _viewportRuler, matOption = null) {
this.matSelect = matSelect;
this.changeDetectorRef = changeDetectorRef;
this._viewportRuler = _viewportRuler;
this.matOption = matOption;
/**
* Label of the search placeholder
*/
this.placeholderLabel = 'Suche';
/**
* Type of the search input field
*/
this.type = 'text';
/**
* Label to be shown when no entries are found. Set to null if no message should be shown.
*/
this.noEntriesFoundLabel = 'Keine Optionen gefunden';
/**
* Whether or not the search field should be cleared after the dropdown menu is closed.
* Useful for server-side filtering. See [#3](https://github.com/bithost-gmbh/ngx-mat-select-search/issues/3)
*/
this.clearSearchInput = true;
/**
* Whether to show the search-in-progress indicator
*/
this.searching = false;
/**
* Disables initial focusing of the input field
*/
this.disableInitialFocus = false;
/**
* Prevents home / end key being propagated to mat-select,
* allowing to move the cursor within the search input instead of navigating the options
*/
this.preventHomeEndKeyPropagation = false;
/**
* Disables scrolling to active options when option list changes. Useful for server-side search
*/
this.disableScrollToActiveOnOptionsChanged = false;
/**
* Adds 508 screen reader support for search box
*/
this.ariaLabel = 'dropdown search';
/**
* Whether to show Select All Checkbox (for mat-select[multi=true])
*/
this.showToggleAllCheckbox = false;
/**
* select all checkbox checked state
*/
this.toggleAllCheckboxChecked = false;
/**
* select all checkbox indeterminate state
*/
this.toggleAllCheckboxIndeterminate = false;
/**
* Output emitter to send to parent component with the toggle all boolean
*/
this.toggleAll = new _angular_core__WEBPACK_IMPORTED_MODULE_5__["EventEmitter"]();
this.onChange = (_) => { };
this.onTouched = (_) => { };
/**
* Whether the backdrop class has been set
*/
this.overlayClassSet = false;
/**
* Event that emits when the current value changes
*/
this.change = new _angular_core__WEBPACK_IMPORTED_MODULE_5__["EventEmitter"]();
/**
* Subject that emits when the component has been destroyed.
*/
this._onDestroy = new rxjs__WEBPACK_IMPORTED_MODULE_3__["Subject"]();
}
/**
* @return {?}
*/
get isInsideMatOption() {
return !!this.matOption;
}
/**
* Current search value
* @return {?}
*/
get value() {
return this._value;
}
/**
* @return {?}
*/
ngOnInit() {
// set custom panel class
/** @type {?} */
const panelClass = 'mat-select-search-panel';
if (this.matSelect.panelClass) {
if (Array.isArray(this.matSelect.panelClass)) {
((/** @type {?} */ (this.matSelect.panelClass))).push(panelClass);
}
else if (typeof this.matSelect.panelClass === 'string') {
this.matSelect.panelClass = [this.matSelect.panelClass, panelClass];
}
else if (typeof this.matSelect.panelClass === 'object') {
this.matSelect.panelClass[panelClass] = true;
}
}
else {
this.matSelect.panelClass = panelClass;
}
// set custom mat-option class if the component was placed inside a mat-option
if (this.matOption) {
this.matOption.disabled = true;
this.matOption._getHostElement().classList.add('contains-mat-select-search');
}
// when the select dropdown panel is opened or closed
this.matSelect.openedChange
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["delay"])(1), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe((opened) => {
if (opened) {
this.updateInputWidth();
// focus the search field when opening
if (!this.disableInitialFocus) {
this._focus();
}
}
else {
// clear it when closing
if (this.clearSearchInput) {
this._reset();
}
}
});
// set the first item active after the options changed
this.matSelect.openedChange
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["take"])(1))
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
if (this.matSelect._keyManager) {
this.matSelect._keyManager.change.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => this.adjustScrollTopToFitActiveOptionIntoView());
}
else {
console.log('_keyManager was not initialized.');
}
this._options = this.matSelect.options;
this._options.changes
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
/** @type {?} */
const keyManager = this.matSelect._keyManager;
if (keyManager && this.matSelect.panelOpen) {
// avoid "expression has been changed" error
setTimeout(() => {
// set first item active and input width
keyManager.setFirstItemActive();
this.updateInputWidth();
// set no entries found class on mat option
if (this.matOption) {
if (this._noEntriesFound()) {
this.matOption._getHostElement().classList.add('mat-select-search-no-entries-found');
}
else {
this.matOption._getHostElement().classList.remove('mat-select-search-no-entries-found');
}
}
if (!this.disableScrollToActiveOnOptionsChanged) {
this.adjustScrollTopToFitActiveOptionIntoView();
}
}, 1);
}
});
});
// detect changes when the input changes
this.change
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
this.changeDetectorRef.detectChanges();
});
// resize the input width when the viewport is resized, i.e. the trigger width could potentially be resized
this._viewportRuler.change()
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
if (this.matSelect.panelOpen) {
this.updateInputWidth();
}
});
this.initMultipleHandling();
}
/**
* @param {?} state
* @return {?}
*/
_emitSelectAllBooleanToParent(state) {
this.toggleAll.emit(state);
}
/**
* @return {?}
*/
ngOnDestroy() {
this._onDestroy.next();
this._onDestroy.complete();
}
/**
* @return {?}
*/
ngAfterViewInit() {
setTimeout(() => {
this.setOverlayClass();
});
// update view when available options change
this.matSelect.openedChange
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["take"])(1), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy)).subscribe(() => {
this.matSelect.options.changes
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
this.changeDetectorRef.markForCheck();
});
});
}
/**
* @return {?}
*/
_isToggleAllCheckboxVisible() {
return this.matSelect.multiple && this.showToggleAllCheckbox;
}
/**
* Handles the key down event with MatSelect.
* Allows e.g. selecting with enter key, navigation with arrow keys, etc.
* @param {?} event
* @return {?}
*/
_handleKeydown(event) {
// Prevent propagation for all alphanumeric characters in order to avoid selection issues
if ((event.key && event.key.length === 1) ||
(event.keyCode >= _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["A"] && event.keyCode <= _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["Z"]) ||
(event.keyCode >= _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["ZERO"] && event.keyCode <= _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["NINE"]) ||
(event.keyCode === _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["SPACE"])
|| (this.preventHomeEndKeyPropagation && (event.keyCode === _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["HOME"] || event.keyCode === _angular_cdk_keycodes__WEBPACK_IMPORTED_MODULE_1__["END"]))) {
event.stopPropagation();
}
}
/**
* @param {?} value
* @return {?}
*/
writeValue(value) {
/** @type {?} */
const valueChanged = value !== this._value;
if (valueChanged) {
this._value = value;
this.change.emit(value);
}
}
/**
* @param {?} value
* @return {?}
*/
onInputChange(value) {
/** @type {?} */
const valueChanged = value !== this._value;
if (valueChanged) {
this.initMultiSelectedValues();
this._value = value;
this.onChange(value);
this.change.emit(value);
}
}
/**
* @param {?} value
* @return {?}
*/
onBlur(value) {
this.writeValue(value);
this.onTouched();
}
/**
* @param {?} fn
* @return {?}
*/
registerOnChange(fn) {
this.onChange = fn;
}
/**
* @param {?} fn
* @return {?}
*/
registerOnTouched(fn) {
this.onTouched = fn;
}
/**
* Focuses the search input field
* @return {?}
*/
_focus() {
if (!this.searchSelectInput || !this.matSelect.panel) {
return;
}
// save and restore scrollTop of panel, since it will be reset by focus()
// note: this is hacky
/** @type {?} */
const panel = this.matSelect.panel.nativeElement;
/** @type {?} */
const scrollTop = panel.scrollTop;
// focus
this.searchSelectInput.nativeElement.focus();
panel.scrollTop = scrollTop;
}
/**
* Resets the current search value
* @param {?=} focus whether to focus after resetting
* @return {?}
*/
_reset(focus) {
if (!this.searchSelectInput) {
return;
}
this.searchSelectInput.nativeElement.value = '';
this.onInputChange('');
if (this.matOption && !focus) {
// remove no entries found class on mat option
this.matOption._getHostElement().classList.remove('mat-select-search-no-entries-found');
}
if (focus) {
this._focus();
}
}
/**
* Sets the overlay class to correct offsetY
* so that the selected option is at the position of the select box when opening
* @private
* @return {?}
*/
setOverlayClass() {
if (this.overlayClassSet) {
return;
}
/** @type {?} */
const overlayClasses = ['cdk-overlay-pane-select-search'];
if (!this.matOption) {
// add offset to panel if component is not placed inside mat-option
overlayClasses.push('cdk-overlay-pane-select-search-with-offset');
}
this.matSelect.overlayDir.attach
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe(() => {
// note: this is hacky, but currently there is no better way to do this
/** @type {?} */
let element = this.searchSelectInput.nativeElement;
/** @type {?} */
let overlayElement;
while (element = element.parentElement) {
if (element.classList.contains('cdk-overlay-pane')) {
overlayElement = element;
break;
}
}
if (overlayElement) {
overlayClasses.forEach(overlayClass => {
overlayElement.classList.add(overlayClass);
});
}
});
this.overlayClassSet = true;
}
/**
* Initializes handling <mat-select [multiple]="true">
* Note: to improve this code, mat-select should be extended to allow disabling resetting the selection while filtering.
* @private
* @return {?}
*/
initMultipleHandling() {
// if <mat-select [multiple]="true">
// store previously selected values and restore them when they are deselected
// because the option is not available while we are currently filtering
this.matSelect.valueChange
.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__["takeUntil"])(this._onDestroy))
.subscribe((values) => {
if (this.matSelect.multiple) {
/** @type {?} */
let restoreSelectedValues = false;
if (this._value && this._value.length
&& this.previousSelectedValues && Array.isArray(this.previousSelectedValues)) {
if (!values || !Array.isArray(values)) {
values = [];
}
/** @type {?} */
const optionValues = this.matSelect.options.map(option => option.value);
this.previousSelectedValues.forEach(previousValue => {
if (values.indexOf(previousValue) === -1 && optionValues.indexOf(previousValue) === -1) {
// if a value that was selected before is deselected and not found in the options, it was deselected
// due to the filtering, so we restore it.
values.push(previousValue);
restoreSelectedValues = true;
}
});
}
if (restoreSelectedValues) {
this.matSelect._onChange(values);
}
this.previousSelectedValues = values;
}
});
}
/**
* Scrolls the currently active option into the view if it is not yet visible.
* @private
* @return {?}
*/
adjustScrollTopToFitActiveOptionIntoView() {
if (this.matSelect.panel && this.matSelect.options.length > 0) {
/** @type {?} */
const matOptionHeight = this.getMatOptionHeight();
/** @type {?} */
const activeOptionIndex = this.matSelect._keyManager.activeItemIndex || 0;
/** @type {?} */
const labelCount = Object(_angular_material__WEBPACK_IMPORTED_MODULE_6__["_countGroupLabelsBeforeOption"])(activeOptionIndex, this.matSelect.options, this.matSelect.optionGroups);
// If the component is in a MatOption, the activeItemIndex will be offset by one.
/** @type {?} */
const indexOfOptionToFitIntoView = (this.matOption ? -1 : 0) + labelCount + activeOptionIndex;
/** @type {?} */
const currentScrollTop = this.matSelect.panel.nativeElement.scrollTop;
/** @type {?} */
const searchInputHeight = this.innerSelectSearch.nativeElement.offsetHeight;
/** @type {?} */
const amountOfVisibleOptions = Math.floor((_angular_material__WEBPACK_IMPORTED_MODULE_6__["SELECT_PANEL_MAX_HEIGHT"] - searchInputHeight) / matOptionHeight);
/** @type {?} */
const indexOfFirstVisibleOption = Math.round((currentScrollTop + searchInputHeight) / matOptionHeight) - 1;
if (indexOfFirstVisibleOption >= indexOfOptionToFitIntoView) {
this.matSelect.panel.nativeElement.scrollTop = indexOfOptionToFitIntoView * matOptionHeight;
}
else if (indexOfFirstVisibleOption + amountOfVisibleOptions <= indexOfOptionToFitIntoView) {
this.matSelect.panel.nativeElement.scrollTop = (indexOfOptionToFitIntoView + 1) * matOptionHeight - (_angular_material__WEBPACK_IMPORTED_MODULE_6__["SELECT_PANEL_MAX_HEIGHT"] - searchInputHeight);
}
}
}
/**
* Set the width of the innerSelectSearch to fit even custom scrollbars
* And support all Operation Systems
* @return {?}
*/
updateInputWidth() {
if (!this.innerSelectSearch || !this.innerSelectSearch.nativeElement) {
return;
}
/** @type {?} */
let element = this.innerSelectSearch.nativeElement;
/** @type {?} */
let panelElement;
while (element = element.parentElement) {
if (element.classList.contains('mat-select-panel')) {
panelElement = element;
break;
}
}
if (panelElement) {
this.innerSelectSearch.nativeElement.style.width = panelElement.clientWidth + 'px';
}
}
/**
* @private
* @return {?}
*/
getMatOptionHeight() {
if (this.matSelect.options.length > 0) {
return this.matSelect.options.first._getHostElement().getBoundingClientRect().height;
}
return 0;
}
/**
* Initialize this.previousSelectedValues once the first filtering occurs.
* @return {?}
*/
initMultiSelectedValues() {
if (this.matSelect.multiple && !this._value) {
this.previousSelectedValues = this.matSelect.options
.filter(option => option.selected)
.map(option => option.value);
}
}
/**
* Returns whether the "no entries found" message should be displayed
* @return {?}
*/
_noEntriesFound() {
if (!this._options) {
return;
}
if (this.matOption) {
return this.noEntriesFoundLabel && this.value && this._options.length === 1;
}
else {
return this.noEntriesFoundLabel && this.value && this._options.length === 0;
}
}
} |
JavaScript | class Obstacle extends Component {
// constructor( props )
// {
// super();
// this.state = {
// positions: props.positions ? props.positions : [0,0,0],
// distance: props.distance ? props.distance : [0,0,0],
// };
// }
// updateState( key, value )
// {
// this.setState({
// [key]: value
// });
// }
// componentDidMount(){}
// // processScale( distance_top )
// // {
// // distance_bottom = distance_bottom < 0
// // ? distance_bottom * -1
// // : distance_bottom;
// // return distance_bottom * 0.006;
// // }
// // processPositionOnStreet( distance_bottom, position_on_street )
// // {
// // distance_bottom = distance_bottom < 0
// // ? distance_bottom * -1
// // : distance_bottom;
// // let root_distance = ( 350 - distance_bottom ); // from the centre of orbit
// // // console.log( position_on_street )
// // switch( position_on_street ){
// // case -1:
// // var degrees = 140;
// // var radians = degrees * (Math.PI / 180);
// // var x = Math.cos(radians) * root_distance;
// // return 250 - x
// // break;
// // case 0:
// // return 600
// // break;
// // case 1:
// // var degrees = 40;
// // var radians = degrees * (Math.PI / 180);
// // var x = Math.cos(radians) * root_distance;
// // return 950 - x
// // break;
// // }
// // }
// processObstacle( track )
// {
// }
// render()
// {
// let { positions } = this.state;
// let left = positions[0] == 1 ? this.processObstacle() : null;
// let mid = positions[1] == 1 ? this.processObstacle() : null;
// let right = positions[2] == 1 ? this.processObstacle() : null;
// return null;
// // return (
// // <ContainerObstacles>
// // <div>
// // <div className="left">
// // </div>
// // <div className="mid">
// // </div>
// // <div className="right">
// // </div>
// // </div>
// // </ContainerObstacles>
// // <StyleObstacle>
// // </StyleObstacle>
// // );
// }
render()
{
return null;
}
} |
JavaScript | class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
} |
JavaScript | class ThemeButton extends Component {
render() {
const className =
this.context === 'light' ? 'ThemeButton ThemeButton--light' : 'ThemeButton ThemeButton--dark';
return <button className={className}>{this.props.children}</button>;
}
} |
JavaScript | class API extends Resource {
constructor(name, version, context, kwargs) {
super();
let properties = kwargs;
if (name instanceof Object) {
properties = name;
} else {
this.name = name;
this.version = version;
this.context = context;
this.isDefaultVersion = false;
this.gatewayEnvironments = ["Production and Sandbox"]; //todo: load the environments from settings API
this.transport = [
"http",
"https"
];
this.visibility = "PUBLIC";
this.context = context;
this.endpoint = [{
inline: {
endpointConfig: {
list: [
]
}
},
type: 'production_endpoints'
}]
}
this._data = properties;
for (const key in properties) {
if (Object.prototype.hasOwnProperty.call(properties, key)) {
this[key] = properties[key];
}
}
}
/**
*
* @param data
* @returns {object} Metadata for API request
* @private
*/
_requestMetaData() {
Resource._requestMetaData();
}
/**
* Create an API with the given parameters in template and call the callback method given optional.
* @param {Object} api_data - API data which need to fill the placeholder values in the @get_template
* @param {function} callback - An optional callback method
* @returns {Promise} Promise after creating and optionally calling the callback method.
*/
create(api_data, callback = null) {
let payload;
let promise_create;
if (api_data.constructor.name === 'Blob' || api_data.constructor.name === 'File') {
payload = {
file: api_data,
'Content-Type': 'multipart/form-data'
};
promise_create = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis_import_definition(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
} else if (api_data.type === 'swagger-url') {
payload = {
url: api_data.url,
'Content-Type': 'multipart/form-data'
};
promise_create = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis_import_definition(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
} else {
payload = {
body: api_data,
'Content-Type': 'application/json'
};
promise_create = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis(payload, this._requestMetaData());
});
}
if (callback) {
return promise_create.then(callback);
} else {
return promise_create;
}
}
/**
* Get detailed policy information of the API
* @returns {Promise} Promise containing policy detail request calls for all the available policies
* @memberof API
*/
getPolicies() {
const promisedPolicies = this.policies.map(policy => {
return this.client.then(
client => client.apis["Throttling Policies"].getThrottlingPolicyByName({
policyLevel: 'subscription',
policyName: policy
},
this._requestMetaData(),
)
)
})
return Promise.all(promisedPolicies).then(policies => policies.map(response => response.body));
}
setInlineProductionEndpoint(serviceURL) {
this.endpoint = this.endpoint.map(endpoint => {
if (endpoint.type.toLowerCase() === 'production') {
endpoint.inline.endpointConfig.list = [{
url: serviceURL
}]
}
return endpoint;
})
}
getProductionEndpoint() {
const productionEndpoint = this.endpoint.filter(endpoint => endpoint.type.toLowerCase() === 'production_endpoints')[0];
if (!productionEndpoint) {
return null;
} else if (productionEndpoint.inline) {
return productionEndpoint.inline;
} else {
throw new Exception('Not Implemented for global Endpoints');
}
}
getSandboxEndpoint() {
const sandboxEndpoint = this.endpoint.filter(endpoint => endpoint.type.toLowerCase() === 'sandbox_endpoints')[0];
if (!sandboxEndpoint) {
return null;
} else if (sandboxEndpoint.inline) {
return sandboxEndpoint.inline;
} else {
throw new Exception('Not Implemented for global Endpoints');
}
}
save() {
const promisedAPIResponse = this.client.then((client) => {
const properties = client.spec.definitions.API.properties;
const data = {};
Object.keys(this).forEach(apiAttribute => {
if (apiAttribute in properties) {
data[apiAttribute] = this[apiAttribute];
}
});
const payload = {
body: data,
'Content-Type': 'application/json'
};
return client.apis['API (Individual)'].post_apis(payload, this._requestMetaData());
});
return promisedAPIResponse.then(response => {
return new API(response.body);
});
}
/**
* Create an API from WSDL with the given parameters and call the callback method given optional.
* @param {Object} api_data - API data which need to fill the placeholder values in the @get_template
* @param {function} callback - An optional callback method
* @returns {Promise} Promise after creating and optionally calling the callback method.
*/
importWSDL(api_data, callback = null) {
let payload;
let promise_create;
payload = {
type: 'WSDL',
additionalProperties: api_data.additionalProperties,
implementationType: api_data.implementationType,
'Content-Type': 'multipart/form-data',
};
if (api_data.url) {
payload.url = api_data.url;
} else {
payload.file = api_data.file;
}
promise_create = this.client.then((client) => {
return client.apis['API (Collection)'].post_apis_import_definition(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
if (callback) {
return promise_create.then(callback);
} else {
return promise_create;
}
}
/**
* Get details of a given API
* @param id {string} UUID of the api.
* @param callback {function} A callback function to invoke after receiving successful response.
* @returns {promise} With given callback attached to the success chain else API invoke promise.
* @deprecated use static API.get() method instead
*/
get(id, callback = null) {
const promise_get = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId_({
apiId: id
}, this._requestMetaData());
});
if (callback) {
return promise_get.then(callback);
} else {
return promise_get;
}
}
/**
* Create a new version of a given API
* @param version {string} new API version.
* @param isDefaultVersion specifies whether new API version is set as default version
* @param callback {function} A callback function to invoke after receiving successful response.
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
createNewAPIVersion(version, isDefaultVersion, callback = null) {
const promise_copy_api = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis_copy_api({
apiId: this.id,
newVersion: version,
defaultVersion: isDefaultVersion,
},
this._requestMetaData(),
);
});
if (callback) {
return promise_copy_api.then(callback);
} else {
return promise_copy_api;
}
}
/**
* Get the swagger of an API
* @param id {String} UUID of the API in which the swagger is needed
* @param callback {function} Function which needs to be called upon success of the API deletion
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
getSwagger(id, callback = null) {
const promise_get = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId__swagger({
apiId: id
}, this._requestMetaData());
});
if (callback) {
return promise_get.then(callback);
} else {
return promise_get;
}
}
/**
* Get the scopes of an API
* @param id {String} UUID of the API in which the swagger is needed
* @param callback {function} Function which needs to be called upon success of the API deletion
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
getScopes(id, callback = null) {
const promise_get = this.client.then((client) => {
return client.apis['Scope (Collection)'].get_apis__apiId__scopes({
apiId: id
}, this._requestMetaData());
});
if (callback) {
return promise_get.then(callback);
} else {
return promise_get;
}
}
/**
* Get the detail of scope of an API
* @param {String} api_id - UUID of the API in which the scopes is needed
* @param {String} scopeName - Name of the scope
* @param {function} callback - Function which needs to be called upon success of the API deletion
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
getScopeDetail(api_id, scopeName, callback = null) {
const promise_get_Scope_detail = this.client.then((client) => {
return client.apis['Scope (Individual)'].get_apis__apiId__scopes__name_({
apiId: api_id,
name: scopeName,
},
this._requestMetaData(),
);
});
if (callback) {
return promise_get_Scope_detail.then(callback);
} else {
return promise_get_Scope_detail;
}
}
/**
* Update a scope of an API
* @param {String} api_id - UUID of the API in which the scopes is needed
* @param {String} scopeName - Name of the scope
* @param {Object} body - Scope details
*/
updateScope(api_id, scopeName, body) {
const promised_updateScope = this.client.then((client) => {
const payload = {
apiId: api_id,
body,
name: scopeName,
'Content-Type': 'application/json',
};
return client.apis['Scope (Individual)'].put_apis__apiId__scopes__name_(payload, this._requestMetaData());
});
return promised_updateScope;
}
addScope(api_id, body) {
const promised_addScope = this.client.then((client) => {
const payload = {
apiId: api_id,
body,
'Content-Type': 'application/json',
};
return client.apis['Scope (Collection)'].post_apis__apiId__scopes(payload, this._requestMetaData());
});
return promised_addScope;
}
deleteScope(api_id, scope_name) {
const promise_deleteScope = this.client.then((client) => {
return client.apis['Scope (Individual)'].delete_apis__apiId__scopes__name_({
apiId: api_id,
name: scope_name,
},
this._requestMetaData(),
);
});
return promise_deleteScope;
}
/**
* Update an api via PUT HTTP method, Need to give the updated API object as the argument.
* @param api {Object} Updated API object(JSON) which needs to be updated
* @deprecated
*/
updateSwagger(id, swagger) {
const promised_update = this.client.then((client) => {
const payload = {
apiId: id,
endpointId: JSON.stringify(swagger),
'Content-Type': 'multipart/form-data',
};
return client.apis['API (Individual)'].put_apis__apiId__swagger(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_update;
}
/**
* Update an api via PUT HTTP method, Need to give the updated API object as the argument.
* @param api {Object} Updated API object(JSON) which needs to be updated
*
*/
updateSwagger(swagger) {
const promised_update = this.client.then((client) => {
const payload = {
apiId: this.id,
apiDefinition: JSON.stringify(swagger),
'Content-Type': 'multipart/form-data',
};
return client.apis['API (Individual)'].put_apis__apiId__swagger(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_update.then(response => {
return this;
});
}
/**
* Delete the current api instance
* @param id {String} UUID of the API which want to delete
* @param callback {function} Function which needs to be called upon success of the API deletion
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
delete() {
return this.client.then((client) => {
return client.apis['API (Individual)'].delete_apis__apiId_({
apiId: this.id
}, this._requestMetaData());
});
}
/**
* Get the life cycle state of an API given its id (UUID)
* @param id {string} UUID of the api
* @param callback {function} Callback function which needs to be executed in the success call
*/
getLcState(id, callback = null) {
const promise_lc_get = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId__lifecycle_state({
apiId: id
}, this._requestMetaData());
});
if (callback) {
return promise_lc_get.then(callback);
} else {
return promise_lc_get;
}
}
/**
* Get the life cycle history data of an API given its id (UUID)
* @param id {string} UUID of the api
* @param callback {function} Callback function which needs to be executed in the success call
*/
getLcHistory(id, callback = null) {
const promise_lc_history_get = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId__lifecycle_history({
apiId: id
},
this._requestMetaData(),
);
});
if (callback) {
return promise_lc_history_get.then(callback);
} else {
return promise_lc_history_get;
}
}
/**
*
* Shortcut method to publish `this` API instance
*
* @param {Object} checkedItems State change checklist items
* @returns {Promise}
* @memberof API
*/
publish(checkedItems) {
const payload = {
action: 'Publish',
apiId: this.id,
lifecycleChecklist: checkedItems,
'Content-Type': 'application/json',
};
return this.client.then((client) => {
return client.apis['API (Individual)'].post_apis_change_lifecycle(payload, this._requestMetaData());
});
}
/**
* Update the life cycle state of an API given its id (UUID)
* @param id {string} UUID of the api
* @param state {string} Target state which need to be transferred
* @param callback {function} Callback function which needs to be executed in the success call
*/
updateLcState(id, state, checkedItems, callback = null) {
const payload = {
action: state,
apiId: id,
lifecycleChecklist: checkedItems,
'Content-Type': 'application/json',
};
const promise_lc_update = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis_change_lifecycle(payload, this._requestMetaData());
});
if (callback) {
return promise_lc_update.then(callback);
} else {
return promise_lc_update;
}
}
/**
* Cleanup pending workflow state change task for API given its id (UUID)
* @param id {string} UUID of the api
* @param callback {function} Callback function which needs to be executed in the success call
*/
cleanupPendingTask(id, callback = null) {
const promise_deletePendingTask = this.client.then((client) => {
return client.apis['API (Individual)'].delete_apis_apiId_lifecycle_lifecycle_pending_task({
apiId: id
},
this._requestMetaData(),
);
});
return promise_deletePendingTask;
}
/**
* Update an api via PUT HTTP method, Need to give the updated API object as the argument.
* @param api {Object} Updated API object(JSON) which needs to be updated
*/
update(api) {
const promised_update = this.client.then((client) => {
const payload = {
apiId: api.id,
body: api
};
return client.apis['API (Individual)'].put_apis__apiId_(payload);
});
return promised_update;
}
/**
* Get the available subscriptions for a given API
* @param {String} apiId API UUID
* @returns {Promise} With given callback attached to the success chain else API invoke promise.
*/
subscriptions(id, callback = null) {
const promise_subscription = this.client.then((client) => {
return client.apis['Subscription (Collection)'].get_subscriptions({
apiId: id
}, this._requestMetaData());
});
if (callback) {
return promise_subscription.then(callback);
} else {
return promise_subscription;
}
}
/**
* Block subscriptions for given subscriptionId
* @param {String} id Subscription UUID
* @param {String} state Subscription status
* @returns {Promise} With given callback attached to the success chain else API invoke promise.
*/
blockSubscriptions(id, state, callback = null) {
const promise_subscription = this.client.then((client) => {
return client.apis['Subscription (Individual)'].post_subscriptions_block_subscription({
subscriptionId: id,
blockState: state
},
this._requestMetaData(),
);
});
if (callback) {
return promise_subscription.then(callback);
} else {
return promise_subscription;
}
}
/**
* Unblock subscriptions for given subscriptionId
* @param {String} id Subscription UUID
* @returns {Promise} With given callback attached to the success chain else API invoke promise.
*/
unblockSubscriptions(id, callback = null) {
const promise_subscription = this.client.then((client) => {
return client.apis['Subscription (Individual)'].post_subscriptions_unblock_subscription({
subscriptionId: id
},
this._requestMetaData(),
);
});
if (callback) {
return promise_subscription.then(callback);
} else {
return promise_subscription;
}
}
/**
* Add endpoint via POST HTTP method, need to provided endpoint properties and callback function as argument
* @param body {Object} Endpoint to be added
*/
addEndpoint(body) {
const promised_addEndpoint = this.client.then((client) => {
const payload = {
body,
'Content-Type': 'application/json'
};
return client.apis['Endpoint (Collection)'].post_endpoints(payload, this._requestMetaData());
});
return promised_addEndpoint;
}
/**
* Delete an Endpoint given its identifier
* @param id {String} UUID of the Endpoint which want to delete
* @returns {promise}
*/
deleteEndpoint(id) {
const promised_delete = this.client.then((client) => {
return client.apis['Endpoint (individual)'].delete_endpoints__endpointId_({
endpointId: id,
'Content-Type': 'application/json',
},
this._requestMetaData(),
);
});
return promised_delete;
}
/**
* Get All Global Endpoints.
* @deprecated Use Endpoint.all() method instead
* @returns {Promise} Promised all list of endpoint
*/
getEndpoints() {
return this.client.then((client) => {
return client.apis['Endpoint (Collection)'].get_endpoints({}, this._requestMetaData());
});
}
/**
* Get endpoint object by its UUID.
* @deprecated Use Endpoint.get(uuid) static method instead
* @param id {String} UUID of the endpoint
* @returns {Promise.<TResult>}
*/
getEndpoint(id) {
return this.client.then((client) => {
return client.apis['Endpoint (individual)'].get_endpoints__endpointId_({
endpointId: id,
'Content-Type': 'application/json',
},
this._requestMetaData(),
);
});
}
/**
* Update endpoint object.
* @param data {Object} Endpoint to be updated
* @returns {Promise.<TResult>}
*/
updateEndpoint(data) {
return this.client.then((client) => {
return client.apis['Endpoint (individual)'].put_endpoints__endpointId_({
endpointId: data.id,
body: data,
'Content-Type': 'application/json',
},
this._requestMetaData(),
);
});
}
/**
* Check if an endpoint name already exists.
* @param {String} endpointName - Name of the Endpoint
* @return {Promise}
*/
checkIfEndpointExists(endpointName) {
return this.client.then((client) => {
return client.apis['Endpoint (Collection)'].head_endpoints({
name: endpointName,
},
this._requestMetaData(),
);
});
}
/**
* Discovered Service Endpoints.
* @returns {Promise} Promised list of discovered services
*/
discoverServices() {
return this.client.then((client) => {
return client.apis['External Resources (Collection)'].get_external_resources_services({},
this._requestMetaData(),
);
});
}
addDocument(api_id, body) {
const promised_addDocument = this.client.then((client) => {
const payload = {
apiId: api_id,
body,
'Content-Type': 'application/json'
};
return client.apis['Document (Collection)'].post_apis__apiId__documents(payload, this._requestMetaData());
});
return promised_addDocument;
}
/*
Add a File resource to a document
*/
addFileToDocument(api_id, docId, fileToDocument) {
const promised_addFileToDocument = this.client.then((client) => {
const payload = {
apiId: api_id,
documentId: docId,
file: fileToDocument,
'Content-Type': 'application/json',
};
return client.apis['Document (Individual)'].post_apis__apiId__documents__documentId__content(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_addFileToDocument;
}
/*
Add inline content to a INLINE type document
*/
addInlineContentToDocument(apiId, documentId, sourceType, inlineContent) {
const promised_addInlineContentToDocument = this.client.then((client) => {
const payload = {
apiId,
documentId,
sourceType,
inlineContent,
'Content-Type': 'application/json',
};
return client.apis['Document (Individual)'].post_apis__apiId__documents__documentId__content(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_addInlineContentToDocument;
}
getFileForDocument(api_id, docId) {
const promised_getDocContent = this.client.then((client) => {
const payload = {
apiId: api_id,
documentId: docId,
Accept: 'application/octet-stream'
};
return client.apis['Document (Individual)'].get_apis__apiId__documents__documentId__content(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_getDocContent;
}
/*
Get the inline content of a given document
*/
getInlineContentOfDocument(api_id, docId) {
const promised_getDocContent = this.client.then((client) => {
const payload = {
apiId: api_id,
documentId: docId
};
return client.apis['Document (Individual)'].get_apis__apiId__documents__documentId__content(payload);
});
return promised_getDocContent;
}
getDocuments(api_id, callback) {
const promise_get_all = this.client.then((client) => {
return client.apis['Document (Collection)'].get_apis__apiId__documents({
apiId: api_id
},
this._requestMetaData(),
);
});
if (callback) {
return promise_get_all.then(callback);
} else {
return promise_get_all;
}
}
updateDocument(api_id, docId, body) {
const promised_updateDocument = this.client.then((client) => {
const payload = {
apiId: api_id,
body,
documentId: docId,
'Content-Type': 'application/json',
};
return client.apis['Document (Individual)'].put_apis__apiId__documents__documentId_(
payload,
this._requestMetaData(),
);
});
return promised_updateDocument;
}
getDocument(api_id, docId, callback) {
const promise_get = this.client.then((client) => {
return client.apis['Document (Individual)'].get_apis__apiId__documents__documentId_({
apiId: api_id,
documentId: docId,
},
this._requestMetaData(),
);
});
return promise_get;
}
deleteDocument(api_id, document_id) {
const promise_deleteDocument = this.client.then((client) => {
return client.apis['Document (Individual)'].delete_apis__apiId__documents__documentId_({
apiId: api_id,
documentId: document_id,
},
this._requestMetaData(),
);
});
return promise_deleteDocument;
}
/**
* Get the available labels.
* @returns {Promise.<TResult>}
*/
labels() {
const promise_labels = this.client.then((client) => {
return client.apis['Label (Collection)'].get_labels({}, this._requestMetaData());
});
return promise_labels;
}
validateWSDLUrl(wsdlUrl) {
const promised_validationResponse = this.client.then((client) => {
return client.apis['API (Collection)'].post_apis_validate_definition({
type: 'WSDL',
url: wsdlUrl,
'Content-Type': 'multipart/form-data',
},
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_validationResponse;
}
validateWSDLFile(file) {
const promised_validationResponse = this.client.then((client) => {
return client.apis['API (Collection)'].post_apis_validate_definition({
type: 'WSDL',
file,
'Content-Type': 'multipart/form-data',
},
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_validationResponse;
}
getWSDL(apiId) {
const promised_wsdlResponse = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId__wsdl({
apiId,
},
this._requestMetaData({
Accept: 'application/octet-stream'
}),
);
});
return promised_wsdlResponse;
}
/**
* Get all threat protection policies
*/
getThreatProtectionPolicies() {
const promisedPolicies = this.client.then((client) => {
return client.apis['Threat Protection Policies'].get_threat_protection_policies();
});
return promisedPolicies;
}
/**
* Retrieve a single threat protection policy
* @param id Threat protection policy id
*/
getThreatProtectionPolicy(id) {
const promisedPolicies = this.client.then((client) => {
return client.apis['Threat Protection Policy'].get_threat_protection_policies__policyId_({
policyId: id
});
});
return promisedPolicies;
}
/**
* Add threat protection policy to an API
* @param apiId APIID
* @param policyId Threat protection policy id
*/
addThreatProtectionPolicyToApi(apiId, policyId) {
const promisedPolicies = this.client.then((client) => {
return client.apis['API (Individual)'].post_apis__apiId__threat_protection_policies({
apiId,
policyId,
});
});
return promisedPolicies;
}
/**
* Delete threat protection policy from an API
* @param apiId APIID
* @param policyId Threat protection policy id
*/
deleteThreatProtectionPolicyFromApi(apiId, policyId) {
console.log(apiId);
const promisedDelete = this.client.then((client) => {
console.log(client.apis);
return client.apis['API (Individual)'].delete_apis__apiId__threat_protection_policies({
apiId,
policyId,
});
});
return promisedDelete;
}
/**
* Update HasOwnGateway property of an API
* @param apiId APIId
* @param body body which contains update details
*/
updateHasOwnGateway(api_id, body) {
const promised_updateDedicatedGateway = this.client.then((client) => {
const payload = {
apiId: api_id,
body,
'Content-Type': 'application/json',
};
return client.apis['DedicatedGateway (Individual)'].put_apis__apiId__dedicated_gateway(
payload,
this._requestMetaData(),
);
});
return promised_updateDedicatedGateway;
}
/**
* Get the HasOwnGateway property of an API
* @param id {string} UUID of the api
* @param callback {function} Callback function which needs to be executed in the success call
*/
getHasOwnGateway(id) {
const promised_getDedicatedGateway = this.client.then((client) => {
return client.apis['DedicatedGateway (Individual)'].get_apis__apiId__dedicated_gateway({
apiId: id
},
this._requestMetaData(),
);
});
return promised_getDedicatedGateway;
}
/**
* Get the thumnail of an API
*
* @param id {string} UUID of the api
*/
getAPIThumbnail(id) {
const promised_getAPIThumbnail = this.client.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId__thumbnail({
apiId: id
},
this._requestMetaData(),
);
});
return promised_getAPIThumbnail;
}
/**
* Add new thumbnail image to an API
*
* @param {String} api_id id of the API
* @param {File} imageFile thumbnail image to be uploaded
*/
addAPIThumbnail(api_id, imageFile) {
const promised_addAPIThumbnail = this.client.then((client) => {
const payload = {
apiId: api_id,
file: imageFile,
'Content-Type': imageFile.type,
};
return client.apis['API (Individual)'].updateAPIThumbnail(
payload,
this._requestMetaData({
'Content-Type': 'multipart/form-data'
}),
);
});
return promised_addAPIThumbnail;
}
/**
* Add new comment to an existing API
* @param apiId apiId of the api to which the comment is added
* @param commentInfo comment text
*/
addComment(apiId, commentInfo, callback = null) {
let promise = this.client.then(
(client) => {
return client.apis["Comment (Individual)"].post_apis__apiId__comments(
{apiId: apiId, body: commentInfo}, this._requestMetaData());
}
).catch(
error => {
console.error(error);
}
);
if (callback) {
return promise.then(callback);
} else {
return promise;
}
}
/**
* Get all comments for a particular API
* @param apiId api id of the api to which the comment is added
*/
getAllComments(apiId, callback = null) {
let promise_get = this.client.then(
(client) => {
return client.apis["Comment (Collection)"].get_apis__apiId__comments(
{apiId: apiId}, this._requestMetaData());
}
).catch(
error => {
console.error(error);
}
);
if (callback) {
return promise_get.then(callback);
} else {
return promise_get;
}
}
/**
* Delete a comment belongs to a particular API
* @param apiId api id of the api to which the comment belongs to
* @param commentId comment id of the comment which has to be deleted
*/
deleteComment(apiId, commentId, callback = null) {
let promise = this.client.then(
(client) => {
return client.apis["Comment (Individual)"].delete_apis__apiId__comments__commentId_(
{apiId: apiId, commentId: commentId}, this._requestMetaData());
}
).catch(
error => {
console.error(error);
}
);
if (callback) {
return promise.then(callback);
} else {
return promise;
}
}
/**
* Update a comment belongs to a particular API
* @param apiId apiId of the api to which the comment is added
* @param commentId comment id of the comment which has to be updated
* @param commentInfo comment text
*/
updateComment(apiId, commentId, commentInfo, callback = null) {
let promise = this.client.then(
(client) => {
return client.apis["Comment (Individual)"].put_apis__apiId__comments__commentId_(
{apiId: apiId, commentId: commentId, body: commentInfo}, this._requestMetaData());
}
).catch(
error => {
console.error(error);
}
);
if (callback) {
return promise.then(callback);
} else {
return promise;
}
}
/**
*
* Static method for get all APIs for current environment user.
* @static
* @param {Object} params APIs filtering parameters i:e { "name": "MyBank API"}
* @returns {Promise} promise object return from SwaggerClient-js
* @memberof API
*/
static all(params) {
let query = "";
if (params && 'query' in params) {
for (const [key, value] of Object.entries(params.query)) {
query += `${key}:${value},`;
}
params.query = query;
}
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
return apiClient.then((client) => {
return client.apis['API (Collection)'].get_apis(params, Resource._requestMetaData());
});
}
/**
* Get details of a given API
* @param id {string} UUID of the api.
* @param callback {function} A callback function to invoke after receiving successful response.
* @returns {promise} With given callback attached to the success chain else API invoke promise.
*/
static get(id) {
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
const promisedAPI = apiClient.then((client) => {
return client.apis['API (Individual)'].get_apis__apiId_({
apiId: id
}, this._requestMetaData());
});
return promisedAPI.then(response => {
return new API(response.body);
});
}
/**
*
* Delete an API given its UUID
* @static
* @param {String} id API UUID
* @returns {Promise} Swagger-Js promise object resolve to NT response object
* @memberof API
*/
static delete(id) {
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
return apiClient.then((client) => {
return client.apis['API (Individual)'].delete_apis__apiId_({
apiId: id
}, this._requestMetaData());
});
}
/**
* Get the available policies information by tier level.
* @param {String} policyLevel List API or Application or Resource type policies.parameter should be one
* of api, application, subscription and resource
* @returns {Promise}
*
*/
static policies(policyLevel) {
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
return apiClient.then((client) => {
return client.apis["Throttling Policies"].getAllThrottlingPolicies({
policyLevel: 'subscription'
},
this._requestMetaData(),
);
});
}
} |
JavaScript | class Users {
/**
* @description controller function that handles the creation of a User
*
* @param {object} req - Express request object
* @param {object} res - Express response object
* @return {undefined}
*/
static async registerUser(req, res) {
const { fullname, email, password } = req.body;
const hash = await HelperUtils.hashPassword(password);
const formInputs = { fullname, email, hashedPassword: hash };
try {
const createUser = await User.create(formInputs);
delete formInputs.hashedPassword;
const token = HelperUtils.generateToken({
...formInputs,
id: createUser.id
});
res.status(201).json({
status: 'success',
message: 'user created successfully',
user: {
email,
token,
fullname,
bio: createUser.bio,
image: createUser.image
}
});
} catch (error) {
return res.status(500).json({ status: 'failed', message: 'Registration Unsuccessful' });
}
}
/**
* @description contoller function that logs a user in
* @param {object} req - request object
* @param {object} res - response object
* @returns {object} user - Logged in user
*/
static async loginUser(req, res) {
const { email, password } = req.body;
try {
const getUser = await User.findOne({
where: { email }
});
if (getUser) {
const { id, fullname, bio, image, hashedPassword } = getUser;
const isValidPassword = HelperUtils.comparePasswordOrEmail(password, hashedPassword);
if (!isValidPassword) {
return res.status(400).json({ status: 'failed', message: 'Invalid email or password' });
}
const userToken = await HelperUtils.generateToken({ id, email, fullname });
return res.status(200).json({
status: 'success',
message: 'user logged in successfully',
user: {
email,
image,
fullname,
bio,
token: userToken
}
});
}
return res.status(400).json({ status: 'failed', message: "User doesn't exist on the database" });
} catch (error) {
return res.status(500).json({ status: 'failed', message: 'Login Unsuccessful' });
}
}
} |
JavaScript | class WebWorker {
constructor(postMessage) {
this.$postMessage = postMessage;
this.saveState = null;
this.isSaveStateRequested = false;
this.isLoadStateRequested = false;
this.isDebugging = false;
this.isDebugStepFrameRequested = false;
this.isDebugStepScanlineRequested = false;
this.sampleRate = 0;
this.availableSamples = 0;
this.samples = [];
this.nes = new NES(this.onFrame, this.onAudio);
this.frameTimer = new FrameTimer(
() => {
if (
this.isDebugging &&
!this.isDebugStepFrameRequested &&
!this.isDebugScanlineRequested
)
return;
const isDebugScanlineRequested = this.isDebugScanlineRequested;
this.isDebugStepFrameRequested = false;
this.isDebugScanlineRequested = false;
if (this.isSaveStateRequested) {
this.saveState = this.nes.getSaveState();
this.isSaveStateRequested = false;
}
if (this.isLoadStateRequested && this.saveState != null) {
this.nes.setSaveState(this.saveState);
this.isLoadStateRequested = false;
}
try {
if (isDebugScanlineRequested) {
this.nes.scanline();
} else if (config.SYNC_TO_AUDIO) {
const requestedSamples = this.sampleRate / config.FPS;
const newBufferSize = this.availableSamples + requestedSamples;
if (newBufferSize <= config.AUDIO_BUFFER_LIMIT)
this.nes.samples(requestedSamples);
} else {
this.nes.frame();
}
this.$postMessage(this.samples);
this.samples = [];
} catch (error) {
this.$postMessage({ id: "error", error });
}
},
(fps) => {
this.$postMessage({ id: "fps", fps });
}
);
}
onFrame = (frameBuffer) => {
this.frameTimer.countNewFrame();
this.$postMessage(frameBuffer);
};
onAudio = (sample) => {
this.samples.push(sample);
};
terminate = () => {
this.frameTimer.stop();
};
postMessage = (data) => {
this.$onMessage({ data });
};
$onMessage = ({ data }) => {
try {
if (data instanceof Uint8Array) {
// rom bytes
this.nes.sampleRate = this.sampleRate;
this.nes.load(data);
this.frameTimer.start();
} else if (Array.isArray(data)) {
// state packet
// -> controller input
for (let i = 0; i < 2; i++) {
if (i === 0) {
if (data[i].$saveState) this.isSaveStateRequested = true;
if (data[i].$loadState) this.isLoadStateRequested = true;
if (data[i].$startDebugging) this.isDebugging = true;
if (data[i].$stopDebugging) this.isDebugging = false;
if (data[i].$debugStepFrame) this.isDebugStepFrameRequested = true;
if (data[i].$debugStepScanline)
this.isDebugScanlineRequested = true;
}
for (let button in data[i])
if (button[0] !== "$")
this.nes.setButton(i + 1, button, data[i][button]);
}
// -> available samples
this.availableSamples = data[2];
} else if (data?.id === "sampleRate") {
this.sampleRate = data.sampleRate;
}
} catch (error) {
this.$postMessage({ id: "error", error });
}
};
} |
JavaScript | class ResearcherProfiles extends Mixin(LitElement)
.with(LitCorkUtils) {
static get properties() {
return {
appRoutes : {type: Array},
page : {type: String},
theme: {type: Object},
navLinks: {type: Array},
user: {type: Object},
textQuery: {type: String},
isSearch: {type: Boolean},
hideMainNav: {type: Boolean},
accountLinks: {type:Array},
quickSearchOpened: {type: Number},
mobileMenuPage: {type: String},
showVersion: {type: Boolean},
hasProfile: {type: Boolean},
};
}
constructor() {
super();
this.render = render.bind(this);
this.appRoutes = config.appRoutes;
this.theme = config.theme;
this.page = 'loading';
this.loadedPages = {};
this.user = config.user;
this.eSearch = config.client;
this.hideMainNav = false;
this.textQuery = "";
this.quickSearchOpened = false;
this.userId = userUtils.getUserId(this.user);
this.userName = userUtils.getUserDisplayName(this.user);
this.userFirstName = userUtils.getUserFirstName(this.user);
this.mobileMenuPage = "";
this.isSearch = false;
this.hasProfile = (this.user && this.user.expertsId);
this.accountLinks = [{text: "Logout", href: "/auth/logout"}];
this.firstAppStateUpdate = true;
//This will change to this.navLinks once the 1.3 release is done
this.navLinks = [
{text: 'People', page: 'people', href: '/people', type: 'person'},
{text: 'Subjects', page: 'concepts', href: '/concepts', type: 'concept'},
{text: 'Works', page: 'works', href: '/works', type: 'work'},
{text: 'Grants', page: 'grants', href: '/grants', type: 'grant'},
{text: 'Help', page: 'help', href: '/help'}];
if( config.hiddenTypes && config.hiddenTypes.length ) {
this.navLinks = this.navLinks.filter(link => {
return !config.hiddenTypes.includes(link.type);
});
}
if( config.user && config.user.impersonatedBy ) {
this.accountLinks.unshift({text: "Stop Impersonating", action: 'stop-impersonating'});
}
if( this.hasProfile ){
this.accountLinks.unshift({text: "My Profile", href: '/'+this.user.expertsId});
}
if( !config.env ) {
config.env = {APP_VERSION:''};
}
this.showVersion = config.env.APP_VERSION.match(/(alpha|beta|rc)/) ? true : false;
this.logVersion();
this._injectModel('AppStateModel', 'CollectionModel', 'PersonModel');
this._onResize = this._onResize.bind(this);
this._init404();
}
/**
* @method _init404
* @description check if is404 flag set in APP_CONFIG, additional register 404
* event handler. Either condition will show the 404 page
*/
async _init404() {
if( config.is404 ) {
// await this.loadPage('404');
this.AppStateModel.show404Page();
}
window.addEventListener('404', async () => {
// await this.loadPage('404');
this.AppStateModel.show404Page();
});
}
/**
* @method logVersion
* @description Logs the versions of this build.
*/
logVersion() {
console.log('App Tags:', config.env);
}
/**
* @method connectedCallback
* @description Lit method called when element enters DOM
*/
connectedCallback() {
super.connectedCallback();
window.addEventListener('resize', this._onResize);
}
/**
* @method disconnectedCallback
* @description Lit method called when element leaves DOM
*/
disconnectedCallback() {
window.removeEventListener('resize', this._onResize);
super.disconnectedCallback();
}
/**
* @method firstUpdated
* @description Lit method called when element is first updated.
*/
firstUpdated() {
}
/**
* @method _onAppStateUpdate
* @description bound to AppStateModel app-state-update event
*
* @param {Object} e
*/
async _onAppStateUpdate(e) {
rpLogger.log('_onAppStateUpdate', e);
if ( e.location.query && e.location.query.s !== undefined ) {
this.isSearch = true;
this.textQuery = e.location.query.s;
if( this.firstAppStateUpdate ) {
let ele = this.shadowRoot.getElementById('quick-search');
if( !ele.opened ) ele.open();
}
}
else {
this.textQuery="";
this.isSearch = false;
}
let page = e.page;
if( this.page === page ) return;
if ( !this.loadedPages[page] ) {
this.page = 'loading';
this.loadedPages[page] = this.loadPage(page);
}
await this.loadedPages[page];
this.page = page;
window.scrollTo(0, 0);
this.firstAppStateUpdate = false;
}
/**
* @method loadPage
* @description code splitting done here. dynamic import a page based on route
*
* @param {String} page page to load
*
* @returns {Promise}
*/
loadPage(page) {
if( bundles.search.includes(page) ) {
return import(/* webpackChunkName: "page-search" */ "./pages/bundles/search");
} else if( bundles.landing.includes(page) ) {
return import(/* webpackChunkName: "page-landing" */ "./pages/bundles/landing");
} else if( bundles.admin.includes(page) ) {
return import(/* webpackChunkName: "page-admin" */ "./pages/bundles/admin");
} else if( page === 'home' ) {
return import(/* webpackChunkName: "page-home" */ "./pages/home/rp-page-home");
} else if( page === 'components' ) {
return import(/* webpackChunkName: "page-components" */ "./pages/components/app-components");
} else if( page === 'help' ) {
return import(/* webpackChunkName: "page-help" */ "./pages/help/rp-page-help");
} else if( page === '404' ) {
return import(/* webpackChunkName: "page-404" */ "./pages/404/rp-page-404");
}
console.warn('No code chunk loaded for this page');
return false;
}
/**
* @method _closeQuickSearch
* @description closes the quick-search element.
*/
_closeQuickSearch(){
this.shadowRoot.getElementById('quick-search').close();
}
/**
* @method toggleMobileMenu
* @description Hides/shows the mobile nav.
*/
toggleMobileMenu(){
let isOpen = this.page == 'app-mobile-menu';
if (isOpen) {
this.page = this.mobileMenuPage;
}
else {
this.mobileMenuPage = this.page;
this.page = 'app-mobile-menu';
}
}
/**
* @method _onQuickSearchClick
* @description bound to rp-quick search element.
* Hides main nav on mobile if quick-search is open;
*/
// _onQuickSearchClick(){
// if (window.innerWidth < 480) {
// if (this.shadowRoot.getElementById('quick-search').opened) {
// this.hideMainNav = true;
// }
// else {
// this.hideMainNav = false;
// }
// }
// else {
// this.hideMainNav = false;
// }
// }
// _onQuickSearchKeyup(e){
// if (e.keyCode === 13 && !e.target.opened) {
// e.target.opened = true;
// }
// }
_onQuickSearchToggle(e) {
this.quickSearchOpened = e.detail.opened;
}
/**
* @method _onResize
* @description bound to window resize.
*/
_onResize(){
let w = window.innerWidth;
// this._onQuickSearchClick();
// this._resizeQuickSearch(w);
if (w >= 480 && this.page == 'app-mobile-menu') this.page = this.mobileMenuPage;
}
/**
* @method _resizeQuickSearch
* @description Resizes the input of the quicksearch based on the view width.
* @param {Number} w - Width of view in pixels.
*/
// _resizeQuickSearch(w) {
// if (!w) w = window.innerWidth;
// if (w > 650) {
// this.quickSearchWidth = 220;
// }
// else if (w > 480) {
// let navWidth = this.shadowRoot.getElementById('nav-left').offsetWidth;
// this.quickSearchWidth = w - navWidth - 56;
// }
// else {
// this.quickSearchWidth = w - 40 - 50;
// }
// }
/**
* @method _onSearch
* @description bound to search elements.
* @param {Event} e - search event
*/
_onSearch(e){
let url = "/search";
if (e.target.nodeName == "RP-QUICK-SEARCH") {
// keep existing main facet if search
if (this.isSearch && this.shadowRoot.getElementById('search')) {
let s = this.shadowRoot.getElementById('search');
if (s.mainFacet != 'none') {
url += ("/" + s.mainFacet);
}
}
url += `?s=${encodeURIComponent(e.target.inputValue)}`;
}
else if(e.target.nodeName == 'RP-SEARCH') {
if (e.target.searchObject.facet.id == 'all') {
url = `/search?s=${encodeURIComponent(e.target.inputValue)}`;
}
else {
url = `/search/${e.target.searchObject.facet.id}?s=${encodeURIComponent(e.target.inputValue)}`;
}
}
this.AppStateModel.setLocation(url);
}
/**
* @method _renderMasthead
* @description Renders the top masthead area - banner, logo, hamburger menu
*
* @returns {TemplateResult}
*/
_renderMasthead(){
if (!this.theme.masthead) {
return html``;
}
let styles = {};
styles['background-image'] = `url(${this.theme.masthead})`;
return html`
<div id="masthead" class="text-light flex align-items-center" style="${styleMap(styles)}">
<div class="container content">
${this.theme.universityLogo? html`
<a href="${this.theme.universityUrl}"><img class="logo" alt="UC Davis Logo" src="${this.theme.universityLogo}"></a>` : html`<div></div>`}
<iron-icon
tabindex="0"
icon="${this.page == 'app-mobile-menu' ? 'close' : 'menu'}"
class="hamburger hidden-tablet-up"
role="button"
aria-label="toggle mobile menu"
aria-expanded="${this.page == 'app-mobile-menu' ? 'true' : 'false'}"
@click="${this.toggleMobileMenu}"
@keyup="${e => {if (e.code === 'Enter') this.toggleMobileMenu();}}">
</iron-icon>
</div>
</div>`;
}
/**
* @method _renderFooterColumns
* @description Renders the site footer columns
*
* @returns {TemplateResult}
*/
_renderFooterColumns(){
let columnTemplates = [];
let prefix = "footerColumn";
for (let i of ["1","2","3"]) {
let col = prefix + i;
if (this.theme[col]) {
columnTemplates.push(
html`<div class="footer-column">
${this.theme[col].title ? html`<div class="title">${this.theme[col].title}</div>` : html``}
${this.theme[col].content ? html`${this.theme[col].content.map(line => html`<div class="col-item">${renderHTML(line)}</div>`)}` : html``}
</div>`
);
}
}
if (columnTemplates.length > 0) {
return html`${columnTemplates}`;
}
return html``;
}
/**
* @method _handleUserDropdownSelection
* @description bound to the rp-dropdown new-selection event
*
* @param {Object} e
*/
_handleUserDropdownSelection(e) {
if( e.detail.selected.action === 'stop-impersonating' ) {
this._stopImpersonating();
}
}
/**
* @method _onMobileNavClick
* @description handle mobile nave
*
* @param {Object} e
*/
_onMobileNavClick(e) {
let action = e.currentTarget.getAttribute('action');
if( action === 'stop-impersonating' ) {
this._stopImpersonating();
}
}
/**
* @method _stopImpersonating
* @description stop admin impersonation by clearing imersonate cookie
* and reloading page
*/
_stopImpersonating() {
document.cookie = "impersonate=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
location.reload();
}
testHarvest() {
this.PersonModel.harvest(config.user.uid);
}
} |
JavaScript | class Home {
// #
// #
// ### ## ###
// # # # ## #
// ## ## #
// # ## ##
// ###
/**
* Processes the request.
* @param {Express.Request} req The request.
* @param {Express.Response} res The response.
* @returns {Promise} A promise that resolves when the request has been completed.
*/
static async get(req, res) {
const logs = await Log.getOldest100();
res.status(200).send(Common.page(
/* html */`
<link rel="stylesheet" href="/css/home.css" />
<script src="/views/home/log.js"></script>
<script src="/views/home/logs.js"></script>
<script src="/js/home.js"></script>
`,
HomeView.get({logs}),
req
));
}
} |
JavaScript | class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
scrolled: false,
whatVisible: 'home',
link: null
};
this.updateNavOnScroll = this.updateNavOnScroll.bind(this);
this.goToLink = this.goToLink.bind(this);
}
static localToGlobal(_el) {
/**
* Reference (2019/06/25): https://stackoverflow.com/a/1350681
* */
let target = _el,
target_width = target.offsetWidth,
target_height = target.offsetHeight,
gleft = 0,
gtop = 0,
rect = {};
const moonwalk = function (_parent) {
if (!!_parent) {
gleft += _parent.offsetLeft;
gtop += _parent.offsetTop;
moonwalk(_parent.offsetParent);
} else {
return rect = {
top: target.offsetTop + gtop,
left: target.offsetLeft + gleft,
bottom: (target.offsetTop + gtop) + target_height,
right: (target.offsetLeft + gleft) + target_width
};
}
};
moonwalk(target.offsetParent);
return rect;
}
updateNavOnScroll() {
const nav = document.getElementsByTagName('nav')[0];
const about = document.getElementsByClassName('section-about')[0];
const aboutApp = document.getElementsByClassName('section-about-app')[0];
const windowOffset = window.pageYOffset + window.innerHeight;
const aboutOffset = Header.localToGlobal(about).top + 50;
const aboutAppOffset = Header.localToGlobal(aboutApp).top + 50;
let whatVisible = 'home';
if (windowOffset > aboutOffset)
whatVisible = 'about';
else if (windowOffset > aboutAppOffset)
whatVisible = 'about-app';
let scrolled = window.pageYOffset > nav.clientHeight / 2;
this.setState({scrolled, whatVisible});
}
goToLink() {
if (this.state.link) {
const link = this.state.link;
this.setState({link: null}, () => {
if (link === 'home')
this.props.loadHome();
else
scrollToElement(link);
});
}
}
setLink(link) {
this.setState({link}, () => {
const togglerButtons = document.getElementsByClassName('navbar-toggler');
let togglerIsVisible = false;
if (togglerButtons) {
togglerIsVisible = window.getComputedStyle(togglerButtons[0]).display !== 'none';
}
if (togglerIsVisible) {
$('#navbarSupportedContent').collapse('toggle');
} else {
this.goToLink();
}
});
}
componentDidMount() {
const collapsible = $('#navbarSupportedContent');
collapsible.on('shown.bs.collapse', this.goToLink);
collapsible.on('hidden.bs.collapse', this.goToLink);
document.body.onscroll = this.updateNavOnScroll;
this.updateNavOnScroll();
}
render() {
return (
<nav
className={`navbar fixed-top navbar-expand-lg navbar-light mb-4 pageNavHeader ${this.state.scrolled ? 'scrolled' : ''}`}>
<span className="navbar-brand logo-wrapper">
<img className="logoImg" alt="ClimateChange.AI" src={newLogo}
onClick={this.props.loadHome}/>
</span>
<button className="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"/>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav ml-auto">
<li className={`nav-item ${this.state.whatVisible === 'home' ? 'active' : ''}`}>
<span className="nav-link button" onClick={() => this.setLink('home')}>
HOME
{this.state.whatVisible === 'home' ? (<span className="sr-only">(current)</span>) : ''}
</span>
</li>
<li className={`nav-item ${this.state.whatVisible === 'about-app' ? 'active' : ''}`}>
<span className="nav-link button" onClick={() => this.setLink('about-app')}>
THE APP
{this.state.whatVisible === 'about-app' ? (
<span className="sr-only">(current)</span>) : ''}
</span>
</li>
<li className={`nav-item ${this.state.whatVisible === 'about' ? 'active' : ''}`}>
<span className="nav-link button" onClick={() => this.setLink('about')}>
ABOUT
{this.state.whatVisible === 'about' ? (<span className="sr-only">(current)</span>) : ''}
</span>
</li>
</ul>
</div>
</nav>
)
}
} |
JavaScript | class ArcPlugin extends AbstractPlugin {
/**
* Constructor.
*/
constructor() {
super();
this.id = arc.ID;
}
/**
* @inheritDoc
*/
init() {
registerMimeTypes();
var dm = DataManager.getInstance();
var arcEntry = new ProviderEntry(this.id, ArcServer, 'Arc Server',
'Arc servers provide feature and tile data.');
dm.registerProviderType(arcEntry);
dm.registerDescriptorType(this.id, ArcLayerDescriptor);
var lcm = LayerConfigManager.getInstance();
lcm.registerLayerConfig(ArcFeatureLayerConfig.ID, ArcFeatureLayerConfig);
lcm.registerLayerConfig(ArcTileLayerConfig.ID, ArcTileLayerConfig);
lcm.registerLayerConfig(ArcImageLayerConfig.ID, ArcImageLayerConfig);
var im = ImportManager.getInstance();
im.registerImportUI(this.id, new ProviderImportUI(`<${arcImportEl}></${arcImportEl}>`));
im.registerServerType(this.id, {
type: 'arc',
helpUi: ArcServerHelpUI.directiveTag,
formUi: ArcImportForm.directiveTag,
label: 'ArcGIS Server'
});
var sm = StateManager.getInstance();
sm.addLoadFunction(arcstate.load);
sm.addSaveFunction(arcstate.save);
// Register a default validator to detect Arc server exceptions.
net.registerDefaultValidator(arc.getException);
// Set the base class for loading an Arc server.
arc.setLoaderClass(ArcLoader);
}
} |
JavaScript | class CodeMirror extends PureComponent {
static propTypes = {
defaultValue: PropTypes.string,
options: PropTypes.object,
...CM_EVENT_PROP_TYPES,
codeMirror: PropTypes.func // for testing
}
static defaultProps = {
options: {},
codeMirror
}
editor = null;
codeMirrorEl = null;
componentDidMount() {
const { options } = this.props;
this.editor = this.props.codeMirror(this.codeMirrorEl, {...DEFAULT_OPTIONS, ...options});
Object.keys(PROP_NAME_TO_CM_EVENT).forEach((propName) => {
if (this.props[propName]) {
// special case onChange to prevent change event when reseting
if (propName === 'onChange') {
this.editor.on('change', this.handleChange);
} else {
this.editor.on(PROP_NAME_TO_CM_EVENT[propName], this.props[propName]);
}
}
});
if (this.props.defaultValue !== undefined) {
this.resetValue();
}
}
// do this in componentDidUpdate so it only happens once mounted.
componentDidUpdate(prevProps) {
if (this.props.defaultValue !== prevProps.defaultValue) {
this.resetValue();
}
invariant(this.props.options === prevProps.options, 'changing options is not implemented');
}
componentWillUnmount() {
if (this.editor && this.editor.toTextArea) {
this.editor.toTextArea(); // free cm from memory
this.editor = null;
}
}
handleChange = (cm, event) => {
if (!this.reseting) {
this.props.onChange(cm, event);
}
}
resetValue() {
this.reseting = true;
try {
this.editor.setValue(this.props.defaultValue || '');
} finally {
this.reseting = false;
}
}
render() {
return (
<div className='ReactCodeMirror' ref={(ref) => this.codeMirrorEl = ref}/>
);
}
} |
JavaScript | class CacheDriverRepository extends Repository {
/**
* Registers a new cache driver.
*
* @param {string} name A string containing the driver name, it must be unique.
* @param {function} object The class that implements the driver, note that it must extend the "CacheDriver" class.
* @param {boolean} [overwrite=false] If set to "true" it means that if the driver has already been registered, it will be overwritten by current one, otherwise an exception will be thrown.
*
* @throws {InvalidArgumentException} If an invalid driver name is given.
* @throws {InvalidArgumentException} If another driver with the same name has already been registered and the "overwrite" option wasn't set to "true".
* @throws {InvalidArgumentException} If an invalid driver class is given.
*
* @async
*/
static async register(name, object, overwrite = false){
if ( typeof object !== 'function' || Object.getPrototypeOf(object).name !== 'CacheDriver' ){
throw new InvalidArgumentException('Invalid driver class.', 4);
}
if ( overwrite !== true && super.has(name, 'com.lala.cache.driver') ){
throw new InvalidArgumentException('The given object has already been registered.', 3);
}
// Call the setup method, if found, to allow the driver to set up connections and variables.
if ( typeof object.setup === 'function' ){
// If set up function returns "false" it means that the driver cannot be used.
if ( await object.setup() === false ){
return;
}
}
super.register(name, object, 'com.lala.cache.driver', overwrite);
}
/**
* Removes a cache driver that has been registered.
*
* @param {string} name A string containing the driver name.
*
* @throws {InvalidArgumentException} If an invalid driver name is given.
*/
static remove(name){
super.remove(name, 'com.lala.cache.driver');
}
/**
* Checks if a cache driver matching a given name has been registered or not.
*
* @param {string} name A string containing the driver name.
*
* @returns {boolean} If the cache driver exists will be returned "true", otherwise "false".
*
* @throws {InvalidArgumentException} If an invalid driver name is given.
*/
static has(name){
return super.has(name, 'com.lala.cache.driver');
}
/**
* Returns the cache driver matching a given name.
*
* @param {string} name A string containing the driver name.
*
* @returns {(function|null)} The class that implements the cache driver found, if no class is found, null will be returned instead.
*
* @throws {InvalidArgumentException} If an invalid driver name is given.
*/
static get(name){
return super.get(name, 'com.lala.cache.driver');
}
/**
* Returns all the cache drivers that have been registered.
*
* @returns {{string: function}} An object having as key the object name and as value the cache driver itself.
*/
static getAll(){
return super.getAll('com.lala.cache.driver');
}
} |
JavaScript | class TauChartReact extends React.Component {
constructor(props) {
super(props);
this.displayName = 'TauChart';
}
componentDidMount() {
this.renderChart();
}
componentDidUpdate() {
this.chart.destroy();
this.renderChart();
}
componentWillUnmount() {
this.chart.destroy();
}
/**
* Render the component.
* @return {JSX.Element}
*/
render() {
return <div style={{ height: '100%' }} className={this.props.className} ref='placeholder'></div>;
}
/**
* Render the chart.
* @return {JSX.Element}
*/
renderChart() {
this.chart = new Chart(Object.assign({}, this.props.options, { data: this.props.data }));
if (this.props.height && this.props.width) {
this.chart.renderTo(this.refs.placeholder, {
height: this.props.height,
width: this.props.width,
});
} else {
this.chart.renderTo(this.refs.placeholder);
}
}
/**
* Determine if the chart should be rerendered.
* @return {boolean}
*/
shouldComponentUpdate(newProps) {
if (
newProps.className === this.props.className &&
newProps.height === this.props.height &&
newProps.width === this.props.width &&
equal(newProps.options, this.props.options, { strict: true })
) {
this.chart.setData(newProps.data);
return false;
}
return true;
}
} |
JavaScript | class Pose {
/**
* Creates a new position and orientation, at a given time.
**/
constructor() {
this.t = 0;
this.p = new Vector3();
this.f = new Vector3();
this.f.set(0, 0, -1);
this.u = new Vector3();
this.u.set(0, 1, 0);
Object.seal(this);
}
/**
* Sets the components of the pose.
* @param {number} px
* @param {number} py
* @param {number} pz
* @param {number} fx
* @param {number} fy
* @param {number} fz
* @param {number} ux
* @param {number} uy
* @param {number} uz
*/
set(px, py, pz, fx, fy, fz, ux, uy, uz) {
this.p.set(px, py, pz);
this.f.set(fx, fy, fz);
this.u.set(ux, uy, uz);
}
/**
* Copies the components of another pose into this pose.
* @param {Pose} other
*/
copy(other) {
this.p.copy(other.p);
this.f.copy(other.f);
this.u.copy(other.u);
}
/**
* Performs a lerp between two positions and a slerp between to orientations
* and stores the result in this pose.
* @param {Pose} a
* @param {Pose} b
* @param {number} p
*/
interpolate(start, end, t) {
if (t <= start.t) {
this.copy(start);
}
else if (end.t <= t) {
this.copy(end);
}
else if (start.t < t) {
const p = project(t, start.t, end.t);
this.p.copy(start.p);
this.p.lerp(end.p, p);
slerpVectors(this.f, start.f, end.f, p);
slerpVectors(this.u, start.u, end.u, p);
this.t = t;
}
}
} |
JavaScript | class TmIframeDialog extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
.page {
display: flex;
flex-direction: column;
padding: 1vmin;
}
iframe {
width: 90vw;
height: 75vh;
outline: none;
box-sizing: border-box;
border: solid lightgray 1px;
}
div.toolbar {
flex:1;
display: flex;
flex-direction: row;
height: 5vh;
width: 100%;
}
div.toolbar > span.title {
flex: 1;
margin-top:0.3vh;
float:left;
font-style: italic;
font-size: 2vh;
}
div.toolbar > div.buttons {
flex: 1;
}
div.toolbar .buttons {
float:right;
flex:1;
}
div.toolbar > .buttons paper-button {
padding:0.3vh 0.5vw 0.3vh 0.5vw;
font-size: 2vh;
border: solid lightgray 1px;
float: right;
}
div.footer {
flex:1;
display: flex;
flex-direction: row;
height: 5vh;
width: 100%;
}
div.footer > span.url {
font-size: 2vh;
font-style: italic;
color: lightgray;
}
</style>
<vaadin-dialog id="sourceDialog">
<template>
<div class="page">
<div class="toolbar">
<span class="title">[[title]]</span>
<div class="buttons">
<paper-button on-tap="_openSourceInTab">Open in Tab</paper-button>
<paper-button on-tap="_closeSourceDialog">Close</paper-button>
</div>
</div>
<iframe src="[[src]]"></iframe>
<div class="footer">
<span class="url">[[src]]</span>
</div>
</div>
</template>
</vaadin-dialog>
`;
}
static get properties() {
return {
/** The url of the page that is to be load. */
src: {
type: String,
value: 'https://google.com',
},
/** Title to describe what is being loaded. */
title: {
type: String,
value: 'Google',
},
};
}
/**
* Open the dialog and view the required page.
*/
open() {
this.$.sourceDialog.opened = true;
}
/**
* Close the dialog.
*/
close() {
this.$.sourceDialog.opened = false;
}
_openSourceInTab() {
window.open(this.src, '_black');
this.$.sourceDialog.opened = false;
}
_closeSourceDialog() {
this.$.sourceDialog.opened = false;
}
ready() {
super.ready();
}
} |
JavaScript | class FailedTxMonitor extends EventEmitter {
constructor(web3, app) {
super();
this.web3 = web3;
this.app = app;
this.LP_EVENT = 'lpEvent';
this.MILESTONE_EVENT = 'milestoneEvent';
this.VAULT_EVENT = 'vaultEvent';
this.decoders = {
lp: {},
vault: {},
milestone: {},
};
}
start() {
this.setDecoders();
this.donationIntervalId = setInterval(this.checkPendingDonations.bind(this), FIFTEEN_MINUTES);
this.dacIntervalId = setInterval(this.checkPendingDACS.bind(this), FIFTEEN_MINUTES);
this.campaignIntervalId = setInterval(this.checkPendingCampaigns.bind(this), FIFTEEN_MINUTES);
this.milestoneIntervalId = setInterval(this.checkPendingMilestones.bind(this), FIFTEEN_MINUTES);
}
close() {
this.removeAllListeners();
clearInterval(this.donationIntervalId);
clearInterval(this.dacIntervalId);
clearInterval(this.campaignIntervalId);
clearInterval(this.milestoneIntervalId);
}
setDecoders() {
LiquidPledgingAbi.filter(method => method.type === 'event').forEach(event => {
this.decoders.lp[event.name] = this.web3.eth.Contract.prototype._decodeEventABI.bind(event);
});
LPVaultAbi.filter(method => method.type === 'event').forEach(event => {
this.decoders.vault[event.name] = this.web3.eth.Contract.prototype._decodeEventABI.bind(
event,
);
});
LPPCappedMilestonesAbi.filter(method => method.type === 'event').forEach(event => {
this.decoders.milestone[event.name] = this.web3.eth.Contract.prototype._decodeEventABI.bind(
event,
);
});
}
checkPendingDonations() {
const donations = this.app.service('donations');
const revertDonationIfFailed = donation => {
if (!donation.previousState || !donation.txHash) return;
this.web3.eth.getTransactionReceipt(donation.txHash).then(receipt => {
if (!receipt) return;
// 0 status if failed tx
logger.info(receipt);
if (hexToNumber(receipt.status) === 0) {
donations
.patch(
donation._id,
Object.assign({}, donation.previousState, { $unset: { previousState: true } }),
)
.catch(logger.error);
return;
}
const topics = [
{ name: 'Transfer', hash: this.web3.utils.keccak256('Transfer(uint64,uint64,uint256)') },
{
name: 'AuthorizePayment',
hash: this.web3.utils.keccak256('AuthorizePayment(uint256,bytes32,address,uint256)'),
},
];
// get logs we're interested in.
const logs = receipt.logs.filter(log => topics.some(t => t.hash === log.topics[0]));
if (logs.length === 0) {
logger.error(
'donation has status === `pending` but transaction was successful donation:',
donation,
'receipt:',
receipt,
);
}
logs.forEach(log => {
logger.info(
'donation has status === `pending` but transaction was successful. re-emitting event donation:',
donation,
'receipt:',
receipt,
);
const topic = topics.find(t => t.hash === log.topics[0]);
if (topic.name === 'AuthorizePayment') {
this.emit(this.VAULT_EVENT, this.decoders.vault[topic.name](log));
} else {
this.emit(this.LP_EVENT, this.decoders.lp[topic.name](log));
}
});
});
};
donations
.find({
paginate: false,
query: {
status: 'pending',
},
})
.then(pendingDonations => pendingDonations.forEach(revertDonationIfFailed))
.catch(logger.error);
}
checkPendingDACS() {
const dacs = this.app.service('dacs');
const updateDACIfFailed = dac => {
if (!dac.txHash) return;
this.web3.eth.getTransactionReceipt(dac.txHash).then(receipt => {
if (!receipt) return;
// 0 status if failed tx
if (hexToNumber(receipt.status) === 0) {
dacs
.patch(dac._id, {
status: 'failed',
})
.catch(logger.error);
return;
}
const topics = [
{ name: 'DelegateAdded', hash: this.web3.utils.keccak256('DelegateAdded(uint64)') },
];
// get logs we're interested in.
const logs = receipt.logs.filter(log => topics.some(t => t.hash === log.topics[0]));
if (logs.length === 0) {
logger.error(
'dac has no delegateId but transaction was successful dac:',
dac,
'receipt:',
receipt,
);
}
logs.forEach(log => {
logger.info(
'dac has no delegateId but transaction was successful. re-emitting AddDelegate event. dac:',
dac,
'receipt:',
receipt,
);
const topic = topics.find(t => t.hash === log.topics[0]);
this.emit(this.LP_EVENT, this.decoders.lp[topic.name](log));
});
});
};
dacs
.find({
paginate: false,
query: {
$not: { delegateId: { $gt: '0' } },
},
})
.then(pendingDACs => pendingDACs.forEach(updateDACIfFailed))
.catch(logger.error);
}
checkPendingCampaigns() {
const campaigns = this.app.service('campaigns');
const updateCampaignIfFailed = campaign => {
if (!campaign.txHash) return;
this.web3.eth.getTransactionReceipt(campaign.txHash).then(receipt => {
if (!receipt) return;
// 0 status if failed tx
if (hexToNumber(receipt.status) === 0) {
// if status !== pending, then the cancel campaign transaction failed, so reset
const mutation =
campaign.status === 'pending'
? { status: 'failed' }
: { status: 'Active', mined: true };
campaigns.patch(campaign._id, mutation).catch(logger.error);
return;
}
const topics = [
{ name: 'ProjectAdded', hash: this.web3.utils.keccak256('ProjectAdded(uint64)') },
{ name: 'CancelProject', hash: this.web3.utils.keccak256('CancelProject(uint64)') },
];
// get logs we're interested in.
const logs = receipt.logs.filter(log => topics.some(t => t.hash === log.topics[0]));
if (logs.length === 0) {
logger.error(
'campaign status === `pending` or mined === false but transaction was successful campaign:',
campaign,
'receipt:',
receipt,
);
}
logs.forEach(log => {
logger.info(
'campaign status === `pending` or mined === false but transaction was successful. re-emitting event. campaign:',
campaign,
'receipt:',
receipt,
);
const topic = topics.find(t => t.hash === log.topics[0]);
this.emit(this.LP_EVENT, this.decoders.lp[topic.name](log));
});
});
};
campaigns
.find({
paginate: false,
query: {
$or: [{ status: 'pending' }, { mined: false }],
},
})
.then(pendingCampaigns => pendingCampaigns.forEach(updateCampaignIfFailed))
.catch(logger.error);
}
checkPendingMilestones() {
const milestones = this.app.service('milestones');
const updateMilestoneIfFailed = milestone => {
if (!milestone.txHash) return; // we can't revert
this.web3.eth.getTransactionReceipt(milestone.txHash).then(receipt => {
if (!receipt) return;
// 0 status if failed tx
if (hexToNumber(receipt.status) === 0) {
let mutation;
if (milestone.status === 'pending') {
// was never created in liquidPledging
mutation = { status: 'failed' };
} else if (['Completed', 'Canceled'].includes(milestone.status)) {
// if canceled, it's possible that the milestone was markedComplete,
// but b/c that process is off-chain
// we just reset to InProgress, and the recipient can mark complete again.
mutation = { status: 'InProgress', mined: true };
} else if (milestone.status === 'Paying') {
mutation = { status: 'Completed', mined: true };
} else if (milestone.status === 'Paid') {
mutation = { status: 'CanWithdraw', mined: true };
}
milestones.patch(milestone._id, mutation).catch(logger.error);
return;
}
const topics = [
{ name: 'ProjectAdded', hash: this.web3.utils.keccak256('ProjectAdded(uint64)') },
{
name: 'MilestoneAccepted',
hash: this.web3.utils.keccak256('MilestoneAccepted(address)'),
},
{ name: 'CancelProject', hash: this.web3.utils.keccak256('CancelProject(uint64)') },
];
// get logs we're interested in.
const logs = receipt.logs.filter(log => topics.some(t => t.hash === log.topics[0]));
if (logs.length === 0) {
logger.error(
'milestone status === `pending` or mined === false but transaction was successful milestone:',
milestone,
'receipt:',
receipt,
);
}
logs.forEach(log => {
logger.info(
'milestone status === `pending` or mined === false but transaction was successful. re-emitting event. milestone:',
milestone,
'receipt:',
receipt,
);
const topic = topics.find(t => t.hash === log.topics[0]);
if (topic.name === 'MilestoneAccepted') {
this.emit(this.MILESTONE_EVENT, this.decoders.milestone[topic.name](log));
} else {
this.emit(this.LP_EVENT, this.decoders.lp[topic.name](log));
}
});
});
};
milestones
.find({
paginate: false,
query: {
$or: [{ status: 'pending' }, { mined: false }],
},
})
.then(pendingMilestones => pendingMilestones.forEach(updateMilestoneIfFailed))
.catch(logger.error);
}
} |
JavaScript | class DeliveryUsage extends Base {
/**
* List all delivery usage during a timeframe for a Mux Environment (tied to your access token)
* @param {Object} params - Request JSON parameters (e.g timeframe)
* @returns {Promise} - Returns a resolved Promise with a response from the Mux API
*
* @example
* const { Video } = new Mux(accessToken, secret);
*
* // List all delivery usage for a Mux Environment within a timeframe
* Video.DeliveryUsage.list({timeframe: [1574076240, 1573471440]});
*
* @see https://docs.mux.com/api-reference/video#operation/list-delivery-usage
*/
list(params) {
return this.http.get(PATH, { params });
}
} |
JavaScript | class ScreenshotController extends React.Component {
constructor() {
super(...arguments);
this.takeScreenshot = async () => {
const { name, finalScreen, captureImage, viewRef } = this.props;
/**
* Capture screenshot with Expo snapshot tool.
*/
const result = await takeSnapshotAsync(viewRef(), {
width,
height,
quality: 1,
format: "png",
result: "data-uri",
});
/**
* Store screenshot data:
*/
await captureImage({
name,
screenshot: result,
}, Boolean(finalScreen));
/**
* Go to next screen, or if this is the final screen reset to the
* initial screen.
*/
if (!finalScreen) {
this.goToNextScreen();
}
else {
this.props.navigation.dispatch(StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: STARGAZER_INIT,
params: { uploadComplete: true },
}),
],
}));
}
};
this.goToNextScreen = () => {
// tslint:disable-next-line
this.timer = setTimeout(() => {
this.props.navigation.navigate(this.props.nextScreen, this.props.paramsForNextScreen);
}, 250);
};
}
componentDidMount() {
// tslint:disable-next-line
this.timer = setTimeout(async () => {
this.takeScreenshot();
}, this.props.screenshotDelay || TIMER_DELAY);
}
componentWillUnmount() {
if (this.timer) {
// @ts-ignore
clearTimeout(this.timer);
// tslint:disable-next-line
this.timer = null;
}
}
render() {
return <View style={{ flex: 1 }}>{this.props.children}</View>;
}
} |
JavaScript | class CacheableStateEvaluator extends DefaultStateEvaluator {
constructor(arweave, cache, executionContextModifiers = []) {
super(arweave, executionContextModifiers);
this.cache = cache;
this.cLogger = LoggerFactory.INST.create('CacheableStateEvaluator');
}
async eval(executionContext, currentTx) {
const requestedBlockHeight = executionContext.blockHeight;
this.cLogger.debug(`Requested state block height: ${requestedBlockHeight}`);
let cachedState = null;
const sortedInteractionsUpToBlock = executionContext.sortedInteractions.filter((tx) => {
return tx.node.block.height <= executionContext.blockHeight;
});
let missingInteractions = sortedInteractionsUpToBlock.slice();
// if there was anything to cache...
if (sortedInteractionsUpToBlock.length > 0) {
// get latest available cache for the requested block height
const benchmark = Benchmark.measure();
cachedState = (await this.cache.getLessOrEqual(executionContext.contractDefinition.txId, requestedBlockHeight));
this.cLogger.trace('Retrieving value from cache', benchmark.elapsed());
if (cachedState != null) {
this.cLogger.debug(`Cached state for ${executionContext.contractDefinition.txId}`, {
block: cachedState.cachedHeight,
requestedBlockHeight
});
// verify if for the requested block height there are any interactions
// with higher block height than latest value stored in cache - basically if there are any non-cached interactions.
missingInteractions = sortedInteractionsUpToBlock.filter(({ node }) => node.block.height > cachedState.cachedHeight && node.block.height <= requestedBlockHeight);
}
this.cLogger.debug(`Interactions until [${requestedBlockHeight}]`, {
total: sortedInteractionsUpToBlock.length,
cached: sortedInteractionsUpToBlock.length - missingInteractions.length
});
// TODO: this probably should be removed, as it seems to protect from
// some specific contract's implementation flaws
// (i.e. inner calls between two contracts that lead to inf. call loop - circular dependency).
// Instead - some kind of stack trace should be generated and "stackoverflow"
// exception should be thrown during contract's execution.
for (const entry of currentTx || []) {
if (entry.contractTxId === executionContext.contractDefinition.txId) {
const index = missingInteractions.findIndex((tx) => tx.node.id === entry.interactionTxId);
if (index !== -1) {
this.cLogger.debug('Inf. Loop fix - removing interaction', {
height: missingInteractions[index].node.block.height,
contractTxId: entry.contractTxId,
interactionTxId: entry.interactionTxId
});
missingInteractions.splice(index, 1);
}
}
}
// if cache is up-to date - return immediately to speed-up the whole process
if (missingInteractions.length === 0 && cachedState) {
this.cLogger.debug(`State up to requested height [${requestedBlockHeight}] fully cached!`);
return cachedState.cachedValue;
}
}
const baseState = cachedState == null ? executionContext.contractDefinition.initState : cachedState.cachedValue.state;
const baseValidity = cachedState == null ? {} : cachedState.cachedValue.validity;
// eval state for the missing transactions - starting from latest value from cache.
return await this.doReadState(missingInteractions, new EvalStateResult(baseState, baseValidity), executionContext, currentTx);
}
async onStateUpdate(currentInteraction, executionContext, state) {
await super.onStateUpdate(currentInteraction, executionContext, state);
await this.cache.put(new BlockHeightKey(executionContext.contractDefinition.txId, currentInteraction.block.height), state);
}
} |
JavaScript | class PathConstraint {
constructor(data, skeleton) {
/**
* The position along the path.
*
* @type {number}
* @default 0
*/
this.position = 0;
/**
* The spacing between bones.
*
* @type {number}
* @default 0
*/
this.spacing = 0;
/**
* A percentage (0-1) that controls the mix between the constrained and unconstrained rotations.
*
* @type {number}
* @default 0
*/
this.rotateMix = 0;
/**
* A percentage (0-1) that controls the mix between the constrained and unconstrained translations.
*
* @type {number}
* @default 0
*/
this.translateMix = 0;
/**
*
* @type {number[]}
* @default []
*/
this.spaces = [];
/**
*
* @type {number[]}
* @default []
*/
this.positions = [];
/**
*
* @type {number[]}
* @default []
*/
this.world = [];
/**
*
* @type {number[]}
* @default []
*/
this.curves = [];
/**
*
* @type {number[]}
* @default []
*/
this.lengths = [];
/**
*
* @type {number[]}
* @default []
*/
this.segments = [];
/**
*
* @type {boolean}
* @default false
*/
this.active = false;
if (data == null) {
throw new Error('data cannot be null.');
}
if (skeleton == null) {
throw new Error('skeleton cannot be null.');
}
/**
* The path constraint's setup pose data.
*
* @type {Tiny.spine.PathConstraintData}
*/
this.data = data;
/**
* The bones that will be modified by this path constraint.
*
* @type {Tiny.spine.Bone[]}
*/
this.bones = [];
for (let i = 0, n = data.bones.length; i < n; i++) {
this.bones.push(skeleton.findBone(data.bones[i].name));
}
/**
* The slot whose path attachment will be used to constrained the bones.
*
* @type {Tiny.spine.Slot}
*/
this.target = skeleton.findSlot(data.target.name);
this.position = data.position;
this.spacing = data.spacing;
this.rotateMix = data.rotateMix;
this.translateMix = data.translateMix;
}
/**
* @return {boolean}
*/
isActive() {
return this.active;
}
/**
* Applies the constraint to the constrained bones.
*/
apply() {
this.update();
}
/**
*
*/
update() {
const attachment = this.target.getAttachment();
if (!(attachment instanceof PathAttachment)) {
return;
}
const rotateMix = this.rotateMix;
const translateMix = this.translateMix;
const translate = translateMix > 0;
const rotate = rotateMix > 0;
if (!translate && !rotate) {
return;
}
const data = this.data;
const spacingMode = data.spacingMode;
const lengthSpacing = spacingMode === SpacingMode.Length;
const rotateMode = data.rotateMode;
const tangents = rotateMode === RotateMode.Tangent;
const scale = rotateMode === RotateMode.ChainScale;
const boneCount = this.bones.length;
const spacesCount = tangents ? boneCount : boneCount + 1;
const bones = this.bones;
const spaces = setArraySize(this.spaces, spacesCount);
let lengths = null;
const spacing = this.spacing;
if (scale || lengthSpacing) {
if (scale) {
lengths = setArraySize(this.lengths, boneCount);
}
for (let i = 0, n = spacesCount - 1; i < n;) {
const bone = bones[i];
const setupLength = bone.data.length;
if (setupLength < PathConstraint.epsilon) {
if (scale) {
lengths[i] = 0;
}
spaces[++i] = 0;
} else {
const x = setupLength * bone.matrix.a;
const y = setupLength * bone.matrix.b;
const length = Math.sqrt(x * x + y * y);
if (scale) {
lengths[i] = length;
}
spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length / setupLength;
}
}
} else {
for (let i = 1; i < spacesCount; i++) {
spaces[i] = spacing;
}
}
const positions = this.computeWorldPositions(
attachment,
spacesCount,
tangents,
data.positionMode === PositionMode.Percent,
spacingMode === SpacingMode.Percent
);
let boneX = positions[0];
let boneY = positions[1];
let offsetRotation = data.offsetRotation;
let tip = false;
if (offsetRotation === 0) {
tip = rotateMode === RotateMode.Chain;
} else {
tip = false;
const p = this.target.bone.matrix;
offsetRotation *= p.a * p.d - p.b * p.c > 0 ? degRad : -degRad;
}
for (let i = 0, p = 3; i < boneCount; i++, p += 3) {
const bone = bones[i];
const mat = bone.matrix;
mat.tx += (boneX - mat.tx) * translateMix;
mat.ty += (boneY - mat.ty) * translateMix;
const x = positions[p];
const y = positions[p + 1];
const dx = x - boneX;
const dy = y - boneY;
if (scale) {
const length = lengths[i];
if (length !== 0) {
const s = (Math.sqrt(dx * dx + dy * dy) / length - 1) * rotateMix + 1;
mat.a *= s;
mat.b *= s;
}
}
boneX = x;
boneY = y;
if (rotate) {
const a = mat.a;
const b = mat.c;
const c = mat.b;
const d = mat.d;
let r = 0;
let cos = 0;
let sin = 0;
if (tangents) {
r = positions[p - 1];
} else if (spaces[i + 1] === 0) {
r = positions[p + 2];
} else {
r = Math.atan2(dy, dx);
}
r -= Math.atan2(c, a);
if (tip) {
cos = Math.cos(r);
sin = Math.sin(r);
const length = bone.data.length;
boneX += (length * (cos * a - sin * c) - dx) * rotateMix;
boneY += (length * (sin * a + cos * c) - dy) * rotateMix;
} else {
r += offsetRotation;
}
if (r > PI) {
r -= PI2;
} else if (r < -PI) {
r += PI2;
}
r *= rotateMix;
cos = Math.cos(r);
sin = Math.sin(r);
mat.a = cos * a - sin * c;
mat.c = cos * b - sin * d;
mat.b = sin * a + cos * c;
mat.d = sin * b + cos * d;
}
bone.appliedValid = false;
}
}
/**
*
* @param {Tiny.spine.PathAttachment} path
* @param {number} spacesCount
* @param {boolean} tangents
* @param {boolean} percentPosition
* @param {boolean} percentSpacing
*/
computeWorldPositions(path, spacesCount, tangents, percentPosition, percentSpacing) {
let target = this.target;
let position = this.position;
let spaces = this.spaces;
let out = setArraySize(this.positions, spacesCount * 3 + 2);
let world = null;
let closed = path.closed;
let verticesLength = path.worldVerticesLength;
let curveCount = verticesLength / 6;
let prevCurve = PathConstraint.NONE;
if (!path.constantSpeed) {
const lengths = path.lengths;
curveCount -= closed ? 1 : 2;
const pathLength = lengths[curveCount];
if (percentPosition) {
position *= pathLength;
}
if (percentSpacing) {
for (let i = 0; i < spacesCount; i++) {
spaces[i] *= pathLength;
}
}
world = setArraySize(this.world, 8);
for (let i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) {
const space = spaces[i];
position += space;
let p = position;
if (closed) {
p %= pathLength;
if (p < 0) {
p += pathLength;
}
curve = 0;
} else if (p < 0) {
if (prevCurve !== PathConstraint.BEFORE) {
prevCurve = PathConstraint.BEFORE;
path.computeWorldVertices(target, 2, 4, world, 0, 2);
}
this.addBeforePosition(p, world, 0, out, o);
continue;
} else if (p > pathLength) {
if (prevCurve !== PathConstraint.AFTER) {
prevCurve = PathConstraint.AFTER;
path.computeWorldVertices(target, verticesLength - 6, 4, world, 0, 2);
}
this.addAfterPosition(p - pathLength, world, 0, out, o);
continue;
}
// Determine curve containing position.
for (;; curve++) {
const length = lengths[curve];
if (p > length) {
continue;
}
if (curve === 0) {
p /= length;
} else {
const prev = lengths[curve - 1];
p = (p - prev) / (length - prev);
}
break;
}
if (curve !== prevCurve) {
prevCurve = curve;
if (closed && curve === curveCount) {
path.computeWorldVertices(target, verticesLength - 4, 4, world, 0, 2);
path.computeWorldVertices(target, 0, 4, world, 4, 2);
} else {
path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0, 2);
}
}
this.addCurvePosition(
p,
world[0],
world[1],
world[2],
world[3],
world[4],
world[5],
world[6],
world[7],
out,
o,
tangents || (i > 0 && space === 0)
);
}
return out;
}
// World vertices.
if (closed) {
verticesLength += 2;
world = setArraySize(this.world, verticesLength);
path.computeWorldVertices(target, 2, verticesLength - 4, world, 0, 2);
path.computeWorldVertices(target, 0, 2, world, verticesLength - 4, 2);
world[verticesLength - 2] = world[0];
world[verticesLength - 1] = world[1];
} else {
curveCount--;
verticesLength -= 4;
world = setArraySize(this.world, verticesLength);
path.computeWorldVertices(target, 2, verticesLength, world, 0, 2);
}
// Curve lengths.
const curves = setArraySize(this.curves, curveCount);
let pathLength = 0;
let x1 = world[0];
let y1 = world[1];
let cx1 = 0;
let cy1 = 0;
let cx2 = 0;
let cy2 = 0;
let x2 = 0;
let y2 = 0;
let tmpx = 0;
let tmpy = 0;
let dddfx = 0;
let dddfy = 0;
let ddfx = 0;
let ddfy = 0;
let dfx = 0;
let dfy = 0;
for (let i = 0, w = 2; i < curveCount; i++, w += 6) {
cx1 = world[w];
cy1 = world[w + 1];
cx2 = world[w + 2];
cy2 = world[w + 3];
x2 = world[w + 4];
y2 = world[w + 5];
tmpx = (x1 - cx1 * 2 + cx2) * 0.1875;
tmpy = (y1 - cy1 * 2 + cy2) * 0.1875;
dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375;
dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375;
ddfx = tmpx * 2 + dddfx;
ddfy = tmpy * 2 + dddfy;
dfx = (cx1 - x1) * 0.75 + tmpx + dddfx * 0.16666667;
dfy = (cy1 - y1) * 0.75 + tmpy + dddfy * 0.16666667;
pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
dfx += ddfx;
dfy += ddfy;
pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
dfx += ddfx + dddfx;
dfy += ddfy + dddfy;
pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
curves[i] = pathLength;
x1 = x2;
y1 = y2;
}
if (percentPosition) {
position *= pathLength;
}
if (percentSpacing) {
for (let i = 0; i < spacesCount; i++) {
spaces[i] *= pathLength;
}
}
const segments = this.segments;
let curveLength = 0;
for (let i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) {
const space = spaces[i];
position += space;
let p = position;
if (closed) {
p %= pathLength;
if (p < 0) {
p += pathLength;
}
curve = 0;
} else if (p < 0) {
this.addBeforePosition(p, world, 0, out, o);
continue;
} else if (p > pathLength) {
this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o);
continue;
}
// Determine curve containing position.
for (;; curve++) {
const length = curves[curve];
if (p > length) {
continue;
}
if (curve === 0) {
p /= length;
} else {
const prev = curves[curve - 1];
p = (p - prev) / (length - prev);
}
break;
}
// Curve segment lengths.
if (curve !== prevCurve) {
prevCurve = curve;
let ii = curve * 6;
x1 = world[ii];
y1 = world[ii + 1];
cx1 = world[ii + 2];
cy1 = world[ii + 3];
cx2 = world[ii + 4];
cy2 = world[ii + 5];
x2 = world[ii + 6];
y2 = world[ii + 7];
tmpx = (x1 - cx1 * 2 + cx2) * 0.03;
tmpy = (y1 - cy1 * 2 + cy2) * 0.03;
dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006;
dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006;
ddfx = tmpx * 2 + dddfx;
ddfy = tmpy * 2 + dddfy;
dfx = (cx1 - x1) * 0.3 + tmpx + dddfx * 0.16666667;
dfy = (cy1 - y1) * 0.3 + tmpy + dddfy * 0.16666667;
curveLength = Math.sqrt(dfx * dfx + dfy * dfy);
segments[0] = curveLength;
for (ii = 1; ii < 8; ii++) {
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
segments[ii] = curveLength;
}
dfx += ddfx;
dfy += ddfy;
curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
segments[8] = curveLength;
dfx += ddfx + dddfx;
dfy += ddfy + dddfy;
curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
segments[9] = curveLength;
segment = 0;
}
// Weight by segment length.
p *= curveLength;
for (;; segment++) {
const length = segments[segment];
if (p > length) {
continue;
}
if (segment === 0) {
p /= length;
} else {
const prev = segments[segment - 1];
p = segment + (p - prev) / (length - prev);
}
break;
}
this.addCurvePosition(p * 0.1, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || (i > 0 && space === 0));
}
return out;
}
/**
*
* @param {number} p
* @param {number[]} temp
* @param {number} i
* @param {number[]} out
* @param {number} o
*/
addBeforePosition(p, temp, i, out, o) {
const x1 = temp[i];
const y1 = temp[i + 1];
const dx = temp[i + 2] - x1;
const dy = temp[i + 3] - y1;
const r = Math.atan2(dy, dx);
out[o] = x1 + p * Math.cos(r);
out[o + 1] = y1 + p * Math.sin(r);
out[o + 2] = r;
}
/**
*
* @param {number} p
* @param {number[]} temp
* @param {number} i
* @param {number[]} out
* @param {number} o
*/
addAfterPosition(p, temp, i, out, o) {
const x1 = temp[i + 2];
const y1 = temp[i + 3];
const dx = x1 - temp[i];
const dy = y1 - temp[i + 1];
const r = Math.atan2(dy, dx);
out[o] = x1 + p * Math.cos(r);
out[o + 1] = y1 + p * Math.sin(r);
out[o + 2] = r;
}
/**
*
* @param {number} p
* @param {number} x1
* @param {number} y1
* @param {number} cx1
* @param {number} cy1
* @param {number} cx2
* @param {number} cy2
* @param {number} x2
* @param {number} y2
* @param {number} out
* @param {number} o
* @param {number} tangents
*/
addCurvePosition(p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents) {
if (p === 0 || isNaN(p)) {
p = 0.0001;
}
const tt = p * p;
const ttt = tt * p;
const u = 1 - p;
const uu = u * u;
const uuu = uu * u;
const ut = u * p;
const ut3 = ut * 3;
const uut3 = u * ut3;
const utt3 = ut3 * p;
const x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt;
const y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt;
out[o] = x;
out[o + 1] = y;
if (tangents) {
out[o + 2] = Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt));
}
}
} |
JavaScript | class Coinhe extends Driver {
/**
* @augments Driver.fetchTickers
* @returns {Promise.Array<Ticker>} Returns a promise of an array with tickers.
*/
async fetchTickers() {
const pairs = await request('https://api.coinhe.io/v1/market-summary');
return pairs.map((pair) => {
const [key] = Object.keys(pair);
// Warning: Coinhe inverts base and quote
const [quote, base] = key.split('_');
const ticker = pair[key];
return new Ticker({
base,
quote,
high: parseToFloat(ticker.high24h),
low: parseToFloat(ticker.low24h),
close: parseToFloat(ticker.LastPrice),
bid: parseToFloat(ticker.highestBid),
ask: parseToFloat(ticker.lowestAsk),
baseVolume: parseToFloat(ticker.quoteVolume24h),
quoteVolume: parseToFloat(ticker.baseVolume24h),
});
});
}
} |
JavaScript | class Transition {
/**
* @constructor function
*
* @params {Object, Class, Class, Class, Class, Object}
* @description Creates a new transition sequence.
* @params description
- options {Object} Transition options.
- element {HTMLElement} The element to set the transition on.
- properties {String / Array} A string or array of strings of CSS properties that are being transitioned.
- setStyles {Object} Styles to be set before / after the transition.
- before {Object} Object of CSS property / value pairs to be set before the transition.
- after {Object} Object of CSS property / value pairs to be set after the transition.
- addClass {Object} Object of classnames to be set before / after the transition.
- before {String} Classname to set before the transition.
- after {String} Classname to set after the transition.
- removeClass {Object} Object of classnames to be removed before / after the transition.
- before {String} Classname to be removed before the transition.
- after {String} Classname to be removed after the transition.
- DomUtils {Class} Dom utility class.
- Prefix {Class} Prefix class.
- CssUtils {Class} CSS Utilities class.
- Tracker {Object} Object that tracks and monitors sequences.
* @returns {Promise}
*/
constructor(options, DomUtils, Prefix, CssUtils, Tracker) {
this.options = options;
this.domUtils = new DomUtils();
this.prefix = new Prefix().getPrefix("transitionend");
this.cssUtils = new CssUtils();
this.onTransitionEnd = this.transitionEnd.bind(this);
this.totaltransitions = Array.isArray(options.properties) ? options.properties.length : 1;
this.transitionendCount = 0;
this.tracker = Tracker;
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.animationFrame = requestAnimationFrame(this.transitionStart.bind(this));
});
}
/**
* @transitionStart function
*
* @description Sets classnames / style rules to trigger the transition.
* @global no
*/
transitionStart() {
let opts = this.options;
opts.element.addEventListener(this.prefix, this.onTransitionEnd, false);
if(opts.setStyles && opts.setStyles.before) {
this.cssUtils.setStyles(opts.element, opts.setStyles.before);
}
if(opts.removeClass && opts.removeClass.before) {
this.domUtils.setClass(opts.element, opts.removeClass.before, false);
}
if(opts.addClass && opts.addClass.before) {
this.domUtils.setClass(opts.element, opts.addClass.before, true);
}
}
/**
* @transitionEnd function
*
* @description Sets classnames / style rules after all transitions have occurred and removes the element from the tracker.
* @global no
* @returns {Resolved Promise}
*/
transitionEnd(evt) {
evt.stopPropagation();
let opts = this.options;
this.transitionendCount++;
if(this.transitionendCount === this.totaltransitions) {
opts.element.removeEventListener(this.prefix, this.onTransitionEnd, false);
cancelAnimationFrame(this.animationFrame);
if(opts.setStyles && opts.setStyles.after) {
this.cssUtils.setStyles(opts.element, opts.setStyles.after);
}
if(opts.removeClass && opts.removeClass.after) {
this.domUtils.setClass(opts.element, opts.removeClass.after, false);
}
if(opts.addClass && opts.addClass.after) {
this.domUtils.setClass(opts.element, opts.addClass.after, true);
}
this.tracker.remove("Transitions", opts.element);
this.resolve(opts.element);
}
}
} |
JavaScript | class AppleAllOf {
/**
* Constructs a new <code>AppleAllOf</code>.
* @alias module:sunshine-conversations-client/sunshine-conversations-client.model/AppleAllOf
* @param businessId {String} Apple Business Chat ID.
* @param apiSecret {String} Your Apple API secret which is tied to your Messaging Service Provider.
* @param mspId {String} Your Messaging Service Provider ID.
*/
constructor(businessId, apiSecret, mspId) {
AppleAllOf.initialize(this, businessId, apiSecret, mspId);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, businessId, apiSecret, mspId) {
obj['businessId'] = businessId;
obj['apiSecret'] = apiSecret;
obj['mspId'] = mspId;
}
/**
* Constructs a <code>AppleAllOf</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:sunshine-conversations-client/sunshine-conversations-client.model/AppleAllOf} obj Optional instance to populate.
* @return {module:sunshine-conversations-client/sunshine-conversations-client.model/AppleAllOf} The populated <code>AppleAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new AppleAllOf();
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
}
if (data.hasOwnProperty('businessId')) {
obj['businessId'] = ApiClient.convertToType(data['businessId'], 'String');
}
if (data.hasOwnProperty('apiSecret')) {
obj['apiSecret'] = ApiClient.convertToType(data['apiSecret'], 'String');
}
if (data.hasOwnProperty('mspId')) {
obj['mspId'] = ApiClient.convertToType(data['mspId'], 'String');
}
}
return obj;
}
/**
* Returns To configure an Apple Business Chat integration, acquire the required information and call the Create Integration endpoint.
* @return {String}
*/
getType() {
return this.type;
}
/**
* Sets To configure an Apple Business Chat integration, acquire the required information and call the Create Integration endpoint.
* @param {String} type To configure an Apple Business Chat integration, acquire the required information and call the Create Integration endpoint.
*/
setType(type) {
this['type'] = type;
}
/**
* Returns Apple Business Chat ID.
* @return {String}
*/
getBusinessId() {
return this.businessId;
}
/**
* Sets Apple Business Chat ID.
* @param {String} businessId Apple Business Chat ID.
*/
setBusinessId(businessId) {
this['businessId'] = businessId;
}
/**
* Returns Your Apple API secret which is tied to your Messaging Service Provider.
* @return {String}
*/
getApiSecret() {
return this.apiSecret;
}
/**
* Sets Your Apple API secret which is tied to your Messaging Service Provider.
* @param {String} apiSecret Your Apple API secret which is tied to your Messaging Service Provider.
*/
setApiSecret(apiSecret) {
this['apiSecret'] = apiSecret;
}
/**
* Returns Your Messaging Service Provider ID.
* @return {String}
*/
getMspId() {
return this.mspId;
}
/**
* Sets Your Messaging Service Provider ID.
* @param {String} mspId Your Messaging Service Provider ID.
*/
setMspId(mspId) {
this['mspId'] = mspId;
}
} |
JavaScript | class AdminSingleCandy extends Component {
constructor(props) {
super(props);
this.handleRemove = this.handleRemove.bind(this);
}
handleRemove() {
this.props.removeCandy(this.props.candy.id);
}
render() {
const candy = this.props.candy;
return (
<div className="admin-single-candy-card">
<div>{`Name: ${candy.name}`}</div>
<div>{`Price: ${candy.price}`}</div>
<button onClick={this.handleRemove} className="admin-remove-btn btn">
Remove
</button>
<Link to={`/edit/${candy.id}`}>
<button className="admin-edit-btn btn">Edit</button>
</Link>
</div>
);
}
} |
JavaScript | class MP4Mixed extends Class {
/**
* Convert into mp4
* @param {string} src - Source file name
* @param {string} dest - Destination file name
* @param {string} options
* @returns {Promise<*>}
*/
async convertIntoMP4(src, dest, options = {}) {
const { preset = 'veryfast', videoCodec = 'libx264' } = options
assert(path.extname(dest), '.mp4')
return this.convert(src, dest, {
params: ['-y', '-f', 'mp4', '-c:v', videoCodec, '-preset', preset],
})
}
} |
JavaScript | class Component
{
show(display) {
throw new Error('Component.show is abstract');
}
setup(actions, display) {
throw new Error('Component.setup is abstract');
}
} |
JavaScript | class SysDatabase extends Component
{
constructor(name)
{
super();
this.name = name;
}
show(display)
{
display.sysDatabase(this.name);
}
setup(actions, display)
{
display.check(0, 'the database', this.name);
const body = new act.DatabaseProps(this).execute(actions.ctxt);
// if DB does not exist
if ( ! body ) {
display.remove(0, 'be created', 'outside', this.name);
}
}
} |
JavaScript | class Database extends Component
{
constructor(json, schema, security, triggers)
{
super();
this.id = json.id;
this.name = json.name;
this.properties = json.properties;
this.schema = schema === 'self' ? this : schema;
this.security = security === 'self' ? this : security;
this.triggers = triggers === 'self' ? this : triggers;
this.forests = {};
// extract the configured properties
this.props = props.database.parse(json);
// the forests
var forests = json.forests;
if ( forests === null || forests === undefined ) {
forests = 1;
}
if ( Number.isInteger(forests) ) {
if ( forests < 0 ) {
throw new Error('Negative number of forests (' + forests + ') on id:'
+ json.id + '|name:' + json.name);
}
if ( forests > 100 ) {
throw new Error('Number of forests greater than 100 (' + forests + ') on id:'
+ json.id + '|name:' + json.name);
}
// TODO: If several hosts, generate forests on each... !
var array = [];
for ( var i = 1; i <= forests; ++i ) {
var num = i.toLocaleString('en-IN', { minimumIntegerDigits: 3 });
array.push({name: json.name + '-' + num});
}
forests = array;
}
forests.forEach(f => {
if ( !f.name ) {
throw new Error('Pleaese verify your forest configuration! Name property is missing');
}
this.forests[f.name] = new Forest(this, f);
});
}
show(display)
{
display.database(
this.name,
this.id,
this.schema,
this.security,
this.triggers,
Object.keys(this.forests).sort(),
this.props);
}
setup(actions, display)
{
display.check(0, 'the database', this.name);
const body = new act.DatabaseProps(this).execute(actions.ctxt);
const forests = new act.ForestList().execute(actions.ctxt);
const items = forests['forest-default-list']['list-items']['list-item'];
const names = items.map(o => o.nameref);
// if DB does not exist yet
if ( ! body ) {
this.create(actions, display, names);
}
// if DB already exists
else {
this.update(actions, display, body, names);
}
}
create(actions, display, forests)
{
display.add(0, 'create', 'database', this.name);
// the base database object
var obj = {
"database-name": this.name
};
// its schema, security and triggers DB
this.schema && ( obj['schema-database'] = this.schema.name );
this.security && ( obj['security-database'] = this.security.name );
this.triggers && ( obj['triggers-database'] = this.triggers.name );
// its properties
Object.keys(this.props).forEach(p => {
this.props[p].create(obj);
});
if ( this.properties ) {
Object.keys(this.properties).forEach(p => {
if ( obj[p] ) {
throw new Error('Explicit property already set on database: name='
+ this.name + ',id=' + this.id + ' - ' + p);
}
obj[p] = this.properties[p];
});
}
// enqueue the "create db" action
actions.add(new act.DatabaseCreate(this, obj));
display.check(1, 'forests');
// check the forests
Object.keys(this.forests).forEach(f => {
this.forests[f].create(actions, display, forests);
});
}
update(actions, display, body, forests)
{
// check databases
this.updateDb(actions, display, this.schema, body, 'schema-database', 'Schemas');
this.updateDb(actions, display, this.security, body, 'security-database', 'Security');
this.updateDb(actions, display, this.triggers, body, 'triggers-database', null);
// check forests
display.check(1, 'forests');
var actual = body.forest || [];
var desired = Object.keys(this.forests);
// forests to remove: those in `actual` but not in `desired`
actual
.filter(name => ! desired.includes(name))
.forEach(name => {
new Forest(this, name).remove(actions, display);
});
// forests to add: those in `desired` but not in `actual`
desired
.filter(name => ! actual.includes(name))
.forEach(name => {
this.forests[name].create(actions, display, forests);
});
// check properties
display.check(1, 'properties');
Object.keys(this.props).forEach(p => {
let res = this.props[p];
// TODO: Rather fix the "_type" setting mechanism, AKA the "root cause"...
if ( ! res.prop._type ) {
res.prop._type = 'database';
}
res.update(actions, display, body, this);
});
if ( this.properties ) {
Object.keys(this.properties).forEach(p => {
if ( this.properties[p] !== body[p] ) {
actions.add(new act.DatabaseUpdate(this, p, this.properties[p]));
}
});
}
}
updateDb(actions, display, db, body, prop, dflt)
{
var actual = body[prop];
var newName;
// do not exist, not desired
if ( ! actual && ! db || (actual === dflt && ! db) ) {
// nothing
}
// does exist, to remove
else if ( ! db ) {
newName = dflt || null;
}
// do not exist, to create, or does exist, to chamge
else if ( ! actual || (actual !== db.name) ) {
newName = db.name;
}
// already set to the right db
else {
// nothing
}
// enqueue the action if necessary
if ( newName !== undefined ) {
display.add(0, 'update', prop);
actions.add(new act.DatabaseUpdate(this, prop, newName));
}
}
} |
JavaScript | class Forest extends Component
{
constructor(db, forestData)
{
super();
this.db = db;
Object.keys(forestData).forEach(p => { this[p] = forestData[p] });
}
create(actions, display, forests)
{
// if already exists, attach it instead of creating it
if ( forests.includes(this.name) ) {
display.add(1, 'attach', 'forest', this.name);
actions.add(new act.ForestAttach(this));
}
else {
display.add(1, 'create', 'forest', this.name);
actions.add(new act.ForestCreate(this));
}
}
remove(actions, display)
{
display.remove(1, 'detach', 'forest', this.name);
// just detach it, not delete it for real
actions.add(new act.ForestDetach(this));
}
} |
JavaScript | class Server extends Component
{
constructor(json, content, modules, src, platform)
{
super();
this.type = json.type;
this.group = json.group || 'Default';
this.id = json.id;
this.name = json.name;
this.properties = json.properties;
this.content = content;
this.modules = modules;
// extract the configured properties
this.props = props.server.parse(json);
// some validation
const error = msg => {
throw new Error(msg + ': ' + this.type + ' - ' + this.id + '/' + this.name);
};
if ( ! content ) {
error('App server with no content database');
}
// validation specific to REST servers
if ( json.type === 'rest' ) {
this.rest = json['rest-config'];
if ( ! modules ) {
error('REST server has no modules database');
}
if ( json.root ) {
error('REST server has root (' + json.root + ')');
}
if ( json.rewriter ) {
error('REST server has rewriter (' + json.rewriter + ')');
}
if ( json.properties && json.properties['rewrite-resolves-globally'] ) {
error('REST server has rewrite-resolves-globally ('
+ json.properties['rewrite-resolves-globally'] + ')');
}
}
// for plain HTTP servers
else {
if ( json['rest-config'] ) {
error('REST config on a non-REST server');
}
// use a source set as filesystem modules if no modules DB and no root
if ( ! this.modules && ! this.props.root ) {
// TODO: For now, only try the default `src`. Once
// implmented the links from databses and servers to source
// sets, check if there is one on this server then.
if ( ! src ) {
throw new Error(
'The app server has no modules db, no root, and there is no default src: ',
this.name);
}
if ( ! src.props.dir ) {
throw new Error(
'The app server has no modules db, no root, and default src has no dir: ',
this.name);
}
var dir = platform.resolve(src.props.dir.value) + '/';
this.props.root = new props.Result(props.server.props.root, dir);
}
}
}
show(display)
{
display.server(
this.name,
this.id,
this.type,
this.group,
this.content,
this.modules,
this.props);
}
setup(actions, display)
{
display.check(0, 'the ' + this.type + ' server', this.name);
const body = new act.ServerProps(this).execute(actions.ctxt);
// if AS does not exist yet
if ( ! body ) {
if ( this.type === 'http' ) {
this.createHttp(actions, display);
}
else if ( this.type === 'xdbc' ) {
this.createHttp(actions, display);
}
else if ( this.type === 'rest' ) {
this.createRest(actions, display);
}
else {
throw new Error('Unknown app server type: ' + this.type);
}
}
// if AS already exists
else {
if ( this.type === 'rest' ) {
this.updateRest(actions, display, body);
}
this.updateHttp(actions, display, body);
}
}
createAddProps(obj)
{
Object.keys(this.props).forEach(p => {
this.props[p].create(obj);
});
if ( this.properties ) {
Object.keys(this.properties).forEach(p => {
if ( obj[p] ) {
throw new Error('Explicit property already set on server: name='
+ this.name + ',id=' + this.id + ' - ' + p);
}
obj[p] = this.properties[p];
});
}
}
createHttp(actions, display)
{
display.add(0, 'create', this.type + ' server', this.name);
// the base server object
var obj = {
"server-name": this.name,
"server-type": this.type,
"content-database": this.content.name
};
// its modules DB
this.modules && ( obj['modules-database'] = this.modules.name );
// its properties
this.createAddProps(obj);
// enqueue the "create server" action
actions.add(new act.ServerCreate(this, obj));
}
createRest(actions, display)
{
display.add(0, 'create', 'rest server', this.name);
let obj = {
"name": this.name,
"group": this.group,
"database": this.content.name,
"modules-database": this.modules.name
};
this.props.port.create(obj);
if ( this.rest ) {
if ( this.rest['error-format'] ) {
obj['error-format'] = this.rest['error-format'];
}
if ( this.rest['xdbc'] ) {
obj['xdbc-enabled'] = this.rest['xdbc'];
}
}
// enqueue the "create rest server" action
actions.add(new act.ServerRestCreate(this, { "rest-api": obj }));
// its other properties
let extra = {};
this.createAddProps(extra);
// port is handled at creation
delete extra['port'];
delete extra['server-type'];
if ( Object.keys(extra).length ) {
// enqueue the "update server" action
actions.add(new act.ServerUpdate(this, extra));
}
if ( this.rest ) {
let keys = Object.keys(this.rest).filter(k => {
return k !== 'error-format' && k !== 'xdbc' && k !== 'ssl';
});
if ( keys.length ) {
const map = {
"debug": 'debug',
"tranform-all": 'document-transform-all',
"tranform-out": 'document-transform-out',
"update-policy": 'update-policy',
"validate-options": 'validate-options',
"validate-queries": 'validate-queries'
};
let props = {};
keys.forEach(k => {
let p = map[k];
if ( ! p ) {
throw new Error('Unknown property on server.rest: ' + k);
}
props[p] = this.rest[k];
});
// enqueue the "update rest server props" action
actions.add(new act.ServerRestUpdate(this, props, this.props.port.value, this.rest.ssl));
}
}
}
// TODO: It should not be hard to make it possible to add more and more
// property/value pairs to the server update action, and send them all
// in one request. That would have an impact on displaying the action
// though, as we would probably want to keep multiple lines for multiple
// properties, as it is clearer.
//
// This is actually required for scenarii where on property depends on
// another, like path range index on path namespaces...
//
updateHttp(actions, display, actual)
{
let type = this.type === 'rest' ? 'http' : this.type;
if ( type !== actual['server-type'] ) {
throw new Error('Server type cannot change, from '
+ actual['server-type'] + ' to ' + this.type);
}
// the content and modules databases
if ( this.content.name !== actual['content-database'] ) {
display.add(0, 'update', 'content-database');
actions.add(new act.ServerUpdate(this, 'content-database', this.content.name));
}
if ( ( ! this.modules && actual['modules-database'] )
|| ( this.modules && ! actual['modules-database'] )
|| ( this.modules && this.modules.name !== actual['modules-database'] ) ) {
var mods = this.modules ? this.modules.name : 0;
display.add(0, 'update', 'modules-database');
actions.add(new act.ServerUpdate(this, 'modules-database', mods));
}
// check properties
display.check(1, 'properties');
Object.keys(this.props)
.filter(p => p !== 'server-type')
.forEach(p => {
this.props[p].update(actions, display, actual, this);
});
if ( this.properties ) {
Object.keys(this.properties).forEach(p => {
if ( this.properties[p] !== actual[p] ) {
actions.add(new act.ServerUpdate(this, p, this.properties[p]));
}
});
}
}
/*~
* For a REST server, check REST-specific config items (its "creation
* properties", the values passed to the endpoint when creating the REST
* server), like `xdbc-enabled`. These properties are to be retrieved
* from `:8002/v1/rest-apis/[name]`.
*
* There seems to be no way to change the value of such a creation
* property (they are used at creation only).
*
* In addition, there are properties specific to REST servers (not for
* HTTP), like `debug` and `update-policy`. These properties are to be
* retrieved from `:[port]/v1/config/properties`.
*
* 1) retrieve creation properties, if anything differs, -> error
* 2) retrieve properties, and update them, as for any component
*/
updateRest(actions, display, actual)
{
// 1) check creation properties for any difference
const check = (name, old, current) => {
if ( old !== current ) {
throw new Error('Cannot update REST server ' + name + ', from ' + old + ' to ' + current);
}
};
const bool = val => {
var type = typeof val;
if ( 'boolean' === type ) {
return val;
}
else if ( 'string' === type ) {
if ( 'false' === val ) {
return false;
}
else if ( 'true' === val ) {
return true;
}
else {
throw new Error('Invalid boolean value: ' + val);
}
}
else {
throw new Error('Boolean value neither a string or a boolean: ' + type);
}
};
const cprops = new act.ServerRestCreationProps(this).execute(actions.ctxt);
check('name', cprops.name, this.name);
check('group', cprops.group, this.group);
check('database', cprops.database, this.content && this.content.name);
check('modules-database', cprops['modules-database'], this.modules && this.modules.name);
check('port', parseInt(cprops.port, 10), this.props.port && this.props.port.value);
check('error-format', cprops['error-format'], this.rest && this.rest['error-format']);
check('xdbc-enabled', bool(cprops['xdbc-enabled']), bool(this.rest && this.rest.xdbc));
// 2) update all properties with different value
let obj = {};
const update = (name, old, current, dflt) => {
if ( old !== (current === undefined ? dflt : current) ) {
obj[name] = current;
}
};
const props = new act.ServerRestProps(this, this.props.port.value, this.rest.ssl).execute(actions.ctxt);
update('debug', bool(props['debug']), this.rest && this.rest['debug'], false);
update('document-transform-all', bool(props['document-transform-all']), this.rest && this.rest['transform-all'], true);
update('document-transform-out', props['document-transform-out'], this.rest && this.rest['transform-out'] || '', '');
update('update-policy', props['update-policy'], this.rest && this.rest['update-policy'], 'merge-metadata');
update('validate-options', bool(props['validate-options']), this.rest && this.rest['validate-options'], true);
update('validate-queries', bool(props['validate-queries']), this.rest && this.rest['validate-queries'], false);
if ( Object.keys(obj).length ) {
actions.add(new act.ServerRestUpdate(this, obj, this.props.port.value,this.rest.ssl));
}
}
} |
JavaScript | class SourceSet extends Component
{
constructor(json, environ, dflt)
{
super();
this.dflt = dflt;
this.name = json && json.name;
this.filter = json && json.filter;
// extract the configured properties
this.props = json ? props.source.parse(json) : {};
this.type = this.props.type && this.props.type.value;
// resolve targets (dbs and srvs)
// TODO: Provide the other way around, `source` on dbs and srvs?
this.targets = [];
this.environ = environ;
if ( this.props.target ) {
if ( ! environ ) {
const msg = 'Source set has target(s) but no environ provided for resolving: ';
throw new Error(msg + this.name);
}
this.props.target.value.forEach(t => {
this.targets.push(environ.database(t) || environ.server(t));
});
}
}
restTarget()
{
if ( this.type === 'rest-src' ) {
let rests = this.targets.filter(t => {
return t instanceof Server && t.type === 'rest';
});
if ( ! rests.length ) {
rests = this.environ.servers().filter(s => s.type === 'rest');
}
if ( rests.length > 1 ) {
throw new Error('More than one REST servers for resolving the REST source set '
+ this.name + ': ' + rests.map(s => s.id + '/' + s.name));
}
if ( ! rests.length ) {
throw new Error('No REST server for resolving the REST source set: ' + this.name);
}
return rests[0];
}
}
show(display)
{
// TODO: What about this.dflt...?
display.source(
this.name,
this.props);
}
prop(name)
{
let v = this.props[name];
if ( ! v && this.dflt ) {
v = this.dflt.props[name];
}
if ( v ) {
return v.value;
}
if ( name === 'garbage' ) {
return [ 'TODO: Set the default default garbage value...', '*~' ];
}
}
// TODO: Resolve the `db` here, to take targets into account? Or at least
// take them into account where `db` is resolved (in LoadCommand...)
//
load(actions, db, srv, display)
{
let meta = { body: {} };
this.props.collection && this.props.collection.create(meta.body);
// TODO: Not the same structure for the Client API than for the
// Management API (permissions vs. permission, etc.)
//this.props.permission && this.props.permission.create(meta.body);
if ( this.props.permission ) {
meta.body.permissions = [];
this.props.permission.value.forEach(p => {
let role = p['role-name'].value;
let cap = p.capability.value;
let perm = meta.body.permissions.find(p => p['role-name'] === role);
if ( ! perm ) {
perm = { "role-name": role, capabilities: [] };
meta.body.permissions.push(perm);
}
perm.capabilities.push(cap);
});
}
let matches = [ meta ];
matches.count = 0;
matches.flush = function() {
if ( this.count ) {
actions.add(
new act.MultiDocInsert(db, this));
// empty the array
this.splice(0);
this.push(meta);
this.count = 0;
}
};
matches.add = function(item) {
this.push(item);
++ this.count;
if ( this.count >= INSERT_LENGTH ) {
this.flush();
}
};
if ( ! this.type || this.type === 'plain' ) {
this.loadPlain(actions.ctxt, display, matches);
}
else if ( this.type === 'rest-src' ) {
const port = (srv || this.restTarget()).props.port.value;
const ssl = ( srv || this.restTarget()).rest.ssl;
this.loadRestSrc(actions, db, port, display, matches, ssl);
}
else {
throw new Error('Unknown source set type: ' + this.type);
}
}
loadRestSrc(actions, db, port, display, matches, ssl)
{
const pf = actions.ctxt.platform;
const dir = this.prop('dir');
// check there is nothing outside of `root/`, `services/` and `transforms/`
const children = pf.dirChildren(dir);
let count = 0;
const filter = (name) => {
let match = children.find(c => c.name === name);
if ( ! match ) {
// nothing
}
else if ( ! match.isdir ) {
throw new Error('REST source child not a dir: ' + name);
}
else {
++ count;
}
};
filter('root');
filter('services');
filter('transforms');
if ( count !== children.length ) {
let unknown = children.map(c => c.name).filter(n => {
return n !== 'root' && n !== 'services' && n !== 'transforms';
});
throw new Error('Unknown children in REST source: ' + unknown);
}
// deploy `root/*`
const root = dir + '/root';
if ( pf.exists(root) ) {
this.loadPlain(actions.ctxt, display, matches, root);
}
else if ( display.verbose ) {
display.check(0, 'dir, not exist', root);
}
// install `services/*`
const services = dir + '/services';
if ( pf.exists(services) ) {
this.walk(actions.ctxt, display, (path, uri) => {
actions.add(
this.installRestThing(port, 'resources', uri.slice(1), path, ssl));
}, services);
}
else if ( display.verbose ) {
display.check(0, 'dir, not exist', services);
}
// install `transforms/*`
const transforms = dir + '/transforms';
if ( pf.exists(transforms) ) {
this.walk(actions.ctxt, display, (path, uri) => {
actions.add(
this.installRestThing(port, 'transforms', uri.slice(1), path, ssl));
}, transforms);
}
else if ( display.verbose ) {
display.check(0, 'dir, not exist', transforms);
}
}
installRestThing(port, kind, filename, path, ssl)
{
// extract mime type from extension
const type = (ext) => {
if ( ext === 'xqy' ) {
return 'application/xquery';
}
else if ( ext === 'sjs' ) {
return 'application/javascript';
}
else {
throw new Error('Extension is neither xqy or sjs: ' + ext);
}
};
// the basename and extension
let [ name, ext ] = filename.split('.');
// return the actual action
return new act.ServerRestDeploy(kind, name, path, type(ext), port, ssl);
}
loadPlain(ctxt, display, matches, dir)
{
this.walk(ctxt, display, (path, uri, meta) => {
if ( meta ) {
// metadata, if any, must be before the doc content
matches.push({ uri: uri, body: meta });
}
matches.add({ uri: uri, path: path });
}, dir);
matches.flush();
}
walk(ctxt, display, onMatch, dir)
{
// from one array of strings, return two arrays:
// - first one with all strings ending with '/', removed
// - second one with all strings not ending with '/'
const dirNotDir = pats => {
let dir = [];
let notdir = [];
if ( pats ) {
pats.forEach(p => {
if ( p.endsWith('/') ) {
dir.push(p.slice(0, -1));
}
else {
notdir.push(p);
}
});
}
return [ dir, notdir ];
};
const options = { matchBase: true, dot: true, nocomment: true };
const compile = name => {
let pats = this.prop(name);
let res = dirNotDir(pats);
patterns.dir[name] = res[0];
patterns.dir['mm_' + name] = res[0].map(p => new match.Minimatch(p, options));
patterns.notdir[name] = res[1];
patterns.notdir['mm_' + name] = res[1].map(p => new match.Minimatch(p, options));
};
// Both `dir` and `notdir` are pupolated with the following properties:
//
// include: [...], mm_include: [...],
// exclude: [...], mm_exclude: [...],
// garbage: [...], mm_garbage: [...]
//
// Properties `include`, `exclude` and `garbage` contain the original
// string patterns, the corresponding `mm_*` are the minimatch compiled
// patterns.
let patterns = {
dir : {},
notdir : {}
};
compile('include');
compile('exclude');
compile('garbage');
const _dir = dir || this.prop('dir');
const path = ctxt.platform.resolve(_dir);
this.walkDir(onMatch, '', _dir, path, path, patterns, ctxt, display);
}
walkDir(onMatch, path, dir, full, base, patterns, ctxt, display)
{
const pf = ctxt.platform;
const match = (path, compiled, ifNone, msg) => {
if ( ! compiled.length ) {
return ifNone;
}
for ( let i = 0; i < compiled.length; ++i ) {
let c = compiled[i];
if ( c.match(path) ) {
if ( ctxt.verbose ) {
pf.warn('[' + pf.bold('verbose') + '] ' + msg
+ ' ' + path + ', matching ' + c.pattern);
}
return true;
}
}
return false;
};
display.check(0, 'the directory', dir);
pf.dirChildren(full).forEach(child => {
let p = path + '/' + child.name;
let pats = child.isdir ? patterns.dir : patterns.notdir;
if ( ! match(p, pats.mm_garbage, false, 'Throwing') ) {
let desc = {
base : base,
path : p,
full : child.path,
name : child.name,
isdir : child.isdir,
isIncluded : match(p, pats.mm_include, true, 'Including'),
isExcluded : match(p, pats.mm_exclude, false, 'Excluding'),
include : pats.include,
exclude : pats.exclude,
collections : this.props.collection && this.props.collection.value.slice(),
mm_include : pats.mm_include,
mm_exclude : pats.mm_exclude
};
let resp = this.doFilter(desc);
if ( resp ) {
if ( child.isdir ) {
let d = dir + '/' + child.name;
this.walkDir(onMatch, p, d, desc.full, base, patterns, ctxt, display);
}
else {
let uri = resp.uri || resp.path;
if ( ! uri ) {
throw new Error('Impossible to compute URI for ' + resp);
}
let full = resp.full || resp.path && (base + resp.path);
// TODO: Support resp.content as well...
if ( ! full ) {
throw new Error('Impossible to compute full path for ' + resp);
}
let overrideColls = false;
// is `collections` set, and different than the default array?
if ( resp.collections ) {
let dfltColls = this.props.collection
? this.props.collection.value.sort()
: [];
let respColls = resp.collections.sort();
if ( dfltColls.length !== respColls.length ) {
overrideColls = true;
}
for ( let i = 0; ! overrideColls && i < respColls.length; ++ i ) {
if ( dfltColls[i] !== respColls[i] ) {
overrideColls = true;
}
}
}
if ( overrideColls ) {
onMatch(full, uri, { collections: resp.collections });
}
else {
onMatch(full, uri);
}
}
}
}
});
}
doFilter(desc) {
if ( this.filter ) {
return this.filter(desc);
}
else if ( desc.isIncluded && ! desc.isExcluded ) {
return desc;
}
}
} |
JavaScript | class SourceDir extends SourceSet
{
constructor(dir)
{
super({ dir : dir });
}
} |
JavaScript | class SourceDoc extends SourceSet
{
constructor(doc)
{
super();
this.doc = doc;
}
load(actions, db, srv, display)
{
display.check(0, 'the file', this.doc);
actions.add(
new act.DocInsert(db, this.uri(null, this.doc), this.doc));
}
uri(dir, path) {
let idx = path.indexOf('/');
if ( idx < 0 ) {
throw new Error('Path in `load doc` must contain at least 1 parent dir');
}
return path.slice(idx);
}
} |
JavaScript | class Host extends Component
{
constructor(json)
{
super();
this.name = json.name;
this.apis = json.apis;
// extract the configured properties
this.props = props.host.parse(json);
}
init(actions, user, pwd, key, licensee)
{
let host = this.props.host && this.props.host.value;
Host.init(actions, user, pwd, key, licensee, host);
}
join(actions, key, licensee, master)
{
let host = this.props.host.value;
let ctxt = actions.ctxt;
let admin = this.apis && this.apis.admin;
// /init
actions.add(new act.AdminInit(key, licensee, host, admin));
// joining sequence
actions.add(new act.FunAction('Join cluster', () => {
// /server-config
let config = new act.ServerConfig(host, admin).execute(ctxt);
// /cluster-config
let group = this.props.group && this.props.group.value;
let cluster = new act.ClusterConfig(config, group).execute(ctxt);
// /cluster-config
new act.ClusterConfigZip(cluster, host, admin).execute(ctxt);
}));
}
} |
JavaScript | class MimeType extends Component
{
constructor(json)
{
super();
this.name = json.name;
// extract the configured properties
this.props = props.mime.parse(json);
}
show(display)
{
display.mimetype(
this.name,
this.props);
}
setup(actions, display)
{
display.check(0, 'the mime type', this.name);
const body = new act.MimeProps(this).execute(actions.ctxt);
// if mime does not exist yet
if ( ! body ) {
this.create(actions, display);
}
// if mime already exists
else {
this.update(actions, display, body);
}
}
create(actions, display)
{
display.add(0, 'create', 'mime', this.name);
var obj = {
"name": this.name
};
Object.keys(this.props).forEach(p => {
this.props[p].create(obj);
});
actions.add(new act.MimeCreate(this, obj));
}
update(actions, display, actual)
{
// check properties
display.check(1, 'properties');
Object.keys(this.props).forEach(p => {
this.props[p].update(actions, display, actual, this);
});
}
} |
JavaScript | class Role extends Component
{
constructor(json, ctxt)
{
super();
// extract the configured properties
this.props = props.role.parse(json, null, ctxt);
// TODO: To handle in properties.js...
// TODO: Value should be a StringList, not necessarily an array...
let priv = json.privileges || {};
this.execpriv = priv.execute || [];
this.uripriv = priv.uri || [];
}
show(display)
{
display.role(this.props);
}
setup(actions, display)
{
display.check(0, 'the role', this.props['role-name'].value);
const body = new act.RoleProps(this).execute(actions.ctxt);
// if role does not exist yet
if ( ! body ) {
this.create(actions, display);
}
// if role already exists
else {
this.update(actions, display, body);
}
}
create(actions, display)
{
display.add(0, 'create', 'role', this.props['role-name'].value);
var obj = {};
Object.keys(this.props).forEach(p => {
this.props[p].create(obj);
});
actions.add(new act.RoleCreate(this, obj));
}
update(actions, display, actual)
{
// check properties
display.check(1, 'properties');
Object.keys(this.props).forEach(p => {
this.props[p].update(actions, display, actual, this);
});
}
} |
JavaScript | class User extends Component
{
constructor(json)
{
super();
// extract the configured properties
this.props = props.user.parse(json);
}
show(display)
{
display.user(this.props);
}
setup(actions, display)
{
display.check(0, 'the user', this.props['user-name'].value);
const body = new act.UserProps(this).execute(actions.ctxt);
// if user does not exist yet
if ( ! body ) {
this.create(actions, display);
}
// if user already exists
else {
this.update(actions, display, body);
}
}
create(actions, display)
{
display.add(0, 'create', 'user', this.props['user-name'].value);
var obj = {};
Object.keys(this.props).forEach(p => {
this.props[p].create(obj);
});
actions.add(new act.UserCreate(this, obj));
}
update(actions, display, actual)
{
// check properties
display.check(1, 'properties');
Object.keys(this.props).forEach(p => {
this.props[p].update(actions, display, actual, this);
});
}
} |
JavaScript | class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
};
}
/**
* routes the user and admin to their dashboard url path
* and calls the getRequest action dispatcher to fetch the
* appropriate requests.
*/
componentDidMount = () => {
const { getRequests, history, user } = this.props;
if (user.role !== 'admin') {
history.push('/dashboard');
}
if (user.role === 'admin') {
history.push('/admin');
}
getRequests();
}
/**
* Toggles the modal state to open
*/
showModal = () => {
this.setState({
show: true,
});
};
/**
* Toggles the modal state to closed
*/
hideModal = () => {
this.setState({
show: false,
});
};
/**
* Renders the Dashboard component on a node in the DOM
*/
render() {
const { show } = this.state;
const {
loading, requests, user, message,
} = this.props;
return (
<React.Fragment>
<Modal
isOpen={show}
handleClose={this.hideModal}
ariaHideApp={false}
overlayClassName="modal-overlay"
className="modal-content"
>
<NewRequest
handleClose={this.hideModal}
handleSubmit={this.handleSubmit}
/>
</Modal>
<Navbar profileIconVisibility="" />
<div className="body" style={{ backgroundImage: `url(${spannerScrewdriver})` }}>
<div className="wrapper">
<div className="left white">
<span id="username">Welcome, {user.firstName}</span>
</div>
<div className="right white">
{ user.role !== 'admin' ? (
<span>
<Input
id="new-request-btn"
className="button"
type="button"
name="new-request"
value="New Request"
handleClick={this.showModal}
/>
</span>)
: false }
</div>
<br />
<br />
{requests ? (
<RequestTable
requests={requests}
message={message}
/>)
: (
<div
className="wrapper white"
>
<p>You have no requests at the moment.
Do you have anything that needs fixing?
We love to fix stuff.
</p>
</div>
)
}
</div>
<br />
<div className="divider" />
</div>
{loading ? <Loader /> : false}
</React.Fragment>
);
}
} |
JavaScript | class WebVRManager extends EventEmitter {
/**
* Construct a new WebVRManager
*/
constructor() {
super();
this.state = State.PREPARING;
// Bind vr display present change event to __onVRDisplayPresentChange
this.__onVRDisplayPresentChange = this.__onVRDisplayPresentChange.bind(this);
window.addEventListener('vrdisplaypresentchange', this.__onVRDisplayPresentChange);
this.__onChangeFullscreen = this.__onChangeFullscreen.bind(this);
if (screenfull.enabled) {
document.addEventListener(screenfull.raw.fullscreenchange, this.__onChangeFullscreen);
}
}
/**
* Check if the browser is compatible with WebVR and has headsets.
* @return {Promise<VRDisplay>}
*/
checkDisplays() {
return WebVRManager.getVRDisplay()
.then((display) => {
this.defaultDisplay = display;
this.__setState(State.READY_TO_PRESENT);
return display;
})
.catch((e) => {
delete this.defaultDisplay;
if (e.name == 'NO_DISPLAYS') {
this.__setState(State.ERROR_NO_PRESENTABLE_DISPLAYS);
} else if (e.name == 'WEBVR_UNSUPPORTED') {
this.__setState(State.ERROR_BROWSER_NOT_SUPPORTED);
} else {
this.__setState(State.ERROR_UNKOWN);
}
});
}
/**
* clean up object for garbage collection
*/
remove() {
window.removeEventListener('vrdisplaypresentchange', this.__onVRDisplayPresentChange);
if (screenfull.enabled) {
document.removeEventListener(screenfull.raw.fullscreenchanged, this.__onChangeFullscreen);
}
this.removeAllListeners();
}
/**
* returns promise returning list of available VR displays.
* @return {Promise<VRDisplay>}
*/
static getVRDisplay() {
return new Promise((resolve, reject) => {
if (!navigator || !navigator.getVRDisplays) {
let e = new Error('Browser not supporting WebVR');
e.name = 'WEBVR_UNSUPPORTED';
reject(e);
return;
}
const rejectNoDisplay = ()=> {
// No displays are found.
let e = new Error('No displays found');
e.name = 'NO_DISPLAYS';
reject(e);
};
navigator.getVRDisplays().then(
function(displays) {
// Promise succeeds, but check if there are any displays actually.
for (let i = 0; i < displays.length; i++) {
if (displays[i].capabilities.canPresent) {
resolve(displays[i]);
break;
}
}
rejectNoDisplay();
},
rejectNoDisplay);
});
}
/**
* Enter presentation mode with your set VR display
* @param {VRDisplay} display the display to request present on
* @param {HTMLCanvasElement} canvas
* @return {Promise.<TResult>}
*/
enterVR(display, canvas) {
this.presentedSource = canvas;
return display.requestPresent([{
source: canvas,
}])
.then(
()=> {},
// this could fail if:
// 1. Display `canPresent` is false
// 2. Canvas is invalid
// 3. not executed via user interaction
()=> this.__setState(State.ERROR_REQUEST_TO_PRESENT_REJECTED)
);
}
/**
* Exit presentation mode on display
* @param {VRDisplay} display
* @return {Promise.<TResult>}
*/
exitVR(display) {
return display.exitPresent()
.then(
()=> {
this.presentedSource = undefined;
},
// this could fail if:
// 1. exit requested while not currently presenting
()=> this.__setState(State.ERROR_EXIT_PRESENT_REJECTED)
);
}
/**
* Enter fullscreen mode
* @param {HTMLCanvasElement} canvas
* @return {boolean}
*/
enterFullscreen(canvas) {
if (screenfull.enabled) {
screenfull.request(canvas);
} else {
// iOS
this.__setState(State.PRESENTING_FULLSCREEN);
}
return true;
}
/**
* Exit fullscreen mode
* @return {boolean}
*/
exitFullscreen() {
if (screenfull.enabled && screenfull.isFullscreen) {
screenfull.exit();
} else if (this.state == State.PRESENTING_FULLSCREEN) {
this.checkDisplays();
}
return true;
}
/**
* Change the state of the manager
* @param {State} state
* @private
*/
__setState(state) {
if (state != this.state) {
this.emit('change', state, this.state);
this.state = state;
}
}
/**
* Triggered on fullscreen change event
* @param {Event} e
* @private
*/
__onChangeFullscreen(e) {
if (screenfull.isFullscreen) {
if(this.state != State.PRESENTING) {
this.__setState(State.PRESENTING_FULLSCREEN);
}
} else {
this.checkDisplays();
}
}
/**
* Triggered on vr present change
* @param {Event} event
* @private
*/
__onVRDisplayPresentChange(event) {
try {
let display;
if(event.display) {
// In chrome its supplied on the event
display = event.display;
} else if(event.detail && event.detail.display) {
// Polyfill stores display under detail
display = event.detail.display;
}
if(display && display.isPresenting && display.getLayers()[0].source !== this.presentedSource) {
// this means a different instance of WebVRManager has requested to present
return;
}
const isPresenting = this.defaultDisplay && this.defaultDisplay.isPresenting;
this.__setState(isPresenting ? State.PRESENTING : State.READY_TO_PRESENT);
} catch(err) {
// continue regardless of error
}
}
} |
JavaScript | class ChannelUserRelationSingleFormatter extends BaseFormatter {
/**
* Constructor for current user channel relation formatter.
*
* @param {object} params
* @param {object} params.channelUserRelation
* @param {number} params.channelUserRelation.id
* @param {number} params.channelUserRelation.isAdmin
* @param {number} params.channelUserRelation.isMember
* @param {number} params.channelUserRelation.updatedAt
*
* @augments BaseFormatter
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.channelUserRelation = params.channelUserRelation;
}
/**
* Validate the input objects.
*
* @returns {result}
* @private
*/
_validate() {
const oThis = this;
const entityConfig = {
id: { isNullAllowed: false },
isAdmin: { isNullAllowed: false },
isMember: { isNullAllowed: false },
updatedAt: { isNullAllowed: false }
};
return oThis.validateParameters(oThis.channelUserRelation, entityConfig);
}
/**
* Format the input object.
*
* @returns {object}
* @private
*/
_format() {
const oThis = this;
return responseHelper.successWithData({
id: oThis.channelUserRelation.id,
is_admin: Number(oThis.channelUserRelation.isAdmin),
is_member: Number(oThis.channelUserRelation.isMember),
uts: oThis.channelUserRelation.updatedAt
});
}
} |
JavaScript | class Spreadsheet {
/**
* Create a new spreadsheet.
* @param {string} key Your Google API key.
* @param {string} hash Your Spreadsheet hash.
*/
constructor(hash, key = 'GOOGLE_API_KEY') {
this.key = key;
this.hash = hash;
this.ready = false;
this.title = null;
this.locale = null;
this.sheets = [];
this.timeZone = null;
this.__cache = new Map();
this.__parsing = new Promise((resolve, reject) => {
fetch(`https://sheets.googleapis.com/v4/spreadsheets/${this.hash}?key=${this.key}`)
.then((response) => {
if (response.ok) {
response.json().then(this.__parse.bind(this, resolve));
} else {
reject(response);
}
})
.catch(reject);
});
}
/**
* Wait for the current long pending task to finish.
* @return {Promise} The promise that resolves when the Spreadsheet is done loading.
*/
wait() {
return this.__parsing;
}
/**
* Load a sheet from the spreadsheet.
* @param {string} name The name of the sheet to request (if left empty, the first sheet is taken).
* @return {Promise} [description]
*/
sheet(name = this.sheets[0]) {
if (this.__cache.has(name)) {
return this.__cache.get(name);
}
const promise = new Promise((resolve, reject) => {
fetch(`https://sheets.googleapis.com/v4/spreadsheets/${this.hash}/values/${name}?key=${this.key}`)
.then((response) => {
if (response.ok) {
response.json().then((data) => {
const sheet = new Sheet(name, data);
resolve(sheet);
});
} else {
reject(response);
}
})
.catch(reject);
});
this.__cache.set(name, promise);
return promise;
}
/**
* Parse the raw data from the API.
* @private
* @param {callback} The resolve callback (internally used).
* @param {Object} raw The raw data returned by the API.
*/
__parse(resolve, raw) {
this.title = raw.properties.title;
this.locale = raw.properties.locale;
this.timeZone = raw.properties.timeZone;
this.sheets = [];
raw.sheets.forEach((sheet) => this.sheets.push(sheet.properties.title));
this.ready = true;
resolve(this);
}
} |
JavaScript | class StoreProvider extends PureComponent {
static propTypes = {
store: PropTypes.object,
children: PropTypes.node,
};
static defaultProps = {
store: {},
children: undefined,
};
render() {
const {
store,
children,
} = this.props;
return (
<Provider ui={store.ui} client={client}>
<ApolloProvider client={client}>
{children}
</ApolloProvider>
</Provider>
);
}
} |
JavaScript | class Atividade {
constructor(dia, mes, ano, tipo, descricao){
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.tipo = tipo;
this.descricao = descricao;
}
// metodo que vai validar se existe algum campo vazio se sim retorna falso se nao retorna true
validaDados(){
for(let i in this){
if(this[i] == null || this[i] == undefined || this[i] == ''){
return false;
}
}
return true;
}
} |
JavaScript | class Bd{
constructor(){
// verificando se ja tem algum identificador no localStorage
let identificacao = localStorage.getItem('identificacao');
// apos o script ser carregado é criado a identificacao no localStorage
if(identificacao == null){
localStorage.setItem('identificacao', 0);
}
}
// metodo responsavel por receber o valor da key gravada no localStorage e retornar o valor +1
getProximoId() {
let proximoId = localStorage.getItem('identificacao');
return parseInt(proximoId) + 1;
}
// metodo responsavel por gravar no localStorage o valor do objeto criado atraves dos campos em cadastro.html
gravar(d){
// recupera o id que vai servir de key
let identificacao = this.getProximoId();
// Armazena como JSON no local storage
localStorage.setItem(identificacao, JSON.stringify(d));
// Armazena o ultimo ID usado como identificacao no localStorage
localStorage.setItem('identificacao', identificacao)
}
recuperarDados(){
// instancia de array que vai receber os objetos JSON em localStorage
let dados = new Array();
// recuperar o valor dos dados para o forIN
let id = localStorage.getItem('identificacao');
for(let i = 1; i<=id; i++){
// recuperar os dados de localStorage e armazenar em uma variavel
let dado = JSON.parse(localStorage.getItem(i));
// testa pra ver se os dados existem
if(dado == null || dado == undefined){
//pula para a proxima execução do laço
continue;
}
// cria um novo atributo no objeto para referenciar ele
dado.id = i;
// adiciona os dados no array
dados.push(dado);
}
return dados;
}
// metodo para pesquisar os dados dentro de localStorage
pesquisar(atividade){
// array que vai receber os dados
let atividadeFiltradas = new Array();
// recupera todos os dados atraves da funcao recuperar dados mostrado acima na classe BD
atividadeFiltradas = this.recuperarDados();
// teste se o campo de pesquisa esta vazio
if(atividade.ano !== ''){
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
atividadeFiltradas = atividadeFiltradas.filter(a => a.ano == atividade.ano);
}
// teste se o campo de pesquisa esta vazio
if(atividade.mes !== ''){
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
atividadeFiltradas = atividadeFiltradas.filter(a => a.mes == atividade.mes);
}
// teste se o campo de pesquisa esta vazio
if(atividade.dia !== ''){
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
atividadeFiltradas = atividadeFiltradas.filter(a => a.dia == atividade.dia);
}
// teste se o campo de pesquisa esta vazio
if(atividade.tipo !== ''){
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
atividadeFiltradas = atividadeFiltradas.filter(a => a.tipo == atividade.tipo);
}
// teste se o campo de pesquisa esta vazio
if(atividade.descricao !== ''){
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
atividadeFiltradas = atividadeFiltradas.filter(a => a.descricao.toLowerCase() == atividade.descricao.toLowerCase());
}
// retorna o resultado da pesquisa
return atividadeFiltradas;
}
//remover o item do localStorage
excluir(id){
localStorage.removeItem(id);
}
} |
JavaScript | class Quark{
constructor(color,flavor){
this.color=color;
this.flavor=flavor
this.baryon_number=1/3
}
interact(obj){
const color1 = obj.color;
const color2 = this.color;
this.color = color1;
obj.color = color2;
};
} |
JavaScript | class IComparable {
/**
* Compares this object to another object.
* @param {T} other The other object
* @return {number} The comparison value
*/
compare(other) {}
} |
JavaScript | class PostStreamRequestTester {
postStreamTest () {
new PostFileStreamTest().test();
new PostChannelStreamTest().test();
new PostDirectStreamTest().test();
new NoAttributeTest({ attribute: 'teamId' }).test();
new NoAttributeTest({ attribute: 'type' }).test();
new InvalidTypeTest().test();
new NameRequiredTest().test();
new NoRepoIdTest().test();
new NoFileTest().test();
new TeamStreamMustBeChannelTest().test();
new ChannelIgnoresFileTest().test();
new FileIgnoresChannelTest().test();
new DirectIgnoresFileTest().test();
new DirectIgnoresChannelTest().test();
new MeDirectTest().test();
new MeChannelTest().test();
new DuplicateChannelTest().test();
new DuplicateDirectTest().test();
new DuplicateFileTest().test();
new ACLChannelStreamTest().test();
new ACLDirectStreamTest().test();
new ACLFileStreamTest().test();
new NewFileStreamMessageToTeamTest().test();
new NewTeamStreamMessageToTeamTest().test();
new NewStreamToMembersTest({ type: 'direct' }).test();
new NewStreamToMembersTest({ type: 'channel' }).test();
new NewStreamNoMessageTest({ type: 'direct' }).test();
new NewStreamNoMessageTest({ type: 'channel' }).test();
new PostTeamStreamTest().test();
new TeamStreamIgnoresPrivacyTest().test();
new TeamStreamIgnoresMembersTest().test();
new ChannelCanBePublicTest().test();
new InvalidPrivacyTest().test();
new DirectStreamIgnoresPrivacyTest().test();
new FileStreamIgnoresPrivacyTest().test();
for (let char of ILLEGAL_CHANNEL_NAME_CHARACTERS) {
new InvalidChannelNameTest({ illegalCharacter: char }).test();
}
/*
for (let char of ILLEGAL_SLACK_CHANNEL_NAME_CHARACTERS) {
new IllegalSlackChannelNameTest({ illegalCharacter: char }).test();
}
new SlackChannelNameTooLongTest().test();
*/
}
} |
JavaScript | class ExpressRoutes extends BaseRoutes {
constructor(app, opts = {}) {
super(app, opts)
this.appRoutes = {}
}
get label() {
return 'ExpressRoutes'
}
// TODO: create Express router
createRouter() {
// this.notImplemented('createRouter')
}
get providerName() {
return 'express'
}
configure() {
super.configure()
this.createAppRoutes()
return this
}
createAppRoutes() {
let {
app,
routeNames,
routeMap
} = this
this.log('createAppRoutes', {
routeNames,
routeMap
})
routeNames.map(name => {
let path = routeMap[name]
this.addAppRoute(name, path)
})
return this
}
prepareConfig(options) {
this.log('prepareConfig', {
options
})
super.prepareConfig(options)
let handler = this.opts.handler
let {
config
} = this
let {
after
} = config
if (typeof handler === 'function') {
after = after.concat(handler);
}
config.appRoutes = this.appRoutes
}
addAppRoute(name, path) {
this.appRoutes[name] = this.app.route(path)
}
createRest(path) {
super.createRest(path)
let name = this.invertedMap[path]
let route = this.appRoutes[name]
let {
opts
} = this
opts.name = name
opts.route = route
this.log('createRest', {
path,
name,
opts
})
return createRest(this.app, this.config, opts).configure()
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.