language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Params extends Weights.Params {
/**
* If a parameter's value is null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {Float32Array} inputFloat32Array
* A Float32Array whose values will be interpreted as weights.
*
* @param {number} byteOffsetBegin
* The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
* (not to the inputFloat32Array.byteOffset).
*
* @param {number} sourceHeight
* The height of the source image which will be processed by apply_and_destroy_or_keep(). If null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
*
* @param {number} sourceWidth
* The width of the source image which will be processed by apply_and_destroy_or_keep(). If null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
*
* @param {number} sourceChannelCount
* The depth (channel count) of the source image. It may be the output channel count of the previous convolution block, so
* it could be large. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {number} stepCountRequested
* How many steps inside this block are wanted.
* - If null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* - If one (== 1), the step count will be automatically calculated so that the block's output has half of source's
* ( height, width ) and double channel count (depth).
* - Every step will use depthwise convolution ( strides = 1, pad = "valid" ) and pointwise21. So every step will
* shrink the input a little.
* - The step0's depthwise convolution will also use channel multiplier 2 to double the channel count.
* - The stepLast may use a smaller depthwise filter so that it could just make ( output height, width ) as half of source.
* - If ( depthwiseFilterHeight == 1 ), the depthwiseFilterHeight will become 2 forcibly. Otherwise, the source size
* could not be shrinked.
*
* - If ( stepCountRequested >= 2 ), this block will use one tf.depthwiseConv2d( strides = 2, pad = "same" ) to shrink
* (i.e. to halve height x width) and use ( stepCountRequested - 1 ) times tf.depthwiseConv2d( strides = 1, pad = "same" )
* until the block end. (This can not be achieved by only one step. So there is at least two steps.)
*
* @param {number} pointwise1ChannelCountRate
* The first 1x1 pointwise convolution output channel count over of the second 1x1 pointwise convolution output channel count.
* That is, pointwise1ChannelCount = ( pointwise21ChannelCount * pointwise1ChannelCountRate ).
* - If ( pointwise1ChannelCountRate == null ), it will be extracted from inputFloat32Array (i.e. by evolution).
* - If ( pointwise1ChannelCountRate == 0 ), there will be no pointwise1.
* - If ( pointwise1ChannelCountRate == 1 ), will be similar to MobileNetV1 (no expanding) or ShuffleNetV2 (expanding by twice depthwise).
* - If ( pointwise1ChannelCountRate == 2 ), will be similar to MobileNetV2 (expanding by twice pointhwise1).
*
* @param {string} nActivationId
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after every convolution. If null, it will be
* extracted from inputFloat32Array (i.e. by evolution).
*
* @param {string} nActivationIdAtBlockEnd
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the convolution of the last PointDepthPoint's
* pointwise2ActivationId of this block. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If the output of
* this block needs to be any arbitrary value, it is recommended not to use activation at the end of this block
* (i.e. nActivationIdAtBlockEnd == ValueDesc.ActivationFunction.Singleton.Ids.NONE) so that it will not be restricted by the range
* of the activation function.
*
* @param {boolean} nWhetherShuffleChannel
* Whether a (concatenator and) channel shuffler will be used.
*
* - If ( nWhetherShuffleChannel == null ), it will be extracted from inputFloat32Array (i.e. by evolution).
*
* - If ( stepCountRequested <= 1 ), this flag will be ignored.
* This block will be NotShuffleNet_NotMobileNet. There will be no channel shuffler.
*
* - If ( nWhetherShuffleChannel == ValueDesc.WhetherShuffleChannelSingleton.Ids.NONE ), (0),
* this block will be MobileNetV1 or MobileNetV2 (i.e. with add-input-to-output, no channel shuffler).
*
* - If ( nWhetherShuffleChannel == ValueDesc.WhetherShuffleChannelSingleton.Ids.BY_CHANNEL_SHUFFLER ), (1),
* this block will be ShuffleNetV2. There is a channel shuffler by concat-shuffle-split.
*
* - If ( nWhetherShuffleChannel == ValueDesc.WhetherShuffleChannelSingleton.Ids.BY_POINTWISE22 ), (2),
* this block will be ShuffleNetV2_ByPointwise22. There is a channel shuffler by pointwise22.
*
* @param {boolean} bKeepInputTensor
* If true, apply() will not dispose inputTensor (i.e. will be kept). If null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
*
* @return {boolean}
* Return false, if initialization failed.
*
* @override
*/
constructor( inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountRequested,
pointwise1ChannelCountRate,
depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd,
nWhetherShuffleChannel,
bKeepInputTensor
) {
// Q: Why the depthwiseChannelMultiplierStep0 is not listed as a parameter?
// A: After considering the following reasons, it is worth to drop this parameter.
//
// - In reality, it is almost no reason to use only avg/max pooling to compose a block because it keep too little information
// for the next block.
//
// - If depthwiseChannelMultiplierStep0 is specified as Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0), the input
// image will not be shrinked a little (for ( stepCountRequested <= 1 )) or will not be halven (for ( stepCountRequested >= 2 ).
// If it is still a parameter it should be forced to 1 at least (always needs depthwise operation) in this case.
//
let parameterMap = new Map( [
[ Params.sourceHeight, sourceHeight ],
[ Params.sourceWidth, sourceWidth ],
[ Params.sourceChannelCount, sourceChannelCount ],
[ Params.stepCountRequested, stepCountRequested ],
[ Params.pointwise1ChannelCountRate, pointwise1ChannelCountRate ],
[ Params.depthwiseFilterHeight, depthwiseFilterHeight ],
[ Params.nActivationId, nActivationId ],
[ Params.nActivationIdAtBlockEnd, nActivationIdAtBlockEnd ],
[ Params.nWhetherShuffleChannel, nWhetherShuffleChannel ],
[ Params.bKeepInputTensor, bKeepInputTensor ],
] );
super( inputFloat32Array, byteOffsetBegin, parameterMap );
}
/**
* Extract parameters from inputFloat32Array.
*
* @return {boolean} Return false, if extraction failed.
*
* @override
*/
extract() {
let bExtractOk = super.extract();
if ( !bExtractOk )
return false;
Params.set_outputHeight_outputWidth_by_sourceHeight_sourceWidth.call( this, this.sourceHeight, this.sourceWidth );
return bExtractOk;
}
/**
* Determine the following properties:
* - this.outputHeight
* - this.outputWidth
*
* @param {number} sourceHeight The height of source image.
* @param {number} sourceWidth The width of source image.
*/
static set_outputHeight_outputWidth_by_sourceHeight_sourceWidth( sourceHeight, sourceWidth ) {
// By default, the output ( height, width ) is half of the input (i.e. result of depthwise convolution with ( strides = 2, pad = "same" ) ).
//
// Note: This calculation copied from the getPadAndOutInfo() of
// (https://github.com/tensorflow/tfjs/blob/tfjs-v3.8.0/tfjs-core/src/ops/conv_util.ts).
//
let stridesHeight = 2, stridesWidth = 2;
this.outputHeight = Math.ceil( sourceHeight / stridesHeight );
this.outputWidth = Math.ceil( sourceWidth / stridesWidth );
}
get sourceHeight() { return this.parameterMapModified.get( Params.sourceHeight ); }
get sourceWidth() { return this.parameterMapModified.get( Params.sourceWidth ); }
get sourceChannelCount() { return this.parameterMapModified.get( Params.sourceChannelCount ); }
get stepCountRequested() { return this.parameterMapModified.get( Params.stepCountRequested ); }
get pointwise1ChannelCountRate() { return this.parameterMapModified.get( Params.pointwise1ChannelCountRate ); }
get depthwiseFilterHeight() { return this.parameterMapModified.get( Params.depthwiseFilterHeight ); }
get nActivationId() { return this.parameterMapModified.get( Params.nActivationId ); }
get nActivationIdName() { return Params.nActivationId.getStringOfValue( this.nActivationId ); }
get nActivationIdAtBlockEnd() { return this.parameterMapModified.get( Params.nActivationIdAtBlockEnd ); }
get nActivationIdAtBlockEndName() { return Params.nActivationIdAtBlockEnd.getStringOfValue( this.nActivationIdAtBlockEnd ); }
get nWhetherShuffleChannel() { return this.parameterMapModified.get( Params.nWhetherShuffleChannel ); }
get nWhetherShuffleChannelName() { return Params.nWhetherShuffleChannel.getStringOfValue( this.nWhetherShuffleChannel ); }
get bKeepInputTensor() { return this.parameterMapModified.get( Params.bKeepInputTensor ); }
} |
JavaScript | class Base {
/**
* Generator for initializing this object.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The created progressToAdvance will be
* increased when every time advanced. The progressParent.getRoot() will be returned when every time yield.
*
* @param {Params} params
* A Params object. The params.extract() will be called to extract parameters.
*
* @yield {ValueMax.Percentage.Aggregate}
* Yield ( value = progressParent.getRoot() ) when ( done = false ).
*
* @yield {boolean}
* Yield ( value = true ) when ( done = true ) successfully.
* Yield ( value = false ) when ( done = true ) failed.
*
* @see PointDepthPoint.Base.initer()
*/
* initer( progressParent, params ) {
// Both MobileNetV3 and ShuffleNetV2:
// - They all do not use (depthwise convolution) channelMultiplier.
// - They all use 1x1 (pointwise) convolution to expand channel count.
// - They all use 1x1 (pointwise) convolution before depthwise convolution.
// - They all use activation function after first pointwise convolution.
// - They all use depthwise convolution with ( pad = "same" ).
// - They all use depthwise convolution with ( strides = 2 ) for shrinking (halving) height x width.
// - They all do use batch normalization (include bias) after pointwise and depthwise convolution.
//
// Inisde one of their block, three convolutions are used:
// A) 1x1 (pointwise) convolution, with activation.
// B) depthwise convolution, (ShuffleNetV2) without or (MobileNetV2) with activation.
// C) 1x1 (pointwise) convolution, (ShuffleNetV2) with or (MobileNetV2) without activation.
//
// In MobileNetV3, convolution A expands channel count (with activation), convolution C shrinks channel count (without activation).
// It may use squeeze-and-excitation after convolution B (without activation). When there is necessary to increase output channel
// count (usually in step 0 of a block), the convolution C is responsible for this.
//
// In ShuffleNetV2, convolution A (with activation), convolution B (without activation) and convolution C (with activation) never
// change channel count. When there is necessary to increase output channel count (usually in step 0 of a block), it expands channel
// count by concatenating two shrinked (halven) height x width.
// 0. Prepare
// Estimate the maximum value of progress.
let progressMax =
1 // for extracting parameters from inputFloat32Array.
;
let progressRoot = progressParent.getRoot();
let progressToAdvance = progressParent.addChild( new ValueMax.Percentage.Concrete( progressMax ) ); // For parameters extracting.
let progressForSteps = progressParent.addChild( new ValueMax.Percentage.Aggregate() ); // for step0, step1, 2, 3, ...
this.disposeTensors();
// 1. Extract parameters.
if ( !params )
return false;
this.byteOffsetEnd = this.byteOffsetBegin = params.defaultByteOffsetBegin;
if ( !params.extract() )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = params.defaultByteOffsetEnd; // Record where to extract next weights. Only meaningful when ( this.bInitOk == true ).
// Get parameters' real (adjusted) values.
//
// Do not keep params in this.params so that the inputFloat32Array could be released.
this.sourceHeight = params.sourceHeight;
this.sourceWidth = params.sourceWidth;
this.sourceChannelCount = params.sourceChannelCount;
this.stepCountRequested = params.stepCountRequested;
this.pointwise1ChannelCountRate = params.pointwise1ChannelCountRate;
this.depthwiseFilterHeight = params.depthwiseFilterHeight; // Assume depthwise filter's width equals its height.
this.nActivationId = params.nActivationId;
this.nActivationIdName = params.nActivationIdName;
this.nActivationIdAtBlockEnd = params.nActivationIdAtBlockEnd;
this.nActivationIdAtBlockEndName = params.nActivationIdAtBlockEndName;
this.nWhetherShuffleChannel = params.nWhetherShuffleChannel;
this.nWhetherShuffleChannelName = params.nWhetherShuffleChannelName;
this.bKeepInputTensor = params.bKeepInputTensor;
// The parameters which are determined (inferenced) from the above parameters.
{
this.outputHeight = params.outputHeight;
this.outputWidth = params.outputWidth;
}
// Pre-allocate array to place intermediate 2 input tensors and 2 output tensors. This could reduce memory re-allocation.
this.intermediateInputTensors = new Array( 2 );
this.intermediateOutputTensors = new Array( 2 );
++progressToAdvance.value;
yield progressRoot; // Parameters extracted. Report progress.
// 2. Create every steps.
let stepParamsMaker = Base.create_Params_to_PointDepthPointParams( params );
stepParamsMaker.determine_stepCount_depthwiseFilterHeight_Default_Last(); // Calculate the real step count.
for ( let i = 0; i < stepParamsMaker.stepCount; ++i ) { // Progress for step0, 1, 2, 3, ...
progressForSteps.addChild( new ValueMax.Percentage.Aggregate() );
}
let stepParams, step, stepIniter;
this.stepsArray = new Array( stepParamsMaker.stepCount );
for ( let i = 0; i < this.stepsArray.length; ++i ) { // Step0, 1, 2, 3, ..., StepLast.
if ( 0 == i ) { // Step0.
stepParamsMaker.configTo_beforeStep0();
}
// StepLast. (Note: Step0 may also be StepLast.)
//
// If this is the last step of this block (i.e. at-block-end)
// - a different depthwise filter size may be used.
// - a different activation function may be used after pointwise2 convolution.
if ( ( this.stepsArray.length - 1 ) == i ) {
stepParamsMaker.configTo_beforeStepLast();
}
stepParams = stepParamsMaker.create_PointDepthPointParams( params.defaultInput, this.byteOffsetEnd );
if ( !this.channelShuffler ) { // If channelShuffler is got first time, keep it.
// If channelShuffler is not null, keep it so that its tensors could be released.
let channelShuffler = stepParamsMaker.channelShuffler;
if ( channelShuffler ) {
tf.util.assert( ( !this.channelShuffler ) || ( this.channelShuffler == channelShuffler ),
`Block.initer(): `
+ `At most, only one (and same) channel shuffler could be used (and shared by all steps of a block).` );
this.channelShuffler = channelShuffler;
this.tensorWeightCountTotal += channelShuffler.tensorWeightCountTotal;
this.tensorWeightCountExtracted += channelShuffler.tensorWeightCountExtracted;
// If channelShuffler is null, do not use it. Otherwise, the this.channelShuffler will be cleared and could not be used
// for releasing tensors.
}
// If channelShuffler has ever got, never change it.
}
step = this.stepsArray[ i ] = new PointDepthPoint.Base();
stepIniter = step.initer( progressForSteps.children[ i ], stepParams, this.channelShuffler );
this.bInitOk = yield* stepIniter;
if ( !this.bInitOk )
return false;
this.byteOffsetEnd = step.byteOffsetEnd;
this.tensorWeightCountTotal += step.tensorWeightCountTotal;
this.tensorWeightCountExtracted += step.tensorWeightCountExtracted;
if ( 0 == i ) { // After step0 (i.e. for step1, 2, 3, ...)
stepParamsMaker.configTo_afterStep0();
}
}
this.step0 = this.stepsArray[ 0 ]; // Shortcut to the first step.
this.stepLast = this.stepsArray[ this.stepsArray.length - 1 ]; // Shortcut to the last step.
this.outputChannelCount = this.stepLast.outChannelsAll;
// In our Block design, no matter which configuration, the outputChannelCount always is twice as sourceChannelCount.
tf.util.assert( ( this.outputChannelCount == ( this.sourceChannelCount * 2 ) ),
`Block.initer(): `
+ `the outputChannelCount ( ${this.outputChannelCount} ) should always be twice as `
+ `sourceChannelCount ( ${this.sourceChannelCount} ).` );
this.bInitOk = true;
return this.bInitOk;
}
/**
* Initialize this object by calling initer() and advance the generator by loop until done.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* If null, a temporary progress object will be created.
*
* @return {boolean}
* Return true if successfully (and progressParent.valuePercentage will be equal to 100).
* Return false if failed (and progressParent.valuePercentage will be less than 100).
*
* @see PointDepthPoint.Base.init()
*/
init( progressParent, params ) {
progressParent = progressParent || ( new ValueMax.Percentage.Aggregate() );
let initer = this.initer( progressParent, params );
let initerNext;
do {
initerNext = initer.next();
} while ( ! initerNext.done ); // When ( false == initerNext.done ), the ( initerNext.value ) will be progressParent.getRoot().
let bInitOk = initerNext.value; // When ( true == initerNext.done ), the ( initerNext.value ) will be initialization successfully or failed.
return bInitOk;
}
/** Release all tensors. */
disposeTensors() {
if ( this.stepsArray ) {
for ( let i = 0; i < this.stepsArray.length; ++i ) {
let step = this.stepsArray[ i ];
step.disposeTensors();
}
this.stepsArray = null;
}
if ( this.channelShuffler ) {
this.channelShuffler.disposeTensors(); // Block is responsible for releasing the channel shuffler shared by all steps of the block.
this.channelShuffler = false;
}
this.step0 = this.stepLast = null; // It has already de disposed by this.step0 or this.steps1After.
this.outputChannelCount = -1;
this.intermediateInputTensors = this.intermediateOutputTensors = null;
this.tensorWeightCountTotal = this.tensorWeightCountExtracted = 0;
this.byteOffsetBegin = this.byteOffsetEnd = -1;
this.bInitOk = false;
}
/**
* @param {Params} blockParams
* The Block.Params object to be reference.
*/
static create_Params_to_PointDepthPointParams( blockParams ) {
if ( blockParams.stepCountRequested <= 1 ) { // 1. Not ShuffleNetV2, Not MobileNetV2.
return new Params.to_PointDepthPointParams.NotShuffleNet_NotMobileNet( blockParams );
} else { // ( this.stepCountRequested >= 2 )
switch ( blockParams.nWhetherShuffleChannel ) {
case ValueDesc.WhetherShuffleChannel.Singleton.Ids.NONE: // (0) 2. MobileNetV2 or MobileNetV1
// ( pointwise1ChannelCountRate == 0 ), will be similar to MobileNetV1.
// ( pointwise1ChannelCountRate == 1 ), will be similar to MobileNetV2 without expanding.
// ( pointwise1ChannelCountRate == 2 ), will be similar to MobileNetV2.
return new Params.to_PointDepthPointParams.MobileNetV2( blockParams );
break;
case ValueDesc.WhetherShuffleChannel.Singleton.Ids.BY_CHANNEL_SHUFFLER: // (1) 3. ShuffleNetV2
return new Params.to_PointDepthPointParams.ShuffleNetV2( blockParams );
break;
case ValueDesc.WhetherShuffleChannel.Singleton.Ids.BY_POINTWISE22: // (2) 4. ShuffleNetV2_ByPointwise22
return new Params.to_PointDepthPointParams.ShuffleNetV2_ByPointwise22( blockParams );
break;
default:
tf.util.assert( false,
`Block.create_Params_to_PointDepthPointParams(): `
+ `unknown this.nWhetherShuffleChannel ( ${blockParams.nWhetherShuffleChannel} ) value.` );
break;
}
}
}
/** Process input, destroy or keep input, return result.
*
* @param {tf.tensor3d} inputTensor
* The source input image ( height x width x channel ) which will be processed. This inputTensor may or may not be disposed
* according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d}
* Return a new tensor. All other intermediate tensors were disposed.
*/
apply( inputTensor ) {
let inputTensors = this.intermediateInputTensors;
let outputTensors = this.intermediateOutputTensors;
outputTensors[ 0 ] = inputTensor;
outputTensors[ 1 ] = null; // Note: The step0 should only input one tensor.
let stepsArray = this.stepsArray;
let step;
for ( let i = 0; i < stepsArray.length; ++i ) {
inputTensors[ 0 ] = outputTensors[ 0 ]; // Previous step's output becomes next step's input.
inputTensors[ 1 ] = outputTensors[ 1 ];
step = stepsArray[ i ];
step.apply( inputTensors, outputTensors );
}
return outputTensors[ 0 ]; // Note: The stepLast should only output one tensor.
}
/** How many steps inside this blocked are created. (may different from this.stepCountRequested.) */
get stepCount() {
return this.stepsArray.length;
}
/** @return {string} The description string of all (adjusted) parameters of initer(). */
get parametersDescription() {
let str =
`sourceHeight=${this.sourceHeight}, sourceWidth=${this.sourceWidth}, sourceChannelCount=${this.sourceChannelCount}, `
+ `stepCountRequested=${this.stepCountRequested}, stepCount=${this.stepCount}, `
+ `pointwise1ChannelCountRate=${this.pointwise1ChannelCountRate}, `
+ `depthwiseFilterHeight=${this.depthwiseFilterHeight}, `
+ `nActivationIdName=${this.nActivationIdName}(${this.nActivationId}), `
+ `nActivationIdAtBlockEndName=${this.nActivationIdAtBlockEndName}(${this.nActivationIdAtBlockEnd}), `
+ `nWhetherShuffleChannel=${this.nWhetherShuffleChannelName}(${this.nWhetherShuffleChannel}), `
+ `outputHeight=${this.outputHeight}, outputWidth=${this.outputWidth}, outputChannelCount=${this.outputChannelCount}, `
+ `bKeepInputTensor=${this.bKeepInputTensor}`
;
return str;
}
} |
JavaScript | class ValueValidator {
/**
* Constructor
* @param {string} [mode] the usage mode
*/
constructor (mode) {
this._mode = mode
}
/**
* Validates value of Edm.Binary type.
* @param {Buffer} value - Edm.Binary value
* @param {number} maxLength - value of MaxLength facet
*/
validateBinary (value, maxLength) {
if (!Buffer.isBuffer(value)) throw this._valueError(value, 'Edm.Binary', 'Buffer instance')
this._checkMaxLength(value, maxLength, 'Edm.Binary')
}
/**
* Validates value of Edm.Boolean type.
* @param {boolean} value - Edm.Boolean value
*/
validateBoolean (value) {
if (typeof value !== 'boolean') throw this._valueError(value, 'Edm.Boolean', 'boolean value')
}
/**
* Validates value of Edm.Byte type.
* @param {number} value - Edm.Byte value
*/
validateByte (value) {
this._validateIntegerValue(value, 'Edm.Byte', 0, 255)
}
/**
* Returns true if value is of type Byte.
* @param {number} value the value to check
* @returns {boolean} true if value is Byte, else false
*/
isByte (value) {
return Number.isInteger(value) && value >= 0 && value <= 255
}
/**
* Validates value of Edm.SByte type.
* @param {number} value - Edm.SByte value
*/
validateSByte (value) {
this._validateIntegerValue(value, 'Edm.SByte', -128, 127)
}
/**
* Returns true if value is of type SByte.
* @param {number} value the value to check
* @returns {boolean} true if value is SByte, else false
*/
isSByte (value) {
return Number.isInteger(value) && value >= -128 && value <= 127
}
/**
* Validates value of Edm.Int16 type.
* @param {number} value - Edm.Int16 value
*/
validateInt16 (value) {
this._validateIntegerValue(value, 'Edm.Int16', -32768, 32767)
}
/**
* Returns true if value is of type Int16.
* @param {number} value the value to check
* @returns {boolean} true if value is Int16, else false
*/
isInt16 (value) {
return Number.isInteger(value) && value >= -32768 && value <= 32767
}
/**
* Validates value of Edm.Int32 type.
* @param {number} value - Edm.Int32 value
*/
validateInt32 (value) {
this._validateIntegerValue(value, 'Edm.Int32', -2147483648, 2147483647)
}
/**
* Returns true if value is of type Int32.
* @param {number} value the value to check
* @returns {boolean} true if value is Int32, else false
*/
isInt32 (value) {
return Number.isInteger(value) && value >= -2147483648 && value <= 2147483647
}
/**
* Validates value of Edm.Int64 type.
* @param {number|string} value - Edm.Int64 value. Values in exponential notation are also supported.
*/
validateInt64 (value) {
if (!this.isInt64(value)) {
throw this._valueError(
value,
'Edm.Int64',
'number without decimals in the range from -9223372036854775808 to 9223372036854775807'
)
}
}
/**
* Returns true if value is of type Int64.
* @param {number|string} value the value to check
* @returns {boolean} true if value is Int64, else false
*/
isInt64 (value) {
const bigValue = this._createBig(value)
return (
!Number.isNaN(bigValue) && bigValue.round(0).eq(bigValue) && bigValue.gte(INT64_MIN) && bigValue.lte(INT64_MAX)
)
}
/**
* Validates, whether the value is an integer value and in the specified value range, defined via 'from'
* and 'to' input parameters.
*
* @param {number} value - Any value, which should be validated
* @param {string} edmType - name of the EDM type for which the value is validated
* @param {number} from - beginning of the valid value range, which the value must belong to
* @param {number} to - end of the valid value range, which the value must belong to
* @private
*/
_validateIntegerValue (value, edmType, from, to) {
if (!Number.isInteger(value)) throw this._valueError(value, edmType, 'number without decimals')
if (value < from || value > to) {
throw this._valueError(value, edmType, 'number in the range from ' + from + ' to ' + to)
}
}
/**
* Create a big.js instance for a value.
* @param {number|string} value the value
* @returns {Big|number} the created big.js instance or Number.NaN in case of error
* @private
*/
_createBig (value) {
try {
return new Big(value)
} catch (e) {
// Big constructor throws NaN if the input is not a number.
// Return NaN here to avoid yet another try-catch block in the calling function
return Number.NaN
}
}
/**
* Validates value of Edm.String type.
* @param {string} value - Edm.String value
* @param {number} maxLength - value of MaxLength facet
*/
validateString (value, maxLength) {
if (typeof value !== 'string') throw this._valueError(value, 'Edm.String', 'string value')
this._checkMaxLength(value, maxLength, 'Edm.String')
}
/**
* Checks that the value is not longer than the specified maximum length.
* @param {string} value value to be checked
* @param {number} maxLength value of the MaxLength facet for the property, which has the specified value
* @param {string} typeName name of the type of the value
* @throws {Error} if the condition is not met
* @private
*/
_checkMaxLength (value, maxLength, typeName) {
// consider only integer maxLength values, ignoring both unspecified and the special 'max' value
if (Number.isInteger(maxLength) && value.length > maxLength) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). The length of the ' +
typeName +
' value must not be greater than the MaxLength facet value (' +
maxLength +
').'
)
}
}
/**
* Validates value of Edm.Date type.
* @param {string} value - Edm.Date value
*/
validateDate (value) {
if (typeof value !== 'string' || !DATE_REG_EXP.test(value)) {
throw this._valueError(value, 'Edm.Date', 'string value in the format YYYY-MM-DD')
}
}
/**
* Validates value of Edm.DateTimeOffset type.
* @param {string} value - Edm.DateTimeOffset value
* @param {number|string} [precision] - value of Precision facet
*/
validateDateTimeOffset (value, precision) {
let result = DATETIME_OFFSET_REG_EXP.exec(value)
if (typeof value !== 'string' || !result) {
throw this._valueError(value, 'Edm.DateTimeOffset', 'string value in the format YYYY-MM-DDThh:mm:ss.sTZD')
}
const milliseconds = result[1]
this._checkMillisecondsPrecision(value, milliseconds, precision)
}
/**
* Validates value of Edm.TimeOfDay type.
* @param {string} value - Edm.TimeOfDay value
* @param {number|string} [precision] - value of Precision facet
*/
validateTimeOfDay (value, precision) {
let result = TIME_OF_DAY_REG_EXP.exec(value)
if (typeof value !== 'string' || !result) {
throw this._valueError(value, 'Edm.TimeOfDay', 'string value in the format hh:mm:ss.s')
}
const milliseconds = result[1]
this._checkMillisecondsPrecision(value, milliseconds, precision)
}
/**
* Validates value of Edm.Duration type.
* @param {string} value - Edm.Duration value
* @param {number|string} [precision] - value of Precision facet
*/
validateDuration (value, precision) {
let result = DURATION_REG_EXP.exec(value)
if (typeof value !== 'string' || !result) {
throw this._valueError(value, 'Edm.Duration', 'string value in the format PnDTnHnMn.nS')
}
// Because of the different combinations of the duration parts (HS, MS, S) we have 6 places (i.e. matching
// groups) in the regular expression, which match milliseconds. Therefore slice() is called on the result
// array to "extract" only these 6 matches and find the one that matches, i.e., is not empty.
const milliseconds = result.slice(1, 7).find(match => match !== undefined)
this._checkMillisecondsPrecision(value, milliseconds, precision)
}
/**
* Checks whether the milliseconds satisfy the specified precision for the value.
* @param {string} value - temporal value, which can contain milliseconds
* @param {string} milliseconds - part of the value, representing milliseconds
* @param {number} precision - value of the Precision facet for the property, which has the specified value
* @throws {Error} if the conditions are not met
* @private
*/
_checkMillisecondsPrecision (value, milliseconds, precision) {
// milliseconds is a string value, so just check its length
if (milliseconds && precision !== null && precision !== undefined && milliseconds.length > precision) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). ' +
'The number of milliseconds does not correspond to the Precision facet value (' +
precision +
').'
)
}
}
/**
* Validates value of Edm.Decimal type.
* @param {number|string} value - Edm.Decimal value. Values in exponential notation are also supported.
* @param {number|string} [precision] - value of Precision facet
* @param {number|string} [scale] - value of Scale facet
*/
validateDecimal (value, precision, scale) {
// Precision and scale values are not validated assuming that the metadata validation is done before calling
// the serializer.
const bigValue = this._createBig(value)
// Check that the value represents a number.
if (Number.isNaN(bigValue)) {
throw this._valueError(value, 'Edm.Decimal', 'number or a string representing a number')
}
// check that the value has no more digits than specified for precision
if (precision !== null && precision !== undefined && bigValue.c.length > precision) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). ' +
'The specified Edm.Decimal value does not correspond to the Precision facet value (' +
precision +
').'
)
}
if (scale === null || scale === undefined || scale === 'variable') {
return
}
// Specify 0 as the rounding mode to simply truncate the number wihout any sort of rounding.
const integerPart = bigValue.round(0, 0)
if (precision === scale) {
if (!integerPart.eq(0)) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). ' +
'If Precision is equal to Scale, a single zero must precede the decimal point ' +
'in the Edm.Decimal value.'
)
}
return
}
// Validate number of digits in the integer (i.e., left) part of the value.
if (precision !== null && precision !== undefined && integerPart.c.length > precision - scale) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). ' +
'The number of digits to the left of the decimal point must not be greater than ' +
'Precision minus Scale, i.e., ' +
(precision - scale) +
'.'
)
}
// Validate number of digits in the decimal (i.e., right) part of the value.
const decimalPart = bigValue.minus(integerPart)
if (decimalPart.c.length > scale && !decimalPart.eq(0)) {
throw new IllegalArgumentError(
'Invalid value ' +
value +
' (JavaScript ' +
typeof value +
'). ' +
'The specified Edm.Decimal value has more digits to the right of the decimal point ' +
'than allowed by the Scale facet value (' +
scale +
').'
)
}
}
/**
* Validates value of Edm.Single type.
* @param {number} value - Edm.Single value
*/
validateSingle (value) {
if (!this.isSingle(value)) {
throw this._valueError(
value,
'Edm.Single',
'number having absolute value in the range from ' + SINGLE_MIN + ' to ' + SINGLE_MAX
)
}
}
/**
* Returns true if the provided value is a single precision float number
* @param {number} value - Any value to check
* @returns {boolean} True if the value is a valid single precision float number, else false
*/
isSingle (value) {
if (typeof value === 'number') {
const absValue = Math.abs(value)
return absValue === 0 || (absValue >= SINGLE_MIN && absValue <= SINGLE_MAX)
}
return false
}
/**
* Validates value of Edm.Double type.
* @param {number} value - Edm.Double value
*/
validateDouble (value) {
if (typeof value !== 'number') throw this._valueError(value, 'Edm.Double', 'number value')
}
/**
* Validates value of Edm.Guid type.
* @param {string} value - Edm.Guid value
*/
validateGuid (value) {
if (typeof value !== 'string' || !GUID_REG_EXP.test(value)) {
throw this._valueError(value, 'Edm.Guid', 'string value in the format 8HEXDIG-4HEXDIG-4HEXDIG-4HEXDIG-12HEXDIG')
}
}
/**
* Validates value of Edm.GeographyPoint or Edm.GeometryPoint type.
* @param {{ type: string, coordinates: number[] }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoPoint (value, srid) {
if (!this._isGeoJsonObject('Point', 'coordinates', value, srid) || !this._isGeoPosition(value.coordinates)) {
throw this._valueError(
value,
'Edm.GeographyPoint or Edm.GeometryPoint',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyLineString or Edm.GeometryLineString type.
* @param {{ type: string, coordinates: Array.<number[]> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoLineString (value, srid) {
if (
!this._isGeoJsonObject('LineString', 'coordinates', value, srid) ||
!value.coordinates.every(this._isGeoPosition, this)
) {
throw this._valueError(
value,
'Edm.GeographyLineString or Edm.GeometryLineString',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyPolygon or Edm.GeometryPolygon type.
* @param {{ type: string, coordinates: Array.<Array.<number[]>> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoPolygon (value, srid) {
if (!this._isGeoJsonObject('Polygon', 'coordinates', value, srid) || !this._isGeoPolygon(value.coordinates)) {
throw this._valueError(
value,
'Edm.GeographyPolygon or Edm.GeometryPolygon',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyMultiPoint or Edm.GeometryMultiPoint type.
* @param {{ type: string, coordinates: Array.<number[]> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoMultiPoint (value, srid) {
if (
!this._isGeoJsonObject('MultiPoint', 'coordinates', value, srid) ||
!value.coordinates.every(this._isGeoPosition, this)
) {
throw this._valueError(
value,
'Edm.GeographyMultiPoint or Edm.GeometryMultiPoint',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyMultiLineString or Edm.GeometryMultiLineString type.
* @param {{ type: string, coordinates: Array.<Array.<number[]>> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoMultiLineString (value, srid) {
if (
!this._isGeoJsonObject('MultiLineString', 'coordinates', value, srid) ||
!value.coordinates.every(linestring => Array.isArray(linestring) && linestring.every(this._isGeoPosition, this))
) {
throw this._valueError(
value,
'Edm.GeographyMultiLineString or Edm.GeometryMultiLineString',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyMultiPolygon or Edm.GeometryMultiPolygon type.
* @param {{ type: string, coordinates: Array.<Array.<Array.<number[]>>> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoMultiPolygon (value, srid) {
if (
!this._isGeoJsonObject('MultiPolygon', 'coordinates', value, srid) ||
!value.coordinates.every(this._isGeoPolygon, this)
) {
throw this._valueError(
value,
'Edm.GeographyMultiPolygon or Edm.GeometryMultiPolygon',
'JavaScript object with type and coordinates'
)
}
}
/**
* Validates value of Edm.GeographyCollection or Edm.GeometryCollection type.
* @param {{ type: string, geometries: Array.<Object> }} value the value
* @param {?(number|string)} [srid] value of SRID facet
*/
validateGeoCollection (value, srid) {
if (
!this._isGeoJsonObject('GeometryCollection', 'geometries', value, srid) ||
!value.geometries.every(
geoObject =>
(this._isGeoJsonObject('Point', 'coordinates', geoObject) && this._isGeoPosition(geoObject.coordinates)) ||
(this._isGeoJsonObject('LineString', 'coordinates', geoObject) &&
geoObject.coordinates.every(this._isGeoPosition, this)) ||
(this._isGeoJsonObject('Polygon', 'coordinates', geoObject) && this._isGeoPolygon(geoObject.coordinates)) ||
(this._isGeoJsonObject('MultiPoint', 'coordinates', geoObject) &&
geoObject.coordinates.every(this._isGeoPosition, this)) ||
(this._isGeoJsonObject('MultiLineString', 'coordinates', geoObject) &&
geoObject.coordinates.every(
linestring => Array.isArray(linestring) && linestring.every(this._isGeoPosition, this)
)) ||
(this._isGeoJsonObject('MultiPolygon', 'coordinates', geoObject) &&
geoObject.coordinates.every(this._isGeoPolygon, this))
)
) {
throw this._valueError(
value,
'Edm.GeographyCollection or Edm.GeometryCollection',
'JavaScript object with type and geometries'
)
}
}
/**
* Returns true if the value is a GeoJSON object of the correct type, otherwise false.
* @param {string} type name of the type
* @param {string} content the name of the property with content ("coordinates" or "geometries")
* @param {Object} value the value to be checked
* @param {?(number|string)} [srid] value of SRID facet
* @returns {boolean} whether the value is a GeoJSON object of the correct type
* @private
*/
_isGeoJsonObject (type, content, value, srid) {
return (
typeof value === 'object' &&
Object.keys(value).length === (srid === 'variable' ? 3 : 2) &&
value.type === type &&
Array.isArray(value[content]) &&
(srid !== 'variable' ||
(value.crs &&
value.crs.type === 'name' &&
value.crs.properties &&
typeof value.crs.properties.name === 'string' &&
GEO_CRS_NAME_REG_EXP.test(value.crs.properties.name)))
)
}
/**
* Returns true if the position is a GeoJSON position array, otherwise false.
* @param {number[]} position the value to be checked
* @returns {boolean} whether the position is a GeoJSON position array
* @private
*/
_isGeoPosition (position) {
return (
Array.isArray(position) &&
(position.length === 2 || position.length === 3) &&
typeof position[0] === 'number' &&
typeof position[1] === 'number' &&
(position[2] === undefined || typeof position[2] === 'number')
)
}
/**
* Returns true if the value is an array of coordinates for a GeoJSON polygon, otherwise false.
* @param {Array.<Array.<number[]>>} polygon the value to be checked
* @returns {boolean} whether the value is an array of coordinates for a GeoJSON polygon
* @private
*/
_isGeoPolygon (polygon) {
return (
polygon.length &&
polygon.every(
ring =>
Array.isArray(ring) &&
ring.length >= 4 &&
ring.every(this._isGeoPosition, this) &&
ring[ring.length - 1][0] === ring[0][0] &&
ring[ring.length - 1][1] === ring[0][1] &&
ring[ring.length - 1][2] === ring[0][2]
)
)
}
/**
* Validates if the provided ETag value matches the expected format.
* The value must be a string of allowed characters as described in RFC 7232
* (see https://tools.ietf.org/html/rfc7232#section-2.3 for details).
*
* @param {string} value the provided etag value to validate
* @returns {string} the provided value
* @throws {IllegalArgumentError} if the etag value doesn't match the required format
*/
validateEtagValue (value) {
if (value === undefined) throw new IllegalArgumentError('Invalid undefined ETag value')
if (value === null) throw new IllegalArgumentError('Invalid null ETag value')
if (typeof value !== 'string') throw new IllegalArgumentError('Invalid ETag value; it must be type of string')
if (!ETAG_VALUE_REG_EXP.test(value)) throw new IllegalArgumentError('Invalid ETag value')
return value
}
/**
* Returns an error instance describing the failed value validation.
* @param {?(string|number|boolean|Buffer|Object)} value the wrong value
* @param {string} typeName the name of the EDM type
* @param {string} requiredText the text describing the requirements for the value
* @returns {IllegalArgumentError} the error instance
* @private
*/
_valueError (value, typeName, requiredText) {
const property =
this._mode === 'decode' &&
this._valueConverter._propertyOrReturnType &&
this._valueConverter._propertyOrReturnType.getName()
const msg =
'Invalid value ' +
(typeName.includes('Geo') ? JSON.stringify(value) : value) +
' (JavaScript ' +
typeof value +
')' +
(property ? ' for property "' + property + '"' : '') +
'. ' +
'A ' +
requiredText +
' must be specified as value for type ' +
typeName +
'.'
return new IllegalArgumentError(msg)
}
} |
JavaScript | class Navbar extends Component {
render() {
return (
<nav className="Navbar">
<ul className="nav nav-tabs nav-dark bg-inverse">
<li className="nav-item"><a href="" className="nav-link">nav link 1</a></li>
<li className="nav-item"><a href="" className="nav-link active">nav link 2</a></li>
<li className="nav-item"><a href="" className="nav-link">nav link 3</a></li>
<li className="nav-item"><a href="" className="nav-link">nav link 4</a></li>
</ul>
</nav>
)
}
} |
JavaScript | class FaqError {
/**
* @param {string} message a descriptive message to be displayed to the user
* @param {string} faqTopic a relevant FAQ topic the user can browse to
*/
constructor (message, faqTopic) {
this.name = 'FaqError'
this.faqTopic = faqTopic
this.message = message
this.stack = new Error().stack
}
} |
JavaScript | class CapturePointer {
update(actor, engine) {
if (!actor.enableCapturePointer) {
return;
}
if (actor.isKilled()) {
return;
}
engine.input.pointers.checkAndUpdateActorUnderPointer(actor);
}
} |
JavaScript | class Schema {
static _classInit(){
/**
* A `debug` instance for the class
* @memberof Schema
* @name debug
* @type Function
*/
this.debug = debugr('mhio:casserole:Schema')
/* istanbul ignore else */
if (!this.debug.enabled) this.debug = noop
/**
* A `debug` instance for the class instance
* @memberof Schema.prototype
* @name debug
* @type Function
*/
this.prototype.debug = this.debug
/**
* Model field names that are not allowed
* @memberof Schema
* @name reserved_fields
* @type Array
*/
this.reserved_fields = Paramaters.reserved_fields
/**
* Model field names that generate a warning
* @memberof Schema
* @name warning_fields
* @type Array
*/
this.warning_fields = Paramaters.warning_fields
/**
* Cassandra data types from datastax driver
* @memberof Schema.prototype
* @name data_types
* @type Array
*/
this.prototype.data_types = Paramaters.types
/**
* Cassandra data types from datastax driver
* @memberof Schema
* @name data_types
* @type Array
*/
this.data_types = Paramaters.types
}
/**
* @param {Object} config - The Schema config object `{ field: { type: 'x' }`
*/
constructor( config, options ){
this.debug('new Schema with ', config)
this.config = config
this.dates = true
if ( options ){
if ( has(options,'dates') ) this.dates = Boolean(options.dates)
if ( has(options,'soft_delete') ) this.soft_delete = Boolean(options.soft_delete)
}
}
/** Schema adds created/modified data handlers
* @type Boolean
*/
get dates(){ return this._dates }
set dates(value){ return this._dates = Boolean(value) }
/** Schema track deletes rathe than deleting data
* @type Boolean
*/
get soft_delete(){ return this._soft_delete }
set soft_delete(value){ return this._soft_delete = Boolean(value) }
/**
* The schemas config object
* @type Object
*/
get config(){
return this._config
}
set config(config){
if (!config || typeof config !== 'object') {
throw new CassException('Schema config must be an object')
}
if (Object.keys(config).length === 0) {
throw new CassException('Schema config must have field definitions')
}
// Validate
forEach(config, ( field_def, field_name )=>{
if (typeof field_def === 'string'){
field_def = { name: field_name, type: field_def }
}
if (!field_def.type) {
throw new CassException(`Schema "type" must be defined for field "${field_name}"`)
}
let subtype_match = /^([a-z]+)?<([a-z]+)>$/.exec(field_def.type)
if ( subtype_match ) {
let [ _, type, subtype ] = subtype_match
if ( ! [ 'map', 'set', 'list', undefined ].includes(type) ) {
throw new CassException(`Schema type "${type}" can not be used to house other types`)
}
if ( type !== undefined ) {
Paramaters.checkType(type)
Paramaters.checkType(subtype)
} else {
// user defined, need definition in schema?
throw new CassException('User defined types are not supported')
}
} else {
field_def.type = Paramaters.checkType(field_def.type)
}
config[field_name] = field_def
})
// Fix options
if ( this.dates === true ) {
config.created_at = { type: 'timestamp' }
config.modified_at = { type: 'timestamp' }
}
if ( this.soft_delete === true ){
config.deleted_at = { type: 'timestamp' }
}
this._config = config
}
/**
* All primary keys for the schema
* @type Array
*/
get primary_keys(){
return transform(this._config, (result, field, key)=>{
if (field.primary) result.push(key)
}, [])
}
/**
* All columns in an array
* @type Array
*/
get column_types(){
return transform(this._config, (result, field, key)=>{
result[key] = field.type
}, {})
}
/**
* All columns types, keyed by name
* @type Object
*/
get columns(){
return Object.keys(this._config)
}
/**
* Run a function for each schema config item
* @param {Function} fn - The function to run
*/
forEach(fn){
forEach(this._config, fn)
}
} |
JavaScript | class Main {
constructor() {
// Initialize variables for display as well as prediction purposes
this.exampleCountDisplay = [];
this.checkMarks = [];
this.gestureCards = [];
this.training = -1; // -1 when no class is being trained
this.videoPlaying = false;
this.previousPrediction = -1;
this.currentPredictedWords = [];
// Variables to restrict prediction rate
this.now;
this.then = Date.now();
this.startTime = this.then;
this.fps = 5; //framerate - number of prediction per second
this.fpsInterval = 1000 / this.fps;
this.elapsed = 0;
// Initalizing kNN model to none.
this.knn = null;
/* Initalizing previous kNN model that we trained when training of the current model
is stopped or prediction has begun. */
this.previousKnn = this.knn;
// Storing all elements that from the User Interface that need to be altered into variables.
this.welcomeContainer = document.getElementById("welcomeContainer");
this.proceedBtn = document.getElementById("proceedButton");
this.proceedBtn.style.display = "block";
this.proceedBtn.classList.add("animated");
this.proceedBtn.classList.add("flash");
this.proceedBtn.addEventListener('click', () => {
this.welcomeContainer.classList.add("slideOutUp");
})
this.stageTitle = document.getElementById("stage");
this.stageInstruction = document.getElementById("steps");
this.predButton = document.getElementById("predictButton");
this.backToTrainButton = document.getElementById("backButton");
this.nextButton = document.getElementById('nextButton');
this.statusContainer = document.getElementById("status");
this.statusText = document.getElementById("status-text");
this.translationHolder = document.getElementById("translationHolder");
this.translationText = document.getElementById("translationText");
this.translatedCard = document.getElementById("translatedCard");
this.initialTrainingHolder = document.getElementById('initialTrainingHolder');
this.videoContainer = document.getElementById("videoHolder");
this.video = document.getElementById("video");
this.trainingContainer = document.getElementById("trainingHolder");
this.addGestureTitle = document.getElementById("add-gesture");
this.plusImage = document.getElementById("plus_sign");
this.addWordForm = document.getElementById("add-word");
this.newWordInput = document.getElementById("new-word");
this.doneRetrain = document.getElementById("doneRetrain");
this.trainingCommands = document.getElementById("trainingCommands");
this.videoCallBtn = document.getElementById("videoCallBtn");
this.videoCall = document.getElementById("videoCall");
this.trainedCardsHolder = document.getElementById("trainedCardsHolder");
// Start Translator function is called
this.initializeTranslator();
// Instantiate Prediction Output
this.predictionOutput = new PredictionOutput();
}
/*This function starts the webcam and initial training process. It also loads the kNN
classifier*/
initializeTranslator() {
this.startWebcam();
this.initialTraining();
this.loadKNN();
}
//This function sets up the webcam
startWebcam() {
navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'user'
},
audio: false
})
.then((stream) => {
this.video.srcObject = stream;
this.video.width = IMAGE_SIZE;
this.video.height = IMAGE_SIZE;
this.video.addEventListener('playing', () => this.videoPlaying = true);
this.video.addEventListener('paused', () => this.videoPlaying = false);
})
}
/*This function initializes the training for Start and Stop Gestures. It also
sets a click listener for the next button.*/
initialTraining() {
// if next button on initial training page is pressed, setup the custom gesture training UI.
this.nextButton.addEventListener('click', () => {
const exampleCount = this.knn.getClassExampleCount();
if (Math.max(...exampleCount) > 0) {
// if start gesture has not been trained
if (exampleCount[0] == 0) {
alert('You haven\'t added examples for the Start Gesture');
return;
}
// if stop gesture has not been trained
if (exampleCount[1] == 0) {
alert('You haven\'t added examples for the Stop Gesture.\n\nCapture yourself in idle states e.g hands by your side, empty background etc.');
return;
}
this.nextButton.style.display = "none";
this.stageTitle.innerText = "Continue Training";
this.stageInstruction.innerText = "Add Gesture Name and Train.";
//Start custom gesture training process
this.setupTrainingUI();
}
});
//Create initial training buttons
this.initialGestures(0, "startButton");
this.initialGestures(1, "stopButton");
}
//This function loads the kNN classifier
loadKNN() {
this.knn = new KNNImageClassifier(words.length, TOPK);
// Load knn model
this.knn.load().then(() => this.initializeTraining());
}
/*This creates the training and clear buttons for the initial Start and Stop gesture.
It also creates the Gesture Card.*/
initialGestures(i, btnType) {
// Get specified training button
var trainBtn = document.getElementById(btnType);
// Call training function for this gesture on click
trainBtn.addEventListener('click', () => {
this.train(i);
});
// Clear button to remove training examples on click
var clearBtn = document.getElementById('clear_' + btnType);
clearBtn.addEventListener('click', () => {
this.knn.clearClass(i);
this.exampleCountDisplay[i].innerText = " 0 examples";
this.gestureCards[i].removeChild(this.gestureCards[i].childNodes[1]);
this.checkMarks[i].src = "Images\\loader.gif";
});
// Variables for training information for the user
var exampleCountDisplay = document.getElementById('counter_' + btnType);
var checkMark = document.getElementById('checkmark_' + btnType);
// Create Gesture Card
var gestureCard = document.createElement("div");
gestureCard.className = "trained-gestures";
var gestName = "";
if (i == 0) {
gestName = "Start";
} else {
gestName = "Stop";
}
var gestureName = document.createElement("h5");
gestureName.innerText = gestName;
gestureCard.appendChild(gestureName);
this.trainedCardsHolder.appendChild(gestureCard);
exampleCountDisplay.innerText = " 0 examples";
checkMark.src = 'Images\\loader.gif';
this.exampleCountDisplay.push(exampleCountDisplay);
this.checkMarks.push(checkMark);
this.gestureCards.push(gestureCard);
}
/*This function sets up the custom gesture training UI.*/
setupTrainingUI() {
const exampleCount = this.knn.getClassExampleCount();
// check if training is complete
if (Math.max(...exampleCount) > 0) {
// if start gesture has not been trained
if (exampleCount[0] == 0) {
alert('You haven\'t added examples for the wake word');
return;
}
// if stop gesture has not been trained
if (exampleCount[1] == 0) {
alert('You haven\'t added examples for the Stop Gesture.\n\nCapture yourself in idle states e.g hands by your side, empty background etc.');
return;
}
// Remove Initial Training Screen
this.initialTrainingHolder.style.display = "none";
// Add the Custom Gesture Training UI
this.trainingContainer.style.display = "block";
this.trainedCardsHolder.style.display = "block";
// Add Gesture on Submission of new gesture form
this.addWordForm.addEventListener('submit', (e) => {
this.trainingCommands.innerHTML = "";
e.preventDefault(); // preventing default submission action
var word = this.newWordInput.value.trim(); // returns new word without whitespace
// if a new word is entered, add it to the gesture classes and start training
if (word && !words.includes(word)) {
//Add word to words array
words.push(word);
// Create train and clear buttons for new gesture and set reset form
this.createTrainingBtns(words.indexOf(word));
this.newWordInput.value = '';
// Increase the amount of classes and array length in the kNN model
this.knn.numClasses += 1;
this.knn.classLogitsMatrices.push(null);
this.knn.classExampleCount.push(0);
// Start training the word and create the translate button
this.initializeTraining();
this.createTranslateBtn();
} else {
alert("Duplicate word or no word entered");
}
return;
});
} else {
alert('You haven\'t added any examples yet.\n\nAdd a Gesture, then perform the sign in front of the webcam.');
}
}
/*This creates the training and clear buttons for the new gesture. It also creates the
Gesture Card.*/
createTrainingBtns(i) { //i is the index of the new word
// Create Train and Clear Buttons
var trainBtn = document.createElement('button');
trainBtn.className = "trainBtn";
trainBtn.innerText = "Train";
this.trainingCommands.appendChild(trainBtn);
var clearBtn = document.createElement('button');
clearBtn.className = "clearButton";
clearBtn.innerText = "Clear";
this.trainingCommands.appendChild(clearBtn);
// Change training class from none to specified class if training button is pressed
trainBtn.addEventListener('mousedown', () => {
this.train(i);
});
// Create clear button to remove training examples on click
clearBtn.addEventListener('click', () => {
this.knn.clearClass(i);
this.exampleCountDisplay[i].innerText = " 0 examples";
this.gestureCards[i].removeChild(this.gestureCards[i].childNodes[1]);
this.checkMarks[i].src = 'Images\\loader.gif';
});
// Create elements to display training information for the user
var exampleCountDisplay = document.createElement('h3');
exampleCountDisplay.style.color = "black";
this.trainingCommands.appendChild(exampleCountDisplay);
var checkMark = document.createElement('img');
checkMark.className = "checkMark";
this.trainingCommands.appendChild(checkMark);
//Create Gesture Card
var gestureCard = document.createElement("div");
gestureCard.className = "trained-gestures";
var gestName = words[i];
var gestureName = document.createElement("h5");
gestureName.innerText = gestName;
gestureCard.appendChild(gestureName);
this.trainedCardsHolder.appendChild(gestureCard);
exampleCountDisplay.innerText = " 0 examples";
checkMark.src = 'Images\\loader.gif';
this.exampleCountDisplay.push(exampleCountDisplay);
this.checkMarks.push(checkMark);
this.gestureCards.push(gestureCard);
// Retrain/Continue Training gesture on click of the gesture card
gestureCard.addEventListener('click', () => { //create btn
/* If gesture card was not already pressed display the specific gesture card's
training buttons to train it*/
if (gestureCard.style.marginTop == "17px" || gestureCard.style.marginTop == "") {
this.addWordForm.style.display = "none";
this.addGestureTitle.innerText = gestName;
this.plusImage.src = "Images/retrain.svg";
this.plusImage.classList.add("rotateIn");
// Display done retraining button and the training buttons for the specific gesture
this.doneRetrain.style.display = "block";
this.trainingCommands.innerHTML = "";
this.trainingCommands.appendChild(trainBtn);
this.trainingCommands.appendChild(clearBtn);
this.trainingCommands.appendChild(exampleCountDisplay);
this.trainingCommands.appendChild(checkMark);
gestureCard.style.marginTop = "-10px";
}
// if gesture card is pressed again, change the add gesture card back to add gesture mode instead of retrain mode
else {
this.addGestureTitle.innerText = "Add Gesture";
this.addWordForm.style.display = "block";
gestureCard.style.marginTop = "17px";
this.trainingCommands.innerHTML = "";
this.addWordForm.style.display = "block";
this.doneRetrain.style.display = "none";
this.plusImage.src = "Images/plus_sign.svg";
this.plusImage.classList.add("rotateInLeft");
}
});
// if done retrain button is pressed again, change the add gesture card back to add gesture mode instead of retrain mode
this.doneRetrain.addEventListener('click', () => {
this.addGestureTitle.innerText = "Add Gesture";
this.addWordForm.style.display = "block";
gestureCard.style.marginTop = "17px";
this.trainingCommands.innerHTML = "";
this.addWordForm.style.display = "block";
this.plusImage.src = "Images/plus_sign.svg";
this.plusImage.classList.add("rotateInLeft");
this.doneRetrain.style.display = "none";
});
}
// This function starts the training process.
initializeTraining() {
if (this.timer) {
this.stopTraining();
}
var promise = this.video.play();
if (promise !== undefined) {
promise.then(_ => {
console.log("Autoplay started")
}).catch(error => {
console.log("Autoplay prevented")
})
}
}
// This function adds examples for the gesture to the kNN model
train(gestureIndex) {
console.log(this.videoPlaying);
if (this.videoPlaying) {
console.log("entered training");
// Get image data from video element
const image = dl.fromPixels(this.video);
// Add current image to classifier
this.knn.addImage(image, gestureIndex);
// Get example count
const exampleCount = this.knn.getClassExampleCount()[gestureIndex];
if (exampleCount > 0) {
//if example count for this particular gesture is more than 0, update it
this.exampleCountDisplay[gestureIndex].innerText = ' ' + exampleCount + ' examples';
//if example count for this particular gesture is 1, add a capture of the gesture to gesture cards
if (exampleCount == 1 && this.gestureCards[gestureIndex].childNodes[1] == null) {
var gestureImg = document.createElement("canvas");
gestureImg.className = "trained_image";
gestureImg.getContext('2d').drawImage(video, 0, 0, 400, 180);
this.gestureCards[gestureIndex].appendChild(gestureImg);
}
// if 30 examples are trained, show check mark to the user
if (exampleCount == 30) {
this.checkMarks[gestureIndex].src = "Images//checkmark.svg";
this.checkMarks[gestureIndex].classList.add("animated");
this.checkMarks[gestureIndex].classList.add("rotateIn");
}
}
}
}
/*This function creates the button that goes to the Translate Page. It also initializes the UI
of the translate page and starts or stops prediction on click.*/
createTranslateBtn() {
this.predButton.style.display = "block";
this.createVideoCallBtn(); // create video call button that displays on translate page
this.createBackToTrainBtn(); // create back to train button that will go back to training page
this.predButton.addEventListener('click', () => {
// Change the styling of video display and start prediction
console.log("go to translate");
const exampleCount = this.knn.getClassExampleCount();
// check if training is complete
if (Math.max(...exampleCount) > 0) {
this.video.style.display = "inline-block"; // turn on video from webscam in case it's off
this.videoCall.style.display = "none"; // turn off video call in case it's on
this.videoCallBtn.style.display = "block";
this.backToTrainButton.style.display = "block";
// Change style of video display
this.video.className = "videoPredict";
this.videoContainer.style.display = "inline-block";
this.videoContainer.style.width = "";
this.videoContainer.style.height = "";
this.videoContainer.className = "videoContainerPredict";
this.videoContainer.style.border = "8px solid black";
// Update stage and instruction info
this.stageTitle.innerText = "Translate";
this.stageInstruction.innerText = "Start Translating with your Start Gesture.";
// Remove training UI
this.trainingContainer.style.display = "none";
this.trainedCardsHolder.style.marginTop = "130px";
// Display translation holder that contains translated text
this.translationHolder.style.display = "block";
this.predButton.style.display = "none";
// Start Translation
this.setUpTranslation();
} else {
alert('You haven\'t added any examples yet.\n\nPress and hold on the "Add Example" button next to each word while performing the sign in front of the webcam.');
}
})
}
/*This function stops the training process and allows user's to copy text on the click of
the translation text.*/
setUpTranslation() {
// stop training
if (this.timer) {
this.stopTraining();
}
// Set status to predict, call copy translated text listener and start prediction
this.setStatusText("Status: Ready to Predict!", "predict");
this.video.play();
this.pred = requestAnimationFrame(this.predict.bind(this));
}
/*This function predicts the class of the gesture and returns the predicted text if its above a set threshold.*/
predict() {
this.now = Date.now();
this.elapsed = this.now - this.then;
if (this.elapsed > this.fpsInterval) {
this.then = this.now - this.elapsed % this.fpsInterval;
if (this.videoPlaying) {
const exampleCount = this.knn.getClassExampleCount();
const image = dl.fromPixels(this.video);
if (Math.max(...exampleCount) > 0) {
this.knn.predictClass(image)
.then((res) => {
for (let i = 0; i < words.length; i++) {
/*if gesture matches this word & is above threshold & isn't same as prev prediction
and is not stop gesture, return that word to the user*/
if (res.classIndex == i && res.confidences[i] > confidenceThreshold && res.classIndex != this.previousPrediction) { // && res.classIndex != 1) {
this.setStatusText("Status: Predicting!", "predict");
// Send word to Prediction Output so it will display or speak out the word.
this.predictionOutput.textOutput(words[i], this.gestureCards[i], res.confidences[i] * 100);
// set previous prediction so it doesnt get called again
this.previousPrediction = res.classIndex;
}
}
}).then(() => image.dispose())
} else {
image.dispose();
}
}
}
// Recursion on predict method
this.pred = requestAnimationFrame(this.predict.bind(this));
}
/*This function pauses the predict method*/
pausePredicting() {
console.log("pause predicting");
this.setStatusText("Status: Paused Predicting", "predict");
cancelAnimationFrame(this.pred);
this.previousKnn = this.knn;
}
// if predict button is actually a back to training button, stop translation and recreate training UI
createBackToTrainBtn() {
this.backToTrainButton.addEventListener('click', () => {
main.pausePredicting();
this.stageTitle.innerText = "Continue Training";
this.stageInstruction.innerText = "Add Gesture Name and Train.";
this.predButton.innerText = "Translate";
this.predButton.style.display = "block";
this.backToTrainButton.style.display = "none";
this.statusContainer.style.display = "none";
// Remove all elements from translation mode
this.video.className = "videoTrain";
this.videoContainer.className = "videoContainerTrain";
this.videoCallBtn.style.display = "none";
this.translationHolder.style.display = "none";
this.statusContainer.style.display = "none";
// Show elements from training mode
this.trainingContainer.style.display = "block";
this.trainedCardsHolder.style.marginTop = "0px";
this.trainedCardsHolder.style.display = "block";
});
}
/*This function stops the training process*/
stopTraining() {
this.video.pause();
cancelAnimationFrame(this.timer);
console.log("Knn for start: " + this.knn.getClassExampleCount()[0]);
this.previousKnn = this.knn; // saves current knn model so it can be used later
}
/*This function displays the button that start video call.*/
createVideoCallBtn() {
// Display video call feed instead of normal webcam feed when video call btn is clicked
videoCallBtn.addEventListener('click', () => {
this.stageTitle.innerText = "Video Call";
this.stageInstruction.innerText = "Translate Gestures to talk to people on Video Call";
this.video.style.display = "none";
this.videoContainer.style.borderStyle = "none";
this.videoContainer.style.overflow = "hidden";
this.videoContainer.style.width = "630px";
this.videoContainer.style.height = "355px";
this.videoCall.style.display = "block";
this.videoCallBtn.style.display = "none";
this.backToTrainButton.style.display = "none";
this.predButton.innerText = "Local Translation";
this.predButton.style.display = "block";
this.setStatusText("Status: Video Call Activated");
})
}
/*This function sets the status text*/
setStatusText(status, type) { //make default type thing
this.statusContainer.style.display = "block";
this.statusText.innerText = status;
if (type == "copy") {
console.log("copy");
this.statusContainer.style.backgroundColor = "blue";
} else {
this.statusContainer.style.backgroundColor = "black";
}
}
} |
JavaScript | class PredictionOutput {
constructor() {
//Initializing variables for speech synthesis and output
this.synth = window.speechSynthesis;
this.voices = [];
this.pitch = 1.0;
this.rate = 0.9;
this.statusContainer = document.getElementById("status");
this.statusText = document.getElementById("status-text");
this.translationHolder = document.getElementById("translationHolder");
this.translationText = document.getElementById("translationText");
this.translatedCard = document.getElementById("translatedCard");
this.trainedCardsHolder = document.getElementById("trainedCardsHolder");
this.selectedVoice = 48; // this is Google-US en. Can set voice and language of choice
this.currentPredictedWords = [];
this.waitTimeForQuery = 10000;
this.synth.onvoiceschanged = () => {
this.populateVoiceList()
};
//Set up copy translation event listener
this.copyTranslation();
}
// Checks if speech synthesis is possible and if selected voice is available
populateVoiceList() {
if (typeof speechSynthesis === 'undefined') {
console.log("no synth");
return;
}
this.voices = this.synth.getVoices();
if (this.voices.indexOf(this.selectedVoice) > 0) {
console.log(this.voices[this.selectedVoice].name + ':' + this.voices[this.selectedVoice].lang);
}
}
/*This function outputs the word using text and gesture cards*/
textOutput(word, gestureCard, gestureAccuracy) {
// If the word is start, clear translated text content
if (word == 'start') {
this.clearPara();
setTimeout(() => {
// if no query detected after start is signed, clear para
if (this.currentPredictedWords.length == 1) {
this.clearPara();
}
}, this.waitTimeForQuery);
}
// If first word is not start, return
if (word != 'start' && this.currentPredictedWords.length == 0) {
return;
}
// If word was already said in this query, return
if (this.currentPredictedWords.includes(word)) {
return;
}
// Add word to predicted words in this query
this.currentPredictedWords.push(word);
// Depending on the word, display the text output
if (word == "start") {
this.translationText.innerText += ' ';
} else if (word == "stop") {
this.translationText.innerText += '.';
} else {
this.translationText.innerText += ' ' + word;
}
//Clone Gesture Card
this.translatedCard.innerHTML = " ";
var clonedCard = document.createElement("div");
clonedCard.className = "trained-gestures";
var gestName = gestureCard.childNodes[0].innerText;
var gestureName = document.createElement("h5");
gestureName.innerText = gestName;
clonedCard.appendChild(gestureName);
var gestureImg = document.createElement("canvas");
gestureImg.className = "trained_image";
gestureImg.getContext('2d').drawImage(gestureCard.childNodes[1], 0, 0, 400, 180);
clonedCard.appendChild(gestureImg);
var gestAccuracy = document.createElement("h7");
gestAccuracy.innerText = "Confidence: " + gestureAccuracy + "%";
clonedCard.appendChild(gestAccuracy);
this.translatedCard.appendChild(clonedCard);
// If its not video call mode, speak out the user's word
if (word != "start" && word != "stop") {
this.speak(word);
}
}
/*This functions clears translation text and cards. Sets the previous predicted words to null*/
clearPara() {
this.translationText.innerText = '';
main.previousPrediction = -1;
this.currentPredictedWords = []; // empty words in this query
this.translatedCard.innerHTML = " ";
}
/*The function below is adapted from https://stackoverflow.com/questions/45071353/javascript-copy-text-string-on-click/53977796#53977796
It copies the translated text to the user's clipboard*/
copyTranslation() {
this.translationHolder.addEventListener('mousedown', () => {
main.setStatusText("Text Copied!", "copy");
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = this.translationText.innerText; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
?
document.getSelection().getRangeAt(0) // Store selection if found
:
false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
});
}
/*This function speaks out the user's gestures. In video call mode, it speaks out the other
user's words.*/
speak(word) {
var utterThis = new SpeechSynthesisUtterance(word);
utterThis.onerror = function (evt) {
console.log("Error speaking");
};
utterThis.voice = this.voices[this.selectedVoice];
utterThis.pitch = this.pitch;
utterThis.rate = this.rate;
this.synth.speak(utterThis);
}
} |
JavaScript | class AdminRequest {
static getAttributeTypeMap() {
return AdminRequest.attributeTypeMap;
}
} |
JavaScript | class Paragraph extends Node {
get name() {
return 'paragraph';
}
get schema() {
return {
content: 'inline*',
group: 'block',
parseDOM: [{ tag: 'p' }],
toDOM: () => ['p', 0],
};
}
toMarkdown(state, node) {
defaultMarkdownSerializer.nodes.paragraph(state, node);
}
} |
JavaScript | class Help {
constructor() {
this.commands = [];
this.inactiveCommands = [];
this.adminCommands = [];
this.setupCommands();
this.setupAdminCommands();
}
setupCommands() {
this.commands.push({
command: '!skipMe',
description:
'Will skip your next turn and put you back to the end of the host queue.',
});
this.commands.push({
command: '!timeLeft',
description: 'Will display the time left until next round starts.',
});
this.inactiveCommands.push({
command: '!new',
description: 'Will start the process of creating a new managed lobby.',
});
}
setupAdminCommands() {
this.adminCommands.push({
command: '!allow',
description: 'Will disable beatmap restriction for upcoming round.',
});
this.adminCommands.push({
command: '!skipTo {playerName}',
description:
'Will skip the queue to given player name. All skipped players will be put to the end of queue as if they had been host already.',
});
}
getCommands(admin = false) {
const output = [];
output.push('Basic commands:');
Object.keys(this.commands).forEach((key) => {
output.push(
`${this.commands[key].command}: ${this.commands[key].description}`
);
});
if (admin) {
output.push('-');
output.push('Admin commands:');
Object.keys(this.adminCommands).forEach((key) => {
output.push(
`${this.adminCommands[key].command}: ${this.adminCommands[key].description}`
);
});
}
return output;
}
} |
JavaScript | class OdemAdapterFile extends Services.OdemAdapter {
/**
* @param {object} config configuration of adapter
*/
constructor( config ) {
super();
const _config = Object.assign( {}, DefaultConfig, config );
Object.defineProperties( this, {
/**
* Exposes configuration customizing behaviour of current adapter.
*
* @name OdemAdapterFile#config
* @property {object}
* @readonly
*/
config: { value: _config },
/**
* Exposes data source managed by current adapter.
*
* @note In context of OdemAdapterFile this is a promise for the path
* name of folder containing all files managed by this adapter
* actually existing in filesystem.
*
* @name OdemAdapterFile#dataSource
* @property {Promise<string>}
* @readonly
*/
dataSource: { value: this.constructor.makeDirectory( PathResolve( _config.dataSource ) ) },
} );
}
/**
* Safely creates folders using map of currently running folder creations to
* prevent multiple actions trying to create same folder resulting in race
* conditions.
*
* @param {string} baseFolder base folder
* @param {string|string[]} folder sub-folder to create in context of given base folder
* @returns {Promise} promises folder created
*/
static makeDirectory( baseFolder, folder = null ) {
const _folder = folder == null ? baseFolder : Array.isArray( folder ) ? PathResolve( baseFolder, ...folder ) : PathResolve( baseFolder, folder );
if ( FolderCreator.has( _folder ) ) {
return FolderCreator.get( _folder );
}
const promise = MkDir( baseFolder, folder );
FolderCreator.set( _folder, promise );
promise
.then( () => FolderCreator.delete( _folder ) )
.catch( () => FolderCreator.delete( _folder ) );
return promise;
}
/** @inheritDoc */
purge() {
return this.dataSource.then( path => RmDir( path, { subsOnly: true } ) );
}
/** @inheritDoc */
create( keyTemplate, data ) {
let key = null;
return this.dataSource.then( path => MkFile( path, {
uuidToPath: uuid => {
key = keyTemplate.replace( /%u/g, uuid );
return this.constructor.keyToPath( key ).split( /[\\/]/ );
},
} ) )
.then( ( { fd } ) => new Promise( ( resolve, reject ) => {
fsWrite( fd, JSON.stringify( data ), 0, "utf8", writeError => {
if ( writeError ) {
close( fd );
reject( writeError );
} else {
close( fd, closeError => {
if ( closeError ) {
reject( closeError );
} else {
resolve( key );
}
} );
}
} );
} ) );
}
/** @inheritDoc */
has( key ) {
return this.dataSource
.then( path => Stat( PathResolve( path, this.constructor.keyToPath( key ) ) ) )
.then( s => Boolean( s ) );
}
/** @inheritDoc */
read( key, { ifMissing = null } = {} ) {
const subPath = this.constructor.keyToPath( key );
if ( subPath.match( /[\\/]\.\.?[\\/]/ ) ) {
return Promise.reject( Object.assign( new Error( "invalid key: " + key ), { code: "EBADKEY" } ) );
}
return this.dataSource
.then( basePath => PathResolve( basePath, subPath ) )
.then( path => {
const parent = dirname( path );
return Stat( parent )
.then( exists => {
if ( exists && exists.isDirectory() ) {
return Read( path )
.then( content => JSON.parse( content.toString( "utf8" ) ) )
.catch( error => {
if ( error.code === "ENOENT" ) {
if ( ifMissing ) {
return ifMissing;
}
throw Object.assign( new Error( `no such record @${key}` ), { code: "ENOENT" } );
}
throw error;
} );
}
if ( ifMissing ) {
return ifMissing;
}
throw Object.assign( new Error( `no such record @${key}` ), { code: "ENOENT" } );
} );
} );
}
/** @inheritDoc */
write( key, data ) {
const path = this.constructor.keyToPath( key );
if ( path.match( /[\\/]\.\.?[\\/]/ ) ) {
return Promise.reject( new Error( "invalid key: " + key ) );
}
const parent = dirname( path );
let promise;
switch ( parent ) {
case "" :
case "." :
case "/" :
promise = this.dataSource;
break;
default :
promise = this.dataSource
.then( basePath => this.constructor.makeDirectory( basePath, parent ).then( () => basePath ) );
}
return promise
.then( basePath => {
// create controllable promise
let resultResolve, resultReject;
const result = new Promise( ( resolve, reject ) => {
resultResolve = resolve;
resultReject = reject;
} );
// make sure to have a queue of writers for resulting file
const filename = PathResolve( basePath, path );
let queue = FileWriters.get( filename );
if ( !Array.isArray( queue ) ) {
queue = [];
FileWriters.set( filename, queue );
}
// create writer triggering next queued writer when finished
const writer = () => {
const written = Write( filename, JSON.stringify( data ) );
written.then( resultResolve, resultReject ); // eslint-disable-line promise/catch-or-return
written // eslint-disable-line promise/catch-or-return
.catch( () => {} )// eslint-disable-line no-empty-function
.then( () => {
if ( queue.length > 0 ) {
queue.shift()();
} else {
FileWriters.delete( filename );
}
} );
};
// enqueue or invoke created writer
if ( queue.length > 0 ) {
queue.push( writer );
} else {
writer();
}
return result;
} )
.then( () => data );
}
/** @inheritDoc */
remove( key ) {
const path = this.constructor.keyToPath( key );
if ( path.match( /[\\/]\.\.?[\\/]/ ) ) {
return Promise.reject( new Error( "invalid key: " + key ) );
}
return this.dataSource
.then( basePath => RmDir( PathResolve( basePath, path ) ) )
.then( () => key );
}
/** @inheritDoc */
keyStream( { prefix = "", maxDepth = Infinity, separator = "/" } = {} ) {
const { pathToKey } = this.constructor;
return this.constructor._createStream( this.dataSource, {
prefix,
maxDepth,
separator,
converter: function( local, full, state ) {
if ( !state.isDirectory() ) {
const key = local === "." ? "" : pathToKey( local );
return prefix === "" ? key : posix.join( prefix, key );
}
return null;
},
} );
}
/**
* Commonly implements integration of file-essential's find() method for
* streaming either keys or values of records stored in selected datasource.
*
* @param {Promise<string>} dataSource path name of folder containing all records of this adapter
* @param {function()} converter callback passed to file-essential's find()
* method for converting matching file's path names into whatever
* should be streamed
* @param {function(object,string):Promise<Buffer>} retriever optional
* callback to be called from filter passed to file-essential's find()
* method on matching files e.g. for reading and caching their content
* @param {string} prefix limits stream to expose records with keys matching this prefix, only
* @param {int} maxDepth maximum depth on descending into keys' hierarchy
* @param {string} separator separator used to divide keys into hierarchical paths
* @returns {Readable} stream generating either keys or content of matching records in backend
* @private
*/
static _createStream( dataSource, { converter, retriever = null, prefix, maxDepth, separator } ) {
const ptnFinal = /(^|[\\/])[ps][^\\/]+$/i;
const { keyToPath, pathToKey } = this;
const prefixPath = keyToPath( prefix );
const stream = new PassThrough( { objectMode: true } );
dataSource.then( basePath => PathResolve( basePath, prefixPath ) ).then( base => {
return Stat( base ).then( stats => { // eslint-disable-line consistent-return
if ( !stats ) {
stream.end();
} else if ( stats.isDirectory() ) {
const source = Find( base, {
stream: true,
filter: function( local, full, state ) {
if ( state.isDirectory() ) {
if ( separator ) {
let key;
try {
key = pathToKey( local );
} catch ( e ) {
return true;
}
if ( key.split( separator ).length >= maxDepth ) {
return false;
}
}
return ptnFinal.test( local );
}
if ( !ptnFinal.test( local ) ) {
return false;
}
let partials = 0;
const segments = local.split( sep );
for ( let i = 0, length = segments.length; i < length; i++ ) {
switch ( segments[i][0] ) {
case "p" :
case "P" :
partials++;
break;
case "s" :
case "S" :
if ( partials % 3 !== 0 ) {
return false;
}
partials = 0;
break;
default :
// basically excluded due to testing directories above
return false;
}
}
if ( partials % 3 === 0 ) {
if ( retriever ) {
return retriever( this, full ).then( () => true );
}
return true;
}
return false;
},
converter,
} );
stream.on( "close", () => {
source.unpipe( stream );
source.pause();
source.destroy();
} );
source.pipe( stream );
} else if ( retriever ) {
const context = {};
return retriever( context, base )
.then( () => stream.end( converter.call( context, ".", base, stats ) ) );
} else {
stream.end( converter.call( {}, ".", base, stats ) );
}
} );
} )
.catch( error => stream.emit( "error", error ) );
return stream;
}
/** @inheritDoc */
static keyToPath( key ) {
if ( key === "" ) {
return "";
}
const segments = key.split( /\//g );
const length = segments.length;
const copy = new Array( length * 3 );
let write = 0;
for ( let i = 0; i < length; i++ ) {
const segment = segments[i];
if ( Services.OdemUtilityUuid.ptnUuid.test( segment ) ) {
copy[write++] = "p" + segment[0];
copy[write++] = "p" + segment.slice( 1, 3 );
copy[write++] = "p" + segment.slice( 3 );
} else {
copy[write++] = "s" + segment;
}
}
copy.splice( write );
return copy.join( sep );
}
/** @inheritDoc */
static pathToKey( path ) {
if ( path === "" ) {
return "";
}
const segments = path.split( /[\\/]/g );
const length = segments.length;
const copy = new Array( length );
let write = 0;
for ( let i = 0; i < length; i++ ) {
const segment = segments[i];
switch ( segment[0] ) {
case "P" :
case "p" : {
const next = segments[i + 1];
const second = segments[i + 2];
if ( next == null || ( next[0] !== "p" && next[0] !== "P" ) || second == null || ( second[0] !== "p" && second[0] !== "P" ) ) {
throw new Error( "insufficient partials of UUID in path" );
}
copy[write++] = segment.slice( 1 ) + next.slice( 1 ) + second.slice( 1 );
i += 2;
break;
}
case "S" :
case "s" :
copy[write++] = segment.slice( 1 );
break;
default :
throw new Error( "malformed segment in path name" );
}
}
copy.splice( write );
return copy.join( "/" );
}
} |
JavaScript | class CmsPageGuardService {
constructor(semanticPathService, cmsService, cmsRoutes, cmsI18n, cmsGuards, cmsComponentsService, routing) {
this.semanticPathService = semanticPathService;
this.cmsService = cmsService;
this.cmsRoutes = cmsRoutes;
this.cmsI18n = cmsI18n;
this.cmsGuards = cmsGuards;
this.cmsComponentsService = cmsComponentsService;
this.routing = routing;
}
/**
* Takes CMS components types in the current CMS page, triggers (configurable) side effects and returns a boolean - whether the route can be activated.
*
* Based on `cmsComponents` config for the components in the page:
* - Evaluates components' guards; if one of them emits false or UrlTree - the route cannot be activated or redirects to the given UrlTree, respectively.
* - If all components' guards emitted true, then the route can be activated
* - Then we trigger loading of configured i18n chunks in parallel
* - And we register the configured children routes of cms components
*
* @param pageContext current cms page context
* @param pageData cms page data
* @param route activated route snapshot
* @param state router state snapshot
*
* @returns boolean observable - whether the route can be activated
*/
canActivatePage(pageContext, pageData, route, state) {
return this.cmsService.getPageComponentTypes(pageContext).pipe(take(1), switchMap((componentTypes) => this.cmsComponentsService.determineMappings(componentTypes)), switchMap((componentTypes) => this.cmsGuards
.cmsPageCanActivate(componentTypes, route, state)
.pipe(withLatestFrom(of(componentTypes)))), tap(([canActivate, componentTypes]) => {
if (canActivate === true) {
this.cmsI18n.loadForComponents(componentTypes);
}
}), map(([canActivate, componentTypes]) => {
var _a;
const pageLabel = pageData.label || pageContext.id; // for content pages the page label returned from backend can be different than ID initially assumed from route
if (canActivate === true && !((_a = route === null || route === void 0 ? void 0 : route.data) === null || _a === void 0 ? void 0 : _a.cxCmsRouteContext)) {
return this.cmsRoutes.handleCmsRoutesInGuard(pageContext, componentTypes, state.url, pageLabel);
}
return canActivate;
}));
}
/**
* Activates the "NOT FOUND" cms page.
*
* It loads cms page data for the "NOT FOUND" page and puts it in the state of the the requested page label.
* Then it processes its CMS components with the method `canActivatePage()` of this service. For more, see its docs.
*/
canActivateNotFoundPage(pageContext, route, state) {
const notFoundCmsPageContext = {
type: PageType.CONTENT_PAGE,
id: this.semanticPathService.get('notFound'),
};
return this.cmsService.getPage(notFoundCmsPageContext).pipe(switchMap((notFoundPage) => {
if (notFoundPage) {
return this.cmsService.getPageIndex(notFoundCmsPageContext).pipe(tap((notFoundIndex) => {
this.cmsService.setPageFailIndex(pageContext, notFoundIndex);
this.routing.changeNextPageContext(notFoundCmsPageContext);
}), switchMap((notFoundIndex) => this.cmsService.getPageIndex(pageContext).pipe(
// we have to wait for page index update
filter((index) => index === notFoundIndex))), switchMap(() => this.canActivatePage(pageContext, notFoundPage, route, state)));
}
return of(false);
}));
}
} |
JavaScript | class JSPanel {
/**
* @constructs JSPanel
* @param {HTMLButtonElement} button The button which will display the panel.
* @param {{top?:number,right?:number,bottom?:number,left?:number,items:Array<{title:string,id?:number,icon?:string,fontawesome_icon?:string,fontawesome_color?:string,className?:string,attributes?:Array<Array<string>>,onclick?:Function,separator?:boolean}>}} options The options to customize the panel.
*/
constructor(button, options) {
/**
* The panel.
* @type {HTMLElement|null}
* @default null
* @private
*/
this.panel = null;
this.button = button;
this.options = options;
this.panel_uniqueid = "jspanel-" + this._rand(0, 1000000);
this._buildPanel();
this.button.setAttribute("aria-expanded", "false");
this.button.setAttribute("aria-controls", this.panel_uniqueid);
}
/**
* Builds the panel.
* @private
*/
_buildPanel() {
const top = this.options.top === undefined ? null : this.options.top + "px";
const right = this.options.right === undefined ? null : this.options.right + "px";
const bottom = this.options.bottom === undefined ? null : this.options.bottom + "px";
const left = this.options.left === undefined ? null : this.options.left + "px";
this.panel = this._createEl("div", { id: this.panel_uniqueid, className: "jspanel panel-hidden" });
if (top || right || bottom || left) {
if (top)
this.panel.style.top = top;
if (left)
this.panel.style.left = left;
if (right)
this.panel.style.right = right;
if (bottom)
this.panel.style.bottom = bottom;
}
else {
this.panel.style.top = "0px";
this.panel.style.left = "0px";
}
const parent = this.button.parentElement === null ? document.body : this.button.parentElement;
const style_position = window.getComputedStyle(parent).getPropertyValue("position");
if (!this._inArray(style_position, ["fixed", "absolute", "relative"]))
parent.style.position = "relative";
//
// items
//
if (this.options.items) {
const container = this._createEl("div", { className: "container-items" });
for (let i = 0; i < this.options.items.length; i++) {
const item = this.options.items[i];
if (item) {
if (!item.id)
item.id = i;
const built_item = this._buildItem(item);
container.appendChild(built_item);
}
}
this.panel.appendChild(container);
}
else {
throw new Error("You need to define items to be displayed in the panel.");
}
//
// events
//
document.addEventListener("click", (e) => {
const target = e.target;
if (target && this.panel) {
if (!this.panel.contains(target) && this.isOpen()) {
this._closePanel();
}
}
});
this.button.onclick = (e) => { this._togglePanel(e); };
this.button.onkeydown = (e) => { this._toggleOnKeyboardEvent(e); };
this._insertAfterButton(this.panel);
this.panel.onkeydown = (e) => {
if (e.key === "Tab" || e.keyCode === 9) {
if (this.isOpen())
this._focusInPanel(e);
}
};
// I absolutly want the focus to stay inside (and only INSIDE) the panel :)
// For that, I need to add a keydown event to the button too because
// I want to include it during the keyboard navigation (with Tab)
// So that it's easier for the user to close the panel with his/her keyboard.
this.button.onkeydown = (e) => {
if (e.key === "Tab" || e.keyCode === 9) {
if (this.isOpen()) {
e.preventDefault();
const active_elements = this._getAllActiveItems();
if (active_elements && active_elements[0]) {
if (e.shiftKey === true) {
active_elements[active_elements.length - 2].focus(); // -2 because we don't want to take into account the button once again
}
else {
active_elements[0].focus();
}
}
}
}
};
}
/**
* Following the digital accessibility recommendations for this kind of panels,
* it is necessary to open or close the panel by clicking either the Enter or Space key.
* See {@link https://www.accede-web.com/en/guidelines/rich-interface-components/show-hide-panels/} for more information.
* @param {KeyboardEvent} e The keyboard event.
* @private
*/
_toggleOnKeyboardEvent(e) {
if (e.key === "Enter" || e.code === "Enter" || e.keyCode === 13 || e.key === " " || e.keyCode === 32 || e.code === "Space") {
e.preventDefault();
this._togglePanel(e);
}
}
/**
* Checks if the panel is currently opened or not.
* @returns {boolean} True if the panel is opened.
* @public
*/
isOpen() {
if (this.panel) {
return !this.panel.classList.contains("panel-hidden");
}
else {
return false;
}
}
/**
* Open the panel if it's closed, close if it's opened.
* @param {MouseEvent|KeyboardEvent} e The mouse event or the keyboard event.
* @private
*/
_togglePanel(e) {
if (this.button && this.panel) {
e.stopPropagation();
if (this.isOpen()) {
this._closePanel();
}
else {
this.button.setAttribute("aria-expanded", "true");
this.panel.classList.remove("panel-hidden");
const all_items = this._getAllItems();
if (all_items && all_items[0])
all_items[0].focus();
}
}
}
/**
* Gets all the items from the panel if it's open.
* @returns {NodeListOf<HTMLButtonElement>|null} All the items.
* @private
*/
_getAllItems() {
if (this.isOpen()) {
return this.panel.querySelectorAll("button");
}
else {
return null;
}
}
/**
* Gets all the active items from the panel if it's open.
* @returns {Array<HTMLElement>|null} All the items that have an onclick property.
* @private
*/
_getAllActiveItems() {
if (this.isOpen()) {
const active_elements = Array.from(this.panel.querySelectorAll("button"));
active_elements.push(this.button);
return active_elements.filter((e) => e.style.display !== "none" && !e.hasAttribute("disabled"));
}
else {
return null;
}
}
/**
* Closes the panel.
* @private
*/
_closePanel() {
if (this.button && this.panel) {
this.button.setAttribute("aria-expanded", "false");
this.panel.classList.add("panel-hidden");
}
}
/**
* Creates a customizable div element.
* @param {string} tagName The name of the tag.
* @param {{id?:string,className?:string,textContent?:string,attributes?:Array<string>,styles?:Array<string>}} options The options to customize the element.
* @returns {HTMLElement} The created element.
* @private
*/
_createEl(tagName, options) {
const el = document.createElement(tagName);
if (!options)
return el;
if (options.id)
el.setAttribute("id", options.id);
if (options.textContent)
el.textContent = options.textContent;
if (options.className) {
const classes = options.className.split(" ");
for (let clas of classes) {
el.classList.add(clas);
}
}
if (options.styles) {
for (let style of options.styles) {
const property = style[0];
const value = style[1];
el.style[property] = value;
}
}
if (options.attributes) {
for (let attr of options.attributes) {
const name = attr[0];
const value = attr[1];
el.setAttribute(name, value);
}
}
return el;
}
/**
* Builds an item.
* @param {{title:string,id?:number,icon?:string,fontawesome_icon?:string,fontawesome_color?:string,className?:string,attributes?:Array<Array<string>>,onclick?:Function,separator?:boolean}} item The item to build.
* @returns {HTMLElement} The item as an HTML element.
* @private
*/
_buildItem(item) {
const id = item.id.toString();
if (item.separator) {
const div = this._createEl("div", { className: 'jspanel-separator', attributes: [["data-id", id]] });
return div;
}
else {
const button = this._createEl("button");
button.setAttribute("data-id", id);
button.setAttribute("aria-label", item.title);
if ((item.icon && !item.fontawesome_icon) || (item.icon && item.fontawesome_icon)) {
const icon = this._createEl("img", { attributes: [["src", item.icon]] });
button.appendChild(icon);
}
else if (!item.icon && item.fontawesome_icon) {
const icon = this._createEl("i", { className: item.fontawesome_icon });
if (item.fontawesome_color)
icon.style.color = item.fontawesome_color;
button.appendChild(icon);
}
if (item.className) {
const classes = item.className.split(" ");
for (let clas of classes) {
button.classList.add(clas);
}
}
if (item.attributes) {
for (let attr of item.attributes) {
const name = attr[0];
const value = attr[1];
button.setAttribute(name, value);
}
}
const title = this._createEl("span", { textContent: item.title });
button.appendChild(title);
button.addEventListener('click', () => {
if (item.onclick)
item.onclick();
this._closePanel();
});
return button;
}
}
/**
* Blocks the focus inside the panel while it's open.
* @param {KeyboardEvent} e The keyboard event.
* @private
*/
_focusInPanel(e) {
const all_items = this._getAllActiveItems();
if (all_items) {
e.preventDefault();
let index = Array.from(all_items).findIndex(f => this.panel ? f === this.panel.querySelector(":focus") : false);
if (e.shiftKey === true) {
index--;
}
else {
index++;
}
if (index >= all_items.length) {
index = 0;
}
if (index < 0) {
index = all_items.length - 1;
}
all_items[index].focus();
}
}
/**
* Checks the presence of an element in an array
* @param {any} needle The element to search in the array.
* @param {Array<any>} haystack The array in which to search for the element.
* @param {boolean} strict Is the type of the needle necessary when searching? By default: false.
* @returns {boolean} True if the needle was found.
* @private
*/
_inArray(needle, haystack, strict = false) {
const length = haystack.length;
for (let i = 0; i < length; i++) {
if (strict) {
if (haystack[i] === needle)
return true;
}
else {
if (haystack[i] == needle)
return true;
}
}
return false;
}
/**
* Inserts the panel into the DOM (after the button).
* @param {HTMLElement} panel The panel to insert after the button.
* @private
*/
_insertAfterButton(panel) {
const parent = this.button.parentElement === null ? document.body : this.button.parentElement;
parent.insertBefore(panel, this.button.nextSibling);
}
/**
* Generates a random number [min;max[
* @param {number} min The minimum number (included).
* @param {number} max The maximum number (not included).
* @returns {number} A random number between minimum and maximum.
* @private
*/
_rand(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* Toggles an item.
* @param {number} id The id of the item.
* @param {boolean} disable If the item is a button (not a separator), then, instead of display:none, we disable it. By default: false.
* @public
* @since 1.2.0
*/
toggleItem(id, disable = false) {
if (this.panel) {
const items = Array.from(this.panel.querySelectorAll("[data-id='" + id + "']"));
if (disable) {
if (items)
for (let item of items) {
if (item.tagName.toLowerCase() === "button") {
item.hasAttribute("disabled") ? item.removeAttribute("disabled") : item.setAttribute("disabled", "disabled");
}
else {
if (items)
for (let item of items)
item.style.display = item.style.display == "none" ? null : "none";
}
}
}
else {
if (items)
for (let item of items)
item.style.display = item.style.display == "none" ? null : "none";
}
}
}
/**
* Removes an item.
* @param {number} id The id of the item to remove.
* @public
* @since 1.2.0
*/
removeItem(id) {
if (this.panel) {
const item = this.getItem(id);
if (item && item.parentElement) {
item.parentElement.removeChild(item);
}
}
}
/**
* Removes several items.
* @param {Array<number>} ids The ids of the items.
* @public
* @since 1.2.0
*/
removeItems(ids) {
if (this.panel) {
for (let id of ids) {
this.removeItem(id);
}
}
}
/**
* Gets the id of each item.
* @returns {Array<number>} The list of ids.
* @public
* @since 1.2.0
*/
getAllIDS() {
if (this.panel) {
const all_items = Array.from(this.panel.querySelectorAll("[data-id]"));
const all_ids = [];
if (all_items) {
for (let item of all_items) {
all_ids.push(parseInt(item.getAttribute("data-id")));
}
return all_ids;
}
}
return [];
}
/**
* Gets an item.
* @param id The id of the item.
* @returns {HTMLElement|null} The item.
* @public
* @since 1.2.0
*/
getItem(id) {
if (this.panel) {
return this.panel.querySelector("[data-id='" + id + "']");
}
return null;
}
/**
* Builds a new item to be added to the panel after its creation.
* @param {{title:string,id?:number,icon?:string,fontawesome_icon?:string,fontawesome_color?:string,className?:string,attributes?:Array<Array<string>>,onclick?:Function,separator?:boolean}} new_item The new item to be built.
* @param default_new_id The ID of the item, just in case the user did not specify any.
* @returns The HTML element of an item.
* @private
* @since 1.2.0
*/
_buildNewItem(new_item, default_new_id) {
if (!new_item.id && (default_new_id === null || default_new_id === undefined))
throw new Error("An item must have an ID.");
if (!new_item.id)
new_item.id = default_new_id;
const build_item = this._buildItem(new_item);
return build_item;
}
/**
* Adds an item
* @param {{title:string,id?:number,icon?:string,fontawesome_icon?:string,fontawesome_color?:string,className?:string,attributes?:Array<Array<string>>,onclick?:Function,separator?:boolean}} new_item The new item to be built.
* @public
* @since 1.2.0
*/
addItem(new_item) {
if (this.panel) {
this.panel.appendChild(this._buildNewItem(new_item, Math.max(...this.getAllIDS())));
}
}
/**
* Replaces an item by another one.
* @param {{title:string,id?:number,icon?:string,fontawesome_icon?:string,fontawesome_color?:string,className?:string,attributes?:Array<Array<string>>,onclick?:Function,separator?:boolean}} new_item The new item.
* @param {number} id The id of the item to be replaced.
* @public
* @since 1.2.0
*/
replaceItemWith(new_item, id) {
if (this.panel) {
const current_item = this.getItem(id);
if (current_item) {
const new_built_item = this._buildNewItem(new_item, parseInt(current_item.getAttribute("data-id")));
current_item.replaceWith(new_built_item);
}
}
}
/**
* Deletes the panel.
* @public
* @since 1.2.0
*/
deletePanel() {
if (this.panel && this.panel.parentElement) {
this.panel.parentElement.removeChild(this.panel);
this._closePanel();
this.panel = null;
}
}
} |
JavaScript | class Manager {
/**
*
* @param {Bancho.BanchoClient} Client
*/
constructor(Client) {
this.client = Client;
this.runningQuestionnaires = new Map();
this.runningGames = new Map();
}
async start() {
try {
await this.client.connect();
logger.info('connected');
this.client.on('PM', (message) => {
if (
message.user.ircUsername === 'BanchoBot' ||
message.self ||
message.user.isClient()
) {
logger.info(
`Blocked private message => ${message.user.ircUsername}: ${message.message}`
);
return;
}
this.handleQuestionnaire(message);
});
} catch (e) {
console.error(e);
}
}
/**
*
* @param {BanchoMessage} message
* @returns
*/
handleQuestionnaire(message) {
const messageUsername = message.user.ircUsername;
if (this.runningQuestionnaires.has(messageUsername)) {
this.runningQuestionnaires
.get(messageUsername)
.questionnaire.handleInput(message.message);
return;
}
const r = /^!new$/i;
if (r.test(message.message)) {
if (this.runningGames.has(messageUsername)) {
message.user.sendMessage('You already have a game running.');
return;
}
const questionnaire = new Questionnaire(this, message);
this.runningQuestionnaires.set(messageUsername, { questionnaire });
questionnaire.ask();
}
}
/**
*
* @param {Questionnaire} questionnaire
*/
evaluateQuestionnaire(questionnaire) {
const creator = questionnaire.message.user;
// Remove questionnaire from running questionnaires map
this.runningQuestionnaires.delete(creator.ircUsername);
const { answers } = questionnaire;
if (answers.confirmation === '!cancel') {
creator.sendMessage('Match creation cancelled.');
return;
}
(() => {
// Use new client to not have the listeners of this client
const Client = new Bancho.BanchoClient({
username: process.env.OSU_USER,
password: process.env.OSU_PASS,
apiKey: process.env.API_KEY,
});
const defaultOptions = {
teamMode: 0,
mods: ['Freemod'],
creator: creator,
};
Object.assign(answers, defaultOptions);
const bot = new Bot(Client, answers);
bot.start();
bot.on('started', () => {
bot.channel.on('PART', (member) => {
if (member.user.isClient)
this.runningGames.delete(member.user.ircUsername);
});
});
// Add bot instance to running games
this.runningGames.set(creator.ircUsername, { bot });
})();
}
} |
JavaScript | class ProductListComponentService {
constructor(productSearchService, routing, activatedRoute, currencyService, languageService, router) {
this.productSearchService = productSearchService;
this.routing = routing;
this.activatedRoute = activatedRoute;
this.currencyService = currencyService;
this.languageService = languageService;
this.router = router;
// TODO: make it configurable
this.defaultPageSize = 10;
this.RELEVANCE_ALLCATEGORIES = ':relevance:allCategories:';
/**
* Emits the search results for the current search query.
*
* The `searchResults$` is _not_ concerned with querying, it only observes the
* `productSearchService.getResults()`
*/
this.searchResults$ = this.productSearchService
.getResults()
.pipe(filter((searchResult) => Object.keys(searchResult).length > 0));
/**
* Observes the route and performs a search on each route change.
*
* Context changes, such as language and currencies are also taken
* into account, so that the search is performed again.
*/
this.searchByRouting$ = combineLatest([
this.routing.getRouterState().pipe(distinctUntilChanged((x, y) => {
// router emits new value also when the anticipated `nextState` changes
// but we want to perform search only when current url changes
return x.state.url === y.state.url;
})),
...this.siteContext,
]).pipe(debounceTime(0), map(([routerState, ..._context]) => routerState.state), tap((state) => {
const criteria = this.getCriteriaFromRoute(state.params, state.queryParams);
this.search(criteria);
}));
/**
* This stream is used for the Product Listing and Product Facets.
*
* It not only emits search results, but also performs a search on every change
* of the route (i.e. route params or query params).
*
* When a user leaves the PLP route, the PLP component unsubscribes from this stream
* so no longer the search is performed on route change.
*/
this.model$ = using(() => this.searchByRouting$.subscribe(), () => this.searchResults$).pipe(shareReplay({ bufferSize: 1, refCount: true }));
}
/**
* Expose the `SearchCriteria`. The search criteria are driven by the route parameters.
*
* This search route configuration is not yet configurable
* (see https://github.com/SAP/spartacus/issues/7191).
*/
getCriteriaFromRoute(routeParams, queryParams) {
return {
query: queryParams.query || this.getQueryFromRouteParams(routeParams),
pageSize: queryParams.pageSize || this.defaultPageSize,
currentPage: queryParams.currentPage,
sortCode: queryParams.sortCode,
};
}
/**
* Resolves the search query from the given `ProductListRouteParams`.
*/
getQueryFromRouteParams({ query, categoryCode, brandCode, }) {
if (query) {
return query;
}
if (categoryCode) {
return this.RELEVANCE_ALLCATEGORIES + categoryCode;
}
// TODO: drop support for brands as they should be treated
// similarly as any category.
if (brandCode) {
return this.RELEVANCE_ALLCATEGORIES + brandCode;
}
}
/**
* Performs a search based on the given search criteria.
*
* The search is delegated to the `ProductSearchService`.
*/
search(criteria) {
const currentPage = criteria.currentPage;
const pageSize = criteria.pageSize;
const sort = criteria.sortCode;
this.productSearchService.search(criteria.query,
// TODO: consider dropping this complex passing of cleaned object
Object.assign({}, currentPage && { currentPage }, pageSize && { pageSize }, sort && { sort }));
}
/**
* Get items from a given page without using navigation
*/
getPageItems(pageNumber) {
this.routing
.getRouterState()
.subscribe((route) => {
const routeCriteria = this.getCriteriaFromRoute(route.state.params, route.state.queryParams);
const criteria = Object.assign(Object.assign({}, routeCriteria), { currentPage: pageNumber });
this.search(criteria);
})
.unsubscribe();
}
/**
* Sort the search results by the given sort code.
*/
sort(sortCode) {
this.route({ sortCode });
}
/**
* Routes to the next product listing page, using the given `queryParams`. The
* `queryParams` support sorting, pagination and querying.
*
* The `queryParams` are delegated to the Angular router `NavigationExtras`.
*/
route(queryParams) {
this.router.navigate([], {
queryParams,
queryParamsHandling: 'merge',
relativeTo: this.activatedRoute,
});
}
/**
* The site context is used to update the search query in case of a
* changing context. The context will typically influence the search data.
*
* We keep this private for now, as we're likely refactoring this in the next
* major version.
*/
get siteContext() {
// TODO: we should refactor this so that custom context will be taken
// into account automatically. Ideally, we drop the specific context
// from the constructor, and query a ContextService for all contexts.
return [this.languageService.getActive(), this.currencyService.getActive()];
}
} |
JavaScript | class ReconstructSentence extends React.Component {
/**
* Renders a component to display sentences in other components.
*
* @return {jsx} the component to be rendered.
*/
render() {
const words = this.props.sentence.slice(1, -1);
const colors = [];
for (const i in words) {
if (words[i] === this.props.target[parseInt(i) + 1]) {
colors.push(this.props.colors[0]);
} else if (words[i] === this.props.original[parseInt(i) + 1]) {
colors.push(this.props.colors[1]);
} else {
colors.push(this.props.colors[2]);
}
}
return (
<Grid container direction="row" spacing={1} className="mainGrid">
{words.map((word, index) => (
<Grid item key={index}>
<Typography variant="body2" style={{ color: colors[index] }}>
{word}
</Typography>
</Grid>
))}
</Grid>
);
}
} |
JavaScript | class CustomScreen extends React.Component {
// for call back to work with field included
handleClick = event => {
log('handleClick', this.props);
// update this if to include the minimum required fields
// if (this.props.tableauSettings.ChoroFillScale && this.props.tableauSettings.ChoroFillScaleColors) {
this.props.customCallBack(this.props.field)
// }
}
render() {
const {
classes,
handleChange,
tableauSettings } = this.props;
log('we are in custom', this.props);
return (
<div className="sheetScreen">
<OptionWrapper>
<div class="content-container">
<OptionTitle>{this.props.configTitle}</OptionTitle>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Edge Type"
tooltipText="Select the style of edge for your viz"
/>
<Select
value={tableauSettings.edgeType || "normal"}
onChange={handleChange}
input={<Input name="edgeType" id="edgeType-helper" />}
>
<MenuItem value={"normal"}>Normal</MenuItem>
<MenuItem value={"linearc"}>Line Arc</MenuItem>
<MenuItem value={"curve"}>Curve</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Viz Layout"
tooltipText="Select the layout for your viz (vertical, horizontal or radial"
/>
<Select
value={tableauSettings.networkProjection || "vertical"}
onChange={handleChange}
input={<Input name="networkProjection" id="networkProjection-helper" />}
>
<MenuItem value={"vertical"}>Vertical</MenuItem>
<MenuItem value={"horizontal"}>Horizontal</MenuItem>
<MenuItem value={"radial"}>Radial</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Edge Render Type"
tooltipText="Select from Semoitic's Render Modes"
/>
<Select
value={tableauSettings.edgeRender || "normal"}
onChange={handleChange}
input={<Input name="edgeRender" id="edgeRender-helper" />}
>
<MenuItem value={"normal"}>Normal</MenuItem>
<MenuItem value={"solid-fill"}>Solid Filled</MenuItem>
<MenuItem value={"hachure-thin"}>Hachure Thin</MenuItem>
<MenuItem value={"hachure-thin-fill"}>Hachure Thin Filled</MenuItem>
<MenuItem value={"hachure-thick"}>Hachure Thick</MenuItem>
<MenuItem value={"hachure-thick-fill"}>Hachure Thick Filled</MenuItem>
<MenuItem value={"dots"}>Dots</MenuItem>
<MenuItem value={"dots-fill"}>Dots Filled</MenuItem>
<MenuItem value={"dashed"}>Dashed</MenuItem>
<MenuItem value={"dashed-fill"}>Dashed Fill</MenuItem>
<MenuItem value={"cross-hatch"}>Cross Hatch</MenuItem>
<MenuItem value={"cross-hatch-fill"}>Cross Hatch Filled</MenuItem>
<MenuItem value={"zigzag"}>Zigzag</MenuItem>
<MenuItem value={"zigzag-line"}>Zigzig Line</MenuItem>
<MenuItem value={"zigzag-fill"}>Zigzag Filled</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Node Render Type"
tooltipText="Select from Semoitic's Render Modes"
/>
<Select
value={tableauSettings.nodeRender || "normal"}
onChange={handleChange}
input={<Input name="nodeRender" id="nodeRender-helper" />}
>
<MenuItem value={"normal"}>Normal</MenuItem>
<MenuItem value={"solid-fill"}>Solid Filled</MenuItem>
<MenuItem value={"hachure-thin"}>Hachure Thin</MenuItem>
<MenuItem value={"hachure-thin-fill"}>Hachure Thin Filled</MenuItem>
<MenuItem value={"hachure-thick"}>Hachure Thick</MenuItem>
<MenuItem value={"hachure-thick-fill"}>Hachure Thick Filled</MenuItem>
<MenuItem value={"dots"}>Dots</MenuItem>
<MenuItem value={"dots-fill"}>Dots Filled</MenuItem>
<MenuItem value={"dashed"}>Dashed</MenuItem>
<MenuItem value={"dashed-fill"}>Dashed Fill</MenuItem>
<MenuItem value={"cross-hatch"}>Cross Hatch</MenuItem>
<MenuItem value={"cross-hatch-fill"}>Cross Hatch Filled</MenuItem>
<MenuItem value={"zigzag"}>Zigzag</MenuItem>
<MenuItem value={"zigzag-line"}>Zigzig Line</MenuItem>
<MenuItem value={"zigzag-fill"}>Zigzag Filled</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Node Render Angle"
tooltipText="The angle in degress for the sketchy drawing, defaults to -41, value from -360 to 360"
/>
<TextField
id="nodeRenderAngle-helper"
name="nodeRenderAngle"
label="Node Render Angle"
placeholder="-41"
className={classes.textField}
value={tableauSettings.nodeRenderAngle}
onChange={handleChange}
margin="normal"
/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Color Config"
tooltipText="The way color will be applied"
/>
<Select
value={tableauSettings.colorConfig || "solid"}
onChange={handleChange}
input={<Input name="colorConfig" id="colorConfig-helper" />}
>
<MenuItem value={"solid"}>Single Color</MenuItem>
<MenuItem value={"scale"}>Color Scale</MenuItem>
<MenuItem value={"field"}>Color Field</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Color"
tooltipText="For single, enter 1 hex code for scale enter two, e.g., #ccc,#ddd"
/>
<TextField
id="nodeColor-helper"
name="nodeColor"
label="Node Fill Color(s)"
placeholder="#CCCCCC or #CCCCCC,#DDDDDD"
className={classes.textField}
value={tableauSettings.nodeColor}
onChange={handleChange}
margin="normal"
/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Node Fill Opacity"
tooltipText="A decimal from 0 to 1 that will control node opacity"
/>
<TextField
id="nodeFillOpacity-helper"
name="nodeFillOpacity"
label="Node Fill Opacity"
placeholder=".35"
className={classes.textField}
value={tableauSettings.nodeFillOpacity}
onChange={handleChange}
margin="normal"
/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Node Size"
tooltipText="Toggle node size from value field"
/>
<Select
value={tableauSettings.nodeSize || "none"}
onChange={handleChange}
input={<Input name="nodeSize" id="nodeSize-helper" />}
>
<MenuItem value={"none"}>None</MenuItem>
<MenuItem value={"value"}>Value</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Minimum Node Size"
tooltipText="Minimum radius for nodes (e.g., 1)"
/>
<TextField
id="markerMinRadius-helper"
name="markerMinRadius"
label="Minimum Radius for Markers"
placeholder="1"
className={classes.textField}
value={tableauSettings.markerMinRadius}
onChange={handleChange}
margin="normal"
/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Maximum Node Size"
tooltipText="Maximum radius for nodes (e.g., 10)"
/>
<TextField
id="markerMaxRadius-helper"
name="markerMaxRadius"
label="Maximum Radius for Markers"
placeholder="25"
className={classes.textField}
value={tableauSettings.markerMaxRadius}
onChange={handleChange}
margin="normal"
/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabelWithTooltip
title="Filter Depth"
tooltipText="Filters everything below and equal to this level/depth out"
/>
<Select
value={tableauSettings.filterDepth || "none"}
onChange={handleChange}
input={<Input name="filterDepth" id="filterDepth-helper" />}
>
<MenuItem value={"none"}>No Filter</MenuItem>
<MenuItem value={"0"}>1</MenuItem>
<MenuItem value={"1"}>2</MenuItem>
<MenuItem value={"2"}>3</MenuItem>
<MenuItem value={"3"}>4</MenuItem>
<MenuItem value={"4"}>5</MenuItem>
<MenuItem value={"5"}>6</MenuItem>
<MenuItem value={"6"}>7</MenuItem>
<MenuItem value={"7"}>8</MenuItem>
<MenuItem value={"8"}>9</MenuItem>
<MenuItem value={"9"}>10</MenuItem>
<MenuItem value={"10"}>11</MenuItem>
<MenuItem value={"11"}>12</MenuItem>
<MenuItem value={"12"}>13</MenuItem>
<MenuItem value={"13"}>14</MenuItem>
<MenuItem value={"14"}>15</MenuItem>
</Select>
</FormControl>
</div>
</OptionWrapper>
</div>
);
}
} |
JavaScript | class RangeTable {
constructor(min, max, array) {
this.min = min;
this.max = max;
this.array = array;
this.range = max - min;
this.step = this.range / this.length;
}
get length() {
return this.array.length;
}
keyToIndex(key) {
let index = Math.floor((key - this.min) / this.step);
/* Case where value == this.max */
if (index == this.length) {
index--;
}
assert(index >= 0 && index < this.length);
return index;
}
computeOffset(key, index) {
return key - index * this.step - this.min;
}
getRange(startKey, endKey, resultPool) {
let startIndex = this.keyToIndex(startKey);
let endIndex = this.keyToIndex(endKey);
let startOffset = this.computeOffset(startKey, startIndex);
let endOffset = this.computeOffset(endKey, endIndex);
if (startIndex == endIndex && endOffset >= startOffset) {
/* Special case when there's only one entry */
this._populateEntry(resultPool.allocate(), startIndex, startOffset, endOffset);
return;
}
/* Range from start key to the end of the table slot */
this._populateEntry(resultPool.allocate(), startIndex, startOffset, this.step);
/* Intermediate slots */
let midStartIndex = (startIndex + 1) % this.length;
for (let i = midStartIndex; i != endIndex; i = (i + 1) % this.length) {
this._populateEntry(resultPool.allocate(), i, 0, this.step);
}
/* Range from start of table slot to end key */
this._populateEntry(resultPool.allocate(), endIndex, 0, endOffset);
}
_populateEntry(entry, index, startOffset, endOffset) {
entry.table = this;
entry.value = this.array[index];
entry.index = index;
entry.startOffset = startOffset;
entry.endOffset = endOffset;
}
} |
JavaScript | class EnvironmentService {
/**
* @function module:engine.EnvironmentService#getPipeline
* @description Validates pipeline exists and returns it.
*
* @param {string} pipelineId - The pipeline to retrieve.
* @returns {object} A reference to the requested Pipeline.
*/
getPipeline(pipelineId) {
return PipelineService.getPipeline(pipelineId);
}
/**
* @function module:engine.EnvironmentService#setEnvironmentVar
* @description Adds/Replaces an environment variable to a pipeline.
*
* @param {string} pipelineId - The pipeline to add to.
* @param {object} environmentVar - A representation of the environment variable.
*/
setEnvironmentVar(pipelineId, environmentVar) {
// validation of additional options
if (_.isNil(environmentVar)) {
log.silly('Cannot set environment variable, parameter required.');
throw new ExecutionError('The environmentVar parameter is required.', 400);
}
if (_.isNil(environmentVar.name) || _.isNil(environmentVar.value)) {
log.silly('Cannot set environment variable, parameter is malformed".');
throw new ExecutionError('The environmentVar parameter is malformed.', 400);
}
log.debug(`Adding environment variable ${environmentVar.name} for Pipeline ${pipelineId}`);
this.getPipeline(pipelineId).getEnvironment().addEnvironmentVariable(environmentVar);
}
/**
* @function module:engine.EnvironmentService#getEnvironmentVar
* @description Gets an environment variable from a pipeline.
*
* @param {string} pipelineId - The pipeline to fetch from.
* @param {string} name - The name of the environment variable to fetch.
* @returns {object} A representation of the environment variable.
*/
getEnvironmentVar(pipelineId, name) {
if (_.isNil(name)) {
log.silly('Cannot get environment variable, parameter required.');
throw new ExecutionError('The name parameter is required.', 400);
}
log.debug(`Getting environment variable ${name} for Pipeline ${pipelineId}`);
const environment = this.getPipeline(pipelineId).getEnvironment();
return JSON.parse(environment.redactSecrets(JSON.stringify(environment.getEnvironmentVariable(name))));
}
/**
* @function module:engine.EnvironmentService#listEnvironmentVar
* @description Lists the environment variables for a given pipeline.
*
* @param {string} pipelineId - The pipeline to fetch the list from.
* @returns {Array} A list of environment variable names.
*/
listEnvironmentVar(pipelineId) {
log.debug(`Getting all environment variables for Pipeline ${pipelineId}`);
return this.getPipeline(pipelineId).getEnvironment().listEnvironmentVariables();
}
} |
JavaScript | class ServiceState {
/**
* Generate a new {@link ServiceState}.
*
* @public
* @constructor
* @memberof ServiceState
*/
constructor() {
// Iterate over the possible catalog names and generate their states.
SERVICE_CATALOGS.forEach(
(catalog) => {
this[catalog] = ServiceState.generateCatalogState();
}
);
}
/**
* Set a catalog to be collecting or not.
*
* @public
* @memberof ServiceState
* @param {string} catalog - Catalog to target.
* @param {boolean} collecting - If the target is collecting or not.
* @returns {undefined}
*/
setCollecting(catalog, collecting) {
// Validate that the catalog state exists.
if (this[catalog]) {
// Set the 'collecting' status of the catalog state.
this[catalog].collecting = collecting;
}
}
/**
* Set a catalog to be ready or not.
*
* @public
* @memberof ServiceState
* @param {string} catalog - Catalog to target.
* @param {boolean} ready - If the target is ready or not.
* @returns {undefined}
*/
setReady(catalog, ready) {
// Validate that the catalog state exists.
if (this[catalog]) {
// Set the 'ready' status of the catalog state.
this[catalog].ready = ready;
}
}
/**
* Generate a {@link CatalogState}.
*
* @public
* @static
* @memberof ServiceState
* @returns {CatalogState} - The generated {@link CatalogState}.
*/
static generateCatalogState() {
return {
collecting: false,
ready: false
};
}
} |
JavaScript | class Test {
/**
*
* @param {string} recipient
* The name of the recipient
*/
constructor(recipient) {
console.log(`Hello ${recipient} ;)`);
}
} |
JavaScript | class Mod {
/**
* Constructs a new <code>Mod</code>.
* @alias module:kleister/model/Mod
* @param name {String}
*/
constructor (name) {
Mod.initialize(this, name)
}
/**
* 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, name) {
obj['name'] = name
}
/**
* Constructs a <code>Mod</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:kleister/model/Mod} obj Optional instance to populate.
* @return {module:kleister/model/Mod} The populated <code>Mod</code> instance.
*/
static constructFromObject (data, obj) {
if (data) {
obj = obj || new Mod()
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String')
}
if (data.hasOwnProperty('slug')) {
obj['slug'] = ApiClient.convertToType(data['slug'], 'String')
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String')
}
if (data.hasOwnProperty('side')) {
obj['side'] = ApiClient.convertToType(data['side'], 'String')
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String')
}
if (data.hasOwnProperty('author')) {
obj['author'] = ApiClient.convertToType(data['author'], 'String')
}
if (data.hasOwnProperty('website')) {
obj['website'] = ApiClient.convertToType(data['website'], 'String')
}
if (data.hasOwnProperty('donate')) {
obj['donate'] = ApiClient.convertToType(data['donate'], 'String')
}
if (data.hasOwnProperty('created_at')) {
obj['created_at'] = ApiClient.convertToType(data['created_at'], 'Date')
}
if (data.hasOwnProperty('updated_at')) {
obj['updated_at'] = ApiClient.convertToType(data['updated_at'], 'Date')
}
}
return obj
}
} |
JavaScript | class GlossRef extends Link {
/**
* @returns {String}
*/
static get role() {
return DPUB_ROLE_PREFIX + super.role
}
} |
JavaScript | class CrawlingSettingModel {
static getAttributeTypeMap() {
return CrawlingSettingModel.attributeTypeMap;
}
} |
JavaScript | class SettingsRepository extends DataRepository
{
/**
* @inheritDoc
*/
static get injections()
{
return { 'parameters': [SettingsLoader] };
}
/**
* @inheritDoc
*/
static get className()
{
return 'model.setting/SettingsRepository';
}
} |
JavaScript | class DatalakeFolderDetail {
/**
* Create a DatalakeFolderDetail.
* @property {string} [name] Gets the datalake folder Friendly Name
* @property {string} [uniqueName] Gets the Cds datalake folder unique Name
*/
constructor() {
}
/**
* Defines the metadata of DatalakeFolderDetail
*
* @returns {object} metadata of DatalakeFolderDetail
*
*/
mapper() {
return {
required: false,
serializedName: 'DatalakeFolderDetail',
type: {
name: 'Composite',
className: 'DatalakeFolderDetail',
modelProperties: {
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
uniqueName: {
required: false,
serializedName: 'uniqueName',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class LedgerDeviceManager extends AbstractDeviceManager {
constructor(options) {
super(options);
this.usb = busb.usb;
this.timeout = 5000;
this._connectHandler = null;
this._disconnectHandler = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from Options
* @param {Object} options
* @param {Object} options
* @param {Logger?} options.logger
* @param {Network?} options.network
* @param {selectorCallback} options.selector
* @param {busb#USB} options.usb
* @param {Number} options.timeout
* @returns {LedgerDevice}
*/
fromOptions(options) {
assert(typeof options === 'object');
this.options = options;
if (options.selector != null) {
assert(typeof options.selector === 'function');
this.selector = options.selector;
this.usb = getUSB(this.selector);
}
if (options.logger != null) {
assert(typeof options.logger === 'object');
this.logger = options.logger.context('ledger-device-manager');
}
if (options.network != null)
this.network = Network.get(options.network);
if (options.usb != null) {
assert(options.usb instanceof busb.USB);
this.usb = options.usb;
}
if (options.timeout != null) {
assert(typeof options.timeout === 'number');
this.timeout = options.timeout;
}
return this;
}
get vendor() {
return vendors.LEDGER;
}
/**
* Handle connect.
* @private
* @param {busb.W3CUSBConnectionEvent}
*/
handleConnect(event) {
const device = LedgerDevice.fromUSBDevice(event.device,
this.options);
const handle = device.handle;
assert(!this.cachedDevices.has(handle),
'Already have device for the handle.');
this.cachedDevices.set(handle, device);
this.emit('connect', device);
}
/**
* Handle disconnect. Diselect if the device
* is selected.
* @private
* @param {busb.W3CUSBConnectionEvent} usbDevice
*/
handleDisconnect(event) {
const handle = event.device._handle;
const device = this.cachedDevices.get(handle);
if (this.selected === device) {
this.selected.destroy();
this.deselectDevice();
}
this.cachedDevices.delete(handle);
this.emit('disconnect', device);
}
/**
* Listen to connect/disconnect events. We need
* to later unbind our handlers, so we cache them.
* @private
*/
bind() {
this._connectHandler = this.handleConnect.bind(this);
this._disconnectHandler = this.handleDisconnect.bind(this);
this.usb.addEventListener('connect', this._connectHandler);
this.usb.addEventListener('disconnect', this._disconnectHandler);
}
/**
* Remove our event listeners from usb.
* @private
*/
unbind() {
this.usb.removeEventListener('connect', this._connectHandler);
this.usb.removeEventListener('disconnect', this._disconnectHandler);
this._connectHandler = null;
this._disconnectHandler = null;
}
/**
* Start listening to events
* @returns {Promise}
*/
async open() {
assert(!this.opened, 'Already opened.');
this.opened = true;
this.bind();
}
/**
* Clean up listeners and cache.
* Destroy connected devices.
* @returns {Promise}
*/
async close() {
assert(this.opened, 'Not open.');
this.opened = false;
for (const device of this.cachedDevices.values()) {
if (device.opened)
await device.close();
device.destroy();
}
this.cachedDevices.clear();
this.unbind();
}
/**
* Select device is general way to select devices
* Get permissions to listen to the events.
* Even though it is not necessary to open
* manager to select device, this is here
* in order to detect disconnection and inform
* user that device was deselected.
* @param {LedgerDevice?} device - custom device (for connect event)
* @returns {LedgerDevice}
*/
async selectDevice(device) {
assert(this.opened, 'Not open.');
if (device) {
const handle = device.handle;
if (!this.cachedDevices.has(handle)) {
throw new Error('Device not found.');
}
this.deselectDevice();
this.selected = device;
this.emit('select', device);
await device.open();
return device;
}
const ledgerDevice = await LedgerUSB.requestDevice(this.usb);
device = LedgerDevice.fromLedgerDevice(ledgerDevice,
this.options);
const handle = device.handle;
device.fromOptions(this.options);
await this.deselectDevice();
this.selected = device;
this.cachedDevices.set(handle, device);
await this.selected.open();
this.emit('select', this.selected);
return device;
}
/**
* Deselect current device.
* @returns {Boolean}
*/
async deselectDevice() {
if (!this.selected)
return false;
if (this.selected.opened)
await this.selected.close();
this.emit('deselect', this.selected);
this.selected = null;
return true;
}
/**
* List allowed and connected devices.
* @returns {Promise<LedgerDevice[]>}
*/
async getDevices() {
assert(this.opened, 'Not open.');
return Array.from(this.cachedDevices.values());
}
/**
* Create LedgerDeviceManager from options.
* @param {Object} options
* @returns {LedgerDeviceManager}
*/
static fromOptions(options) {
return new this(options);
}
} |
JavaScript | class AsyncAPIDocument extends Base {
/**
* @constructor
*/
constructor(...args) {
super(...args);
if (this.ext(xParserSpecParsed) === true) {
return;
}
assignNameToComponentMessages(this);
assignNameToAnonymousMessages(this);
assignUidToComponentSchemas(this);
assignUidToComponentParameterSchemas(this);
assignUidToParameterSchemas(this);
assignIdToAnonymousSchemas(this);
// We add `x-parser-spec-parsed=true` extension to determine that the specification is parsed and validated
// and when the specification is re-passed to the AsyncAPIDocument constructor,
// there is no need to perform the same operations.
this.json()[String(xParserSpecParsed)] = true;
}
/**
* @returns {string}
*/
version() {
return this._json.asyncapi;
}
/**
* @returns {Info}
*/
info() {
return new Info(this._json.info);
}
/**
* @returns {string}
*/
id() {
return this._json.id;
}
/**
* @returns {boolean}
*/
hasServers() {
return !!this._json.servers;
}
/**
* @returns {Object<string, Server>}
*/
servers() {
return createMapOfType(this._json.servers, Server);
}
/**
* @returns {string[]}
*/
serverNames() {
if (!this._json.servers) return [];
return Object.keys(this._json.servers);
}
/**
* @param {string} name - Name of the server.
* @returns {Server}
*/
server(name) {
return getMapValueOfType(this._json.servers, name, Server);
}
/**
* @returns {boolean}
*/
hasDefaultContentType() {
return !!this._json.defaultContentType;
}
/**
* @returns {string|null}
*/
defaultContentType() {
return this._json.defaultContentType || null;
}
/**
* @returns {boolean}
*/
hasChannels() {
return !!this._json.channels;
}
/**
* @returns {Object<string, Channel>}
*/
channels() {
return createMapOfType(this._json.channels, Channel, this);
}
/**
* @returns {string[]}
*/
channelNames() {
if (!this._json.channels) return [];
return Object.keys(this._json.channels);
}
/**
* @param {string} name - Name of the channel.
* @returns {Channel}
*/
channel(name) {
return getMapValueOfType(this._json.channels, name, Channel, this);
}
/**
* @returns {boolean}
*/
hasComponents() {
return !!this._json.components;
}
/**
* @returns {Components}
*/
components() {
if (!this._json.components) return null;
return new Components(this._json.components);
}
/**
* @returns {boolean}
*/
hasMessages() {
return !!this.allMessages().size;
}
/**
* @returns {Map<string, Message>}
*/
allMessages() {
const messages = new Map();
if (this.hasChannels()) {
this.channelNames().forEach(channelName => {
const channel = this.channel(channelName);
if (channel.hasPublish()) {
channel.publish().messages().forEach(m => {
messages.set(m.uid(), m);
});
}
if (channel.hasSubscribe()) {
channel.subscribe().messages().forEach(m => {
messages.set(m.uid(), m);
});
}
});
}
if (this.hasComponents()) {
Object.values(this.components().messages()).forEach(m => {
messages.set(m.uid(), m);
});
}
return messages;
}
/**
* @returns {Map<string, Schema>}
*/
allSchemas() {
const schemas = new Map();
const allSchemasCallback = (schema) => {
if (schema.uid()) {
schemas.set(schema.uid(), schema);
}
};
traverseAsyncApiDocument(this, allSchemasCallback);
return schemas;
}
/**
* @returns {boolean}
*/
hasCircular() {
return !!this._json[String(xParserCircle)];
}
/**
* Callback used when crawling a schema.
* @callback module:@asyncapi/parser.TraverseSchemas
* @param {Schema} schema which is being crawled
* @param {String} propName if the schema is from a property get the name of such
* @param {SchemaIteratorCallbackType} callbackType is the schema a new one or is the crawler finishing one.
* @returns {boolean} should the crawler continue crawling the schema?
*/
/**
* Traverse schemas in the document and select which types of schemas to include.
* By default all schemas are iterated
* @param {TraverseSchemas} callback
* @param {SchemaTypesToIterate[]} schemaTypesToIterate
*/
traverseSchemas(callback, schemaTypesToIterate) {
traverseAsyncApiDocument(this, callback, schemaTypesToIterate);
}
/**
* Converts a valid AsyncAPI document to a JavaScript Object Notation (JSON) string.
* A stringified AsyncAPI document using this function should be parsed via the AsyncAPIDocument.parse() function - the JSON.parse() function is not compatible.
*
* @param {AsyncAPIDocument} doc A valid AsyncAPIDocument instance.
* @param {(number | string)=} space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
* @returns {string}
*/
static stringify(doc, space) {
const rawDoc = doc.json();
const copiedDoc = { ...rawDoc };
copiedDoc[String(xParserSpecStringified)] = true;
return JSON.stringify(copiedDoc, refReplacer(), space);
}
/**
* Converts a valid stringified AsyncAPIDocument instance into an AsyncAPIDocument instance.
*
* @param {string} doc A valid stringified AsyncAPIDocument instance.
* @returns {AsyncAPIDocument}
*/
static parse(doc) {
let parsedJSON = doc;
if (typeof doc === 'string') {
parsedJSON = JSON.parse(doc);
} else if (typeof doc === 'object') {
// shall copy
parsedJSON = { ...parsedJSON };
}
// the `doc` must be an AsyncAPI parsed document
if (typeof parsedJSON !== 'object' || !parsedJSON[String(xParserSpecParsed)]) {
throw new Error('Cannot parse invalid AsyncAPI document');
}
// if the `doc` is not stringified via the `stringify` static method then immediately return a model.
if (!parsedJSON[String(xParserSpecStringified)]) {
return new AsyncAPIDocument(parsedJSON);
}
// remove `x-parser-spec-stringified` extension
delete parsedJSON[String(xParserSpecStringified)];
const objToPath = new Map();
const pathToObj = new Map();
traverseStringifiedDoc(parsedJSON, undefined, parsedJSON, objToPath, pathToObj);
return new AsyncAPIDocument(parsedJSON);
}
} |
JavaScript | class EmployeeBankAccount {
/**
* Constructs a new <code>EmployeeBankAccount</code>.
* @alias module:model/EmployeeBankAccount
*/
constructor() {
EmployeeBankAccount.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>EmployeeBankAccount</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/EmployeeBankAccount} obj Optional instance to populate.
* @return {module:model/EmployeeBankAccount} The populated <code>EmployeeBankAccount</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EmployeeBankAccount();
if (data.hasOwnProperty("id")) {
obj["id"] = ApiClient.convertToType(data["id"], "Number");
}
if (data.hasOwnProperty("user_id")) {
obj["user_id"] = ApiClient.convertToType(data["user_id"], "Number");
}
if (data.hasOwnProperty("account_number")) {
obj["account_number"] = ApiClient.convertToType(data["account_number"], "String");
}
if (data.hasOwnProperty("bank_name")) {
obj["bank_name"] = ApiClient.convertToType(data["bank_name"], "String");
}
if (data.hasOwnProperty("location")) {
obj["location"] = ApiClient.convertToType(data["location"], "String");
}
if (data.hasOwnProperty("branch_code")) {
obj["branch_code"] = ApiClient.convertToType(data["branch_code"], "String");
}
if (data.hasOwnProperty("current")) {
obj["current"] = ApiClient.convertToType(data["current"], "Boolean");
}
if (data.hasOwnProperty("deleted")) {
obj["deleted"] = ApiClient.convertToType(data["deleted"], "Boolean");
}
}
return obj;
}
} |
JavaScript | class Player {
constructor(sprite, rectangle) {
this.sprite = sprite;
this.rectangle = rectangle;
this.velocityX = 0;
this.maximumVelocityX = 8;
this.accelerationX = 2;
this.frictionX = 0.9;
this.velocityY = 0;
this.maximumVelocityY = 30;
this.accelerationY = 3;
this.jumpVelocity = -30;
this.climbingSpeed = 10;
this.isOnGround = false;
this.isOnLadder = false;
}
animate(state) {
if (state.keys[37]) {
// left
this.velocityX = Math.max(
this.velocityX - this.accelerationX,
this.maximumVelocityX * -1,
);
}
if (state.keys[39]) {
// right
this.velocityX = Math.min(
this.velocityX + this.accelerationX,
this.maximumVelocityX,
);
}
this.velocityX *= this.frictionX;
this.velocityY = Math.min(
this.velocityY + this.accelerationY,
this.maximumVelocityY,
);
state.objects.forEach(object => {
if (object === this) {
return;
}
const me = this.rectangle;
const you = object.rectangle;
const collides = object.collides;
if (
me.x < you.x + you.width &&
me.x + me.width > you.x &&
me.y < you.y + you.height &&
me.y + me.height > you.y
) {
if (object.constructor.name === 'Ladder') {
if (state.keys[38] || state.keys[40]) {
this.isOnLadder = true;
this.isOnGround = false;
this.velocityY = 0;
this.velocityX = 0;
}
if (state.keys[38]) {
this.rectangle.y -= this.climbingSpeed;
}
if (state.keys[40] && me.y + me.height < you.y + you.height) {
this.rectangle.y += this.climbingSpeed;
}
if (me.y <= you.x - me.height) {
this.isOnLadder = false;
}
}
// Klesání
if (collides && this.velocityY > 0 && you.y >= me.y) {
this.isOnGround = true;
this.velocityY = 0;
return;
}
// Stoupání
if (collides && this.velocityY < 0 && you.y <= me.y) {
this.velocityY = this.accelerationY;
return;
}
if (collides && this.velocityX < 0 && you.x <= me.x) {
this.velocityX = 0;
return;
}
if (collides && this.velocityX > 0 && you.x >= me.x) {
this.velocityX = 0;
return;
}
}
});
if (state.keys[32] && this.isOnGround) {
this.velocityY = this.jumpVelocity;
this.isOnGround = false;
}
this.rectangle.x += this.velocityX;
if (!this.isOnLadder) {
this.rectangle.y += this.velocityY;
}
this.sprite.x = this.rectangle.x;
this.sprite.y = this.rectangle.y;
}
} |
JavaScript | class HouseCommands {
constructor(manager, announce, economy, finance, limits, location) {
this.manager_ = manager;
this.announce_ = announce;
this.economy_ = economy;
this.finance_ = finance;
this.limits_ = limits;
this.location_ = location;
this.parkingLotCreator_ = new ParkingLotCreator();
this.parkingLotRemover_ = new ParkingLotRemover();
// Command: /house [buy/cancel/create/enter/goto/interior/modify/remove/save/settings]
server.commandManager.buildCommand('house')
.description('Manage your house(s) on the server.')
.sub('buy')
.description('Purchase a new house.')
.build(HouseCommands.prototype.onHouseBuyCommand.bind(this))
.sub('cancel')
.description('Cancel purchase of a house.')
.build(HouseCommands.prototype.onHouseCancelCommand.bind(this))
.sub('create')
.description('Create a new house location.')
.restrict(Player.LEVEL_ADMINISTRATOR, /* restrictTemporary= */ true)
.build(HouseCommands.prototype.onHouseCreateCommand.bind(this))
.sub('enter')
.description('Forcefully enter a house.')
.restrict(Player.LEVEL_ADMINISTRATOR)
.build(HouseCommands.prototype.onHouseEnterCommand.bind(this))
.sub('goto')
.description('Teleport to one of your houses.')
.parameters([{ name: 'filter', type: CommandBuilder.kTypeText, optional: true }])
.build(HouseCommands.prototype.onHouseGotoCommand.bind(this))
.sub('interior')
.description('Teleport to a particular house interior.')
.restrict(Player.LEVEL_MANAGEMENT)
.parameters([{ name: 'id', type: CommandBuilder.kTypeNumber }])
.build(HouseCommands.prototype.onHouseInteriorCommand.bind(this))
.sub('modify')
.description('Modify settings for the house location.')
.restrict(Player.LEVEL_ADMINISTRATOR, /* restrictTemporary= */ true)
.build(HouseCommands.prototype.onHouseModifyCommand.bind(this))
.sub('remove')
.description('Remove the house.')
.restrict(Player.LEVEL_ADMINISTRATOR, /* restrictTemporary= */ true)
.parameters([{ name: 'id', type: CommandBuilder.kTypeNumber }])
.build(HouseCommands.prototype.onHouseRemoveCommand.bind(this))
.sub('save')
.description('Save a parking lot for the current house.')
.restrict(Player.LEVEL_ADMINISTRATOR, /* restrictTemporary= */ true)
.build(HouseCommands.prototype.onHouseSaveCommand.bind(this))
.sub('settings')
.description('Change the settings for this house.')
.build(HouseCommands.prototype.onHouseSettingsCommand.bind(this))
.build(HouseCommands.prototype.onHouseCommand.bind(this));
}
// Called when a player types the `/house buy` command to start purchasing a house. They must be
// standing in a house entrance in order for the command to work.
async onHouseBuyCommand(player) {
const location = this.manager_.getCurrentLocationForPlayer(player);
if (!location) {
player.sendMessage(Message.HOUSE_BUY_NO_LOCATION);
return;
}
if (!location.isAvailable()) {
player.sendMessage(Message.HOUSE_BUY_NOT_AVAILABLE, location.owner);
return;
}
const currentHouses = this.manager_.getHousesForPlayer(player);
if (currentHouses.length > 0) {
if (currentHouses.length >= this.manager_.getMaximumHouseCountForPlayer(player)) {
player.sendMessage(Message.HOUSE_BUY_NO_MULTIPLE);
return;
}
let distanceToClosestHouse = Number.MAX_SAFE_INTEGER;
currentHouses.forEach(existingHouse => {
const distance = location.position.distanceTo(existingHouse.position);
distanceToClosestHouse = Math.min(distanceToClosestHouse, distance);
});
const minimumDistance = this.manager_.getMinimumHouseDistance(player);
if (distanceToClosestHouse < minimumDistance) {
player.sendMessage(Message.HOUSE_BUY_TOO_CLOSE, minimumDistance);
return;
}
}
// |location| is available for purchase, and the |player| hasn't exceeded their house limit
// nor has an house in the immediate environment.
const balance = await this.finance_().getPlayerAccountBalance(player);
const interiorList = InteriorList.forEconomy(player, this.economy_(), location);
const interior = await InteriorSelector.select(player, balance, interiorList);
if (!interior)
return;
// Revalidate that the player has sufficient money available to buy the house. This works
// around their bank value changes whilst they're in the interior selector.
const refreshedBalance = await this.finance_().getPlayerAccountBalance(player);
if (interior.price > refreshedBalance) {
player.sendMessage(Message.HOUSE_BUY_NOT_ENOUGH_MONEY, interior.price);
return;
}
// Withdraw the cost of this house from the |player|'s bank account.
await this.finance_().withdrawFromPlayerAccount(player, interior.price);
// Actually claim the house within the HouseManager, which writes it to the database.
await this.manager_.createHouse(player, location, interior.id);
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_PURCHASED,
PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_BUY,
player.name, player.id, interior.price, location.id);
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Congratulations on your purchase!',
message: Message.HOUSE_BUY_CONFIRMED
});
}
// Called when a |player| types the `/house cancel` command in response to an interactive
// operation, for instance whilst adding a parking lot.
onHouseCancelCommand(player) {
if (this.parkingLotCreator_.isSelecting(player))
this.parkingLotCreator_.cancelSelection(player);
else if (this.parkingLotRemover_.isSelecting(player))
this.parkingLotRemover_.cancelSelection(player);
else
player.sendMessage(Message.HOUSE_CANCEL_UNKNOWN);
}
// Called when an administrator types `/house create`. It will confirm with them whether they
// do want to create a house at their current location, together with the price range for which
// the house will be on offer to players.
async onHouseCreateCommand(player) {
const position = player.position;
// SA-MP pickups are limited to [-4096, 4096] due to the compression being applied when
// packing their coordinates. This, sadly, places quite a restriction on where they can be.
if (position.x < -4096 || position.x > 4096 || position.y < -4096 || position.y > 4096) {
player.sendMessage(Message.HOUSE_CREATE_OUT_OF_BOUNDS);
return;
}
// Certain areas are considered to be of high strategic value, and only allow for limited
// residential activity. Houses should be maintained by players elsewhere.
if (this.economy_().isResidentialExclusionZone(position)) {
const rightButton = player.isManagement() ? 'Override' : '';
const confirmation =
await Dialog.displayMessage(
player, 'Create a new house location',
Message.format(Message.HOUSE_CREATE_RESIDENTIAL_EXCLUSION_ZONE),
'Close' /* leftButton */, rightButton);
if (!player.isManagement() || confirmation.response)
return;
}
const minimumPrice = this.economy_().calculateHousePrice(position, 0 /* parkingLotCount */,
0 /* interiorValue */);
const maximumPrice = this.economy_().calculateHousePrice(position, 0 /* parkingLotCount */,
9 /* interiorValue */);
const confirmation =
await Dialog.displayMessage(player, 'Create a new house location',
Message.format(Message.HOUSE_CREATE_CONFIRM, minimumPrice,
maximumPrice),
'Yes' /* leftButton */, 'No' /* rightButton */);
if (!confirmation.response)
return;
const facingAngle = player.rotation;
const interiorId = player.interiorId;
await this.manager_.createLocation(player, { facingAngle, interiorId, position });
// Announce creation of the location to other administrators.
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_CREATED,
PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_CREATED,
player.name, player.id);
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Create a new house location',
message: Message.HOUSE_CREATE_CONFIRMED
});
}
// Called when an administrator wants to override the access restrictions to a house and gain
// entry to it anyway. Only works when they're standing in an entrance point.
async onHouseEnterCommand(player) {
const location = await this.manager_.findClosestLocation(player, { maximumDistance: 15 });
if (location && !location.isAvailable()) {
// TODO: Should we announce this to the other administrators? We really need
// announcement channels to deal with the granularity of messages. (Issue #271.)
this.manager_.forceEnterHouse(player, location);
player.sendMessage(Message.HOUSE_ENTERED);
return;
}
player.sendMessage(Message.HOUSE_ENTER_NONE_NEAR);
}
// Called when a player types `/house goto`. Administrators get a list of house owners to choose
// from, optionally |filter|ed, after which they get a list of houses owned by the subject.
// Players using this command will get their own dialog immediately.
async onHouseGotoCommand(player, filter) {
if (!player.account.isRegistered()) {
player.sendMessage(Message.HOUSE_GOTO_UNREGISTERED);
return;
}
if (!player.isAdministrator())
return await this.displayHouseGotoDialog(player, player.account.userId);
const potentialPlayerId = parseFloat(filter);
// Fast-path to display another player's houses when |filter| is a player Id.
if (!isNaN(potentialPlayerId) && isFinite(potentialPlayerId)) {
const subject = server.playerManager.getById(potentialPlayerId);
if (!subject || !subject.account.isRegistered()) {
player.sendMessage(Message.HOUSE_GOTO_NONE_FOUND);
return;
}
return await this.displayHouseGotoDialog(player, subject.account.userId);
}
const menu = new Menu('Select a house owner', ['Nickname', 'Owned houses']);
const normalizedFilter = filter ? filter.toLowerCase() : null;
const housesByOwner = new Map();
// Load all occupied houses in to |housesByOwner|, keyed by the owner's nickname, valued by
// a dictionary containing their user Id and number of owned houses.
for (const location of this.manager_.locations) {
if (location.isAvailable())
continue;
const normalizedOwnerName = location.settings.ownerName.toLowerCase();
if (filter && !normalizedOwnerName.includes(normalizedFilter))
continue;
if (!housesByOwner.has(normalizedOwnerName)) {
housesByOwner.set(normalizedOwnerName, {
nickname: location.settings.ownerName,
userId: location.settings.ownerId,
count: 0
});
}
housesByOwner.get(normalizedOwnerName).count++;
}
// Display an error message if an invalid |filter| had been applied.
if (filter && !housesByOwner.size) {
player.sendMessage(Message.HOUSE_GOTO_INVALID_FILTER, filter);
return;
}
// Fast-track to the actual dialog if only a single home owner was found.
if (filter && housesByOwner.size === 1) {
const { nickname, userId, count } = Array.from(housesByOwner.values())[0];
return await this.displayHouseGotoDialog(player, userId);
}
// Order the owners by their normalized nickname, then add them as a list to the |menu|.
Array.from(housesByOwner.keys()).sort().forEach(normalizedNickname => {
const { nickname, userId, count } = housesByOwner.get(normalizedNickname);
menu.addItem(nickname, count, async(player) =>
await this.displayHouseGotoDialog(player, userId));
});
await menu.displayForPlayer(player);
}
// Displays the dialog that allows players to go to a specific house. An error will be shown
// when the player represented by |userId| does not own any houses.
async displayHouseGotoDialog(player, userId) {
const houses = new Set();
let nickname = null;
const teleportStatus = this.limits_().canTeleport(player);
// Bail out if the |player| is not currently allowed to teleport.
if (!teleportStatus.isApproved()) {
player.sendMessage(Message.HOUSE_GOTO_TELEPORT_BLOCKED, teleportStatus);
return;
}
// Bail out if the user is in an interior, or in a different virtual world.
if (player.interiorId != 0 || player.virtualWorld != 0) {
player.sendMessage(Message.HOUSE_GOTO_TELEPORT_BLOCKED, `you're not outside`);
return;
}
// Find the houses owned by |userId|. This operation is O(n) on the number of locations.
for (const location of this.manager_.locations) {
if (location.isAvailable())
continue;
if (location.settings.ownerId != userId)
continue;
nickname = location.settings.ownerName;
houses.add(location);
}
// Display an error message if the |userId| does not own any houses.
if (!houses.size) {
player.sendMessage(Message.HOUSE_GOTO_NONE_FOUND);
return;
}
// Display a menu with the player's houses. Selecting one will teleport the |player| inside.
const menu = new Menu(nickname + '\'s houses');
for (const location of houses) {
menu.addItem(location.settings.name, player => {
this.manager_.forceEnterHouse(player, location);
this.limits_().reportTeleportation(player);
// Announce creation of the location to other administrators.
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_TELEPORTED,
PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_TELEPORTED,
player.name, player.id, location.settings.name, location.settings.ownerName);
});
}
await menu.displayForPlayer(player);
}
// Called when a Management member uses `/house interior` to teleport to a particular house
// interior. Restrictions will be ignored, and there won't be a way back for them.
onHouseInteriorCommand(player, interiorId) {
if (!InteriorList.isValid(interiorId)) {
player.sendMessage(Message.HOUSE_INTERIOR_INVALID, interiorId);
return;
}
const interiorData = InteriorList.getById(interiorId);
player.position = new Vector(...interiorData.exits[0].position);
player.rotation = interiorData.exits[0].rotation;
player.interiorId = interiorData.interior;
player.virtualWorld = VirtualWorld.forPlayer(player);
player.resetCamera();
player.sendMessage(Message.HOUSE_INTERIOR_TELEPORTED, interiorData.name);
}
// Called when an administrator types the `/house modify` command to change settings for the
// house closest to their location, allowing them to, for example, add or remove parking lots.
async onHouseModifyCommand(player) {
const closestLocation =
await this.manager_.findClosestLocation(player, { maximumDistance: 15 });
if (!closestLocation) {
player.sendMessage(Message.HOUSE_MODIFY_NONE_NEAR);
return;
}
// Create a beam for |player| at the house's entrance to clarify what's being edited.
const identityBeam = new IdentityBeam(closestLocation.position.translate({ z: -10 }), {
timeout: IdentityBeamDisplayTimeMs,
player: player
});
const menu = new Menu('What do you want to modify?');
menu.addItem('Add a parking lot', async(player) => {
await MessageBox.display(player, {
title: 'Add a parking lot',
message: Message.format(Message.HOUSE_PARKING_LOT_ADD,
this.parkingLotCreator_.maxDistance)
});
player.sendMessage(Message.HOUSE_PARKING_LOT_ADD_MSG);
const parkingLot = await this.parkingLotCreator_.select(player, closestLocation);
if (!parkingLot)
return;
await this.manager_.createLocationParkingLot(player, closestLocation, parkingLot);
// TODO: Should we announce this to the other administrators? We really need
// announcement channels to deal with the granularity of messages. (Issue #271.)
await MessageBox.display(player, {
title: 'Add a parking lot',
message: Message.HOUSE_PARKING_LOT_ADDED
});
});
const removeParkingLotTitle =
'Remove a parking lot ({FFFF00}' + closestLocation.parkingLotCount + '{FFFFFF})';
menu.addItem(removeParkingLotTitle, async(player) => {
if (!closestLocation.parkingLotCount) {
return await MessageBox.display(player, {
title: 'Remove a parking lot',
message: Message.HOUSE_PARKING_LOT_NONE
});
}
await MessageBox.display(player, {
title: 'Remove a parking lot',
message: Message.HOUSE_PARKING_LOT_REMOVE
});
player.sendMessage(Message.HOUSE_PARKING_LOT_REMOVE_MSG);
const parkingLot = await this.parkingLotRemover_.select(player, closestLocation);
if (!parkingLot)
return;
await this.manager_.removeLocationParkingLot(closestLocation, parkingLot);
// TODO: Should we announce this to the other administrators? We really need
// announcement channels to deal with the granularity of messages. (Issue #271.)
await MessageBox.display(player, {
title: 'Remove a parking lot',
message: Message.HOUSE_PARKING_LOT_REMOVED
});
});
// Give house extensions the ability to provide their additional functionality.
this.manager_.invokeExtensions('onHouseModifyCommand', player, closestLocation, menu);
if (!closestLocation.isAvailable()) {
const ownerName = closestLocation.settings.ownerName;
menu.addItem('Evict the owner ({FFFF00}' + ownerName + '{FFFFFF})', async(player) => {
const confirmation =
await Dialog.displayMessage(
player, 'Evict the current owner',
Message.format(Message.HOUSE_MODIFY_EVICT_CONFIRM, ownerName),
'Yes' /* leftButton */, 'No' /* rightButton */);
if (!confirmation.response)
return;
await this.manager_.removeHouse(closestLocation);
// Announce eviction of the previous owner to other administrators.
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_EVICTED,
PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_EVICTED,
player.name, player.id, ownerName, closestLocation.id);
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Evict the current owner',
message: Message.format(Message.HOUSE_MODIFY_EVICT_CONFIRMED, ownerName)
});
});
}
menu.addItem('Delete the location', async(player) => {
const confirmation =
await Dialog.displayMessage(player, 'Delete the house location',
Message.format(Message.HOUSE_MODIFY_DELETE_CONFIRM),
'Yes' /* leftButton */, 'No' /* rightButton */);
if (!confirmation.response)
return;
await this.manager_.removeLocation(closestLocation);
// Announce creation of the location to other administrators.
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_DELETED,
PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_DELETED,
player.name, player.id, closestLocation.id);
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Delete the house location',
message: Message.HOUSE_MODIFY_DELETE_CONFIRMED
});
});
await menu.displayForPlayer(player);
// Remove the identity beam that was displayed for this house.
identityBeam.dispose();
}
// Called when a |player| types the `/house remove` command with the given |id|. Will find the
// in-progress interactive operation that should receive this value.
onHouseRemoveCommand(player, id) {
if (this.parkingLotRemover_.isSelecting(player))
this.parkingLotRemover_.confirmSelection(player, id);
else
player.sendMessage(Message.HOUSE_REMOVE_UNKNOWN);
}
// Called when a |player| types the `/house save` command in response to an interactive
// operation, for instance whilst adding a parking lot.
onHouseSaveCommand(player) {
if (this.parkingLotCreator_.isSelecting(player))
this.parkingLotCreator_.confirmSelection(player);
else
player.sendMessage(Message.HOUSE_SAVE_UNKNOWN);
}
// Called when the |player| types `/house settings`. This enables them to change properties of
// the house that they're presently located in. Not to be confused with `/house modify`, which
// is meant to be used for the exterior aspects of a house.
async onHouseSettingsCommand(player) {
const location = this.manager_.getCurrentHouseForPlayer(player);
if (!location || location.isAvailable()) {
player.sendMessage(Message.HOUSE_SETTINGS_OUTSIDE);
return;
}
const isOwner = location.settings.ownerId === player.account.userId;
if (!isOwner && (!player.isAdministrator() || player.isTemporaryAdministrator())) {
player.sendMessage(Message.HOUSE_SETTINGS_NOT_OWNER);
return;
}
const menu = new Menu('What would you like to modify?', ['Option', 'Current value']);
const accessValue = this.toHouseAccessLabel(location.settings.access);
const vehicleValue = '{FFFF00}' + location.settings.vehicles.size;
menu.addItem('Change the access level', accessValue, async(player) => {
const accessMenu = new Menu('Who should be able to access your house?');
const accessLevels = [
HouseSettings.ACCESS_EVERYBODY,
HouseSettings.ACCESS_FRIENDS_AND_GANG,
HouseSettings.ACCESS_FRIENDS,
HouseSettings.ACCESS_PERSONAL
];
accessLevels.forEach(level => {
const labelPrefix = location.settings.access === level ? '{FFFF00}' : '';
const label = labelPrefix + this.toHouseAccessLabel(level);
// Add the menu item for the |level| to the sub-menu shown to the player.
accessMenu.addItem(label, async(player) => {
await this.manager_.updateHouseSetting(player, location, 'access', level);
// Change casing of the |label| so that it gramatically works in the message.
const confirmationLabel =
label.charAt(0).toUpperCase() + label.slice(1).toLowerCase();
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Changing the access level',
message: Message.format(Message.HOUSE_SETTINGS_LEVEL, confirmationLabel)
});
});
});
// Show the access sub-menu to the player.
await accessMenu.displayForPlayer(player);
});
menu.addItem('Manage your vehicles', vehicleValue, async(player) => {
await alert(player, {
title: 'Manage your vehicles',
message: 'You are now able to use "/v save" while driving any vehicle to save\n' +
'it to a parking lot, or "/v delete" in one of your vehicles to delete it.'
});
});
// Give house extensions the ability to provide their additional functionality.
this.manager_.invokeExtensions('onHouseSettingsCommand', player, location, menu);
menu.addItem('Sell this house', '-', async(player) => {
const offer = this.economy_().calculateHouseValue(
location.position, location.parkingLotCount, location.interior.getData().value,
Math.floor(server.clock.currentTime() / 1000) - location.settings.purchaseTime);
const message = isOwner ? Message.format(Message.HOUSE_SETTINGS_SELL_OFFER, offer)
: Message.format(Message.HOUSE_SETTINGS_SELL_CONFIRM,
location.settings.ownerName);
const confirmation =
await Dialog.displayMessage(player, 'Selling the house', message,
'Yes' /* leftButton */, 'No' /* rightButton */);
if (!confirmation.response)
return;
this.announce_().announceToAdministratorsWithFilter(
Message.HOUSE_ANNOUNCE_SOLD, PlayerSetting.ANNOUNCEMENT.HOUSES, PlayerSetting.SUBCOMMAND.HOUSES_SELL,
player.name, player.id, location.settings.name, location.settings.id, offer);
await this.manager_.removeHouse(location);
if (isOwner)
await this.finance_().depositToPlayerAccount(player, offer);
// Display a confirmation dialog to the player to inform them of their action.
await MessageBox.display(player, {
title: 'Congratulations on the sell!',
message: Message.format(
(isOwner ? Message.HOUSE_SETTINGS_SELL_CONFIRMED
: Message.HOUSE_SETTINGS_SELL_CONFIRMED_ADMIN), offer)
});
});
await menu.displayForPlayer(player);
}
// Called when an administrator types the `/house` command. Gives an overview of the available
// options, with information on how to use the command, depending on the |player|'s level.
onHouseCommand(player) {
player.sendMessage(Message.HOUSE_HEADER);
player.sendMessage(Message.HOUSE_INFO_1);
player.sendMessage(Message.HOUSE_INFO_2);
let options = ['buy', 'goto', 'settings'];
if (player.isAdministrator())
options.push('enter');
if (player.isAdministrator() && !player.isTemporaryAdministrator())
options.push('create', 'modify', 'remove', 'save');
if (player.isManagement())
options.push('interior');
player.sendMessage(Message.COMMAND_USAGE, '/house [' + options.sort().join('/') + ']');
}
// ---------------------------------------------------------------------------------------------
// Returns the menu label to use for enabling players to change the access level of their house.
toHouseAccessLabel(value) {
switch (value) {
case HouseSettings.ACCESS_EVERYBODY:
return 'All players';
case HouseSettings.ACCESS_FRIENDS_AND_GANG:
return 'Your friends and fellow gang members';
case HouseSettings.ACCESS_FRIENDS:
return 'Your friends';
case HouseSettings.ACCESS_PERSONAL:
return 'Only you';
default:
throw new Error('Invalid house access value: ' + value);
}
}
// ---------------------------------------------------------------------------------------------
dispose() {
server.commandManager.removeCommand('house');
this.parkingLotCreator_.dispose();
this.parkingLotCreator_ = null;
this.parkingLotRemover_.dispose();
this.parkingLotRemover_ = null;
this.economy_ = null;
this.announce_ = null;
this.manager_ = null;
}
} |
JavaScript | class NotificationClearer extends Component {
componentDidMount() {
const {
api,
notificationId
} = this.props;
api.clearNotification(notificationId);
}
render() {
const {
children
} = this.props;
return children;
}
} |
JavaScript | class AutocompleteMutipleEdit extends Component {
/**
* Component's display name.
*/
static displayName = 'AutocompleteMutipleEdit';
/**
* Component's prop types.
*/
static propTypes = {
value: PropTypes.arrayOf(PropTypes.number).isRequired,
onChange: PropTypes.func.isRequired,
keyResolver: PropTypes.func.isRequired,
querySearcher: PropTypes.func.isRequired,
checkDuplicate: PropTypes.bool.isRequired,
error: PropTypes.string,
ChipElement: PropTypes.any,
position: PropTypes.oneOf(['top', 'bottom'])
};
/**
* Component's default props.
*/
static defaultProps = {
value: [],
checkDuplicate: false,
error: null,
ChipElement: undefined,
position: 'top'
};
/**
* Class constructor.
* @param {object} props props given to component.
*/
constructor(props) {
super(props);
this.state = { customError: '' };
this.handleOnChange = this.handleOnChange.bind(this);
this.renderConsult = this.renderConsult.bind(this);
}
/**
* Handle update behavior.
* @param {number} id Identifier.
*/
handleOnChange(id) {
this.setState({ customError: '' });
const alreadyIncluded = (this.props.value).includes(id);
if (!alreadyIncluded && id) {
this.props.onChange((this.props.value).concat([id]));
} else if (this.props.checkDuplicate && alreadyIncluded) {
this.setState({ customError: 'input.multiAutocomplete.duplicate' });
}
}
/**
* Render consult component.
* @return {ReactElement} markup.
*/
renderConsult() {
return (
<Consult
value={this.props.value}
keyResolver={this.props.keyResolver}
readonly={false}
onChange={value => this.props.onChange(value)}
ChipElement={this.props.ChipElement}
/>
);
}
/**
* Render component.
* @return {ReactElement} markup.
*/
render() {
const { keyResolver, querySearcher, error, keyName, labelName } = this.props;
return (
<div data-focus='autocomplete-select-multiple'>
{this.props.position === 'top' && this.renderConsult()}
<AutocompleteSelectEdit
customError={this.state.customError || error}
keyResolver={keyResolver}
keyName={keyName}
labelName={labelName}
querySearcher={querySearcher}
onChange={this.handleOnChange}
onSelectClear
/>
{this.props.position === 'bottom' && this.renderConsult()}
</div>
);
}
} |
JavaScript | class App extends React.Component{
state = {
value1:'111',
value2:'222',
value3:'333',
value4:'444',
};
constructor(props){
super(props);
window.demo = this;
window.refs = this.refs;
window.rc = this.refs.rc;
}
componentDidMount() {
ReactVirtualKeyboardCtrl.createInstance();
}
_click1_1 = e =>{
ReactVirtualKeyboardCtrl.show({
maxLength:10,
value:this.state.value1,
onChange: (inEvent)=>{
const {value} = inEvent.target;
this.setState({value1: value},()=>{
console.log(this.state)
})
},
onHidden:()=>{
console.log('on hidden..');
},
onDocClick: ()=>{
console.log('on drop click...');
}
}).then(()=>{
console.log('shown.');
})
};
_click1_2 = e =>{
ReactVirtualKeyboardCtrl.show({
value:this.state.value2,
type:'identity',
onChange: (inEvent)=>{
const {value} = inEvent.target;
this.setState({value2: value},()=>{
console.log(this.state)
})
},
})
};
_click1_3 = e =>{
ReactVirtualKeyboardCtrl.show({
type:'number',
value:this.state.value3,
onChange: (inEvent)=>{
const {value} = inEvent.target;
this.setState({value3: value},()=>{
console.log(this.state)
})
},
})
};
_click1_4 = e =>{
ReactVirtualKeyboardCtrl.show({
type:'currency',
value:this.state.value4,
onChange: (inEvent)=>{
const {value} = inEvent.target;
this.setState({value4: value},()=>{
console.log(this.state)
})
},
})
};
_click2 = e =>{
ReactVirtualKeyboardCtrl.hide();
};
_click = e =>{
console.log('click!!!');
};
render(){
return (
<div className="hello-react-virtual-keyboard-ctrl">
<button onClick={this._click1_1}>Show - default</button>
<button onClick={this._click1_2}>Show - identity</button>
<button onClick={this._click1_3}>Show - number</button>
<button onClick={this._click1_4}>Show - currency</button>
<button onClick={this._click}>Test click</button>
<button onClick={this._click2}>Hide</button>
</div>
);
}
} |
JavaScript | class EulersMethod {
/**
* @param {!ODESim} ode the set of differential equations to solve
*/
constructor(ode) {
/** the set of differential equations to solve.
* @type {!ODESim}
* @private
*/
this.ode_ = ode;
/** array used within algorithm, retained to avoid reallocation of array.
* @type {!Array<number>}
* @private
*/
this.inp_ = [];
/** array used within algorithm, retained to avoid reallocation of array.
* @type {!Array<number>}
* @private
*/
this.k1_ = [];
/** array used within algorithm, retained to avoid reallocation of array.
* @type {!Array<number>}
* @private
*/
this.k2_ = [];
};
/** @override */
toString() {
return Util.ADVANCED ? '' : this.toStringShort();
};
/** @override */
toStringShort() {
return Util.ADVANCED ? '' : 'EulersMethod{ode_: '+this.ode_.toStringShort()+'}';
};
/** @override */
getName(opt_localized) {
return opt_localized ? EulersMethod.i18n.NAME :
Util.toName(EulersMethod.en.NAME);
};
/** @override */
nameEquals(name) {
return this.getName() == Util.toName(name);
};
/** @override */
step(stepSize) {
const va = this.ode_.getVarsList();
const vars = va.getValues();
const N = vars.length;
if (this.inp_.length != N) {
this.inp_ = new Array(N);
this.k1_ = new Array(N);
}
const inp = this.inp_;
const k1 = this.k1_;
for (let i=0; i<N; i++) {
// set up input to diffeqs (note: this protects vars from being changed)
inp[i] = vars[i];
}
Util.zeroArray(k1);
const error = this.ode_.evaluate(inp, k1, 0); // evaluate at time t
if (error != null) {
return error;
}
/* Filip's Method for DoublePendulumSim.
* See email of May 24, 2021 with Filip Optołowicz.
vars[9] += k1[9] * stepSize; // time
vars[1] += k1[1] * stepSize;
vars[3] += k1[3] * stepSize;
vars[0] += vars[1] * stepSize;
vars[2] += vars[3] * stepSize;
*/
for (let i=0; i<N; i++) {
vars[i] += k1[i] * stepSize;
}
va.setValues(vars, /*continuous=*/true);
return null;
};
} // end class |
JavaScript | class LedgerWallet {
constructor(opts) {
this._path = "44'/60'/0'/0/0";
this._accounts = undefined;
this.isU2FSupported = null;
this.getAppConfig = this.getAppConfig.bind(this);
this.getAccounts = this.getAccounts.bind(this);
this.signTransaction = this.signTransaction.bind(this);
this._getLedgerConnection = this._getLedgerConnection.bind(this);
this._onSubmit = opts.onSubmit;
this._onSigned = opts.onSigned;
this._getChainID = opts.getChainID;
}
async init() {
this.isU2FSupported = await LedgerWallet.isSupported();
}
showSpinner () {
if (this._onSubmit) {
this._onSubmit();
}
}
closeSpinner () {
if (this._onSigned) {
this._onSigned();
}
}
/**
* Checks if the browser supports u2f.
* Currently there is no good way to do feature-detection,
* so we call getApiVersion and wait for 100ms
*/
static async isSupported() {
return new Promise((resolve, reject) => {
if (window.u2f && !window.u2f.getApiVersion) {
// u2f object is found (Firefox with extension)
resolve(true);
} else {
// u2f object was not found. Using Google polyfill
const intervalId = setTimeout(() => {
resolve(false);
}, 3000);
u2f.getApiVersion((version) => {
clearTimeout(intervalId);
resolve(true);
});
}
});
};
async _getLedgerConnection() {
return new Eth(await TransportU2F.create());
}
async _closeLedgerConnection(eth) {
await eth.transport.close()
}
/**
@typedef {function} failableCallback
@param error
@param result
*/
/**
* Gets the version of installed ethereum app
* Check the isSupported() before calling that function
* otherwise it never returns
* @param {failableCallback} callback
*/
async getAppConfig(callback) {
if (!this.isU2FSupported) {
callback(new Error(NOT_SUPPORTED_ERROR_MSG));
return;
}
let eth = await this._getLedgerConnection();
let cleanupCallback = (error, data) => {
this._closeLedgerConnection(eth);
callback(error, data);
};
eth.getAppConfiguration()
.then(config => cleanupCallback(null, config))
.catch(error => cleanupCallback(error))
}
/**
* Gets a list of accounts from a device
* @param {failableCallback} callback
* @param askForOnDeviceConfirmation
*/
async getAccounts(callback, askForOnDeviceConfirmation = true) {
if (!this.isU2FSupported) {
callback(new Error(NOT_SUPPORTED_ERROR_MSG));
return;
}
if (this._accounts !== undefined) {
callback(null, this._accounts);
return;
}
const chainCode = false; // Include the chain code
let eth = await this._getLedgerConnection();
let cleanupCallback = (error, data) => {
this._closeLedgerConnection(eth);
callback(error, data);
};
eth.getAddress(this._path, askForOnDeviceConfirmation, chainCode)
.then(result => {
this._accounts = [result.address.toLowerCase()];
cleanupCallback(null, this._accounts);
})
.catch(error => cleanupCallback(error));
}
/**
* Signs txData in a format that ethereumjs-tx accepts
* @param {object} txData - transaction to sign
* @param {failableCallback} callback - callback
*/
async signTransaction(txData, callback) {
if (!this.isU2FSupported) {
callback(new Error(NOT_SUPPORTED_ERROR_MSG));
return;
}
this.showSpinner();
// Encode using ethereumjs-tx
let tx = new EthereumTx(txData);
// Fetch the chain id
this._getChainID(async function (error, chain_id) {
// Force chain_id to int
chain_id = 0 | chain_id;
// Set the EIP155 bits
tx.raw[6] = Buffer.from([chain_id]); // v
tx.raw[7] = Buffer.from([]); // r
tx.raw[8] = Buffer.from([]); // s
// Encode as hex-rlp for Ledger
const hex = tx.serialize().toString("hex");
let eth = await this._getLedgerConnection();
let cleanupCallback = (error, data) => {
this._closeLedgerConnection(eth);
this.closeSpinner();
callback(error, data);
};
if (error) {
cleanupCallback(error);
}
else {
// Pass to _ledger for signing
eth.signTransaction(this._path, hex)
.then(result => {
// Store signature in transaction
tx.v = new Buffer(result.v, "hex");
tx.r = new Buffer(result.r, "hex");
tx.s = new Buffer(result.s, "hex");
// EIP155: v should be chain_id * 2 + {35, 36}
const signed_chain_id = Math.floor((tx.v[0] - 35) / 2);
if (signed_chain_id !== chain_id) {
cleanupCallback("Invalid signature received. Please update your Ledger Nano S.");
}
// Return the signed raw transaction
const rawTx = "0x" + tx.serialize().toString("hex");
cleanupCallback(undefined, rawTx);
})
.catch(error => cleanupCallback(error))
}
}.bind(this))
}
} |
JavaScript | class NoValidatorInfos extends ExtendableError {
/**
* Constructor
*/
constructor() {
super("Unable to retrieve the validator metadata.");
}
} |
JavaScript | class ChoreView extends Component {
constructor(props) {
super(props)
this.state = {
item: null,
choreLists: [],
householdMembers: []
}
}
componentDidMount() {
const { match: { params } } = this.props;
API.getChoreListWithTasks(params.Id)
.then(({ data: user }) => {
this.setState({ user });
});
//Make API Req same as before using USER ID => this.props.match.params.userId
//Filter results down to only have the result with the correct listId => this.props.match.params.listId
setTimeout(() => {
this.setState({ item: {} });
}, 3000)
}
render() {
if (this.state.item === null) return <div>Loading....</div>
return (
<div>
<p>Render Your data</p>
</div>
)
}
} |
JavaScript | class Stars extends Container {
constructor(count = 10) {
super();
this.starCount = count;
this.name = 'stars';
this._addStars();
}
/**
* @private
*/
_addStars() {
for (let i = 0; i < this.starCount; i++) {
const star = new Sprite.from('star');
star.x = Math.random() * 1600 - 800;
star.y = Math.random() * 800 - 500;
const scaleFactor = Math.random() + 0.5;
star.scale.x = scaleFactor;
star.scale.y = scaleFactor;
star.rotation = Math.random() - 0.5;
this.addChild(star);
}
}
} |
JavaScript | class AssertionUtils {
static assertReservation(actual, responseObj) {
assert.exists(actual, 'actual reservation is either null or undefined');
assert.exists(actual, 'responseObj reservation is either null or undefined');
assert.equal(actual.accountSid, responseObj.account_sid);
assert.equal(actual.workspaceSid, responseObj.workspace_sid);
assert.equal(actual.sid, responseObj.sid);
assert.equal(actual.workerSid, responseObj.worker_sid);
assert.equal(actual.status, responseObj.reservation_status);
assert.equal(actual.timeout, responseObj.reservation_timeout);
assert.deepEqual(actual.dateCreated, new Date(responseObj.date_created * 1000));
assert.deepEqual(actual.dateUpdated, new Date(responseObj.date_updated * 1000));
assert.isTrue(typeof actual.taskDescriptor === 'undefined');
assert.deepEqual(actual.task.addOns, JSON.parse(responseObj.task.addons));
assert.equal(actual.task.age, responseObj.task.age);
assert.deepEqual(actual.task.attributes, JSON.parse(responseObj.task.attributes));
assert.deepEqual(actual.task.dateCreated, new Date(responseObj.task.date_created * 1000));
assert.deepEqual(actual.task.dateUpdated, new Date(responseObj.task.date_updated * 1000));
assert.equal(actual.task.priority, responseObj.task.priority);
assert.equal(actual.task.queueName, responseObj.task.queue_name);
assert.equal(actual.task.queueSid, responseObj.task.queue_sid);
assert.equal(actual.task.reason, responseObj.task.reason);
assert.equal(actual.task.sid, responseObj.task.sid);
assert.equal(actual.task.status, responseObj.task.assignment_status);
assert.equal(actual.task.taskChannelUniqueName, responseObj.task.task_channel_unique_name);
assert.equal(actual.task.taskChannelSid, responseObj.task.task_channel_sid);
assert.equal(actual.task.timeout, responseObj.task.timeout);
assert.equal(actual.task.workflowSid, responseObj.task.workflow_sid);
assert.equal(actual.task.workflowName, responseObj.task.workflow_name);
assert.equal(actual.task.routingTarget, responseObj.task.routing_target);
if (responseObj.task_transfer) {
assert.exists(actual.transfer);
AssertionUtils.assertTransfer(actual.transfer, responseObj.task_transfer);
assert.exists(actual.task.transfers);
assert.exists(actual.task.transfers.incoming);
AssertionUtils.assertTransfer(actual.task.transfers.incoming, responseObj.task_transfer);
}
if (responseObj.active_outgoing_task_transfer) {
assert.exists(actual.task.transfers);
assert.exists(actual.task.transfers.outgoing);
AssertionUtils.assertTransfer(actual.task.transfers.outgoing, responseObj.active_outgoing_task_transfer);
}
if (responseObj.canceled_reason_code) {
assert.equal(actual.canceledReasonCode, responseObj.canceled_reason_code);
}
}
static assertTransfer(actual, responseObj) {
assert.exists(actual, 'actual reservation is either null or undefined');
assert.exists(actual, 'expected reservation is either null or undefined');
assert.equalDate(actual.dateCreated, new Date(responseObj.date_created * 1000));
assert.equalDate(actual.dateUpdated, new Date(responseObj.date_updated * 1000));
assert.equal(actual.to, responseObj.transfer_to);
assert.equal(actual.reservationSid, responseObj.initiating_reservation_sid);
assert.equal(actual.mode, responseObj.transfer_mode);
assert.equal(actual.type, responseObj.transfer_type);
assert.equal(actual.sid, responseObj.sid);
assert.equal(actual.status, responseObj.transfer_status);
assert.equal(actual.workerSid, responseObj.initiating_worker_sid);
assert.equal(actual.queueSid, responseObj.initiating_queue_sid);
assert.equal(actual.workflowSid, responseObj.initiating_workflow_sid);
}
static assertSid(sid, prefix, msg) {
const re = new RegExp(`^${prefix}\\w{32}$`);
assert.match(sid, re, msg);
}
/**
* Verify Transfer properties
* @param {IncomingTransfer} transfer The Transfer object on Reservation
* @param {string} expectedFrom The worker sid of transferor
* @param {string} expectedTo The worker sid of transferee
* @param {string} expectedMode expected Transfer Mode (COLD or WARM)
* @param {string} expectedType expected Transfer Type (WORKER or QUEUE)
* @param {string} expectedStatus expected Transfer Status
* @param {string} prefixMessage Prefix for assertion failure message
*/
static verifyTransferProperties(transfer, expectedFrom, expectedTo, expectedMode, expectedType, expectedStatus, prefixMessage) {
assert.strictEqual(transfer.reservationSid.substring(0, 2), 'WR', `${prefixMessage} Reservation Sid Prefix`);
assert.strictEqual(transfer.sid.substring(0, 2), 'TT', `${prefixMessage} Sid Prefix`);
assert.strictEqual(transfer.workerSid, expectedFrom, `${prefixMessage} Initiating Worker Sid`);
assert.strictEqual(transfer.to, expectedTo, `${prefixMessage} to Worker Sid`);
assert.strictEqual(transfer.mode, expectedMode, `${prefixMessage} Mode`);
assert.strictEqual(transfer.type, expectedType, `${prefixMessage} Type`);
assert.strictEqual(transfer.status, expectedStatus, `${prefixMessage} Status`);
}
static verifyCreatedReservationProperties(reservation, worker, expectedFrom, expectedTo) {
assert.strictEqual(reservation.task.status, 'reserved', 'Task status');
assert.strictEqual(reservation.task.routingTarget, worker.sid, 'Routing target');
assert.deepStrictEqual(reservation.task.attributes.from, expectedFrom, 'Conference From number');
assert.deepStrictEqual(reservation.task.attributes.outbound_to, expectedTo, 'Conference To number');
assert.strictEqual(reservation.status, 'pending', 'Reservation Status');
assert.strictEqual(reservation.workerSid, worker.sid, 'Worker Sid in conference');
}
} |
JavaScript | class BusinessEvent{
constructor(title, description, duration, effect, repeats=false, reverts=true){
this.title = title;
this.description = description
this.duration = duration; // q of days, or false
this.effect = effect; // [<affected item>, q]
this.repeats = repeats; // bool or number to reset duration to
this.reverts = reverts; // bool
this.parent = null; // id of parent
}
// TODO: find way to do this more dynamically
revert(){
var business = getBusiness(this.parent);
if (-1 < ['workers'].indexOf(this.effect[0])) {
business[this.effect[0]] -= this.effect[1];
}
console.log(`DELME reverting ${this.title}`);
}
activate(){
var business = getBusiness(this.parent);
if (-1 < ['workers'].indexOf(this.effect[0])) {
business[this.effect[0]] += this.effect[1];
}
console.log(`DELME activating ${this.title}`);
}
progress(q=1){
// only need to reduce duration if there is a duration
if (typeof this.duration == 'number'){
if (this.duration - q < 1){
this.revert();
if (this.repeats){
this.activate();
this.duration = this.repeats;
} else {
console.log(`Duration of ${this.title} has ended.`)
}
} else {
this.duration -= q;
}
}
}
} |
JavaScript | class Azure_PaaS {
/**
*
* @param {module} azureRestSdk Azure Rest SDK
*/
constructor(azureRestSdk) {
this._azureRestSdk = azureRestSdk;
}
/**
* Trigers the createOrUpdate function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} siteEnvelope - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<createOrUpdateResponse>}
*/
create(resourceGroupName, name, siteEnvelope, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.createOrUpdate(resourceGroupName, name, siteEnvelope, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the update function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} siteEnvelope - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<updateResponse>}
*/
update(resourceGroupName, name, siteEnvelope, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.update(resourceGroupName, name, siteEnvelope, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the get function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<getResponse>}
*/
describe(resourceGroupName, name, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps.get(resourceGroupName, name, options).then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the deleteMethod function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<deleteMethodResponse>}
*/
delete(resourceGroupName, name, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.deleteMethod(resourceGroupName, name, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the restart function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<restartResponse>}
*/
restart(resourceGroupName, name, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.restart(resourceGroupName, name, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the createOrUpdate function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} hostingEnvironmentEnvelope - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<createOrUpdateResponse>}
*/
createEnvironment(
resourceGroupName,
name,
hostingEnvironmentEnvelope,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.appServiceEnvironments
.createOrUpdate(
resourceGroupName,
name,
hostingEnvironmentEnvelope,
options
)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the update function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} hostingEnvironmentEnvelope - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<updateResponse>}
*/
updateEnvironment(
resourceGroupName,
name,
hostingEnvironmentEnvelope,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.appServiceEnvironments
.update(
resourceGroupName,
name,
hostingEnvironmentEnvelope,
options
)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the createOrUpdateSlot function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} siteEnvelope - Mandatory parameter
* @param {StringKeyword} slot - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<createOrUpdateSlotResponse>}
*/
createConfigTemplate(
resourceGroupName,
name,
siteEnvelope,
slot,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.createOrUpdateSlot(
resourceGroupName,
name,
siteEnvelope,
slot,
options
)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the getSlot function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {StringKeyword} slot - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<getSlotResponse>}
*/
describeConfigSettings(resourceGroupName, name, slot, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.getSlot(resourceGroupName, name, slot, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the deleteSlot function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {StringKeyword} slot - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<deleteSlotResponse>}
*/
deleteConfigTemplate(resourceGroupName, name, slot, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.webApps
.deleteSlot(resourceGroupName, name, slot, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the checkAvailability function of appservice
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<checkAvailabilityResponse>}
*/
checkDNSAvailability(options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.domains.checkAvailability(options).then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the deleteMethod function of appservice
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} name - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<deleteMethodResponse>}
*/
terminateEnvironment(resourceGroupName, name, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new WebSiteManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.appServiceEnvironments
.deleteMethod(resourceGroupName, name, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
} |
JavaScript | class NetworkService extends Observable {
/**
* Initially setup network connection and start monitoring for changes
*
* @return {void}
*/
constructor() {
super();
this.networkStatus = connectivityModule.getConnectionType();
this.isOnline = this.checkIfOnline(connectivityModule.getConnectionType());
this.monitorNetworkChange();
}
/**
* Determine if Connection Type is offline or online
*
* @param ConnectionType {Integer}
* @return {void}
*/
checkIfOnline(connectionType) {
return connectionType != connectivityModule.connectionType.none;
}
/**
* Monitor for Network changes and emit an event if so
*
* @return {void}
*/
monitorNetworkChange() {
connectivityModule.startMonitoring((newConnectionType) => {
this.networkStatus = newConnectionType;
this.isOnline = this.checkIfOnline(newConnectionType);
this.notify({
eventName: 'networkStatusChanged',
object: this
});
});
}
} |
JavaScript | class IOnboardingTask {
/**
* Constructs a new <code>IOnboardingTask</code>.
* Onboarding task, required for the onbarding proccess of a new Employee, if the property [requireDoc] is set to 1, then the OnboardingTask require the employee to upload a document, and the fkDocumentType will contain the id of the IDocumentType object with the template of the document to be filled by the employee. Otherwise the [fkDocumentType] property will be null.
* @alias module:model/IOnboardingTask
* @class
* @param fkEmployee {Number} employee ID, foreign key of the Employee that needs to upload this onboarding task
* @param createdDate {Date} created date, of this onboarding task
* @param dueDate {Date} due date, of this onboarding task
* @param requireDoc {Number} require doc, controls wether the Onboarding task requires document upload or not.
* @param status {Number} status, controls wether the Onboarding task is done or not
*/
constructor(fkEmployee, createdDate, dueDate, requireDoc, status) {
this['fkEmployee'] = fkEmployee;this['createdDate'] = createdDate;this['dueDate'] = dueDate;this['requireDoc'] = requireDoc;this['status'] = status;
}
/**
* Constructs a <code>IOnboardingTask</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/IOnboardingTask} obj Optional instance to populate.
* @return {module:model/IOnboardingTask} The populated <code>IOnboardingTask</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new IOnboardingTask();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('fkDocumentType')) {
obj['fkDocumentType'] = ApiClient.convertToType(data['fkDocumentType'], 'Number');
}
if (data.hasOwnProperty('fkEmployee')) {
obj['fkEmployee'] = ApiClient.convertToType(data['fkEmployee'], 'Number');
}
if (data.hasOwnProperty('createdDate')) {
obj['createdDate'] = ApiClient.convertToType(data['createdDate'], 'String');
}
if (data.hasOwnProperty('dueDate')) {
obj['dueDate'] = ApiClient.convertToType(data['dueDate'], 'String');
}
if (data.hasOwnProperty('requireDoc')) {
obj['requireDoc'] = ApiClient.convertToType(data['requireDoc'], 'Number');
}
if (data.hasOwnProperty('status')) {
obj['status'] = ApiClient.convertToType(data['status'], 'Number');
}
if (data.hasOwnProperty('expiryDate')) {
obj['expiryDate'] = ApiClient.convertToType(data['expiryDate'], 'String');
}
if (data.hasOwnProperty('file')) {
obj['file'] = ApiClient.convertToType(data['file'], 'String');
}
if (data.hasOwnProperty('template')) {
obj['template'] = ApiClient.convertToType(data['template'], 'String');
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String');
}
if (data.hasOwnProperty('type')) {
obj['type'] = IDocumentType.constructFromObject(data['type']);
}
}
return obj;
}
/**
* onboarding task ID, the unique identifier of the Role
* @member {Number} id
*/
id = undefined;
/**
* document template ID, foreign key of the DocumentType of this onboarding task
* @member {Number} fkDocumentType
*/
fkDocumentType = undefined;
/**
* employee ID, foreign key of the Employee that needs to upload this onboarding task
* @member {Number} fkEmployee
*/
fkEmployee = undefined;
/**
* created date, of this onboarding task
* @member {Date} createdDate
*/
createdDate = undefined;
/**
* due date, of this onboarding task
* @member {Date} dueDate
*/
dueDate = undefined;
/**
* require doc, controls wether the Onboarding task requires document upload or not.
* @member {Number} requireDoc
*/
requireDoc = undefined;
/**
* status, controls wether the Onboarding task is done or not
* @member {Number} status
*/
status = undefined;
/**
* expiry date, of this onboarding task
* @member {Date} expiryDate
*/
expiryDate = undefined;
/**
* link to file, to the file if it is required
* @member {String} file
*/
file = undefined;
/**
* description, of this onboarding task
* @member {String} description
*/
description = undefined;
/**
* @member {module:model/IDocumentType} type
*/
type = undefined;
} |
JavaScript | class LabJob {
/**
* Constructs a new <code>LabJob</code>.
* @alias module:model/LabJob
* @class
*/
constructor() {}
/**
* Constructs a <code>LabJob</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/LabJob} obj Optional instance to populate.
* @return {module:model/LabJob} The populated <code>LabJob</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new LabJob();
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('dockerId')) {
obj['dockerId'] = ApiClient.convertToType(data['dockerId'], 'String');
}
if (data.hasOwnProperty('dockerName')) {
obj['dockerName'] = ApiClient.convertToType(
data['dockerName'],
'String'
);
}
if (data.hasOwnProperty('dockerImage')) {
obj['dockerImage'] = ApiClient.convertToType(
data['dockerImage'],
'String'
);
}
if (data.hasOwnProperty('adminLink')) {
obj['adminLink'] = ApiClient.convertToType(data['adminLink'], 'String');
}
if (data.hasOwnProperty('startedAt')) {
obj['startedAt'] = ApiClient.convertToType(data['startedAt'], 'Number');
}
if (data.hasOwnProperty('status')) {
obj['status'] = ApiClient.convertToType(data['status'], 'String');
}
if (data.hasOwnProperty('featureType')) {
obj['featureType'] = ApiClient.convertToType(
data['featureType'],
'String'
);
}
if (data.hasOwnProperty('configuration')) {
obj['configuration'] = ApiClient.convertToType(data['configuration'], {
String: 'String',
});
}
if (data.hasOwnProperty('labels')) {
obj['labels'] = ApiClient.convertToType(data['labels'], {
String: 'String',
});
}
if (data.hasOwnProperty('finishedAt')) {
obj['finishedAt'] = ApiClient.convertToType(
data['finishedAt'],
'Number'
);
}
if (data.hasOwnProperty('exitCode')) {
obj['exitCode'] = ApiClient.convertToType(data['exitCode'], 'Number');
}
}
return obj;
}
/**
* @member {String} name
*/
name = undefined;
/**
* @member {String} dockerId
*/
dockerId = undefined;
/**
* @member {String} dockerName
*/
dockerName = undefined;
/**
* @member {String} dockerImage
*/
dockerImage = undefined;
/**
* @member {String} adminLink
*/
adminLink = undefined;
/**
* @member {Number} startedAt
*/
startedAt = undefined;
/**
* @member {String} status
*/
status = undefined;
/**
* @member {String} featureType
*/
featureType = undefined;
/**
* @member {Object.<String, String>} configuration
*/
configuration = undefined;
/**
* @member {Object.<String, String>} labels
*/
labels = undefined;
/**
* @member {Number} finishedAt
*/
finishedAt = undefined;
/**
* @member {Number} exitCode
*/
exitCode = undefined;
} |
JavaScript | class CurrentUsers {
constructor() {
Object.assign(this, {
list: []
});
}
set(list) {
angular.copy(list, this.list);
return this.list;
}
clear() {
angular.copy([], this.list);
}
get(id) {
return this.list.find((e) => e.id === id);
}
} |
JavaScript | class DragGroupItem extends React.Component {
static propTypes = {
/**
* Must be exactly one node. The children will be passed a
* `wrapDragHandle` prop which MUST be used to wrap the draggable
* portion of the child content inside the child's render function
*/
children: PropTypes.node.isRequired,
/**
* Called with (fromGroupId, toGroupId) when the item is moved
* between groups.
*/
onMove: PropTypes.func.isRequired,
/**
* Provided by parent DragGroup
* Indicates the current parent's group id.
*/
groupId: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
};
static styles = styles;
componentDidMount() {
// Use empty image as a drag preview so browsers don't draw it
// and we can draw whatever we want on the custom drag layer instead.
this.props.connectDragPreview(getEmptyImage(), {
// IE fallback: specify that we'd rather screenshot the node
// when it already knows it's being dragged so we can hide it with CSS.
captureDraggingState: true,
});
}
wrapDragHandle = dragHandleNode =>
/**
* The element passed to connectDragSource must be a plain
* React element, not a component. Thus, to do proper
* vendor prefixing with styling, we assign a class name
* and target it from DragItemContainer's styles; see
* styles/DragItemContainer.js
*/
this.props.connectDragSource(
<div
className="DragGroupItem--handle"
style={{
display: this.props.canDrag ? 'block' : 'none',
}}
>
{dragHandleNode}
</div>,
);
render() {
const {
props: {
connectDragSource,
connectDragPreview,
isDragging,
children,
onMove,
...rest
},
wrapDragHandle,
} = this;
return (
<styles.DragItemContainer isDragging={isDragging} {...rest}>
<DragContext.Provider value={{ isDragging, wrapDragHandle }}>
{children}
</DragContext.Provider>
</styles.DragItemContainer>
);
}
} |
JavaScript | class Workflow extends BatchJob {
static type = 'workflow'
static getPipelineHash = (pipeline) => {
const input = pipeline.map((job) => job.type).join(',')
return hasha(input, { encoding: 'hex', algorithm: 'md5' })
}
constructor(data, opts) {
const { pipeline } = data.params
if (!pipeline) {
throw new Error(
`Workflow "${data.type}" missing required param "pipeline"`
)
}
const type = data.type || Workflow.type
const id =
data.id ||
`${type}:${Workflow.getPipelineHash(pipeline)}:${shortid.generate()}`
if (
!Array.isArray(pipeline) ||
pipeline.length < 2 ||
!pipeline.every((job) => job.type) ||
!pipeline
.slice(1)
.every((job) => job.connect && Object.keys(job.connect).length >= 1)
) {
throw new Error(`Workflow "${id}" invalid value for param "pipeline"`)
}
super(
{
state: {
jobIndex: 0
},
...data,
type,
id
},
opts
)
}
async _run() {
const { pipeline, ...sharedParams } = this.params
let { jobIndex = 0 } = this.state
let job
while (jobIndex < pipeline.length) {
const jobConfig = pipeline[jobIndex]
if (!jobConfig) {
throw new Error(`Workflow "${this.id}" invalid current job ${jobIndex}`)
}
if (!this.state.pipeline) {
this.state.pipeline = []
}
const jobId = this.state.pipeline[jobIndex]
let jobData
if (jobId) {
jobData = await this._context.db.get(jobId)
} else {
const connectParams = {}
// connect the current job's params to the results of a previous job
// in the pipeline
if (jobIndex > 0 && jobConfig.connect) {
for (const key of Object.keys(jobConfig.connect)) {
const label = jobConfig.connect[key]
let found = false
for (let i = 0; i < jobIndex; ++i) {
const pipelineJobConfig = pipeline[i]
if (pipelineJobConfig.label === label) {
const connectedJobId = this.state.pipeline[i]
const connectedJobData = await this._context.db.get(
connectedJobId
)
if (connectedJobData) {
connectParams[key] = connectedJobData.results
if (connectParams[key]) {
found = true
}
}
break
}
}
if (!found) {
throw new Error(
`Workflow "${this.id}" invalid job ${jobIndex} unable to resolve connected data for "${key}" and label "${label}"`
)
}
}
}
jobData = {
type: jobConfig.type,
params: {
...sharedParams,
...jobConfig.params,
...connectParams
}
}
}
job = BatchJobFactory.deserialize(jobData, this._context)
if (job.status === 'active') {
if (!jobId) {
this.state.pipeline[jobIndex] = job.id
await job.save()
await this._update()
}
this._logger.debug('>>>', this.id, 'job', {
jobIndex,
id: job.id,
status: job.status,
results: job.results.length
})
await job.run()
this._logger.debug('<<<', this.id, 'job', {
jobIndex,
id: job.id,
status: job.status,
results: job.results.length
})
this._logger.debug()
}
if (job.status === 'done') {
this.state.jobIndex = ++jobIndex
await this._update()
} else {
return {
status: job.status,
error: job.error
}
}
}
if (job) {
return {
results: job.results
}
}
}
} |
JavaScript | class Graph extends Component {
state = {
graph: sample,
selected: {}
};
/* Define custom graph editing methods here */
render() {
const {graph} =this.state;
const {nodes, edges, selected} = graph;
const {NodeTypes, NodeSubtypes
,EdgeTypes} = GraphConfig;
return (
<div id="graph" style={styles.graph}>
<GraphView
nodeKey={NODE_KEY}
emptyType={EMPTY_TYPE}
nodes={nodes}
edges={edges}
selected={selected}
nodeTypes={NodeTypes}
nodeSubtypes={NodeSubtypes}
edgeTypes={EdgeTypes}
/>
</div>
);
}
} |
JavaScript | class candidateController {
/**
* creating and saving candidate data in the database
* @param {Object} req The request object
* @param {Object} res The response object
* @returns {Object} A user object with selected fields
*/
static async signup(req, res) {
try {
const {
firstName,
lastName,
email,
image,
votes
} = req.body;
const newCandidate = {
firstName,
lastName,
image,
email,
votes
};
const createdCandidate = await CandidateServices.createCandidate(newCandidate);
response.successMessage(
res,
'Candidate was created successfully',
201
);
} catch (e) {
return response.errorMessage(
res,
e.message,
500,
);
}
}
/**
* creating and saving candidate data in the database
* @param {Object} req The request object
* @param {Object} res The response object
* @returns {Object} A user object with selected fields
*/
static async getCandidates(req, res) {
try {
const candidates = await CandidateServices.findCandidates();
response.successMessage(
res,
'All candidates',
201,
candidates
);
} catch (e) {
return response.errorMessage(
res,
e.message,
500,
);
}
}
} |
JavaScript | class MoveTo {
constructor(gameObject) {
/** @type {Phaser.GameObjects.GameObject} */
this.gameObject;
/** @type {number} */
this.x = 0;
/** @type {number} */
this.y = 0;
this.gameObject = gameObject;
gameObject["__MoveTo"] = this;
/* START-USER-CTR-CODE */
// If x/y is 0 then use gameObject coordinate
this.x = (this.x) ? this.x : gameObject.x
this.y = (this.y) ? this.y : gameObject.y
this.gameObject.on('pointerup', (pointer) => this.onPointerUp(pointer))
/* END-USER-CTR-CODE */
}
/** @returns {MoveTo} */
static getComponent(gameObject) {
return gameObject["__MoveTo"];
}
/* START-USER-CODE */
onPointerUp(pointer) {
if (pointer.button != 0) {
return
}
this.gameObject.scene.world.client.penguin.move(this.x, this.y)
}
/* END-USER-CODE */
} |
JavaScript | class RequestResponseData {
constructor(data, headers, status, statusText, request) {
this.data = data;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.request = request;
}
} |
JavaScript | class APIBase {
/**
*
* @param core Reference to the Avalanche instance using this baseURL
* @param baseURL Path to the baseURL
*/
constructor(core, baseURL) {
/**
* Sets the path of the APIs baseURL.
*
* @param baseURL Path of the APIs baseURL - ex: "/ext/bc/X"
*/
this.setBaseURL = (baseURL) => {
if (this.db && this.baseURL !== baseURL) {
const backup = this.db.getAll();
this.db.clearAll();
this.baseURL = baseURL;
this.db = db_1.default.getNamespace(baseURL);
this.db.setAll(backup, true);
}
else {
this.baseURL = baseURL;
this.db = db_1.default.getNamespace(baseURL);
}
};
/**
* Returns the baseURL's path.
*/
this.getBaseURL = () => this.baseURL;
/**
* Returns the baseURL's database.
*/
this.getDB = () => this.db;
this.core = core;
this.setBaseURL(baseURL);
}
} |
JavaScript | class Faq extends Component {
// context
static contextTypes = {
t: PropTypes.func.isRequired
};
/**
* constructor
*/
constructor(props) {
// parent constructor
super(props);
// get translation method
this.t = this.props.t;
// set initial state
this.state = {
pageHeader: 'Faq.pageCaption',
pageHeaderSmall: ''
};
}
/**
* updates given parts of the state
*
* @param state the state name to be updated
* @param value the value for state
*/
updateState(state, value) {
var currentState = this.state;
// check if state exists
if(this.state[state] != undefined) {
currentState[state] = value;
this.setState(currentState);
}
}
/**
* handleSetSubtitle(subtitle, translationArgs)
* eventhandler to handle the change of the subtitle
*
* @param string subtitle the new subtitle
* @param object translationArgs arguments for the translation engine
*/
handleSetSubtitle(subtitle, translationArgs = undefined) {
// prepare header
var pageHeaderSmall = {
title: subtitle,
args: translationArgs
};
// update the state with the new subtitle
this.updateState('pageHeaderSmall', pageHeaderSmall);
}
/**
* method to render the component
*/
render() {
// set title
document.title = 'JudoIntranet - ' + this.t(this.state.pageHeader);
return (
<div className="container">
<PageHeader>
{this.t(this.state.pageHeader)}{' '}
<small>
{this.t(this.state.pageHeaderSmall.title, this.state.pageHeaderSmall.args)}
</small>
</PageHeader>
<Switch>
<Route exact path={this.props.match.url} render={() => <Redirect to={this.props.match.url + '/listall'} />} />
<Route path={this.props.match.url + '/listall/:categoryId?'} children={({match, history}) =>
<FaqCategory
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
<Route path={this.props.match.url + '/category/new'} children={({match, history}) =>
<FaqCategoryForm
form="new"
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
<Route path={this.props.match.url + '/category/edit/:id'} children={({match, history}) =>
<FaqCategoryForm
form="edit"
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
<Route path={this.props.match.url + '/new'} children={({match, history}) =>
<FaqForm
form="new"
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
<Route path={this.props.match.url + '/edit/:id'} children={({match, history}) =>
<FaqForm
form="edit"
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
<Route path={this.props.match.url + '/view/:id'} children={({match, history}) =>
<FaqEntry
handleSetSubtitle={this.handleSetSubtitle.bind(this)}
match={match}
history={history}
/>}
/>
</Switch>
</div>
);
}
} |
JavaScript | class EmptyIterable extends Iterable {
/** The constructor actually returns a singleton, created the first time it
* is called.
*/
constructor() {
if (singletonEmptyIterable) {
return singletonEmptyIterable;
}
const source = empty;
super(source);
singletonEmptyIterable = this;
}
// Conversions /////////////////////////////////////////////////////////////////
/** An empty sequence converts to an empty array.
*/
toArray(array) {
return (array || []);
}
/** An empty sequence converts to an empty set.
*/
toSet(set = null) {
return set || new Set();
}
// Properties //////////////////////////////////////////////////////////////////
/** An empty sequence is always empty, by definition.
*/
isEmpty() {
return true;
}
/** An empty sequence is always zero, of course.
*/
get length() {
return 0;
}
// Reductions //////////////////////////////////////////////////////////////////
/** All reductions of empty sequences result in the initial value.
*/
reduce(foldFunction, initial) {
return initial;
}
// Selections //////////////////////////////////////////////////////////////////
/** Nothing can be got from an empty sequence. So `get` will always fail
* unless.
*/
get(index, defaultValue) {
if (arguments.length < 2) {
throw new Error(`Cannot get value at ${index}!`);
} else {
return defaultValue;
}
}
} // class EmptyIterable |
JavaScript | class Ray3 {
/**
* Creates a new Ray3.
* @param {Vector3} origin The origin of the ray.
* @param {Vector3} direction The direction of the ray. It should be a unit vector.
*/
constructor(origin = new Vector3(0, 0, 0), direction = new Vector3(0, 0, -1)) {
this.origin = origin;
this.direction = direction;
}
/**
* Creates a clone of the ray.
* @returns {Ray3} The cloned ray.
*/
clone() {
return new Ray3(this.origin.clone(), this.direction.clone());
}
/**
* Copies the origin and the direction of another ray.
* @param {Ray3} ray The ray to copy.
* @returns {Ray3} The ray.
*/
copy(ray) {
this.origin.copy(ray.origin);
this.direction.copy(ray.direction);
return this;
}
/**
* Compares the origin and the direction to another ray.
* @param {Ray3} ray The ray to compare to.
* @returns {Boolean} A value indicating whether the rays are equal.
*/
equals(ray) {
return this.origin.equals(ray.origin) && this.direction.equals(ray.direction);
}
} |
JavaScript | class ProfileDataBusiness {
/**
* Constructs a new <code>ProfileDataBusiness</code>.
* @alias module:model/ProfileDataBusiness
* @param description {module:model/ProfileDataBusinessDescription}
* @param industry {module:model/ProfileDataBusinessIndustry}
* @param sector {module:model/ProfileDataBusinessIndustry}
* @param name {module:model/ProfileDataBusinessIndustry}
*/
constructor(description, industry, sector, name) {
ProfileDataBusiness.initialize(this, description, industry, sector, name);
}
/**
* 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, description, industry, sector, name) {
obj['description'] = description;
obj['industry'] = industry;
obj['sector'] = sector;
obj['name'] = name;
}
/**
* Constructs a <code>ProfileDataBusiness</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/ProfileDataBusiness} obj Optional instance to populate.
* @return {module:model/ProfileDataBusiness} The populated <code>ProfileDataBusiness</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ProfileDataBusiness();
if (data.hasOwnProperty('description')) {
obj['description'] = ProfileDataBusinessDescription.constructFromObject(data['description']);
}
if (data.hasOwnProperty('industry')) {
obj['industry'] = ProfileDataBusinessIndustry.constructFromObject(data['industry']);
}
if (data.hasOwnProperty('sector')) {
obj['sector'] = ProfileDataBusinessIndustry.constructFromObject(data['sector']);
}
if (data.hasOwnProperty('name')) {
obj['name'] = ProfileDataBusinessIndustry.constructFromObject(data['name']);
}
if (data.hasOwnProperty('dbaName')) {
obj['dbaName'] = ProfileDataBusinessIndustry.constructFromObject(data['dbaName']);
}
if (data.hasOwnProperty('crunchbaseCategories')) {
obj['crunchbaseCategories'] = ProfileDataBusinessCrunchbaseCategories.constructFromObject(data['crunchbaseCategories']);
}
if (data.hasOwnProperty('crunchbaseUrl')) {
obj['crunchbaseUrl'] = ProfileDataBusinessCrunchbaseUrl.constructFromObject(data['crunchbaseUrl']);
}
}
return obj;
}
} |
JavaScript | class PlayingField extends Observable {
constructor() {
super();
this.gameView = document.getElementById("game");
this.playingFieldArray = [];
this.playingField = document.querySelector(".field");
this.promptField = document.getElementById("promptField");
this.playingFieldArea = document.getElementById("playingField");
}
} |
JavaScript | class Producer {
/**
* Constructor
* @param {CrimsonQClient} cqClient The CrimsonQ client for Producer to use as a connection
*/
constructor(cqClient) {
this.cqClient = cqClient;
}
/**
* Send messages to the consumer queue
* @param {string} consumerId The consumer Id that will recieve the message
* @param {Object} message The message object that needs to be pushed to consumers
*/
async pushToConsumer(consumerId, message) {
try {
message = JSON.stringify(message)
var exists = await this.cqClient.command.consumer_exists(consumerId);
if (exists.value == 'true') {
let result = await this.cqClient.command.msg_push_consumer(consumerId, message)
return result
} else {
throw new Error("Consumer Id does not exist")
}
} catch (e) {
throw e
}
}
/**
* Send message to the topic queue
* @param {string} topic The topic that will be used to send to consumers listening to the topic. The topic can have MQTT style wildcards.
* @param {Object} message The message object that needs to be pushed to consumers
*/
async pushToTopic(topic, message) {
try {
message = JSON.stringify(message)
let result = await this.cqClient.command.msg_push_topic(topic, message)
return result
} catch (e) {
throw e
}
}
/**
* The good old Ping with a message, helps you debug your connection.
* @returns Pong! CrimsonQ
*/
async ping() {
return await this.cqClient.command.ping("Producer")
}
} |
JavaScript | class App extends Component {
state = {
value: "some editable text",
isEditable: false,
};
changeEditMode = () => {
console.log("change edit mode");
this.setState({
isEditable: !this.state.isEditable,
});
};
updateComponentValue = () => {
this.setState({
isEditable: false,
value: this.refs.theTextInput.value,
});
};
// inputRef = (text) => this.setState((prev) => ({ ...prev, value: text }));
renderEditView = () => {
return (
<div>
{/* <input
type="text"
defaultValue={this.state.value}
ref={this.inputRef}
/> */}
<button onClick={this.changeEditMode}>Cancel</button>
<button onClick={this.updateComponentValue}>Save</button>
</div>
);
};
renderDefaultView = () => {
return <div onDoubleClick={this.changeEditMode}>{this.state.value}</div>;
};
render() {
return this.state.isEditable
? this.renderEditView()
: this.renderDefaultView();
}
} |
JavaScript | class MBitUART {
/**
* Construct a MicroBit communication object.
* @param {Runtime} runtime - the Scratch 3.0 runtime
* @param {string} extensionId - the id of the extension
*/
constructor (runtime, extensionId) {
/**
* The Scratch 3.0 runtime used to trigger the green flag button.
* @type {Runtime}
* @private
*/
this._runtime = runtime;
/**
* The id of the extension this peripheral belongs to.
*/
this._extensionId = extensionId;
if( this._runtime._mbitlink == undefined) {
this._runtime._mbitlink = { instance: null, extensions: { mbituart : this } };
} else {
this._runtime._mbitlink.extensions.mbituart = this;
}
/**
* The most recently received value for each sensor.
* @type {Object.<string, number>}
* @private
*/
this._sensors = {
buttonA: 0,
buttonB: 0,
// micro:bit v2
touchLogo: 0,
touch_pins: [0, 0, 0],
gestureState: "",
ledMatrixState: new Uint8Array(5),
light_level: 0,
temperature: 0,
magnetic_force: [0, 0, 0],
acceleration: [0, 0, 0],
rotation: [0, 0],
// micro:bit v2
play_sound: 0,
microphone: 0,
};
/**
* The most recently received value for each gesture.
* @type {Object.<string, Object>}
* @private
*/
this._gestures = {
moving: false,
move: {
active: false,
timeout: false
},
shake: {
active: false,
timeout: false
},
jump: {
active: false,
timeout: false
}
};
this.onMessage = this.onMessage.bind(this);
}
send (cmd, data) {
if( this._runtime._mbitlink.instance != null) {
this._runtime._mbitlink.instance.send(cmd + data + "\n");
}
}
onMessage (data) {
if(data[0] == 'B') {
if(data[1] == 'A')
this._sensors.buttonA = parseInt(data[2]);
else if(data[1] == 'B')
this._sensors.buttonB = parseInt(data[2]);
else if(data[1] == 'L')
this._sensors.touchLogo = parseInt(data[2]);
else if(data[1] == '0')
this._sensors.touch_pins[0] = parseInt(data[2]);
else if(data[1] == '1')
this._sensors.touch_pins[1] = parseInt(data[2]);
else if(data[1] == '2')
this._sensors.touch_pins[2] = parseInt(data[2]);
return true;
}
if(data[0] == 'G') {
this._sensors.gestureState = data.substr(2);
return true;
}
if(data[0] == 'V') {
this._sensors.light_level = parseInt(data.substr(2));
return true;
}
if(data[0] == 'T') {
this._sensors.temperature = parseInt(data.substr(2));
return true;
}
if(data[0] == 'F') {
this._sensors.magnetic_force = this.hex_array(data.substr(2));
return true;
}
if(data[0] == 'A') {
this._sensors.acceleration = this.hex_array(data.substr(2));
return true;
}
if(data[0] == 'R') {
this._sensors.rotation = this.hex_array(data.substr(2));
return true;
}
if(data[0] == 'P') {
this._sensors.microphone = parseInt(data.substr(2));
return true;
}
if(data[0] == 'D') {
if(data[1] == 'T') {
if(data[2] == 'S') {
this._sensors.play_sound = 1;
} else {
this._sensors.play_sound = 0;
}
return true;
}
}
return false;
}
/**
* @return {boolean} - the latest value received for the A button.
*/
get buttonA () {
return this._sensors.buttonA;
}
/**
* @return {boolean} - the latest value received for the B button.
*/
get buttonB () {
return this._sensors.buttonB;
}
/**
* @return {boolean} - the latest value received for the B button.
*/
get touchLogo () {
return this._sensors.touchLogo;
}
/**
* @return {number} - the latest value received for the motion gesture states.
*/
get gestureState () {
return this._sensors.gestureState;
}
/**
* @return {Uint8Array} - the current state of the 5x5 LED matrix.
*/
get ledMatrixState () {
return this._sensors.ledMatrixState;
}
get light_level () {
return this._sensors.light_level;
}
get temperature () {
return this._sensors.temperature;
}
get magnetic_force () {
return this._sensors.magnetic_force;
}
get acceleration () {
return this._sensors.acceleration;
}
get rotation () {
return this._sensors.rotation;
}
get touch_pins () {
return this._sensors.touch_pins;
}
get play_sound () {
return this._sensors.play_sound;
}
get microphone () {
return this._sensors.microphone;
}
hex2dec (val) {
let d = parseInt(val, 16);
if (d & 0x00008000) {
d |= 0xffff0000;
}
return d;
}
hex_array (val) {
let v = [];
if (val.length >= 4)
v[0] = this.hex2dec(val.substring(0, 4));
if (val.length >= 8)
v[1] = this.hex2dec(val.substring(4, 8));
if (val.length >= 12)
v[2] = this.hex2dec(val.substring(8, 12));
return v;
}
} |
JavaScript | class Scratch3_MBitUART_Blocks {
/**
* @return {string} - the name of this extension.
*/
static get EXTENSION_NAME () {
return 'micro:bit';
}
/**
* @return {string} - the ID of this extension.
*/
static get EXTENSION_ID () {
return 'mbituart';
}
/**
* @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold.
*/
static get TILT_THRESHOLD () {
return 15;
}
/**
* @return {array} - text and values for each buttons menu element
*/
get BUTTONS_MENU () {
return [
{
text: 'A',
value: MBitUART_Buttons.A
},
{
text: 'B',
value: MBitUART_Buttons.B
},
{
text: formatMessage({
id: 'mbituart.buttonsMenu.any',
default: 'Any',
description: 'label for "any" element in button picker'
}),
value: MBitUART_Buttons.ANY
}
];
}
get TOUCH_PINS_MENU () {
return [
{
text: '0',
value: 0
},
{
text: '1',
value: 1
},
{
text: '2',
value: 2
},
];
}
get TOUCH_PINMODE_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.pinModeMenu.none',
default: 'None',
description: 'label for pin mode picker'
}),
value: MBitUART_PINMODE.NONE
},
{
text: formatMessage({
id: 'mbituart.pinModeMenu.onoff',
default: 'On/Off',
description: 'label for pin mode picker'
}),
value: MBitUART_PINMODE.ONOFF
},
{
text: formatMessage({
id: 'mbituart.pinModeMenu.value',
default: 'Value',
description: 'label for pin mode picker'
}),
value: MBitUART_PINMODE.VALUE
},
];
}
/**
* @return {array} - text and values for each gestures menu element
*/
get GESTURES_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.gesturesMenu.shake',
default: 'Shake',
description: 'label for shake gesture in gesture picker'
}),
value: MBitUART_Gestures.SHAKE
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.tiltforward',
default: 'LogoUp',
description: 'label for tiltforward gesture in gesture picker'
}),
value: MBitUART_Gestures.TILTFORWORD
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.tiltbackwards',
default: 'Logo Down',
description: 'label for tiltbackwards gesture in gesture picker'
}),
value: MBitUART_Gestures.TILTBACKWORDS
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.frontsideup',
default: 'Screen Up',
description: 'label for frontsideup gesture in gesture picker'
}),
value: MBitUART_Gestures.FRONTSIDEUP
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.backsideup',
default: 'Screen Down',
description: 'label for backsideup gesture in gesture picker'
}),
value: MBitUART_Gestures.BACKSIDEUP
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.tiltleft',
default: 'Tilt Left',
description: 'label for tiltleft gesture in gesture picker'
}),
value: MBitUART_Gestures.TILTLEFT
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.tiltright',
default: 'Tilt Right',
description: 'label for tiltright gesture in gesture picker'
}),
value: MBitUART_Gestures.TILTRIGHT
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.freefall',
default: 'FreeFall',
description: 'label for freefall gesture in gesture picker'
}),
value: MBitUART_Gestures.FREEFALL
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.impact3g',
default: '3G',
description: 'label for impact3g gesture in gesture picker'
}),
value: MBitUART_Gestures.IMPACT3G
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.impact6g',
default: '6G',
description: 'label for impact6g gesture in gesture picker'
}),
value: MBitUART_Gestures.IMPACT6G
},
{
text: formatMessage({
id: 'mbituart.gesturesMenu.impact8g',
default: '8G',
description: 'label for frontsideup gesture in gesture picker'
}),
value: MBitUART_Gestures.IMPACT8G
}
];
}
get AXIS_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.axisMenu.x',
default: 'X',
description: 'label for type picker'
}),
value: MBitUART_Axis.X
},
{
text: formatMessage({
id: 'mbituart.axisMenu.y',
default: 'Y',
description: 'label for type picker'
}),
value: MBitUART_Axis.Y
},
{
text: formatMessage({
id: 'mbituart.axisMenu.z',
default: 'Z',
description: 'label for type picker'
}),
value: MBitUART_Axis.Z
}
];
}
get ROTATION_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.rotationMenu.roll',
default: 'Roll',
description: 'label for rotate picker'
}),
value: MBitUART_Rotation.ROLL
},
{
text: formatMessage({
id: 'mbituart.rotationMenu.pitch',
default: 'Pitch',
description: 'label for rotate picker'
}),
value: MBitUART_Rotation.PITCH
}
];
}
get ENABLE_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.enableMenu.enable',
default: 'Enable',
description: 'label for enable picker'
}),
value: MBitUART_Enable.ENABLE
},
{
text: formatMessage({
id: 'mbituart.enableManu.disable',
default: 'Disable',
description: 'label for enable picker'
}),
value: MBitUART_Enable.DISABLE
}
];
}
get SOUND_LENGTH_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.soundLengthMenu.Len16',
default: '1/16',
description: 'label for enable picker'
}),
value: MBitUART_SoundLength.LEN16
},
{
text: formatMessage({
id: 'mbituart.soundLengthMenu.Len8',
default: '1/8',
description: 'label for enable picker'
}),
value: MBitUART_SoundLength.LEN8
},
{
text: formatMessage({
id: 'mbituart.soundLengthMenu.Len4',
default: '1/4',
description: 'label for enable picker'
}),
value: MBitUART_SoundLength.LEN4
},
{
text: formatMessage({
id: 'mbituart.soundLengthMenu.Len2',
default: '1/2',
description: 'label for enable picker'
}),
value: MBitUART_SoundLength.LEN2
},
{
text: formatMessage({
id: 'mbituart.soundLengthMenu.Len1',
default: '1',
description: 'label for enable picker'
}),
value: MBitUART_SoundLength.LEN1
}
];
}
get SOUND_LEVEL_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.soundLevelMenu.Low',
default: 'Low',
description: 'label for enable picker'
}),
value: MBitUART_SoundLevel.LOW
},
{
text: formatMessage({
id: 'mbituart.soundLevelMenu.Mid',
default: 'Middle',
description: 'label for enable picker'
}),
value: MBitUART_SoundLevel.MID
},
{
text: formatMessage({
id: 'mbituart.soundLevelMenu.High',
default: 'High',
description: 'label for enable picker'
}),
value: MBitUART_SoundLevel.HIGH
}
];
}
get SOUND_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.soundMenu.Do',
default: 'Do',
description: 'label for enable picker'
}),
value: MBitUART_Sound.DO
},
{
text: formatMessage({
id: 'mbituart.soundMenu.DoS',
default: 'Do#',
description: 'label for enable picker'
}),
value: MBitUART_Sound.DOS
},
{
text: formatMessage({
id: 'mbituart.soundMenu.Re',
default: 'Re',
description: 'label for enable picker'
}),
value: MBitUART_Sound.RE
},
{
text: formatMessage({
id: 'mbituart.soundMenu.ReS',
default: 'Re#',
description: 'label for enable picker'
}),
value: MBitUART_Sound.RES
},
{
text: formatMessage({
id: 'mbituart.soundMenu.Mi',
default: 'Mi',
description: 'label for enable picker'
}),
value: MBitUART_Sound.MI
},
{
text: formatMessage({
id: 'mbituart.soundMenu.Fa',
default: 'Fa',
description: 'label for enable picker'
}),
value: MBitUART_Sound.FA
},
{
text: formatMessage({
id: 'mbituart.soundMenu.FaS',
default: 'Fa#',
description: 'label for enable picker'
}),
value: MBitUART_Sound.FAS
},
{
text: formatMessage({
id: 'mbituart.soundMenu.So',
default: 'So',
description: 'label for enable picker'
}),
value: MBitUART_Sound.SO
},
{
text: formatMessage({
id: 'mbituart.soundMenu.SoS',
default: 'So#',
description: 'label for enable picker'
}),
value: MBitUART_Sound.SOS
},
{
text: formatMessage({
id: 'mbituart.soundMenu.Ra',
default: 'Ra',
description: 'label for enable picker'
}),
value: MBitUART_Sound.RA
},
{
text: formatMessage({
id: 'mbituart.soundMenu.Shi',
default: 'Shi',
description: 'label for enable picker'
}),
value: MBitUART_Sound.SHI
}
];
}
get EXPRESS_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.expressMenu.giggle',
default: 'Giggle',
description: 'label for enable picker'
}),
value: MBitUART_Express.giggle
},
{
text: formatMessage({
id: 'mbituart.expressMenu.happy',
default: 'Happy',
description: 'label for enable picker'
}),
value: MBitUART_Express.happy
},
{
text: formatMessage({
id: 'mbituart.expressMenu.hello',
default: 'Hello',
description: 'label for enable picker'
}),
value: MBitUART_Express.hello
},
{
text: formatMessage({
id: 'mbituart.expressMenu.mysterious',
default: 'Mysterious',
description: 'label for enable picker'
}),
value: MBitUART_Express.mysterious
},
{
text: formatMessage({
id: 'mbituart.expressMenu.sad',
default: 'Sad',
description: 'label for enable picker'
}),
value: MBitUART_Express.sad
},
{
text: formatMessage({
id: 'mbituart.expressMenu.slide',
default: 'Slide',
description: 'label for enable picker'
}),
value: MBitUART_Express.slide
},
{
text: formatMessage({
id: 'mbituart.expressMenu.soaring',
default: 'Soaring',
description: 'label for enable picker'
}),
value: MBitUART_Express.soaring
},
{
text: formatMessage({
id: 'mbituart.expressMenu.spring',
default: 'Spring',
description: 'label for enable picker'
}),
value: MBitUART_Express.spring
},
{
text: formatMessage({
id: 'mbituart.expressMenu.twinkle',
default: 'Twinkle',
description: 'label for enable picker'
}),
value: MBitUART_Express.twinkle
},
{
text: formatMessage({
id: 'mbituart.expressMenu.yawn',
default: 'Yawn',
description: 'label for enable picker'
}),
value: MBitUART_Express.yawn
}
];
}
/**
* @return {array} - text and values for each tilt direction menu element
*/
get TILT_DIRECTION_MENU () {
return [
{
text: formatMessage({
id: 'mbituart.tiltDirectionMenu.front',
default: 'Front',
description: 'label for front element in tilt direction picker for micro:bit extension'
}),
value: MBitUART_TiltDirection.FRONT
},
{
text: formatMessage({
id: 'mbituart.tiltDirectionMenu.back',
default: 'Back',
description: 'label for back element in tilt direction picker for micro:bit extension'
}),
value: MBitUART_TiltDirection.BACK
},
{
text: formatMessage({
id: 'mbituart.tiltDirectionMenu.left',
default: 'Left',
description: 'label for left element in tilt direction picker for micro:bit extension'
}),
value: MBitUART_TiltDirection.LEFT
},
{
text: formatMessage({
id: 'mbituart.tiltDirectionMenu.right',
default: 'Right',
description: 'label for right element in tilt direction picker for micro:bit extension'
}),
value: MBitUART_TiltDirection.RIGHT
}
];
}
/**
* @return {array} - text and values for each tilt direction (plus "any") menu element
*/
get TILT_DIRECTION_ANY_MENU () {
return [
...this.TILT_DIRECTION_MENU,
{
text: formatMessage({
id: 'mbituart.tiltDirectionMenu.any',
default: 'Any',
description: 'label for any direction element in tilt direction picker'
}),
value: MBitUART_TiltDirection.ANY
}
];
}
/**
* Construct a set of MBitUART blocks.
* @param {Runtime} runtime - the Scratch 3.0 runtime.
*/
constructor (runtime) {
/**
* The Scratch 3.0 runtime.
* @type {Runtime}
*/
this.runtime = runtime;
// Create a new MBitUART peripheral instance
this.instance = new MBitUART(this.runtime, Scratch3_MBitUART_Blocks.EXTENSION_ID);
}
/**
* @returns {object} metadata for this extension and its blocks.
*/
getInfo () {
this.setupTranslations();
return {
id: Scratch3_MBitUART_Blocks.EXTENSION_ID,
name: Scratch3_MBitUART_Blocks.EXTENSION_NAME,
color1: '#0FBDAC',
color2: '#0DA59A',
color3: '#0B8E89',
blockIconURI: blockIconURI,
//showStatusButton: true,
blocks: [
{
opcode: 'whenLogoTouched',
text: formatMessage({
id: 'mbituart.whenLogoTouched',
default: 'When logo touched',
description: 'when the logo on the micro:bit is touched'
}),
blockType: BlockType.HAT
},
{
opcode: 'isLogoTouched',
text: formatMessage({
id: 'mbituart.isLogoTouched',
default: 'Logo touched?',
description: 'is the logo on the micro:bit touched?'
}),
blockType: BlockType.BOOLEAN
},
{
opcode: 'whenButtonPressed',
text: formatMessage({
id: 'mbituart.whenButtonPressed',
default: 'When [BTN] button pressed',
description: 'when the selected button on the micro:bit is pressed'
}),
blockType: BlockType.HAT,
arguments: {
BTN: {
type: ArgumentType.STRING,
menu: 'buttons',
defaultValue: MBitUART_Buttons.A
}
}
},
{
opcode: 'isButtonPressed',
text: formatMessage({
id: 'mbituart.isButtonPressed',
default: '[BTN] button pressed?',
description: 'is the selected button on the micro:bit pressed?'
}),
blockType: BlockType.BOOLEAN,
arguments: {
BTN: {
type: ArgumentType.STRING,
menu: 'buttons',
defaultValue: MBitUART_Buttons.A
}
}
},
{
opcode: 'getLightLevel',
text: formatMessage({
id: 'mbituart.getLightLevel',
default: 'Light level',
description: 'light level'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'getTemperature',
text: formatMessage({
id: 'mbituart.getTemperature',
default: 'Temperature',
description: 'temperature'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'whenPinConnected',
text: formatMessage({
id: 'mbituart.whenPinConnected',
default: 'When pin [PIN] connected',
description: 'when the pin detects a connection to Earth/Ground'
}),
blockType: BlockType.HAT,
arguments: {
PIN: {
type: ArgumentType.NUMBER,
menu: 'touchPins',
defaultValue: 0
}
}
},
{
opcode: 'getPinConnected',
text: formatMessage({
id: 'mbituart.getPinConnected',
default: 'When pin [PIN] connected',
description: 'when the pin detects a connection to Earth/Ground'
}),
blockType: BlockType.REPORTER,
arguments: {
PIN: {
type: ArgumentType.NUMBER,
menu: 'touchPins',
defaultValue: 0
}
}
},
{
opcode: 'outPinValue',
text: formatMessage({
id: 'mbituart.outPinValue',
default: 'Output [VALUE] to pin [PIN] ',
description: 'output value to the pin'
}),
blockType: BlockType.COMMAND,
arguments: {
PIN: {
type: ArgumentType.NUMBER,
menu: 'touchPins',
defaultValue: 0
},
VALUE: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'setPinConfig',
text: formatMessage({
id: 'mbituart.setPinConfig',
default: 'Pin [PIN] with [MODE]',
description: 'set the pin mode'
}),
blockType: BlockType.COMMAND,
arguments: {
PIN: {
type: ArgumentType.NUMBER,
menu: 'touchPins',
defaultValue: 0
},
MODE: {
type: ArgumentType.STRING,
menu: 'pinMode',
defaultValue: MBitUART_PINMODE.NONE
}
}
},
{
opcode: 'whenGesture',
text: formatMessage({
id: 'mbituart.whenGesture',
default: 'When [GESTURE]',
description: 'when the selected gesture is detected by the micro:bit'
}),
blockType: BlockType.HAT,
arguments: {
GESTURE: {
type: ArgumentType.STRING,
menu: 'gestures',
defaultValue: MBitUART_Gestures.MOVED
}
}
},
{
opcode: 'getGesture',
text: formatMessage({
id: 'mbituart.getGesture',
default: 'Get gesture',
description: 'get gesture'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'setSensor',
text: formatMessage({
id: 'mbituart.setSensor',
default: '[ENABLE] basic sensor(Logo, Buttons, Light level, Temperature)',
description: 'enable/disable basic sensor(logo, buttons, light level, temperature, etc)'
}),
blockType: BlockType.COMMAND,
arguments: {
ENABLE: {
type: ArgumentType.NUMBER,
menu: 'enable',
defaultValue: 1
}
}
},
'---',
{
opcode: 'displaySymbol',
text: formatMessage({
id: 'mbituart.displaySymbol',
default: 'Display [MATRIX]',
description: 'display a pattern on the micro:bit display'
}),
blockType: BlockType.COMMAND,
arguments: {
MATRIX: {
type: ArgumentType.MATRIX,
defaultValue: '0101010101100010101000100'
}
}
},
{
opcode: 'displayText',
text: formatMessage({
id: 'mbituart.displayText',
default: 'Display text [TEXT]',
description: 'display text on the micro:bit display'
}),
blockType: BlockType.COMMAND,
arguments: {
TEXT: {
type: ArgumentType.STRING,
defaultValue: formatMessage({
id: 'mbituart.defaultTextToDisplay',
default: 'Hello!',
description: `default text to display.
IMPORTANT - the micro:bit only supports letters a-z, A-Z.
Please substitute a default word in your language
that can be written with those characters,
substitute non-accented characters or leave it as "Hello!".
Check the micro:bit site documentation for details`
})
}
}
},
{
opcode: 'displayClear',
text: formatMessage({
id: 'mbituart.clearDisplay',
default: 'Clear display',
description: 'display nothing on the micro:bit display'
}),
blockType: BlockType.COMMAND
},
'---',
{
opcode: 'playExpress',
text: formatMessage({
id: 'mbituart.playExpress',
default: 'Play [EXPRESS]',
description: 'play express'
}),
blockType: BlockType.COMMAND,
arguments: {
EXPRESS: {
type: ArgumentType.STRING,
menu: 'express',
defaultValue: MBitUART_Express.giggle
}
}
},
{
opcode: 'playTone',
text: formatMessage({
id: 'mbituart.playTone',
default: 'Play tone [LEVEL] [KIND], Length [LEN]',
description: 'play tone'
}),
blockType: BlockType.COMMAND,
arguments: {
LEVEL: {
type: ArgumentType.NUMBER,
menu: 'soundlevel',
defaultValue: MBitUART_SoundLevel.MID
},
KIND: {
type: ArgumentType.NUMBER,
menu: 'sound',
defaultValue: MBitUART_Sound.DO
},
LEN: {
type: ArgumentType.NUMBER,
menu: 'soundlength',
defaultValue: MBitUART_SoundLength.LEN16
}
}
},
{
opcode: 'getPlaySound',
text: formatMessage({
id: 'mbituart.getPlaySound',
default: 'Is play sound?',
description: 'is play sound?'
}),
blockType: BlockType.REPORTER,
},
'---',
{
opcode: 'getAcceleration',
text: formatMessage({
id: 'mbituart.getAcceleration',
default: 'Acceleration [AXIS]',
description: 'acceleration'
}),
blockType: BlockType.REPORTER,
arguments: {
AXIS: {
type: ArgumentType.NUMBER,
menu: 'axis',
defaultValue: 0
}
}
},
{
opcode: 'setAcceleration',
text: formatMessage({
id: 'mbituart.setAcceleration',
default: 'Round acceleration with [ROUND]',
description: 'round value of acceleration'
}),
blockType: BlockType.COMMAND,
arguments: {
ROUND: {
type: ArgumentType.NUMBER,
defaultValue: 10
}
}
},
'---',
{
opcode: 'getMagneticForce',
text: formatMessage({
id: 'mbituart.getMagneticForce',
default: 'Magnetic force [AXIS]',
description: 'magnetic force'
}),
blockType: BlockType.REPORTER,
arguments: {
AXIS: {
type: ArgumentType.NUMBER,
menu: 'axis',
defaultValue: 0
}
}
},
{
opcode: 'setMagneticForce',
text: formatMessage({
id: 'mbituart.setMagneticForce',
default: 'Round magnetic force with [ROUND]',
description: 'round value of magnetic force'
}),
blockType: BlockType.COMMAND,
arguments: {
ROUND: {
type: ArgumentType.NUMBER,
defaultValue: 10
}
}
},
'---',
{
opcode: 'whenTilted',
text: formatMessage({
id: 'mbituart.whenTilted',
default: 'When tilted [DIRECTION]',
description: 'when the micro:bit is tilted in a direction'
}),
blockType: BlockType.HAT,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirectionAny',
defaultValue: MBitUART_TiltDirection.ANY
}
}
},
{
opcode: 'isTilted',
text: formatMessage({
id: 'mbituart.isTilted',
default: 'Tilted [DIRECTION]?',
description: 'is the micro:bit is tilted in a direction?'
}),
blockType: BlockType.BOOLEAN,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirectionAny',
defaultValue: MBitUART_TiltDirection.ANY
}
}
},
{
opcode: 'getTiltAngle',
text: formatMessage({
id: 'mbituart.tiltAngle',
default: 'tilt angle [DIRECTION]',
description: 'how much the micro:bit is tilted in a direction'
}),
blockType: BlockType.REPORTER,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirection',
defaultValue: MBitUART_TiltDirection.FRONT
}
}
},
{
opcode: 'getRotation',
text: formatMessage({
id: 'mbituart.getRotation',
default: 'Rotation [ROTATION]',
description: 'rotation'
}),
blockType: BlockType.REPORTER,
arguments: {
ROTATION: {
type: ArgumentType.NUMBER,
menu: 'rotation',
defaultValue: 0
}
}
},
{
opcode: 'setRotation',
text: formatMessage({
id: 'mbituart.setRotation',
default: 'Round rotation with [ROUND]',
description: 'round value of rotation'
}),
blockType: BlockType.COMMAND,
arguments: {
ROUND: {
type: ArgumentType.NUMBER,
defaultValue: 10
}
}
},
'---',
{
opcode: 'getMicrophone',
text: formatMessage({
id: 'mbituart.getMicrophone',
default: 'Microphone level',
description: 'microphone level'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'setMicrophone',
text: formatMessage({
id: 'mbituart.setMicrophone',
default: 'Round microphone with [ROUND]',
description: 'round value of microphone'
}),
blockType: BlockType.COMMAND,
arguments: {
ROUND: {
type: ArgumentType.NUMBER,
defaultValue: 5
}
}
},
],
menus: {
buttons: {
acceptReporters: true,
items: this.BUTTONS_MENU
},
gestures: {
acceptReporters: true,
items: this.GESTURES_MENU
},
//pinState: {
// acceptReporters: true,
// items: this.PIN_STATE_MENU
//},
tiltDirection: {
acceptReporters: true,
items: this.TILT_DIRECTION_MENU
},
tiltDirectionAny: {
acceptReporters: true,
items: this.TILT_DIRECTION_ANY_MENU
},
touchPins: {
acceptReporters: true,
items: this.TOUCH_PINS_MENU
},
pinMode: {
acceptReporters: true,
items: this.TOUCH_PINMODE_MENU
},
rotation: {
acceptReporters: true,
items: this.ROTATION_MENU
},
axis: {
acceptReporters: true,
items: this.AXIS_MENU
},
enable: {
acceptReporters: true,
items: this.ENABLE_MENU
},
soundlength: {
acceptReporters: true,
items: this.SOUND_LENGTH_MENU
},
soundlevel: {
acceptReporters: true,
items: this.SOUND_LEVEL_MENU
},
sound: {
acceptReporters: true,
items: this.SOUND_MENU
},
express: {
acceptReporters: true,
items: this.EXPRESS_MENU
}
}
};
}
/**
* Test whether the A or B button is pressed
* @param {object} args - the block's arguments.
* @return {boolean} - true if the button is pressed.
*/
whenButtonPressed (args) {
if (args.BTN === 'any') {
return this.instance.buttonA
| this.instance.buttonB;
} else if (args.BTN === 'A') {
return this.instance.buttonA;
} else if (args.BTN === 'B') {
return this.instance.buttonB;
}
return false;
}
/**
* Test whether the A or B button is pressed
* @param {object} args - the block's arguments.
* @return {boolean} - true if the button is pressed.
*/
isButtonPressed (args) {
if (args.BTN === 'any') {
return (this.instance.buttonA
| this.instance.buttonB) !== 0;
} else if (args.BTN === 'A') {
return this.instance.buttonA !== 0;
} else if (args.BTN === 'B') {
return this.instance.buttonB !== 0;
}
return false;
}
whenLogoTouched () {
return this.instance.touchLogo;
}
isLogoTouched (args) {
return this.instance.touchLogo !== 0;
}
/**
* Test whether the micro:bit is moving
* @param {object} args - the block's arguments.
* @return {boolean} - true if the micro:bit is moving.
*/
whenGesture (args) {
if (args.GESTURE === this.instance.gestureState)
return true;
return false;
}
getGesture () {
return this.instance.gestureState;
}
/**
* Display a predefined symbol on the 5x5 LED matrix.
* @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves after a tick.
*/
displaySymbol (args) {
const symbol = cast.toString(args.MATRIX).replace(/\s/g, '');
const reducer = (accumulator, c, index) => {
const value = (c === '0') ? accumulator : accumulator + Math.pow(2, index);
return value;
};
const hex = symbol.split('').reduce(reducer, 0);
if (hex !== null) {
this.instance.ledMatrixState[0] = hex & 0x1F;
this.instance.ledMatrixState[1] = (hex >> 5) & 0x1F;
this.instance.ledMatrixState[2] = (hex >> 10) & 0x1F;
this.instance.ledMatrixState[3] = (hex >> 15) & 0x1F;
this.instance.ledMatrixState[4] = (hex >> 20) & 0x1F;
const c = "0123456789ABCDEFGHIJKLMNOPQRSTUV"
let s = c.charAt(this.instance.ledMatrixState[0]);
s += c.charAt(this.instance.ledMatrixState[1]);
s += c.charAt(this.instance.ledMatrixState[2]);
s += c.charAt(this.instance.ledMatrixState[3]);
s += c.charAt(this.instance.ledMatrixState[4]);
this.instance.send(CMD.DISPLAY_LED, s);
}
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, BLESendInterval);
});
}
/**
* Display text on the 5x5 LED matrix.
* @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves after the text is done printing.
* Note the limit is 18 characters
* The print time is calculated by multiplying the number of horizontal pixels
* by the default scroll delay of 120ms.
* The number of horizontal pixels = 6px for each character in the string,
* 1px before the string, and 5px after the string.
*/
displayText (args) {
const text = String(args.TEXT).substring(0, 18);
//if (text.length > 0)
this.instance.send(CMD.DISPLAY_TEXT, text);
const yieldDelay = 120 * ((6 * text.length) + 6);
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, yieldDelay);
});
}
/**
* Turn all 5x5 matrix LEDs off.
* @return {Promise} - a Promise that resolves after a tick.
*/
displayClear () {
this.displayText({TEXT:""});
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
*/
whenTilted (args) {
return this._isTilted(args.DIRECTION);
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
*/
isTilted (args) {
return this._isTilted(args.DIRECTION);
}
/**
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the direction (front, back, left, right) to check.
* @return {number} - the tilt sensor's angle in the specified direction.
* Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right).
*/
getTiltAngle (args) {
return this._getTiltAngle(args.DIRECTION);
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {TiltDirection} direction - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
* @private
*/
_isTilted (direction) {
switch (direction) {
case MBitUART_TiltDirection.ANY:
return (Math.abs(this.instance.rotation[0] / 10) >= Scratch3_MBitUART_Blocks.TILT_THRESHOLD) ||
(Math.abs(this.instance.rotation[1] / 10) >= Scratch3_MBitUART_Blocks.TILT_THRESHOLD);
default:
return this._getTiltAngle(direction) >= Scratch3_MBitUART_Blocks.TILT_THRESHOLD;
}
}
/**
* @param {TiltDirection} direction - the direction (front, back, left, right) to check.
* @return {number} - the tilt sensor's angle in the specified direction.
* Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right).
* @private
*/
_getTiltAngle (direction) {
switch (direction) {
case MBitUART_TiltDirection.FRONT:
return Math.round(this.instance.rotation[1] / -10);
case MBitUART_TiltDirection.BACK:
return Math.round(this.instance.rotation[1] / 10);
case MBitUART_TiltDirection.LEFT:
return Math.round(this.instance.rotation[0] / -10);
case MBitUART_TiltDirection.RIGHT:
return Math.round(this.instance.rotation[0] / 10);
default:
log.warn(`Unknown tilt direction in _getTiltAngle: ${direction}`);
}
}
/**
* @param {object} args - the block's arguments.
* @return {boolean} - the touch pin state.
* @private
*/
whenPinConnected (args) {
return this.instance.touch_pins[args.PIN];
}
getPinConnected (args) {
return this.instance.touch_pins[args.PIN];
}
outPinValue (args) {
if(argsPIN == "0") {
this.command(CMD.WRITE_PIN_0, args.VALUE);
return;
}
if(argsPIN == "1") {
this.command(CMD.WRITE_PIN_1, args.VALUE);
return;
}
if(argsPIN == "2") {
this.command(CMD.WRITE_PIN_2, args.VALUE);
return;
}
}
setPinConfig (args) {
let flag = (args.MODE == "onoff")? "1" :
(args.MODE == "value")? "2" : "0";
if(argsPIN == "0") {
this.command(CMD.MODE_PIN_0, flag);
return;
}
if(argsPIN == "1") {
this.command(CMD.MODE_PIN_1, flag);
return;
}
if(argsPIN == "2") {
this.command(CMD.MODE_PIN_2, flag);
return;
}
}
getLightLevel () {
return this.instance.light_level;
}
getTemperature () {
return this.instance.temperature;
}
getMagneticForce (args) {
return this.instance.magnetic_force[args.AXIS];
}
getAcceleration (args) {
return this.instance.acceleration[args.AXIS];
}
getRotation (args) {
return this.instance.rotation[args.ROTATION];
}
getMicrophone (args) {
return this.instance.microphone;
}
setSensor (args) {
this.command(CMD.SENSOR, (args.ENABLE == 0)? "0" : ("" + (1 + 2 + 4 + 16)));
}
setMagneticForce (args) {
this.command(CMD.MAGNETIC_FORCE, args.ROUND);
}
setAcceleration (args) {
this.command(CMD.ACCELERATION, args.ROUND);
}
setRotation (args) {
this.command(CMD.ROTATION, args.ROUND);
}
setMicrophone (args) {
this.command(CMD.MICROPHONE, args.ROUND);
}
playTone(args) {
const tone = [
[131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247],
[262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 498],
[523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988] ];
if(args.LEN == "1") {
this.command(CMD.PLAY_TONE_1, tone[args.LEVEL][args.KIND]);
} else if(args.LEN == "2") {
this.command(CMD.PLAY_TONE_2, tone[args.LEVEL][args.KIND]);
} else if(args.LEN == "4") {
this.command(CMD.PLAY_TONE_4, tone[args.LEVEL][args.KIND]);
} else if(args.LEN == "8") {
this.command(CMD.PLAY_TONE_8, tone[args.LEVEL][args.KIND]);
} else {
this.command(CMD.PLAY_TONE_16, tone[args.LEVEL][args.KIND]);
}
}
playExpress(args) {
this.command(CMD.PLAY_EXPRESS, args.EXPRESS);
}
getPlaySound() {
return this.instance.play_sound;
}
command(cmd, arg) {
this.instance.send(cmd, arg);
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, BLESendInterval);
});
}
setupTranslations () {
const localeSetup = formatMessage.setup();
const extTranslations = {
'ja': {
"mbituart.buttonsMenu.any": "どれかの",
"mbituart.clearDisplay": "画面を消す",
"mbituart.defaultTextToDisplay": "Hello!",
"mbituart.displaySymbol": "[MATRIX]を表示する",
"mbituart.displayText": "[TEXT]を表示する",
//"mbituart.gesturesMenu.jumped": "ジャンプした",
//"mbituart.gesturesMenu.moved": "動いた",
//"mbituart.gesturesMenu.shaken": "振られた",
"mbituart.isButtonPressed": "ボタン[BTN]が押された",
"mbituart.isTilted": "[DIRECTION]に傾いた",
//"mbituart.pinStateMenu.off": "切",
//"mbituart.pinStateMenu.on": "入",
"mbituart.tiltAngle": "[DIRECTION]方向の傾き",
"mbituart.tiltDirectionMenu.any": "どれかの向き",
"mbituart.tiltDirectionMenu.back": "後ろ",
"mbituart.tiltDirectionMenu.front": "前",
"mbituart.tiltDirectionMenu.left": "左",
"mbituart.tiltDirectionMenu.right": "右",
"mbituart.whenButtonPressed": "ボタン[BTN]が押されたとき",
"mbituart.whenGesture": "[GESTURE]とき",
"mbituart.getGesture": "ジェスチャー",
"mbituart.whenPinConnected": "ピン[PIN]がつながったとき",
"mbituart.getPinConnected": "ピン[PIN]",
"mbituart.outPinValue": "ピン[PIN]を[VALUE]にする",
"mbituart.setPinConfig": "ピン[PIN]を[MODE]",
"mbituart.whenTilted": "[DIRECTION]に傾いたとき",
'mbituart.whenLogoTouched': 'ロゴがタッチされたとき',
'mbituart.isLogoTouched':"ロゴがタッチされた",
'mbituart.getLightLevel': '明るさセンサー',
'mbituart.getTemperature': '温度センサー',
'mbituart.getAcceleration': '加速度センサー[AXIS]',
'mbituart.getMagneticForce': '磁力センサー[AXIS]',
'mbituart.getRotation': '回転センサー[ROTATION]',
'mbituart.getMicrophone': 'マイク音量',
'mbituart.setSensor': '基本センサー(ロゴ,ボタン,明るさ,温度など)を[ENABLE]',
'mbituart.setMagneticForce': '磁力センサーを[ROUND]でまるめる',
'mbituart.setAcceleration': '加速度センサーを[ROUND]でまるめる',
'mbituart.setRotation': '回転センサーを[ROUND]でまるめる',
'mbituart.setMicrophone': 'マイク音量を[ROUND]でまるめる',
'mbituart.axisMenu.x': 'X軸',
'mbituart.axisMenu.y': 'Y軸',
'mbituart.axisMenu.z': 'Z軸',
'mbituart.rotationMenu.roll': 'ロール',
'mbituart.rotationMenu.pitch': 'ピッチ',
'mbituart.enableMenu.enable': '使う',
'mbituart.enableManu.disable': '使わない',
'mbituart.gesturesMenu.shake': 'ゆさぶられた',
'mbituart.gesturesMenu.freefall': '落とした',
'mbituart.gesturesMenu.frontsideup': '画面が上になった',
'mbituart.gesturesMenu.backsideup': '画面が下になった',
'mbituart.gesturesMenu.impact3g': '3G',
'mbituart.gesturesMenu.impact6g': '6G',
'mbituart.gesturesMenu.impact8g': '8G',
'mbituart.gesturesMenu.tiltleft': '左に傾けた',
'mbituart.gesturesMenu.tiltright': '右に傾けた',
'mbituart.gesturesMenu.tiltbackwards': 'ロゴが下になった',
'mbituart.gesturesMenu.tiltforward': 'ロゴが上になった',
'mbituart.enableManu.disable': '使わない',
'mbituart.playTone': '[LEVEL][KIND]を[LEN]で鳴らす',
'mbituart.soundMenu.Do': 'ド',
'mbituart.soundMenu.DoS': 'ド#',
'mbituart.soundMenu.Re': 'レ',
'mbituart.soundMenu.ReS': 'レ#',
'mbituart.soundMenu.Mi': 'ミ',
'mbituart.soundMenu.Fa': 'ファ',
'mbituart.soundMenu.FaS': 'ファ#',
'mbituart.soundMenu.So': 'ソ',
'mbituart.soundMenu.SoS': 'ソ#',
'mbituart.soundMenu.Ra': 'ラ',
'mbituart.soundMenu.RaS': 'ラ#',
'mbituart.soundMenu.Shi': 'シ',
'mbituart.soundLengthMenu.Len1': '1拍',
'mbituart.soundLengthMenu.Len2': '1/2拍',
'mbituart.soundLengthMenu.Len4': '1/4拍',
'mbituart.soundLengthMenu.Len8': '1/8拍',
'mbituart.soundLengthMenu.Len16': '1/16拍',
'mbituart.soundLevelMenu.Mid': '中音',
'mbituart.soundLevelMenu.High': '高音',
'mbituart.soundLevelMenu.Low': '低音',
'mbituart.playExpress': '[EXPRESS]を鳴らす',
'mbituart.getPlaySound': '演奏中',
'mbituart.expressMenu.giggle': 'クスクス笑う',
'mbituart.expressMenu.happy': 'ハッピー',
'mbituart.expressMenu.hello': 'ハロー',
'mbituart.expressMenu.mysterious': '神秘的',
'mbituart.expressMenu.sad': '寂しい',
'mbituart.expressMenu.slide': 'スライド',
'mbituart.expressMenu.soaring': '急上昇',
'mbituart.expressMenu.spring': '春',
'mbituart.expressMenu.twinkle': 'きらめく',
'mbituart.expressMenu.yawn': 'あくび',
'mbituart.pinModeMenu.none': '使わない',
'mbituart.pinModeMenu.onoff': 'デジタルで使う',
'mbituart.pinModeMenu.value': 'アナログで使う',
}
};
for (const locale in extTranslations) {
if (!localeSetup.translations[locale]) {
localeSetup.translations[locale] = {};
}
Object.assign(localeSetup.translations[locale], extTranslations[locale]);
}
}
} |
JavaScript | class InputDataHolder {
/**
* Constructor
*/
constructor() {
this._values = new Object();
};
/**
* Sets an input of this function, and skipping null values.
*
* @param aName String The name of the input.
* @param aValue SourceData|* The value of the input
*
* @return InputDataHolder self
*/
setInputWithoutNull(aName, aValue) {
if(aValue !== null && aValue !== undefined) {
this.setInput(aName, aValue);
}
return this;
}
/**
* Sets an input of this function
*
* @param aName String The name of the input.
* @param aValue SourceData|* The value of the input
*
* @return InputDataHolder self
*/
setInput(aName, aValue) {
this._values[aName] = aValue;
return this;
}
/**
* Gets the input without resolving sources
*
* @param aName String The name of the input.
*
* @return * The raw value of the input
*/
getRawInput(aName) {
if(this._values[aName] === undefined) {
console.warn("Input " + aName + " doesn't exist.", this);
return null;
}
return this._values[aName];
}
/**
* Checks if an input exists. The source can still resolve to nothing.
*
* @param aName String The name of the input.
*
* @return Boolean True if there is an input
*/
hasInput(aName) {
return (this._values[aName] !== undefined);
}
/**
* Gets an input for this function.
*
* @param aName String The name of the input.
* @param aProps Object The object with the current props.
* @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing.
*
* @return * The value of the input
*/
getInput(aName, aProps = null, aManipulationObject = null) {
if(this._values[aName] === undefined) {
console.warn("Input " + aName + " doesn't exist.", this);
return null;
}
return this.resolveSource(this._values[aName], aProps, aManipulationObject);
}
/**
* Function that removes the used props
*
* @param aProps Object The props object that should be adjusted
*/
removeUsedProps(aProps) {
for(let objectName in this._values) {
let currentValue = this._values[objectName];
if(currentValue instanceof SourceData) {
currentValue.removeUsedProps(aProps);
}
}
}
/**
* Resolves a source
*
* @param aData * The data to resolve
* @param aProps Object The object with the current props.
* @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing.
*/
resolveSource(aData, aProps = null, aManipulationObject = null) {
//console.log("wprr/manipulation/adjustfunctions/AdjustFunction::resolveSource");
//console.log(aData, aProps, aManipulationObject);
if(aData instanceof SourceData) {
if(aManipulationObject) {
let changePropsAndStateObject = {"props": aProps, "state": aManipulationObject.state, "input": this};
return aManipulationObject.resolveSourcedDataInStateChange(aData, changePropsAndStateObject);
}
else {
return aData.getSourceInStateChange(null, {"props": null, "state": null, "input": this});
}
}
return aData;
}
static create() {
let newInputDataHolder = new InputDataHolder();
return newInputDataHolder;
}
} |
JavaScript | class Growatt extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'growatt',
});
this.callTimeout = null;
this.objNames = {};
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
this.getForeignObject('system.config', (err, obj) => {
this.config.objUpdate = this.config.objUpdate || {}
this.getStates(this.name+'.'+this.instance+".*", (err, states) => {
for(var id in states) {
let ebene = id.toString().split('.');
ebene.shift();
ebene.shift();
if (ebene[0] != "info" && ebene.length>1) {
let ownID = ebene.join('.')
let ownIDsearch = ownID.toLowerCase()
if (this.config.objUpdate[ownIDsearch] && this.config.objUpdate[ownIDsearch].action=='delete'){
this.delObject(ownID);
this.log.info('deleted: '+ownID)
} else {
if ( (!this.config.weather && ebene.length>1 && ebene[1].toLowerCase() == 'weather') ||
(!this.config.totalData && ebene.length>3 && ebene[3].toLowerCase() == 'totaldata') ||
(!this.config.statusData && ebene.length>3 && ebene[3].toLowerCase() == 'statusdata') ||
(!this.config.plantData && ebene.length>1 && ebene[1].toLowerCase() == 'plantdata') ||
(!this.config.deviceData && ebene.length>3 && ebene[3].toLowerCase() == 'devicedata') ||
(!this.config.historyLast && ebene.length>3 && ebene[3].toLowerCase() == 'historylast') ||
(!this.config.chartLast && ebene.length>3 && ebene[3].toLowerCase() == 'chart') ){
this.delObject(ownID);
this.log.info('deleted: '+ownID)
} else if (this.objNames[ownIDsearch]) {
this.log.warn(this.objNames[ownIDsearch]+' exists twice: '+ownID)
} else if (ebene.length>5 && ebene[3].toLowerCase() == 'historylast' &&
(ebene[4] == 'calendar' || ebene[4] == 'time') &&
(ebene[5] == 'year' || ebene[5] == 'month' || ebene[5] == 'dayOfMonth' ||
ebene[5] == 'hourOfDay' || ebene[5] == 'minute' || ebene[5] == 'second') ) {
this.delObject(ownID);
this.log.info('deleted: '+ownID)
} else {
this.objNames[ownIDsearch] = ownID
}
}
}
}
});
if (!this.supportsFeature || !this.supportsFeature('ADAPTER_AUTO_DECRYPT_NATIVE')) {
if (obj && obj.native && obj.native.secret) {
this.config.password = this.decrypt(obj.native.secret, this.config.password);
this.config.shareKey = this.decrypt(obj.native.secret, this.config.shareKey);
} else {
this.config.password = this.decrypt('Zgfr56gFe87jJOM', this.config.password);
this.config.shareKey = this.decrypt('Zgfr56gFe87jJOM', this.config.shareKey);
}
}
this.callRun = true;
this.growattData();
});
}
/**
* Is called to decrypt the Password
* @param {key} the secret
* @param {value} the encrypted password
**/
decrypt(key, value) {
let result = '';
for (let i = 0; i < value.length; ++i) {
result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
}
return result;
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.callRun = false;
clearTimeout(this.callTimeout);
this.setStateAsync('info.connection', { val: false, ack: true});
callback();
} catch (e) {
callback();
}
}
/**
* Parses the data from the website into objects. Is called recrusively.
* @param {object} plantData
* @param {path} path to object
* @param {key} the key in the object
*/
async storeData(plantData, path, key) {
let ele = path+key;
let eleSearch = ele.toLowerCase();
this.log.silly('ParseData for '+ele);
let data = plantData[key];
if (typeof data === 'object'){
this.parseData(data,ele+'.');
} else {
if (!(typeof this.config.objUpdate[eleSearch] === 'undefined') && this.config.objUpdate[eleSearch].action!='normal'){
return
}
let objType = 'string';
let objRole = 'value';
if (key.toLowerCase().includes('name'.toLowerCase())) {
data = data.toString();
} if (typeof data === 'number') {
objType = 'number';
} else {
data = data.toString();
// Date: yyyy-mm-dd hh:mi:ss
if (data.match('^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$')||
data.match('^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d\\d\\dZ$')) {
data = (new Date(data)).getTime();
objType = 'number';
objRole = 'value.time';
// Date: yyyy-mm-dd hh:mi
} else if (data.match('^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d$')) {
data = (new Date(data+':00')).getTime();
objType = 'number';
objRole = 'value.time';
// Date: yyyy-mm-dd
} else if (data.match('^\\d\\d\\d\\d-\\d\\d-\\d\\d$')) {
data = (new Date(data)).getTime();
objType = 'number';
objRole = 'date';
// number: -123 or +123.45
} else if (data.match('^(\\+|\\-)?\\d+(\\.\\d*)?$')) {
data = parseFloat(data)
objType = 'number';
// json: {...} or [...]
} else if (data.match('^({.*}|\\[.*\\])$')) {
objRole = 'json';
// boolean: true or false
} else if (data.match('^(true)|(false)$')) {
data = (data==='true');
objType = 'boolean';
}
}
if (typeof this.objNames[eleSearch] === 'undefined') {
this.log.debug('Create object not exists '+ele+' type:'+objType+ ' role:'+objRole);
await this.setObjectNotExistsAsync(ele, {
type: 'state',
common: {
name: key,
type: objType,
role: objRole,
read: true,
write: false,
},
native: {},
}).catch(e => {this.log.error('setObjectNotExists:'+e)});
this.log.info('added: '+ele);
this.objNames[eleSearch] = ele;
}
this.log.debug('Set value '+this.objNames[eleSearch]+':'+data);
this.setStateAsync(this.objNames[eleSearch], { val: data, ack: true });
}
}
/**
* Parses the data from the website into objects. Is called recrusively.
* @param {object} plantData
* @param {path} path to object
*/
async parseData(plantData, path) {
if (plantData) {
let keys = Object.keys(plantData)
//Duplicate keys are transmitted, we try to filter them here.
let processed = {}
keys.forEach(key => {
if (typeof processed[key.toLowerCase()] === 'undefined') {
processed[key.toLowerCase()] = true
this.storeData(plantData, path, key)
}
})
}
}
/**
* Is Called to get Data
*/
async growattData() {
let timeout = 150000
try {
let growatt = new api({timeout:5000})
if (this.config.keyLogin) {
this.log.debug('Growatt share plant login');
await growatt.sharePlantLogin(this.config.shareKey).catch(e => {this.log.error('Login to share plant:'+((typeof e === 'object')?JSON.stringify(e):e))});
} else {
this.log.debug('Growatt login');
await growatt.login(this.config.user,this.config.password).catch(e => {this.log.error('Login:'+((typeof e === 'object')?JSON.stringify(e):e))});
}
this.log.debug('Growatt connected '+growatt.isConnected());
if (growatt.isConnected()) {
let allPlantData = await growatt.getAllPlantData({
weather : this.config.weather,
totalData : this.config.totalData,
statusData : this.config.statusData,
plantData : this.config.plantData,
deviceData : this.config.deviceData,
historyLast : this.config.historyLast
}).catch(e => {this.log.error('Get all plant data:'+e)});
this.parseData(allPlantData,'');
growatt.logout().catch(e => {});
if (this.callRun) {
this.setStateAsync('info.connection', { val: true, ack: true});
timeout = 30000
return
}
} else {
this.log.info('not connected');
this.setStateAsync('info.connection', { val: false, ack: true });
}
} catch (e) {
this.log.error('Get all plant data exception: '+e);
this.setStateAsync('info.connection', { val: false, ack: true });
} finally {
if (this.callRun) {
this.callTimeout = setTimeout(() => {this.growattData()}, timeout);
}
}
}
} |
JavaScript | class SalarygraphController {
constructor($http, $timeout, $uibModal, $stateParams, TableExamplesService, SalaryGraphService, SalaryGraphParser, SalaryGraphDataConverter) {
this.name = 'salarygraph';
this.tableExamplesService = TableExamplesService;
this.columns = [];
this.dataset = [];
this.tableExamplesService.getColumns().then((response) => {
if (response.status === 200) {
this.columns = response.data;
}
});
this.tableExamplesService.getData().then((response) => {
if (response.status === 200) {
this.dataset = response.data.map((data, index) => {
// console.log(this.columns);
let obj = {};
for(let key in this.columns) {
//console.log(this.columns[key]);
let dataFieldKey = this.columns[key]['data'];
obj[dataFieldKey] = data[dataFieldKey];
if (!obj[dataFieldKey]) {
obj[dataFieldKey] = '';
}
}
return obj;
});
}
});
// console.log('salarygraphcontroller', $stateParams.id, ' was passed');
// assign reference parameters
this.$http = $http;
this.$timeout = $timeout;
this.$uibModal = $uibModal;
this._salaryGraphService = SalaryGraphService;
this._salaryGraphParser = SalaryGraphParser;
this._salaryGraphDataConverter = SalaryGraphDataConverter;
this.keys = []; // track header names
this.data = []; // track data fields
this.selectedKey; // selected key
// default graph data
this.labels = [];
this.graphData = SalaryGraphService.getDefaultGraphData();
this.series = [];
this.graphDataObjects = [];
// side bar - graph view data
SalaryGraphService.getFilterListData().then((response) => {
this.listData = response.data;
// console.log(response)
});
// initial call to kick off getting data
this.httpGET_inputFile('./static/ngaio2016.tsv');
}
btnOpenSettingsModal() {
let modalInstance = this.$uibModal.open({
animation: true,
component: 'salaryGraphSettingsComponent',
// component "bindings"
resolve: {
items: () => {
return this.listData;
}
}
});
// component return values
modalInstance.result.then(function (selectedItem) {
// console.log(selectedItem);
//model.selected = selectedItem;
}, function () {
});
}
/*
* @function httpGET_inputFile
* @description makes a HTTP GET call to a data input file
* the callback handler processes the result set
*/
httpGET_inputFile(pathToDataFile) {
this.$http.get(pathToDataFile).then((response) => {
// console.log(`result of ${pathToDataFile}`, response);
let parsedResult = this._salaryGraphParser.parseData(response.data, 'tsv');
// console.log(parsedResult);
// set controller values
this.keys = parsedResult.headers;
this.data = this._salaryGraphDataConverter
.arrayOfStringArraysToArrayOfObjectsBasedOnProperties(parsedResult.dataRows, parsedResult.headers);
// set default selections
this.selectedKey = [];
this.selectedY = [];
});
}
/*
* @function onClickListElement
* @description on click handler which updates the graph on screen
*/
onClickListElement() {
this.$timeout(() => {
// console.log('calling updateGraph() with ', this.selectedListData);
this.updateGraph(this.selectedListData.title);
}, 0);
}
/*
* @function sortBySelectedKey
* @description simple sort utility to sort by the controller's selectedKey at index 0
* @param a first object to compare
* @param b second object to compare
* returns -1 if a is less than b, 1 if a is greater than b and 0 if both are equal
*/
sortBySelectedKey(a, b) {
let x = this.selectedKey[0]; // get x key
if (a[x] > b[x]) return 1;
else if (a[x] < b[x]) return -1;
else return 0;
}
/*
* @function updateGraph
* @description updates the graph on ui-select change. the goal of this function is to update internal this parameters
* which will be reflected on the user interface. this.labels and this.graphData are the primary ones
* @param filter
*/
updateGraph(filter) {
// console.log('Selected Y:', this.selectedY);
// console.log('data to format', this.data);
// console.log('sorting data by ', this.selectedKey[0]);
this.data.sort((a,b) => this.sortBySelectedKey);
// reset values
this.resetGraph();
// get the formatted graph data
let formattedGraphData = this.getFormattedGraphData();
console.log(formattedGraphData, 'formatted graph data');
// set values
this.labels = formattedGraphData.labels;
this.graphData = formattedGraphData.graphData;
this.series = formattedGraphData.series;
this.updateGraphDataByFilters(filter);
}
/*
* @function resetGraph
* @description resets the parameters which will reset the graph ui
*/
resetGraph() {
this.labels = [];
this.graphData = [];
}
/*
* @function getFormattedGraphData
* @description formats and returns the graph data based on the selected x and y properties
* @return an object containing the values for labels and graphData
{
labels: ['label1', 'label2'],
graphData: [
[1, 2, 3],
[2, 3, 4]
]
}
*/
getFormattedGraphData() {
let labels = [];
let graphData = [];
let series = [];
// the keyArr map will store the yProperty key name and contain arrays for each of these keys
// { 'AnnualizedBaseSalary': [], 'Company Base': [] }
let keyArr = {};
// foreach parsed data object
for (let j = 0; j < this.selectedY.length; j++) {
let yProperty = this.selectedY[j];
keyArr[yProperty] = [];
}
let arr = [];
// get the x-axis and y-axis properties
let xProperty = this.selectedKey[0];
// iterate through the graph data array
this.data.forEach((data, i) => {
// console.log('data element', data);
// get selected index
let labelVal = data[xProperty];
// add labels
labels.push(labelVal);
// iterate and process yValues
for (let j = 0; j < this.selectedY.length; j++) {
let yProperty = this.selectedY[j];
let valToInsert = 0;
// if the data value is not null or undefined
let dataVal = data[yProperty];
if (dataVal) {
valToInsert = parseInt(dataVal.replace('$', '').replace(',', ''));
if (isNaN(valToInsert)) {
valToInsert = dataVal;
}
}
// add values (to multiple arrays)
keyArr[yProperty].push(valToInsert);
}
});
// add arrays to graphData as multiple entries
for (let j = 0; j < this.selectedY.length; j++) {
let yProperty = this.selectedY[j];
if (keyArr[yProperty].length > 0) {
graphData.push(keyArr[yProperty]);
series.push(yProperty);
}
}
return {
labels,
graphData,
series
};
}
/*
* @function updateGraphDataByFilters
* @description filters out data that doesn't meet the search condition
* @param filter a string that is compared to the graphDataObjects[0].label property
*/
updateGraphDataByFilters(filter) {
// map graph data array of array ints to an array of objects based on the x-property
// [{"label":"Quora","value":10416},{"label":"AT&T","value":3813}]
// labels and graphData should be in-sync in terms of index positional value
this.graphDataObjects = [];
console.log(this.graphData)
console.log(this.graphData[0]);
// graphData[0] is the first key used... we woud like to extend this to support all keys
this.graphData[0].forEach((d, i) => {
this.graphDataObjects.push({
label: this.labels[i],
value: d
});
});
if (filter && filter !== '') {
// apply filter
this.graphDataObjects = this.graphDataObjects.filter((d) => {
return d.label.toLowerCase() === filter.toLowerCase();
});
// update labels and graphData based on the graphDataObjects array which has been filtered
this.labels = this.graphDataObjects.map((d) => {
return d.label;
});
this.graphData = this.graphDataObjects.map((d) => {
return d.value;
});
}
console.log('post filtering', this.labels, this.graphData, this.graphDataObjects);
}
// cleans $100,000 the comma and the $
cleanMoneyFormats(data) {
return data.replace(/\"\$(\d+,*\d*,*)*\"/, )
}
} |
JavaScript | class BootDiagnosticsInstanceView {
/**
* Create a BootDiagnosticsInstanceView.
* @member {string} [consoleScreenshotBlobUri] The console screenshot blob
* URI.
* @member {string} [serialConsoleLogBlobUri] The Linux serial console log
* blob Uri.
*/
constructor() {
}
/**
* Defines the metadata of BootDiagnosticsInstanceView
*
* @returns {object} metadata of BootDiagnosticsInstanceView
*
*/
mapper() {
return {
required: false,
serializedName: 'BootDiagnosticsInstanceView',
type: {
name: 'Composite',
className: 'BootDiagnosticsInstanceView',
modelProperties: {
consoleScreenshotBlobUri: {
required: false,
serializedName: 'consoleScreenshotBlobUri',
type: {
name: 'String'
}
},
serialConsoleLogBlobUri: {
required: false,
serializedName: 'serialConsoleLogBlobUri',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class SelectEvent extends Event {
/**
* @param {string} type The event type.
* @param {Array<import("ol/Feature.js").default<import('ol/geom/Geometry.js').default>>} selected Selected features.
* @param {Array<import("ol/Feature.js").default<import('ol/geom/Geometry.js').default>>} deselected Deselected features.
* @param {import("ol/MapBrowserEvent.js").default<unknown>} mapBrowserEvent Associated
* {@link module:ol/MapBrowserEvent}.
*/
constructor(type, selected, deselected, mapBrowserEvent) {
super(type);
/**
* Selected features array.
*
* @type {Array<import("ol/Feature.js").default<import('ol/geom/Geometry.js').default>>}
* @api
*/
this.selected = selected;
/**
* Deselected features array.
*
* @type {Array<import("ol/Feature.js").default<import('ol/geom/Geometry.js').default>>}
* @api
*/
this.deselected = deselected;
/**
* Associated {@link module:ol/MapBrowserEvent}.
*
* @type {import("ol/MapBrowserEvent.js").default<unknown>}
* @api
*/
this.mapBrowserEvent = mapBrowserEvent;
}
} |
JavaScript | class Client extends EventEmitter {
/**
*
* @param {Object} params Configuration object for netconf
*/
constructor(params) {
super();
// bind functions to self
this.rpc = this.rpc.bind(this);
this._send = this._send.bind(this);
this._parse = this._parse.bind(this);
this._sendHello = this._sendHello.bind(this);
this._createError = this._createError.bind(this);
this._objectHelper = this._objectHelper.bind(this);
this.open = this.open.bind(this);
this.close = this.close.bind(this);
// Constructor paramaters
this.host = params.host;
this.username = params.username;
this.port = params.port || 22;
this.password = params.password;
this.pkey = params.pkey;
// Debug and informational
this.connected = false;
this.sessionID = null;
this.remoteCapabilities = [];
this.idCounter = 100;
this.rcvBuffer = '';
this.debug = params.debug;
// Runtime option tweaks
this.raw = false;
this.parseOpts = {
trim: true,
explicitArray: false,
emptyTag: true,
ignoreAttrs: false,
tagNameProcessors: [this._objectHelper],
attrNameProcessors: [this._objectHelper],
valueProcessors: [xml2js.processors.parseNumbers],
attrValueProcessors: [xml2js.processors.parseNumbers]
};
this.algorithms = params.algorithms;
}
/**
* Direct RPC session request, transforms requested json object, and sends the xml through the RPC tunnel
* @function rpc
* @param {object} request Request json object to send through XML
* @param {Function} callback Callback function called on completion
* @return {Self} Returns class self to hook on event listeners
*/
rpc(request, callback) {
const self = this,
messageID = this.idCounter += 1,
object = {},
builder = new xml2js.Builder({
headless: false,
allowEmpty: true
});
const defaultAttr = {
'message-id': messageID,
'xmlns': 'urn:ietf:params:xml:ns:netconf:base:1.0'
};
let xml;
if (typeof(request) === 'string') {
object.rpc = {
$: defaultAttr,
[request]: null
};
} else if (typeof(request) === 'object') {
object.rpc = request;
if (object.rpc.$) {
object.rpc.$['message-id'] = messageID;
} else {
object.rpc.$ = defaultAttr;
}
}
// build XML for request
try {
xml = builder.buildObject(object) + '\n' + DELIM;
} catch (err) {
return callback(err);
}
this._send(xml, messageID, callback);
}
/**
* Opens a new netconf session with provided credentials
* @function open
* @param {Function} callback Callback called after session call completes
* @return {Client} Returns copy of current class object
*/
open(callback) {
const self = this;
this.sshConn = ssh.Client();
this.sshConn.on('ready', function invokeNETCONF() {
vasync.waterfall([
function getStream(next) {
self.sshConn.subsys('netconf', next);
},
function handleStream(stream, next) {
self.netconf = stream;
self._sendHello();
stream.on('data', function buffer(chunk) {
self.rcvBuffer += chunk;
self.emit('data');
}).on('error', function streamErr(err) {
self.sshConn.end();
self.connected = false;
self.emit('error');
throw (err);
}).on('close', function handleClose() {
self.sshConn.end();
self.connected = false;
self.emit('close');
}).on('data', function handleHello() {
if (self.rcvBuffer.match(DELIM)) {
const helloMessage = self.rcvBuffer.replace(DELIM, '');
self.rcvBuffer = '';
self.netconf.removeListener('data', handleHello);
next(null, helloMessage);
}
});
},
function parseHello(helloMessage, next) {
self._parse(helloMessage, function assignSession(err, message) {
if (err) {
return next(err);
}
if (message.hello.session_id > 0) {
self.remoteCapabilities = message.hello.capabilities.capability;
self.sessionID = message.hello.session_id;
self.connected = true;
next(null);
} else {
next(new Error('NETCONF session not established'));
}
});
}
],
function(err) {
if (err) {
return callback(err);
}
return callback(null);
});
}).on('error', function(err) {
self.connected = false;
callback(err);
}).connect({
host: this.host,
username: this.username,
password: this.password,
port: this.port,
privateKey: this.pkey,
debug: this.debug,
algorithms: this.algorithms
});
return self;
}
/**
* Closes the SSH connection to netconf
* @function close
* @param {Function} callback Callback function fired after netconf session ends
*/
close(callback) {
const self = this;
// send close-session request to netconf
self.rpc('close-session', (err, reply) => {
// close out SSH tunnel
self.sshConn.end();
self.connected = false;
// if callback function is passed, continue with callback
if(typeof callback === 'function'){
callback(err, reply);
}
});
}
/**
* direct netconf send
* @function _send
* @private
* @param {[type]} xml [description]
* @param {[type]} messageID [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*/
_send(xml, messageID, callback) {
const self = this;
this.netconf.write(xml, function startReplyHandler() {
const rpcReply = new RegExp(`(<rpc-reply.*message-id="${messageID}"[\\s\\S]*</rpc-reply>)\\n?]]>]]>\\s*`);
// Add an event handler to search for our message on data events.
self.netconf.on('data', function replyHandler() {
const replyFound = self.rcvBuffer.search(rpcReply) !== -1;
if (replyFound) {
const message = self.rcvBuffer.match(rpcReply);
self._parse(message[1], callback);
// Tidy up, remove matched message from buffer and
// remove this messages replyHandler.
self.rcvBuffer = self.rcvBuffer.replace(message[0], '');
self.netconf.removeListener('data', replyHandler);
}
});
});
}
/**
* Parses xml response
* @function _parse
* @private
* @param {string} xml XML string to parse
* @param {Function} callback [description]
* @return {[type]} [description]
*/
_parse(xml, callback) {
const self = this;
xml2js.parseString(xml, this.parseOpts, function checkRPCErrors(err, message) {
if (err) {
return callback(err, null);
}
if (message.hasOwnProperty('hello')) {
return callback(null, message);
}
if (self.raw) {
message.raw = xml;
}
if (message.rpc_reply.hasOwnProperty('rpc_error')) {
return callback(self._createError(JSON.stringify(message), 'rpcError'), null);
}
return callback(null, message);
});
}
/**
* Sends hello to confirm connection
* @function _sendHello
* @private
*/
_sendHello() {
const message = {
hello: {
$: {
xmlns: 'urn:ietf:params:xml:ns:netconf:base:1.0'
},
capabilities: {
capability: ['urn:ietf:params:xml:ns:netconf:base:1.0', 'urn:ietf:params:netconf:base:1.0']
}
}
};
const builder = new xml2js.Builder();
const xml = builder.buildObject(message) + '\n' + DELIM;
this.netconf.write(xml);
}
/**
* Creates an error object from the error thrown
* @function _createError
* @private
* @param {string} msg Error message
* @param {string} type Error type
* @return {Error} returns javascript Error object
*/
_createError(msg, type) {
const err = new Error(msg),
self = this;
err.name = type;
Error.captureStackTrace(err, self._createError);
return err;
}
/**
* Replaces characters that prevent dot-style object navigation
* @function _objectHelper
* @private
* @param {string} name String to transform
* @return {string} Transformed string
*/
_objectHelper(name) {
// Replaces characters that prevent dot-style object navigation.
return name.replace(/-|:/g, '_');
}
} |
JavaScript | class Point {
/**
* Constructor
* @param {number} x
* @param {number} y
*/
constructor(x, y) {
// if x looks like a point object, initialize from it
if (x.x && x.y) {
this.x = x.x;
this.y = x.y;
} else {
this.x = x;
this.y = y;
}
}
/**
* Determine if two point are equal
* @param {number} a
* @param {number} b
* @return {boolean}
*/
static arePointsEqual(a, b) {
return a.x == b.x && a.y == b.y;
}
equals(other) {
return this.arePointsEqual(this, other);
}
difference(other) {
return new Point(this.x - other.x, this.y - other.y);
}
add(other) {
this.x += other.x;
this.y += other.y;
}
} |
JavaScript | class AuthenticationConfiguration {
/**
* General configuration settings for authentication.
*
* @param {string[]} requiredEndorsements An array of JWT endorsements.
* @param {(claims: Claim[]) => Promise<void>} validateClaims Function that validates a list of Claims
* and should throw an exception if the validation fails.
*/
constructor(requiredEndorsements = [], validateClaims) {
this.requiredEndorsements = requiredEndorsements;
this.validateClaims = validateClaims;
}
} |
JavaScript | class ProcessingEngine {
/**
* Constructs the object.
*
* @param {PluginStore} pluginStore The plugin store
*/
constructor(pluginStore) {
Assert.that(pluginStore).not(undefined);
this.pluginStore = pluginStore;
/**
* Stacks for each media object instances.
*/
this.stacks = new StackStore();
/**
* Snapshots of each media object's stack.
*/
this.snapshots = new StackStore();
/**
* Stats of each plugin execution.
*/
this.stats = new Store();
/**
* Configuration.
*/
this.configuration = new Configuration({});
/**
* Default rendering plugin.
*/
this.defaultPlugin = new DownloadPlugin(
'<p> MediaTag cannot find a plugin able to render your content </p>');
/**
* The max size of a plugin stack.
*/
this.STACK_SIZE = 50;
/**
* The max count of snapshots.
*/
this.SNAPSHOTS_LIMIT = 50;
}
/**
* Gets key from mediaObject.
*
* @param {MediaObject} mediaObject The media object
* @return {number}
*/
key(mediaObject) {
return mediaObject.getId();
}
/**
* Configures the processing engine.
*
* @param {Configuration} configuration The configuration
*/
configure(configuration) {
this.configuration = configuration;
if (configuration.processingEngine) {
Object.keys(configuration.processingEngine).forEach(key => {
if (key === 'defaultPlugin') {
this[key] = configuration.getDefaultPlugin();
} else {
this[key] = key;
}
});
}
}
/**
* Determines if configured.
*
* @return {boolean} True if configured, False otherwise.
*/
isConfigured() {
return Boolean(this.configuration);
}
/**
* Prepares mediaObject with some stuff.
*
* @param {MediaObject} mediaObject The media object
*/
prepare(mediaObject) {
// TODO Handle this stuff properly by test it...
(() => {
mediaObject.return = () => {
return this.return(mediaObject);
};
mediaObject.state = 'processing';
})();
const key = mediaObject.getId();
this.stacks.store(key, new PluginStack());
this.snapshots.store(key, new Stack());
this.stats.store(key, {});
}
/**
* Starts a processing over an instance of mediaObject.
*
* @param {MediaObject} mediaObject The media object
*/
start(mediaObject) {
this.prepare(mediaObject);
this.routine(mediaObject);
this.run(mediaObject);
}
/**
* Runs a processing engine step on mediaObject.
*
* @param {MediaObject} mediaObject The media object
* @return {?MediaObject}
*/
run(mediaObject) {
const key = this.key(mediaObject);
const plugin = this.stacks.top(key);
if (!plugin) {
return this.end(mediaObject);
}
if (this.configuration) {
if (this.configuration.isAllowed(plugin.identifier)) {
if (!plugin.process) {
console.warn('FALSY PLUGIN', plugin);
}
plugin.process(mediaObject);
} else {
this.skip(mediaObject, plugin);
this.return(mediaObject);
}
} else {
plugin.process(mediaObject);
}
}
/**
* Routine
*
* @param {MediaObject} mediaObject The media object
*/
routine(mediaObject) {
this.fill(mediaObject);
this.snapshot(mediaObject);
this.check(mediaObject);
}
/**
* Snapshots the current mediaObject plugin stack.
*
* @param {MediaObject} mediaObject The media object
*/
snapshot(mediaObject) {
const key = this.key(mediaObject);
const stack = this.stacks.get(key).clone();
this.snapshots.stack(key, stack);
}
/**
* Fills up the stack of usable plugins on this media object.
*
* @param {MediaObject} mediaObject The media object
*/
fill(mediaObject) {
const key = this.key(mediaObject);
const plugins = this.pluginStore.values();
const matchedIdentifiers = plugins.filter(plugin => {
return plugin.getType() === Type.MATCHER;
}).filter(matcher => {
return matcher.process(mediaObject);
}).map(matcher => {
return matcher.getIdentifier();
});
const matchedPlugins = plugins.filter(plugin => {
return plugin.getType() !== Type.MATCHER;
}).filter(plugin => {
return matchedIdentifiers.includes(plugin.getIdentifier());
});
const pbo = PluginUtils.filterByOccurrencies(matchedPlugins);
Object.keys(pbo).forEach(occurrence => {
pbo[occurrence].forEach(plugin => {
if (this.configuration.isAllowed(plugin.getIdentifier())) {
if (this.stacks.get(key).isStackable(plugin)) {
this.stacks.stack(key, plugin);
}
} else {
this.skip(mediaObject, plugin);
}
});
});
}
/**
* Updates skipped plugins.
*
* @param {MediaObject} mediaObject The media object
* @param {Plugin} plugin The plugin
*/
skip(mediaObject, plugin) {
const key = mediaObject.getId();
let stat = this.stats.get(key);
if (stat) {
if (!stat.skipped) {
stat.skipped = [];
}
} else {
stat = {
skipped: []
};
}
stat.skipped.push(plugin.identifier);
}
/**
* Unstacks the top plugin.
*
* @param {MediaObject} mediaObject The media object
*/
unstack(mediaObject) {
const stackId = mediaObject.getId();
if (this.stacks[stackId]) {
return this.stacks[stackId].pop();
}
return null;
}
/**
* Checks the stack.
*
* @param {MediaObject} mediaObject The media object
*/
check(mediaObject) {
const key = mediaObject.getId();
if (this.stacks.length(key) >= this.STACK_SIZE) {
console.error('SNAPSHOTS', this.snapshots.get(key));
throw new Error('Plugin stack size exceed');
}
if (this.snapshots.length(key) >= this.SNAPSHOT_LIMIT) {
console.error('SNAPSHOTS', this.snapshots.get(key));
throw new Error('Plugin snapshots count exceed');
}
let rendererCount = 0;
this.stacks.plugins(key).forEach(plugin => {
if (plugin.type === Type.RENDERER) {
rendererCount++;
}
});
if (rendererCount > 1) {
console.error('SNAPSHOTS', this.snapshots.get(key));
throw new Error('More of one renderer in the stack');
}
/**
* To ends correctly, the stack have to be empty and only one renderer
* have to be executed on a mediaObject instance.
*/
if (this.stacks.length(key) === 0 && !this.stats.get(key)[Type.RENDERER]) {
if (!this.defaultPlugin) {
throw new Error('No default plugin assignated');
}
this.stacks.stack(key, this.defaultPlugin);
}
}
/**
* Returns the media object to the processing engine.
* Every plugin must call this function when their job is done.
*
* @param {MediaObject} mediaObject The media object
*/
return(mediaObject) {
const key = mediaObject.getId();
const plugin = this.stacks.unstack(key);
if (!plugin) {
return this.end(mediaObject);
}
try {
if (!this.stats.get(key)) {
this.stats.store(key, {});
}
if (this.stats.get(key)[plugin.type]) {
this.stats.get(key)[plugin.type] += 1;
} else {
this.stats.get(key)[plugin.type] = 1;
}
} catch (err) {
console.error(err, this.snapshots.get(key));
}
/**
* These types are ineffective on attributes contained
* inside a mediaObject instance then we don't need to
* refill the stack.
*/
if (
plugin.type !== Type.SANITIZER &&
plugin.type !== Type.RENDERER
) {
this.fill(mediaObject);
}
this.snapshot(mediaObject);
this.check(mediaObject);
this.run(mediaObject);
}
end(mediaObject) {
mediaObject.status = 'processed';
return mediaObject;
}
setDefaultPlugin(plugin) {
this.defaultPlugin = plugin;
}
} |
JavaScript | class Node {
constructor() {
this.childNodes = [];
}
} |
JavaScript | class TextNode extends Node {
constructor(value) {
super();
/**
* Node Type declaration.
* @type {Number}
*/
this.nodeType = NodeType.TEXT_NODE;
this.rawText = value;
}
/**
* Get unescaped text value of current node and its children.
* @return {string} text content
*/
get text() {
return he_1.decode(this.rawText);
}
/**
* Detect if the node contains only white space.
* @return {bool}
*/
get isWhitespace() {
return /^(\s| )*$/.test(this.rawText);
}
toString() {
return this.text;
}
} |
JavaScript | class HTMLElement extends Node {
/**
* Creates an instance of HTMLElement.
* @param keyAttrs id and class attribute
* @param [rawAttrs] attributes in string
*
* @memberof HTMLElement
*/
constructor(tagName, keyAttrs, rawAttrs = '', parentNode = null) {
super();
this.tagName = tagName;
this.rawAttrs = rawAttrs;
this.parentNode = parentNode;
this.classNames = [];
/**
* Node Type declaration.
*/
this.nodeType = NodeType.ELEMENT_NODE;
this.rawAttrs = rawAttrs || '';
this.parentNode = parentNode || null;
this.childNodes = [];
if (keyAttrs.id) {
this.id = keyAttrs.id;
}
if (keyAttrs.class) {
this.classNames = keyAttrs.class.split(/\s+/);
}
}
/**
* Remove Child element from childNodes array
* @param {HTMLElement} node node to remove
*/
removeChild(node) {
this.childNodes = this.childNodes.filter((child) => {
return (child !== node);
});
}
/**
* Exchanges given child with new child
* @param {HTMLElement} oldNode node to exchange
* @param {HTMLElement} newNode new node
*/
exchangeChild(oldNode, newNode) {
let idx = -1;
for (let i = 0; i < this.childNodes.length; i++) {
if (this.childNodes[i] === oldNode) {
idx = i;
break;
}
}
this.childNodes[idx] = newNode;
}
/**
* Get escpaed (as-it) text value of current node and its children.
* @return {string} text content
*/
get rawText() {
let res = '';
for (let i = 0; i < this.childNodes.length; i++)
res += this.childNodes[i].rawText;
return res;
}
/**
* Get unescaped text value of current node and its children.
* @return {string} text content
*/
get text() {
return he_1.decode(this.rawText);
}
/**
* Get structured Text (with '\n' etc.)
* @return {string} structured text
*/
get structuredText() {
let currentBlock = [];
const blocks = [currentBlock];
function dfs(node) {
if (node.nodeType === NodeType.ELEMENT_NODE) {
if (kBlockElements[node.tagName]) {
if (currentBlock.length > 0) {
blocks.push(currentBlock = []);
}
node.childNodes.forEach(dfs);
if (currentBlock.length > 0) {
blocks.push(currentBlock = []);
}
}
else {
node.childNodes.forEach(dfs);
}
}
else if (node.nodeType === NodeType.TEXT_NODE) {
if (node.isWhitespace) {
// Whitespace node, postponed output
currentBlock.prependWhitespace = true;
}
else {
let text = node.text;
if (currentBlock.prependWhitespace) {
text = ' ' + text;
currentBlock.prependWhitespace = false;
}
currentBlock.push(text);
}
}
}
dfs(this);
return blocks
.map(function (block) {
// Normalize each line's whitespace
return block.join('').trim().replace(/\s{2,}/g, ' ');
})
.join('\n').replace(/\s+$/, ''); // trimRight;
}
toString() {
const tag = this.tagName;
if (tag) {
const is_un_closed = /^meta$/i.test(tag);
const is_self_closed = /^(img|br|hr|area|base|input|doctype|link)$/i.test(tag);
const attrs = this.rawAttrs ? ' ' + this.rawAttrs : '';
if (is_un_closed) {
return `<${tag}${attrs}>`;
}
else if (is_self_closed) {
return `<${tag}${attrs} />`;
}
else {
return `<${tag}${attrs}>${this.innerHTML}</${tag}>`;
}
}
else {
return this.innerHTML;
}
}
get innerHTML() {
return this.childNodes.map((child) => {
return child.toString();
}).join('');
}
set_content(content) {
if (content instanceof Node) {
content = [content];
}
else if (typeof content == 'string') {
const r = parse(content);
content = r.childNodes.length ? r.childNodes : [new TextNode(content)];
}
this.childNodes = content;
}
get outerHTML() {
return this.toString();
}
/**
* Trim element from right (in block) after seeing pattern in a TextNode.
* @param {RegExp} pattern pattern to find
* @return {HTMLElement} reference to current node
*/
trimRight(pattern) {
for (let i = 0; i < this.childNodes.length; i++) {
const childNode = this.childNodes[i];
if (childNode.nodeType === NodeType.ELEMENT_NODE) {
childNode.trimRight(pattern);
}
else {
const index = childNode.rawText.search(pattern);
if (index > -1) {
childNode.rawText = childNode.rawText.substr(0, index);
// trim all following nodes.
this.childNodes.length = i + 1;
}
}
}
return this;
}
/**
* Get DOM structure
* @return {string} strucutre
*/
get structure() {
const res = [];
let indention = 0;
function write(str) {
res.push(' '.repeat(indention) + str);
}
function dfs(node) {
const idStr = node.id ? ('#' + node.id) : '';
const classStr = node.classNames.length ? ('.' + node.classNames.join('.')) : '';
write(node.tagName + idStr + classStr);
indention++;
for (let i = 0; i < node.childNodes.length; i++) {
const childNode = node.childNodes[i];
if (childNode.nodeType === NodeType.ELEMENT_NODE) {
dfs(childNode);
}
else if (childNode.nodeType === NodeType.TEXT_NODE) {
if (!childNode.isWhitespace)
write('#text');
}
}
indention--;
}
dfs(this);
return res.join('\n');
}
/**
* Remove whitespaces in this sub tree.
* @return {HTMLElement} pointer to this
*/
removeWhitespace() {
let o = 0;
for (let i = 0; i < this.childNodes.length; i++) {
const node = this.childNodes[i];
if (node.nodeType === NodeType.TEXT_NODE) {
if (node.isWhitespace)
continue;
node.rawText = node.rawText.trim();
}
else if (node.nodeType === NodeType.ELEMENT_NODE) {
node.removeWhitespace();
}
this.childNodes[o++] = node;
}
this.childNodes.length = o;
return this;
}
/**
* Query CSS selector to find matching nodes.
* @param {string} selector Simplified CSS selector
* @param {Matcher} selector A Matcher instance
* @return {HTMLElement[]} matching elements
*/
querySelectorAll(selector) {
let matcher;
if (selector instanceof Matcher) {
matcher = selector;
matcher.reset();
}
else {
matcher = new Matcher(selector);
}
const res = [];
const stack = [];
for (let i = 0; i < this.childNodes.length; i++) {
stack.push([this.childNodes[i], 0, false]);
while (stack.length) {
const state = arr_back(stack);
const el = state[0];
if (state[1] === 0) {
// Seen for first time.
if (el.nodeType !== NodeType.ELEMENT_NODE) {
stack.pop();
continue;
}
if (state[2] = matcher.advance(el)) {
if (matcher.matched) {
res.push(el);
// no need to go further.
matcher.rewind();
stack.pop();
continue;
}
}
}
if (state[1] < el.childNodes.length) {
stack.push([el.childNodes[state[1]++], 0, false]);
}
else {
if (state[2])
matcher.rewind();
stack.pop();
}
}
}
return res;
}
/**
* Query CSS Selector to find matching node.
* @param {string} selector Simplified CSS selector
* @param {Matcher} selector A Matcher instance
* @return {HTMLElement} matching node
*/
querySelector(selector) {
let matcher;
if (selector instanceof Matcher) {
matcher = selector;
matcher.reset();
}
else {
matcher = new Matcher(selector);
}
const stack = [];
for (let i = 0; i < this.childNodes.length; i++) {
stack.push([this.childNodes[i], 0, false]);
while (stack.length) {
const state = arr_back(stack);
const el = state[0];
if (state[1] === 0) {
// Seen for first time.
if (el.nodeType !== NodeType.ELEMENT_NODE) {
stack.pop();
continue;
}
if (state[2] = matcher.advance(el)) {
if (matcher.matched) {
return el;
}
}
}
if (state[1] < el.childNodes.length) {
stack.push([el.childNodes[state[1]++], 0, false]);
}
else {
if (state[2])
matcher.rewind();
stack.pop();
}
}
}
return null;
}
/**
* Append a child node to childNodes
* @param {Node} node node to append
* @return {Node} node appended
*/
appendChild(node) {
// node.parentNode = this;
this.childNodes.push(node);
if (node instanceof HTMLElement) {
node.parentNode = this;
}
return node;
}
/**
* Get first child node
* @return {Node} first child node
*/
get firstChild() {
return this.childNodes[0];
}
/**
* Get last child node
* @return {Node} last child node
*/
get lastChild() {
return arr_back(this.childNodes);
}
/**
* Get attributes
* @return {Object} parsed and unescaped attributes
*/
get attributes() {
if (this._attrs)
return this._attrs;
this._attrs = {};
const attrs = this.rawAttributes;
for (const key in attrs) {
this._attrs[key] = he_1.decode(attrs[key]);
}
return this._attrs;
}
/**
* Get escaped (as-it) attributes
* @return {Object} parsed attributes
*/
get rawAttributes() {
if (this._rawAttrs)
return this._rawAttrs;
const attrs = {};
if (this.rawAttrs) {
const re = /\b([a-z][a-z0-9\-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/ig;
let match;
while (match = re.exec(this.rawAttrs)) {
attrs[match[1]] = match[2] || match[3] || match[4] || "";
}
}
this._rawAttrs = attrs;
return attrs;
}
} |
JavaScript | class Matcher {
/**
* Creates an instance of Matcher.
* @param {string} selector
*
* @memberof Matcher
*/
constructor(selector) {
this.nextMatch = 0;
functionCache["f5"] = functionCache["f5"];
this.matchers = selector.split(' ').map((matcher) => {
if (pMatchFunctionCache[matcher])
return pMatchFunctionCache[matcher];
const parts = matcher.split('.');
const tagName = parts[0];
const classes = parts.slice(1).sort();
let source = '"use strict";';
let function_name = 'f';
let attr_key = "";
let value = "";
if (tagName && tagName != '*') {
let matcher;
if (tagName[0] == '#') {
source += 'if (el.id != ' + JSON.stringify(tagName.substr(1)) + ') return false;'; //1
function_name += '1';
}
else if (matcher = tagName.match(/^\[\s*(\S+)\s*(=|!=)\s*((((["'])([^\6]*)\6))|(\S*?))\]\s*/)) {
attr_key = matcher[1];
let method = matcher[2];
if (method !== '=' && method !== '!=') {
throw new Error('Selector not supported, Expect [key${op}value].op must be =,!=');
}
if (method === '=') {
method = '==';
}
value = matcher[7] || matcher[8];
source += `let attrs = el.attributes;for (let key in attrs){const val = attrs[key]; if (key == "${attr_key}" && val == "${value}"){return true;}} return false;`; //2
function_name += '2';
}
else {
source += 'if (el.tagName != ' + JSON.stringify(tagName) + ') return false;'; //3
function_name += '3';
}
}
if (classes.length > 0) {
source += 'for (let cls = ' + JSON.stringify(classes) + ', i = 0; i < cls.length; i++) if (el.classNames.indexOf(cls[i]) === -1) return false;'; //4
function_name += '4';
}
source += 'return true;'; //5
function_name += '5';
let obj = {
func: functionCache[function_name],
tagName: tagName || "",
classes: classes || "",
attr_key: attr_key || "",
value: value || ""
};
source = source || "";
return pMatchFunctionCache[matcher] = obj;
});
}
/**
* Trying to advance match pointer
* @param {HTMLElement} el element to make the match
* @return {bool} true when pointer advanced.
*/
advance(el) {
if (this.nextMatch < this.matchers.length &&
this.matchers[this.nextMatch].func(el, this.matchers[this.nextMatch].tagName, this.matchers[this.nextMatch].classes, this.matchers[this.nextMatch].attr_key, this.matchers[this.nextMatch].value)) {
this.nextMatch++;
return true;
}
return false;
}
/**
* Rewind the match pointer
*/
rewind() {
this.nextMatch--;
}
/**
* Trying to determine if match made.
* @return {bool} true when the match is made
*/
get matched() {
return this.nextMatch == this.matchers.length;
}
/**
* Rest match pointer.
* @return {[type]} [description]
*/
reset() {
this.nextMatch = 0;
}
/**
* flush cache to free memory
*/
flushCache() {
pMatchFunctionCache = {};
}
} |
JavaScript | class IndexBuffer {
/**
* @param {WebGLRenderingContext} ctx
* @param {Array.<number>} indices
*/
constructor( ctx, indices ) {
this.ctx = ctx;
this.resource = this.createResource(indices);
}
/**
* Bind the resource.
*/
bind() {
this.ctx.bindBuffer(this.ctx.ELEMENT_ARRAY_BUFFER, this.resource);
}
/**
* @private
* @param {Array.<number>} indices
* @return {WebGLBuffer}
*/
createResource( indices ) {
var resource = this.ctx.createBuffer();
this.ctx.bindBuffer(this.ctx.ELEMENT_ARRAY_BUFFER, resource);
this.ctx.bufferData(this.ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this.ctx.STATIC_DRAW);
return resource;
}
} |
JavaScript | class examService extends Service {
constructor(ctx) {
super(ctx);
this.User = this.ctx.model.User;
this.Exam = this.ctx.model.Exam;
this.questionExam = this.ctx.model.QuestionExam;
this.hearExam = this.ctx.model.HearExam;
this.Hear = this.ctx.model.Hear;
this.Question = this.ctx.model.Question;
this.OwnExam = this.ctx.model.OwnExam;
}
async getExamList() {
const data = this.Exam.findAll({
});
return data;
}
async createExam(title, describe, uid) {
// console.log(this.app.model.sequelize)
const t = await this.ctx.model.transaction();
try {
const data = await this.Exam.create({
title,
describe,
});
// console.log(data.get('id'));
await this.OwnExam.create({
uid,
eid: data.get('id'),
});
await t.commit();
return data;
} catch (err) {
await t.rollback();
return err;
}
}
async editExam(id, title, describe) {
const data = await this.Exam.update({
title,
describe,
}, {
where: {
id,
},
});
return data;
}
async deleteExam(eid, uid) {
const t = await this.ctx.model.transaction();
try {
const dele = await this.OwnExam.destroy({
where: {
uid,
eid,
},
});
await this.Exam.update({
status: 2,
}, {
where: {
id: eid,
},
});
await t.commit();
return dele;
} catch (err) {
await t.rollback();
return err;
}
}
// async addExamQuestion(eid, qid) {
// const data = await this.questionExam.findOrCreate({
// where: {
// qid,
// eid,
// },
// });
// return data;
// }
// async deleteExamQuestion(eid, qid) {
// const data = await this.questionExam.destroy({
// where: {
// eid,
// qid,
// }
// });
// // console.log(data);
// return data;
// }
// async addExamHear(eid, hid) {
// const data = await this.hearExam.findOrCreate({
// where: {
// hid,
// eid,
// },
// });
// return data;
// }
// async deleteExamHear(eid, hid) {
// const data = await this.hearExam.destroy({
// where: {
// hid,
// eid,
// }
// });
// // console.log(data);
// return data;
// }
async getExamInfo(eid) {
const t = await this.ctx.model.transaction();
try {
const Question = await this.questionExam.findAll({
where: {
eid
}
});
// console.log(Question)
let tiem;
const result = {
question: [],
hear: []
};
for (tiem in Question) {
// const temp = await this.ctx.helper.getIssue(data[tiem].get('sid'));
// result.push(temp); //issues 获取
console.log(Question)
const score = await this.Question.findOne({
where: {
id: Question[tiem].get('qid')
}
});
// console.log(score)
result.question.push(score);
}
const Hear = await this.hearExam.findAll({
// attributes: ['vid', 'uid'],
where: {
eid,
},
});
for (tiem in Hear) {
// const temp = await this.ctx.helper.getIssue(data[tiem].get('sid'));
// result.push(temp); //issues 获取
const score = await this.Hear.findOne({
where: {
id: Hear[tiem].get('hid')
}
});
result.hear.push(score);
}
await t.commit();
return result;
} catch (err) {
await t.rollback();
return err;
}
}
async getExamHear(eid) {
const data = await this.hearExam.findAll({
where: {
eid
}
})
return data;
}
async getExamQuestion(eid) {
const data = await this.questionExam.findAll({
where: {
eid
}
})
return data;
}
async addExamHear(eid, hid) {
const data = await this.hearExam.findOrCreate({
where: {
eid,
hid
}
})
return data;
}
async addExamQuestion(eid, qid) {
const data = await this.questionExam.findOrCreate({
where: {
eid,
qid
}
})
return data;
}
async deleteExamQuestion(eid, qid) {
const data = await this.questionExam.destroy({
where: {
eid,
qid
}
})
return data;
}
async deleteExamHear(eid, hid) {
const data = await this.hearExam.destroy({
where: {
eid,
hid
}
})
return data;
}
async findOwner(eid) {
const data = await this.OwnExam.findOne({
where: {
eid
}
})
return data;
}
} |
JavaScript | class DirectoryLayoutComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
errorOccurred: false,
accordionData: [],
treeData: [],
infoBoardType: BOARD_TYPES.NONE,
infoBoardData: {},
allFiles: [],
fileIdFileMap: {},
dirContextMenu: {
selectedDirectory: null,
AnchorPos: null
},
selectedDirLayout: null,
breadCrumb: [],
message: null,
messageType: 'info'
};
this.directoryIdDirectoryMap = null;
this.getBreadCrumbs = this.getBreadCrumbs.bind(this);
this.handleDirectoryLayoutClick = this.handleDirectoryLayoutClick.bind(this);
this.handleDirectoryLeftClick = this.handleDirectoryLeftClick.bind(this);
this.handleDirectoryRightClick = this.handleDirectoryRightClick.bind(this);
this.createDirectory = this.createDirectory.bind(this);
this.createDirectoryLayout = this.createDirectoryLayout.bind(this);
this.saveDirLayoutCallback = this.saveDirLayoutCallback.bind(this);
this.deleteDirLayoutCallback = this.deleteDirLayoutCallback.bind(this);
this.saveDirectoryCallback = this.saveDirectoryCallback.bind(this);
this.deleteDirectoryCallback = this.deleteDirectoryCallback.bind(this);
this.removeDirectoryEntry = this.removeDirectoryEntry.bind(this);
this.handleMenuClose = this.handleMenuClose.bind(this);
this.handleCloseSnackbar = this.handleCloseSnackbar.bind(this);
}
componentDidMount() {
this.loadData();
}
componentWillUnmount() {
// clearInterval(this.timerID);
clearTimeout(this.timerID);
}
transformTagsToTreeData(tags) {
const allTagInfo = {};
const topLevelTags = [];
tags.forEach(eachTag => {
if (allTagInfo[eachTag.id]) {
allTagInfo[eachTag.id].id = eachTag.id;
allTagInfo[eachTag.id].name = eachTag.name;
allTagInfo[eachTag.id].title = (<Button style={{textTransform: 'none'}}>{eachTag.name}</Button>);
allTagInfo[eachTag.id].parent = eachTag.parent;
allTagInfo[eachTag.id].description = eachTag.description;
} else {
allTagInfo[eachTag.id] = {
id: eachTag.id,
name: eachTag.name,
title: (<Button style={{textTransform: 'none'}}>{eachTag.name}</Button>),
parent: eachTag.parent,
description: eachTag.description,
children: []
}
}
if (eachTag.parent) {
const currentTagTreeNode = allTagInfo[eachTag.id];
if (allTagInfo[eachTag.parent]) {
allTagInfo[eachTag.parent].children.push(currentTagTreeNode);
} else {
allTagInfo[eachTag.parent] = {children: [currentTagTreeNode]};
}
} else {
topLevelTags.push(eachTag.id);
}
});
const treeData = [];
topLevelTags.forEach(eachTagId => {
treeData.push(allTagInfo[eachTagId]);
});
return treeData;
}
transformDirectoriesToTreeData(dirLayouts, inputData) {
const directoryLayoutInfo = {};
dirLayouts.forEach(eachLayout => {
directoryLayoutInfo[eachLayout.id] = {
directories: {},
topLevelDirectories: [],
treeData: [],
}
});
inputData.forEach(eachDir => {
const currentLayoutInfo = directoryLayoutInfo[eachDir.dir_layout];
const layoutDirectories = currentLayoutInfo.directories;
if (! layoutDirectories[eachDir.id]) {
layoutDirectories[eachDir.id] = {
children: []
}
}
layoutDirectories[eachDir.id].id = eachDir.id;
layoutDirectories[eachDir.id].name = eachDir.name;
layoutDirectories[eachDir.id].title = (
<Button fullWidth>{eachDir.name}</Button>
);
layoutDirectories[eachDir.id].parent = eachDir.parent;
layoutDirectories[eachDir.id].dirLayoutId = eachDir.dir_layout;
layoutDirectories[eachDir.id].bannerFile = eachDir.banner_file;
layoutDirectories[eachDir.id].originalFileName = eachDir.original_file_name;
layoutDirectories[eachDir.id].individualFiles = eachDir.individual_files;
layoutDirectories[eachDir.id].creators = eachDir.creators;
layoutDirectories[eachDir.id].coverages = eachDir.coverages;
layoutDirectories[eachDir.id].subjects = eachDir.subjects;
layoutDirectories[eachDir.id].keywords = eachDir.keywords;
layoutDirectories[eachDir.id].workareas = eachDir.workareas;
layoutDirectories[eachDir.id].languages = eachDir.languages;
layoutDirectories[eachDir.id].catalogers = eachDir.catalogers;
layoutDirectories[eachDir.id].creatorsNeedAll = eachDir.creators_need_all;
layoutDirectories[eachDir.id].coveragesNeedAll = eachDir.coverages_need_all;
layoutDirectories[eachDir.id].subjectsNeedAll = eachDir.subjects_need_all;
layoutDirectories[eachDir.id].keywordsNeedAll = eachDir.keywords_need_all;
layoutDirectories[eachDir.id].workareasNeedAll = eachDir.workareas_need_all;
layoutDirectories[eachDir.id].languagesNeedAll = eachDir.languages_need_all;
layoutDirectories[eachDir.id].catalogersNeedAll = eachDir.catalogers_need_all;
if (eachDir.parent) {
/* Since the directory has a parent, it is a subdirectory, so add it to the children
* list of its parent directory
* 1. If the parent already exists in the map, its good. else add the parent to the map. */
const currentDirTreeNode = layoutDirectories[eachDir.id];
if (layoutDirectories[eachDir.parent]) { // If the parent is already present in the map
layoutDirectories[eachDir.parent].children.push(currentDirTreeNode);
} else {
layoutDirectories[eachDir.parent] = {children: [currentDirTreeNode]};
}
} else {
// Add it to the top level directories.
currentLayoutInfo.topLevelDirectories.push(eachDir.id);
}
});
const retval = {};
Object.keys(directoryLayoutInfo).forEach(eachLayoutId => {
const currentLayoutInfo = directoryLayoutInfo[eachLayoutId];
const layoutDirectories = currentLayoutInfo.directories;
const topLevelDirectories = currentLayoutInfo.topLevelDirectories;
const treeData = currentLayoutInfo.treeData;
topLevelDirectories.forEach(topLevelDirId => {
treeData.push(layoutDirectories[topLevelDirId]);
});
retval[eachLayoutId] = treeData;
});
return retval;
}
loadData() {
const currInstance = this;
const allRequests = [];
allRequests.push(axios.get(APP_URLS.ALLTAGS_LIST, {responseType: 'json'}).then(function(response) {
return response;
}));
allRequests.push(axios.get(APP_URLS.CONTENTS_LIST, {responseType: 'json'}).then(function(response) {
const fileIdFileMap = buildMapFromArray(response.data, 'id');
return {
fileIdFileMap,
allFiles: response.data
};
}));
allRequests.push(axios.get(APP_URLS.DIRLAYOUT_LIST, {responseType: 'json'}));
allRequests.push(axios.get(APP_URLS.DIRECTORY_LIST, {responseType: 'json'}).then(function(response) {
currInstance.directoryIdDirectoryMap = buildMapFromArray(response.data, 'id');
return response;
}));
Promise.all(allRequests).then(function(values){
const tags = values[0].data;
const allFiles = values[1].allFiles;
const fileIdFileMap = values[1].fileIdFileMap;
const dirLayouts = values[2].data;
const directories = values[3].data;
const transformedData = currInstance.transformDirectoriesToTreeData(dirLayouts, directories);
dirLayouts.forEach(eachDirLayout => {
eachDirLayout.isOpen = false;
});
currInstance.setState({
tags: tags,
allFiles: allFiles,
fileIdFileMap: fileIdFileMap,
isLoaded: true,
accordionData: dirLayouts,
treeData: transformedData,
infoBoardType: BOARD_TYPES.NONE,
infoBoardData: {},
breadCrumb: []
})
}).catch(function(error) {
console.error(error);
console.error(error.response.data);
});
}
handleDirectoryLayoutClick(targetDirLayout, evt) {
this.setState((prevState, props) => {
const newState = {
accordionData: prevState.accordionData,
infoBoardType: BOARD_TYPES.DIRLAYOUT,
infoBoardData: targetDirLayout,
selectedDirLayout: targetDirLayout,
breadCrumb: this.getBreadCrumbs(targetDirLayout, null)
};
newState.accordionData.forEach(eachDirLayout => {
if (eachDirLayout.id == targetDirLayout.id) {
eachDirLayout.isOpen = !eachDirLayout.isOpen;
} else {
eachDirLayout.isOpen = false;
}
});
return newState;
});
}
getBreadCrumbs(dirLayout, currentDir) {
const breadCrumbs = [];
while (currentDir) {
breadCrumbs.unshift(currentDir.name);
currentDir = this.directoryIdDirectoryMap[currentDir.parent];
}
breadCrumbs.unshift(dirLayout.name);
return breadCrumbs;
}
handleDirectoryLeftClick(nodeInfo, evt) {
const evtTarget = evt.target;
/* This is used to determine whether the click event was directed at the tree node,
* or at the expand/collapse buttons in the SortableTree. */
if (!(evtTarget.className.includes('expandButton') || evtTarget.className.includes('collapseButton'))) {
this.setState((prevState, props) => {
return {
breadCrumb: this.getBreadCrumbs(prevState.selectedDirLayout, nodeInfo.node),
infoBoardType: BOARD_TYPES.DIRECTORY,
infoBoardData: nodeInfo.node
}
});
}
}
handleDirectoryRightClick(nodeInfo, evt) {
const evtTarget = evt.target;
/* This is used to determine whether the click event was directed at the tree node,
* or at the expand/collapse buttons in the SortableTree. */
if (!(evtTarget.className.includes('expandButton') || evtTarget.className.includes('collapseButton'))) {
this.setState({
dirContextMenu: {
selectedDirectory: nodeInfo.node,
AnchorPos: {top:evt.clientY, left:evt.clientX}
}
});
}
evt.preventDefault();
}
handleMenuClose(evt) {
this.setState({
dirContextMenu: {
selectedDirectory: null,
AnchorPos: null
}
});
}
createDirectory(dirLayout, parentDir) {
/*
* If the parentDirId is null, there is no parent directory and will be created at the root.
*/
this.setState((prevState, props) => {
return {
breadCrumb: this.getBreadCrumbs(dirLayout, parentDir),
infoBoardType: BOARD_TYPES.DIRECTORY,
infoBoardData: {
id: -1,
name: '',
individualFiles: [],
bannerFile: '',
originalFileName: '',
creators: [],
coverages: [],
subjects: [],
keywords: [],
workareas: [],
languages: [],
catalogers: [],
creatorsNeedAll: false,
coveragesNeedAll: false,
subjectsNeedAll: false,
keywordsNeedAll: false,
workareasNeedAll: false,
languagesNeedAll: false,
catalogersNeedAll: false,
dirLayoutId: dirLayout.id,
parent: Boolean(parentDir) ? parentDir.id : null,
}
}});
}
createDirectoryLayout(evt) {
this.setState({
breadCrumb: [],
infoBoardType: BOARD_TYPES.DIRLAYOUT,
infoBoardData: {
id: -1,
name: '',
description: '',
original_file_name: '',
banner_file: ''
}
});
}
render() {
var elements = null;
if (this.state.isLoaded) {
const accordionItems = [];
this.state.accordionData.forEach(eachDirLayout => {
accordionItems.push(<ListItem button key={eachDirLayout.id} onClick={evt => this.handleDirectoryLayoutClick(eachDirLayout, evt)}>
<ListItemText inset primary={ eachDirLayout.name } />
{ eachDirLayout.isOpen ? <ExpandLess /> : <ExpandMore /> }
</ListItem>);
accordionItems.push(<Collapse key={'collapse-' + eachDirLayout.id} in={eachDirLayout.isOpen} timeout="auto" unmountOnExit>
<Button variant="contained" color="primary" onClick={evt => {this.createDirectory(eachDirLayout, null); }} style={{display: 'block', marginLeft: 'auto', marginRight: 'auto'}}>
New Top Folder
</Button>
<div className={'autoScrollX'}>
{
this.state.treeData[eachDirLayout.id].length > 0 &&
<SortableTree
canDrag={false}
treeData={this.state.treeData[eachDirLayout.id]}
onChange={newTreeData=> {
var currentTreeData = this.state.treeData;
currentTreeData[eachDirLayout.id] = newTreeData;
this.setState({ treeData: currentTreeData })}
}
isVirtualized={false}
generateNodeProps={nodeInfo => ({
onClick: (evt) => this.handleDirectoryLeftClick(nodeInfo, evt),
onContextMenu: (evt) => this.handleDirectoryRightClick(nodeInfo, evt)
})}
/>
}
</div>
</Collapse>);
accordionItems.push(<Divider key={'divider_' + eachDirLayout.id} />);
});
const breadCrumbItems = [];
for (let i=0; i<this.state.breadCrumb.length; i++) {
const eachCrumb = this.state.breadCrumb[i];
breadCrumbItems.push(<span key={'bcrumb_' + i}>
{eachCrumb}
<ChevronRight style={{verticalAlign: 'middle'}}/>
</span>);
}
elements = (
<Grid container spacing={8}>
<Grid item xs={3} style={{paddingLeft: '20px'}}>
<Button variant="contained" color="primary" onClick={this.createDirectoryLayout} style={{display: 'block', marginLeft: 'auto', marginRight: 'auto'}}>
New Library Version
</Button>
<List component="nav">
<ListSubheader disableSticky component="div">Library Versions</ListSubheader>
{
accordionItems
}
</List>
</Grid>
<Grid item xs={8}>
<AppBar position="static" style={{ minHeight: '50px', margin: 'auto', padding: '13px 0px 7px 10px'}}>
<Typography gutterBottom variant="subtitle1" style={{color: '#ffffff'}}>
{
breadCrumbItems
}
</Typography>
</AppBar>
<div style={{marginTop: '20px'}}> </div>
{
this.state.infoBoardType == BOARD_TYPES.DIRLAYOUT &&
<DirlayoutInfoBoard boardData={this.state.infoBoardData} onSave={this.saveDirLayoutCallback} onDelete={this.deleteDirLayoutCallback} />
}
{
this.state.infoBoardType == BOARD_TYPES.DIRECTORY &&
<DirectoryInfoBoard boardData={this.state.infoBoardData} onSave={this.saveDirectoryCallback} onDelete={this.deleteDirectoryCallback} tags={this.state.tags} allFiles={this.state.allFiles} fileIdFileMap={this.state.fileIdFileMap} />
}
</Grid>
<Menu
id="simple-menu"
anchorPosition={this.state.dirContextMenu.AnchorPos}
anchorReference={'anchorPosition'}
open={Boolean(this.state.dirContextMenu.AnchorPos)}
onClose={this.handleMenuClose}
>
<MenuItem
onClick={evt => {
this.createDirectory(this.state.selectedDirLayout, this.state.dirContextMenu.selectedDirectory);
this.handleMenuClose(evt);
}}
>
Create SubFolder
</MenuItem>
</Menu>
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
open={Boolean(this.state.message)}
autoHideDuration={6000}
onClose={this.handleCloseSnackbar}
message={<span>{this.state.message}</span>}
/>
</Grid>
);
} else {
elements = (
<div>Loading...</div>
)
}
return elements;
}
handleCloseSnackbar() {
this.setState({
message: null,
messageType: 'info'
})
}
saveDirLayoutCallback(savedInfo, saveType) {
if (saveType == DIRLAYOUT_SAVE_TYPE.CLONE) {
// TODO : Create a new endpoint for getting the directories associated with a layout, and reload just them.
this.loadData();
this.setState({
message: 'Successfully cloned the library version.',
messageType: 'info'
});
} else {
this.setState((prevState, props) => {
const newState = {
accordionData: prevState.accordionData,
infoBoardData: savedInfo,
breadCrumb: [savedInfo.name],
};
if (saveType == DIRLAYOUT_SAVE_TYPE.CREATE) {
const newDirLayout = {
id: savedInfo.id,
name: savedInfo.name,
description: savedInfo.description,
original_file_name: savedInfo.original_file_name,
banner_file: savedInfo.banner_file,
isOpen: false
};
newState.treeData = prevState.treeData;
newState.treeData[savedInfo.id] = [];
newState.accordionData.push(newDirLayout);
} else if (saveType == DIRLAYOUT_SAVE_TYPE.UPDATE) {
newState.accordionData.forEach(eachDirLayout => {
if (eachDirLayout.id == savedInfo.id) {
eachDirLayout.name = savedInfo.name;
eachDirLayout.description = savedInfo.description;
eachDirLayout.banner_file = savedInfo.banner_file;
eachDirLayout.original_file_name = savedInfo.original_file_name;
}
});
}
return newState;
});
}
}
deleteDirLayoutCallback(deletedItemId) {
this.setState((prevState, props) => {
const newState = {
infoBoardType: BOARD_TYPES.NONE,
infoBoardData: {},
accordionData: prevState.accordionData,
treeData: prevState.treeData,
selectedDirLayout: null,
breadCrumb: [],
message: 'Successfully deleted the library version.'
};
delete newState.treeData[deletedItemId];
for (var i=0; i<newState.accordionData.length; i++) {
if (newState.accordionData[i].id == deletedItemId) {
newState.accordionData.splice(i, 1);
break;
}
}
return newState;
});
}
updateDirectoryEntry(directoryId, array, newValue, created) {
for (var i=0; i<array.length; i++) {
if (array[i].id == directoryId) {
if (created) {
// If the operation is a create operation
array[i].children = array[i].children.concat({
id: newValue.id,
name: newValue.name,
title: (<Button fullWidth>{newValue.name}</Button>),
dirLayoutId: newValue.dir_layout,
parent: newValue.parent,
bannerFile: newValue.banner_file,
originalFileName: newValue.original_file_name,
individualFiles: newValue.individual_files,
creators: newValue.creators,
coverages: newValue.coverages,
subjects: newValue.subjects,
keywords: newValue.keywords,
workareas: newValue.workareas,
languages: newValue.languages,
catalogers: newValue.catalogers,
creatorsNeedAll: newValue.creators_need_all,
coveragesNeedAll: newValue.coverages_need_all,
subjectsNeedAll: newValue.subjects_need_all,
keywordsNeedAll: newValue.keywords_need_all,
workareasNeedAll: newValue.workareas_need_all,
languagesNeedAll: newValue.languages_need_all,
catalogersNeedAll: newValue.catalogers_need_all,
children: []
});
} else {
// If the operation is an update operation
array[i].name = newValue.name;
array[i].title = (<Button fullWidth>{newValue.name}</Button>);
array[i].parent = newValue.parent;
array[i].bannerFile = newValue.banner_file;
array[i].originalFileName = newValue.original_file_name;
array[i].individualFiles = newValue.individual_files;
array[i].creators = newValue.creators;
array[i].coverages = newValue.coverages;
array[i].subjects = newValue.subjects;
array[i].keywords = newValue.keywords;
array[i].workareas = newValue.workareas;
array[i].languages = newValue.languages;
array[i].catalogers = newValue.catalogers;
array[i].creatorsNeedAll = newValue.creators_need_all;
array[i].coveragesNeedAll = newValue.coverages_need_all;
array[i].subjectsNeedAll = newValue.subjects_need_all;
array[i].keywordsNeedAll = newValue.keywords_need_all;
array[i].workareasNeedAll = newValue.workareas_need_all;
array[i].languagesNeedAll = newValue.languages_need_all;
array[i].catalogersNeedAll = newValue.catalogers_need_all;
}
return true;
}
if (array[i].children.length > 0) {
var found = this.updateDirectoryEntry(directoryId, array[i].children, newValue, created);
if (found) {
return true;
}
}
}
return false;
}
updateBoardData(boardData, directory) {
boardData.id = directory.id;
boardData.name = directory.name;
boardData.dirLayoutId = directory.dir_layout;
boardData.bannerFile = directory.banner_file;
boardData.originalFileName = directory.original_file_name;
boardData.individualFiles = directory.individual_files;
boardData.creators = directory.creators;
boardData.coverages = directory.coverages;
boardData.subjects = directory.subjects;
boardData.keywords = directory.keywords;
boardData.workareas = directory.workareas;
boardData.languages = directory.languages;
boardData.catalogers = directory.catalogers;
boardData.creatorsNeedAll = directory.creators_need_all;
boardData.coveragesNeedAll = directory.coverages_need_all;
boardData.subjectsNeedAll = directory.subjects_need_all;
boardData.keywordsNeedAll = directory.keywords_need_all;
boardData.workareasNeedAll = directory.workareas_need_all;
boardData.languagesNeedAll = directory.languages_need_all;
boardData.catalogersNeedAll = directory.catalogers_need_all;
boardData.parent = directory.parent;
}
saveDirectoryCallback(savedInfo, created=false) {
this.setState((prevState, props) => {
const dirLayoutId = savedInfo.dir_layout;
const newState = {
breadCrumb: this.getBreadCrumbs(prevState.selectedDirLayout, savedInfo),
treeData: cloneDeep(prevState.treeData),
infoBoardData: cloneDeep(prevState.treeData)
};
this.updateBoardData(newState.infoBoardData, savedInfo);
if (created) {
if (savedInfo.parent) {
// Add it to the parent.
this.updateDirectoryEntry(savedInfo.parent, newState.treeData[dirLayoutId], savedInfo, created);
} else {
// Add it as a top level directory for the layout.
newState.treeData[dirLayoutId] = newState.treeData[dirLayoutId].concat({
id: savedInfo.id,
name: savedInfo.name,
title: (<Button>{savedInfo.name}</Button>),
dirLayoutId: savedInfo.dir_layout,
parent: savedInfo.parent,
bannerFile: savedInfo.banner_file,
originalFileName: savedInfo.original_file_name,
individualFiles: savedInfo.individual_files,
creators: savedInfo.creators,
coverages: savedInfo.coverages,
subjects: savedInfo.subjects,
keywords: savedInfo.keywords,
workareas: savedInfo.workareas,
languages: savedInfo.languages,
catalogers: savedInfo.catalogers,
creatorsNeedAll: savedInfo.creators_need_all,
coveragesNeedAll: savedInfo.coverages_need_all,
subjectsNeedAll: savedInfo.subjects_need_all,
keywordsNeedAll: savedInfo.keywords_need_all,
workareasNeedAll: savedInfo.workareas_need_all,
languagesNeedAll: savedInfo.languages_need_all,
catalogersNeedAll: savedInfo.catalogers_need_all,
children: []
});
}
} else {
// Update the existing value.
this.updateDirectoryEntry(savedInfo.id, newState.treeData[dirLayoutId], savedInfo, created);
}
return newState;
});
}
/* Remove the directory entry from the array */
removeDirectoryEntry(directoryId, array) {
for (var i=0; i<array.length; i++) {
if (array[i].id == directoryId) {
array.splice(i, 1);
return true;
}
if (array[i].children.length > 0) {
var found = this.removeDirectoryEntry(directoryId, array[i].children);
if (found) {
return true;
}
}
}
return false;
}
deleteDirectoryCallback(dirLayoutId, directoryId) {
this.setState((prevState, props) => {
const newState = {
infoBoardType: BOARD_TYPES.NONE,
infoBoardData: {},
treeData: cloneDeep(prevState.treeData),
breadCrumb: [],
message: 'Successfully deleted the directory.'
};
this.removeDirectoryEntry(directoryId, newState.treeData[dirLayoutId]);
return newState;
});
}
} |
JavaScript | class DirectorController {
/**
* Show a list of all directors.
* GET directors
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index ({ request, transform }) {
const page = request.input('page', 1)
const limit = request.input('limit', 15)
const directors = await Director.query().paginate(page, limit)
return transform.paginate(directors, 'DirectorsTransformer')
}
/**
* Create/save a new director.
* POST directors
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store ({ request, response }) {
const director = await Director.create(request.all())
return response.status(201).send(director)
}
/**
* Display a single director.
* GET directors/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show ({ params, transform }) {
const director = await Director.findOrFail(params.id)
return transform.item(director, 'DirectorTransformer')
}
/**
* Update director details.
* PUT or PATCH directors/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update ({ params, request }) {
const director = await Director.findOrFail(params.id)
director.merge(request.all())
await director.save()
return director
}
/**
* Delete a director with id.
* DELETE directors/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy ({ params, response }) {
const director = await Director.findOrFail(params.id)
await director.delete()
return response.status(204).send()
}
/**
* Return all videos from director.
* GET tags/:id/videos
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async videos({ params }) {
const director = await Director.findOrFail(params.id)
const videos = director.videos().fetch()
return videos
}
} |
JavaScript | class App extends React.Component {
constructor (props) {
super(props)
this.state = {
contenuaffichage: "",
latitude: "latitude",
}
}
//call back des fonctions d'affichage
fonctiontexte = () => {
this.setState({ contenuaffichage: "texte" });
};
fonctionphoto = () => {
this.setState({ contenuaffichage: "photo" });
};
fonctionaudio = () => {
this.setState({ contenuaffichage: "audio" });
};
render() {
// initialise ici le point du circuit repéré
let a=1;
let numdupoint=0;
let tableauCoordonnees = [];
// defini les variables de travail
var latitude, longitude, latitudefichier, longitudefichier, latitudeGPS, longitudeGPS;
//console.log (this.props.data.allImageSharp.edges[num].node.sizes.originalName);
function roundup (val){
return val = Math.round(val*100000)/100000;
}
function changeNum () {
//arrondis coords gps
//latitudeGPS=roundup(latitude);
//longitudeGPS=roundup(longitude);
//verifier pour chaque point si lat et long corresponde
// si oui numpoint=num+1 sinon ?
//envoyer infos dans les props
//, numdupoint=this.props.data.allTableaudespointsCsv.edges[numdupoint].node.field1
// else this.forceUpdate() et num =num+1
//tableauCoordonnees[1].node.field2
/*<div>Coordonnées en mémoire du circuit</div>
<div>Latitude : {this.props.data.allTableaudespointsCsv.edges[numdupoint].node.field2}</div>
<div>Longitude : {this.props.data.allTableaudespointsCsv.edges[numdupoint].node.field3}</div>*/
var i=0;
for (i=0; i<tableauCoordonnees.length; i++) {
//alert (tableauCoordonnees[i].node.field2+" "+latitudeGPS+" - "+tableauCoordonnees[i].node.field3+" "+longitudeGPS );
if (latitudeGPS==tableauCoordonnees[i].node.field2 && longitudeGPS==tableauCoordonnees[i].node.field3){
//alert ("N° "+tableauCoordonnees[i].node.field1);
return tableauCoordonnees[i].node.field1;
}
}
}
return (
!this.props.isGeolocationAvailable
? <div>Your browser does not support Geolocation</div>
: !this.props.isGeolocationEnabled
? <div>Geolocation is not enabled</div>
: this.props.coords
? <div>
<div>
<div>Coordonnées du téléphone</div>
<div>latitude : {this.props.coords.latitude}</div>
<div>longitude : {this.props.coords.longitude}</div>
<div><br /></div>
{/* Transférer les coords GPS réelles et gps du tableau dans des variables */}
{latitudeGPS=this.props.coords.latitude,
longitudeGPS=this.props.coords.longitude,
tableauCoordonnees=this.props.data.allTableaudespointsCsv.edges, ""
}
{/* Vérifier si un point correspond dans le tableau */}
{/*{latitudeGPS} {latitudefichier} */}
{/* pour i=1 à longueur du tableau */}
{/* je passe la valeur de i à la fonction ? */}
{numdupoint=changeNum(), ""}
<div>Vous êtes au point N° : {numdupoint}</div>
{/* Envoyer les infos dans les props */}
<div><Fenetre contenu={this.state.contenuaffichage}
descriptif={this.props.data.allTableaudespointsCsv.edges[1].node.field4}
photoNum={numdupoint}
photoName={this.props.data.allImageSharp.edges[1].node.sizes.originalName}
photoLieu={this.props.data.allImageSharp.edges[1].node.sizes.src}
/></div>
<div><Navigation fonctiontexte={this.fonctiontexte}
fonctionphoto={this.fonctionphoto}
fonctionaudio={this.fonctionaudio}/>
</div>
</div>
</div>
: <div>Getting the location data… </div>
)
}
} |
JavaScript | class Lucro {
constructor(dia, mes, ano, tipo, valor, barbeiro) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.tipo = tipo;
this.valor = valor;
this.barbeiro = barbeiro;
}
// 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;
}
}
if (this.dia < 0 || this.dia>31 || isNaN(this.dia)) {
return 'erroDia';
}
if (isNaN(this.valor) || this.valor < 1) {
return 'erroValor';
}
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(lucro) {
// array que vai receber os dados
let lucroFiltrado = new Array();
// recupera todos os dados atraves da funcao recuperar dados mostrado acima na classe BD
lucroFiltrado = this.recuperarDados();
// teste se o campo de pesquisa esta vazio
if (lucro.ano !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.ano == lucro.ano);
}
// teste se o campo de pesquisa esta vazio
if (lucro.mes !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.mes == lucro.mes);
}
// teste se o campo de pesquisa esta vazio
if (lucro.dia !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.dia == lucro.dia);
}
// teste se o campo de pesquisa esta vazio
if (lucro.tipo !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.tipo == lucro.tipo);
}
// teste se o campo de pesquisa esta vazio
if (lucro.valor !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.valor == lucro.valor);
}
// teste se o campo de pesquisa esta vazio
if (lucro.barbeiro !== '') {
// faz o filter no array do objeto e retorna os objetos encontrados fazendo um efeito cascata com os itens de baixo
lucroFiltrado = lucroFiltrado.filter(a => a.barbeiro == lucro.barbeiro);
}
// retorna o resultado da pesquisa
return lucroFiltrado;
}
//remover o item do localStorage
excluir(id) {
localStorage.removeItem(id);
}
} |
JavaScript | class BaseEntity {
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Checks if entity has an id.
* If entity composite compose ids, it will check them all.
*/
hasId() {
const baseEntity = this.constructor;
return baseEntity.getRepository().hasId(this);
}
/**
* Saves current entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
save(options) {
const baseEntity = this.constructor;
return baseEntity.getRepository().save(this, options);
}
/**
* Removes current entity from the database.
*/
remove(options) {
const baseEntity = this.constructor;
return baseEntity.getRepository().remove(this, options);
}
/**
* Records the delete date of current entity.
*/
softRemove(options) {
const baseEntity = this.constructor;
return baseEntity.getRepository().softRemove(this, options);
}
/**
* Recovers a given entity in the database.
*/
recover(options) {
const baseEntity = this.constructor;
return baseEntity.getRepository().recover(this, options);
}
/**
* Reloads entity data from the database.
*/
async reload() {
const baseEntity = this.constructor;
const id = baseEntity.getRepository().metadata.getEntityIdMap(this);
if (!id) {
throw new Error(`Entity doesn't have id-s set, cannot reload entity`);
}
const reloadedEntity = await baseEntity
.getRepository()
.findOneByOrFail(id);
ObjectUtils.assign(this, reloadedEntity);
}
// -------------------------------------------------------------------------
// Public Static Methods
// -------------------------------------------------------------------------
/**
* Sets DataSource to be used by entity.
*/
static useDataSource(dataSource) {
this.dataSource = dataSource;
}
/**
* Gets current entity's Repository.
*/
static getRepository() {
const dataSource = this.dataSource;
if (!dataSource)
throw new Error(`DataSource is not set for this entity.`);
return dataSource.getRepository(this);
}
/**
* Returns object that is managed by this repository.
* If this repository manages entity from schema,
* then it returns a name of that schema instead.
*/
static get target() {
return this.getRepository().target;
}
/**
* Checks entity has an id.
* If entity composite compose ids, it will check them all.
*/
static hasId(entity) {
return this.getRepository().hasId(entity);
}
/**
* Gets entity mixed id.
*/
static getId(entity) {
return this.getRepository().getId(entity);
}
/**
* Creates a new query builder that can be used to build a SQL query.
*/
static createQueryBuilder(alias) {
return this.getRepository().createQueryBuilder(alias);
}
/**
* Creates a new entity instance and copies all entity properties from this object into a new entity.
* Note that it copies only properties that present in entity schema.
*/
static create(entityOrEntities) {
return this.getRepository().create(entityOrEntities);
}
/**
* Merges multiple entities (or entity-like objects) into a given entity.
*/
static merge(mergeIntoEntity, ...entityLikes) {
return this.getRepository().merge(mergeIntoEntity, ...entityLikes);
}
/**
* Creates a new entity from the given plain javascript object. If entity already exist in the database, then
* it loads it (and everything related to it), replaces all values with the new ones from the given object
* and returns this new entity. This new entity is actually a loaded from the db entity with all properties
* replaced from the new object.
*
* Note that given entity-like object must have an entity id / primary key to find entity by.
* Returns undefined if entity with given id was not found.
*/
static preload(entityLike) {
const thisRepository = this.getRepository();
return thisRepository.preload(entityLike);
}
/**
* Saves one or many given entities.
*/
static save(entityOrEntities, options) {
return this.getRepository().save(entityOrEntities, options);
}
/**
* Removes one or many given entities.
*/
static remove(entityOrEntities, options) {
return this.getRepository().remove(entityOrEntities, options);
}
/**
* Records the delete date of one or many given entities.
*/
static softRemove(entityOrEntities, options) {
return this.getRepository().softRemove(entityOrEntities, options);
}
/**
* Inserts a given entity into the database.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT query.
* Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
*/
static insert(entity) {
return this.getRepository().insert(entity);
}
/**
* Updates entity partially. Entity can be found by a given conditions.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient UPDATE query.
* Does not check if entity exist in the database.
*/
static update(criteria, partialEntity) {
return this.getRepository().update(criteria, partialEntity);
}
/**
* Inserts a given entity into the database, unless a unique constraint conflicts then updates the entity
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT ... ON CONFLICT DO UPDATE/ON DUPLICATE KEY UPDATE query.
*/
static upsert(entityOrEntities, conflictPathsOrOptions) {
return this.getRepository().upsert(entityOrEntities, conflictPathsOrOptions);
}
/**
* Deletes entities by a given criteria.
* Unlike remove method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient DELETE query.
* Does not check if entity exist in the database.
*/
static delete(criteria) {
return this.getRepository().delete(criteria);
}
/**
* Counts entities that match given options.
*/
static count(options) {
return this.getRepository().count(options);
}
/**
* Counts entities that match given WHERE conditions.
*/
static countBy(where) {
return this.getRepository().countBy(where);
}
/**
* Finds entities that match given options.
*/
static find(options) {
return this.getRepository().find(options);
}
/**
* Finds entities that match given WHERE conditions.
*/
static findBy(where) {
return this.getRepository().findBy(where);
}
/**
* Finds entities that match given find options.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
static findAndCount(options) {
return this.getRepository().findAndCount(options);
}
/**
* Finds entities that match given WHERE conditions.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
static findAndCountBy(where) {
return this.getRepository().findAndCountBy(where);
}
/**
* Finds entities by ids.
* Optionally find options can be applied.
*
* @deprecated use `findBy` method instead in conjunction with `In` operator, for example:
*
* .findBy({
* id: In([1, 2, 3])
* })
*/
static findByIds(ids) {
return this.getRepository().findByIds(ids);
}
/**
* Finds first entity that matches given conditions.
*/
static findOne(options) {
return this.getRepository().findOne(options);
}
/**
* Finds first entity that matches given conditions.
*/
static findOneBy(where) {
return this.getRepository().findOneBy(where);
}
/**
* Finds first entity that matches given options.
*
* @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:
*
* .findOneBy({
* id: 1 // where "id" is your primary column name
* })
*/
static findOneById(id) {
return this.getRepository().findOneById(id);
}
/**
* Finds first entity that matches given conditions.
*/
static findOneOrFail(options) {
return this.getRepository().findOneOrFail(options);
}
/**
* Finds first entity that matches given conditions.
*/
static findOneByOrFail(where) {
return this.getRepository().findOneByOrFail(where);
}
/**
* Executes a raw SQL query and returns a raw database results.
* Raw query execution is supported only by relational databases (MongoDB is not supported).
*/
static query(query, parameters) {
return this.getRepository().query(query, parameters);
}
/**
* Clears all the data from the given table/collection (truncates/drops it).
*/
static clear() {
return this.getRepository().clear();
}
} |
JavaScript | class AbstractProvider {
/**
* Returns the name of the provider
* @returns {string}
*/
get providerName() {
throw new Error('Provider not implemented');
}
/**
* Sends a message to the queue
* @param msg Message to send
* @param cb Callback
*/
sendMessage(msg, cb) {
throw new Error('Provider not implemented');
}
/**
* Long Polls the queue for any incoming messages
* @param cb The callback to call with the result
*/
receiveMessage(cb) {
throw new Error('Provider not implemented');
}
/**
* Remove a message from the queue
* @param msg The message object
* @param cb Callback to call when it's done
*/
deleteMessage(msg, cb) {
throw new Error('Provider not implemented');
}
} |
JavaScript | class PortfolioForm extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
description: "",
category: "",
// category: "eCommerce", could create a default here or create a "select" option in drop down
position: "",
url: "",
thumb_image: "",
banner_image: "",
logo: "",
editMode: false,
apiUrl: "https://galenmontague.devcamp.space/portfolio/portfolio_items",
apiAction: "post"
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.componentConfig = this.componentConfig.bind(this);
this.djsConfig = this.djsConfig.bind(this);
this.handleThumbDrop = this.handleThumbDrop.bind(this);
this.handleBannerDrop = this.handleBannerDrop.bind(this);
this.handleLogoDrop = this.handleLogoDrop.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.thumbRef = React.createRef();
this.bannerRef = React.createRef();
this.logoRef = React.createRef();
//this creates a reference object and stores it in thumbRef so we have access to it in the JSX code so we can call it from any other function.
}
deleteImage(imageType) {
// imageType will be a thumb or a logo, etc
axios.delete(
`https://api.devcamp.space/portfolio/delete-portfolio-image/${this.state.id}?image_type=${imageType}`, { withCredentials: true }
).then(response => {
this.setState({
[`${imageType}_url`]: ""
// use [] when setting state dynamically and don't know exact name of the key. The value in this case is set to an empty string. This clears off the exiting image.
})
}).catch(error => {
console.log("deleteImage error", error)
})
// most api's allow for optional parameters to be set (use '?')
}
componentDidUpdate() {
// clicking on the edit button in the portfolio will trigger this function because we are going to populate that prop and pass in that data.
// checking to see if the object has keys or not _(not react related)
// ** from an exercise in the console
// const obj1 = {};
// const obj2 = { greeting: "asdfasdf" }
// Object.keys(obj1).length
// 0
// Object.keys(obj2).length
// 1
if (Object.keys(this.props.portfolioToEdit).length > 0) {
// if the object is empty, then skip below
const {
id,
name,
description,
category,
position,
url,
thumb_image_url,
banner_image_url,
logo_url
} = this.props.portfolioToEdit;
// all stored in a local variable using desctructuring
this.props.clearPortfolioToEdit();
// this will go into the parent (portfolio-manager) and run clearPortfolioToEdit() so that the conditional above doesn't get fired anymore
// the componentDidUpdate() will run everytime something is typed into the form unless we run this
this.setState({
id: id,
name: name || "",
// nill check: we don't want to work with nill/null values (if there's a name, then put name, if not have an empty string)
description: description || "",
category: category || "",
position: position || "",
url: url || "",
editMode: true,
apiUrl: `https://galenmontague.devcamp.space/portfolio/portfolio_items/${id}`,
apiAction: "patch",
thumb_image_url: thumb_image_url || "",
banner_image_url: banner_image_url || "",
logo_url: logo_url || ""
});
}
}
handleThumbDrop() {
return {
addedfile: file => this.setState({ thumb_image: file })
};
}
handleBannerDrop() {
return {
addedfile: file => this.setState({ banner_image: file })
};
}
handleLogoDrop() {
return {
addedfile: file => this.setState({ logo: file })
};
}
componentConfig() {
return {
iconFiletypes: [".jpg", ".png"],
// limits file types (part of Dropzone)
showFiletypeIcon: true,
postUrl: "https://httpbin.org/post"
// We want to wait for "submit" to pass the file to the api. This creates a mock url that returns true always. Creates animations when file is accepted. This url just returns true.
}
}
djsConfig() {
return {
addRemoveLinks: true,
maxFiles: 1
}
}
buildForm() {
let formData = new FormData();
//creating an empty object
// fills the empty object (keys and values)
formData.append("portfolio_item[name]", this.state.name);
formData.append("portfolio_item[description]", this.state.description);
formData.append("portfolio_item[url]", this.state.url);
formData.append("portfolio_item[category]", this.state.category);
formData.append("portfolio_item[position]", this.state.position);
if (this.state.thumb_image) {
formData.append("portfolio_item[thumb_image]", this.state.thumb_image);
}
if (this.state.banner_image) {
formData.append("portfolio_item[banner_image]", this.state.banner_image);
}
if (this.state.logo) {
formData.append("portfolio_item[logo]", this.state.logo);
}
return formData;
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
axios({
// This is a configuration object. The keys can dynamically be updated.
// Could do separate handle submits for post and patch, but 90% of the code would be the same.
method: this.state.apiAction,
// Will be post if no portfolio record to edit, if there is, it will switch to patch
url: this.state.apiUrl,
data: this.buildForm(),
withCredentials: true
})
.then(response => {
if (this.state.editMode) {
// When response comes back, if in edit mode, do this.
this.props.handleEditFormSubmission();
} else {
this.props.handleNewFormSubmission(response.data.portfolio_item);
}
this.setState = ({
name: "",
description: "",
category: "",
position: "",
url: "",
thumb_image: "",
banner_image: "",
logo: "",
// Resets the state back to empty string.
// These are attributes in the state, below are elements in the DOM.
editMode: false,
apiUrl: "https://galenmontague.devcamp.space/portfolio/portfolio_items",
apiAction: "post"
});
[this.thumbRef, this.bannerRef, this.logoRef].forEach(ref => {
ref.current.dropzone.removeAllFiles()
// forEach loops over each reference and gives us access to each. The first "ref" is this.thumbRef, then this.bannerRef, etc.
// "Current" gives us the current state of each element.
// This is all in Dropzone Component docs on how to remove files.
})
})
.catch(error => {
console.log("portfolio form handleSubmit error", error);
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit} className="portfolio-form-wrapper">
<div className="two-column">
<input
type="text"
name="name"
placeholder="Portfolio Item Name"
value={this.state.name}
onChange={this.handleChange}
/>
<input
type="text"
name="url"
placeholder="URL"
value={this.state.url}
onChange={this.handleChange}
/>
</div>
<div className="two-column">
<input
type="text"
name="position"
placeholder="Position"
value={this.state.position}
onChange={this.handleChange}
/>
<select
name="category"
value={this.state.category}
onChange={this.handleChange}
className="select-element"
>
<option>Select Category</option>
<option value="HTML/CSS">HTML/CSS</option>
<option value="JavaScript">JavaScript</option>
<option value="React">React</option>
<option value="Python">Python</option>
{/* <option value="eCommerce">eCommerce</option>
<option value="Scheduling">Scheduling</option>
<option value="Enterprise">Enterprise</option> */}
</select>
</div >
<div className="one-column">
<textarea
type="text"
name="description"
placeholder="Description"
value={this.state.description}
onChange={this.handleChange}
/>
</div>
<div className="image-uploaders">
{/* {true ? "do if true" : "do if false"} */}
{this.state.thumb_image_url && this.state.editMode ? (
// if there's a thumb img AND we're in edit mode
<div className="portfolio-manager-image-wrapper">
<img src={this.state.thumb_image_url} />
<div className="image-removal-link">
<a onClick={() => this.deleteImage("thumb_image")}>
Remove File
</a>
</div>
</div>
) : (
<DropzoneComponent
ref = {this.thumbRef}
// Allows us to place a handle in this component (or any component). Gives us the ability to interact with the real DOM.
config={this.componentConfig()}
djsConfig={this.djsConfig()}
eventHandlers={this.handleThumbDrop()}
>
<div className="dz-message">Thumbnail</div>
</DropzoneComponent>
)}
{this.state.banner_image_url && this.state.editMode ? (
<div className="portfolio-manager-image-wrapper">
<img src={this.state.banner_image_url} />
<div className="image-removal-link">
<a onClick={() => this.deleteImage("banner_image")}>
Remove File
</a>
</div>
</div>
) : (
<DropzoneComponent
ref = {this.bannerRef}
config={this.componentConfig()}
djsConfig={this.djsConfig()}
eventHandlers={this.handleBannerDrop()}
>
<div className="dz-message">Banner</div>
</DropzoneComponent>
)}
{this.state.logo_url && this.state.editMode ? (
// if there's a thumb img AND we're in edit mode
<div className="portfolio-manager-image-wrapper">
<img src={this.state.logo_url} />
<div className="image-removal-link">
<a onClick={() => this.deleteImage("logo")}>
Remove File
</a>
</div>
</div>
) : (
<DropzoneComponent
ref = {this.logoRef}
config={this.componentConfig()}
djsConfig={this.djsConfig()}
eventHandlers={this.handleLogoDrop()}
>
<div className="dz-message">Logo</div>
</DropzoneComponent>
)}
</div>
<div>
<button className="btn" type="submit">Save</button>
</div>
</form>
)
}
} |
JavaScript | class Intern extends Employee{
// constructor with param for name, id, email, and school
constructor(name, id, email, school){
super(name, id, email);
this.school = school;
this.role = 'Intern';
}
// method to return school
getSchool(){
return this.school;
}
// method to return role
getRole(){
return this.role;
}
} |
JavaScript | class FoodalScraper extends BaseScraper {
constructor(url) {
super(url, "foodal.com/");
}
scrape($) {
this.defaultSetImage($);
const { ingredients, instructions, time } = this.recipe;
this.recipe.name = $("h2.tasty-recipes-title").text().trim();
$("div.tasty-recipes-ingredients")
.find("li")
.each((i, el) => {
ingredients.push(
$(el)
.text()
.replace(/(\s\s+|▢)/g, " ")
.trim()
);
});
$("div.tasty-recipes-instructions")
.find("li")
.each((i, el) => {
instructions.push($(el).text().trim());
});
time.prep = $("span.tasty-recipes-prep-time").text();
time.cook = $("span.tasty-recipes-cook-time").text();
time.total = $("span.tasty-recipes-total-time").text();
this.recipe.servings = $("span.tasty-recipes-yield")
.find("span")
.first()
.text();
}
} |
JavaScript | class GitHubFileCache {
constructor(disableCron) {
this.auth = readAuthCreds();
this.cache = {};
this.repos = _.chain(_.range(LOWEST_JAVA_VERSION, HIGHEST_JAVA_VERSION + 1))
.map(num => {
return [
`openjdk${num}-openj9-nightly`,
`openjdk${num}-nightly`,
`openjdk${num}-binaries`
]
})
.flatten()
.values();
if (disableCron !== true) {
this.scheduleCacheRefresh();
}
}
refreshCache(cache) {
console.log('Refresh at:', new Date());
return _.chain(this.repos)
.map(repo => this.getReleaseDataFromGithub(repo, cache))
.value();
}
scheduleCacheRefresh() {
const refresh = () => {
try {
const cache = {};
Q.allSettled(this.refreshCache(cache))
.then(() => {
this.cache = cache;
console.log("Cache refreshed")
})
} catch (e) {
console.error(e)
}
};
new CronJob(getCooldown(this.auth), refresh, undefined, true, undefined, undefined, true);
}
getReleaseDataFromGithub(repo, cache) {
return octokit
.paginate(`GET /repos/AdoptOpenJDK/${repo}/releases`, {
owner: 'AdoptOpenJDK',
repo: repo
})
.then(data => {
cache[repo] = data;
return data;
});
}
cachedGet(repo) {
const data = this.cache[repo];
if (data === undefined) {
return this.getReleaseDataFromGithub(repo, this.cache)
.catch(error => {
this.cache[repo] = [];
return [];
})
} else {
return Q(data);
}
}
getInfoForVersion(version, releaseType) {
const newRepoPromise = this.cachedGet(`${version}-binaries`);
const legacyHotspotPromise = this.cachedGet(`${version}-${releaseType}`);
let legacyOpenj9Promise;
if (version.indexOf('amber') > 0) {
legacyOpenj9Promise = Q({});
} else {
legacyOpenj9Promise = this.cachedGet(`${version}-openj9-${releaseType}`);
}
return Q.allSettled([
newRepoPromise,
legacyHotspotPromise,
legacyOpenj9Promise
])
.catch(error => {
console.error("failed to get", error);
return [];
})
.spread(function (newData, oldHotspotData, oldOpenJ9Data) {
if (newData.state === "fulfilled" || oldHotspotData.state === "fulfilled" || oldOpenJ9Data.state === "fulfilled") {
newData = newData.state === "fulfilled" ? newData.value : [];
oldHotspotData = oldHotspotData.state === "fulfilled" ? oldHotspotData.value : [];
oldOpenJ9Data = oldOpenJ9Data.state === "fulfilled" ? oldOpenJ9Data.value : [];
oldHotspotData = markOldReleases(oldHotspotData);
oldOpenJ9Data = markOldReleases(oldOpenJ9Data);
return _.union(newData, oldHotspotData, oldOpenJ9Data);
} else {
throw newData.reason;
}
});
}
} |
JavaScript | class Layout extends React.Component {
constructor(options) {
super(options);
// dynamically inject reducer
injectReducer(Constants.ARTICLE_STORE, reducer);
this.handleDataViewTabsChange = this
.handleDataViewTabsChange
.bind(this);
};
handleDataViewTabsChange(newTab) {
this
.props
.history
.push(`${newTab}`);
};
render() {
const getEnvURL = path => `${process.env.PUBLIC_URL}${path}`;
return (
<span>
<div>
<Switch>
<Redirect exact from={getEnvURL("/")} to={getEnvURL(Constants.articleList)}/>
<Route path={getEnvURL(Constants.addArticle)} component={AddArticlePage}/>
<Route path={getEnvURL(Constants.articleList)} component={ArticlesListPage}/>
<Route path="*" component={PageNotFound}/>
</Switch>
</div>
</span>
);
}
} |
JavaScript | class Connection {
/**
* Construct with builder.
* @param builder
*/
constructor(builder) {
this.socket = builder.socket;
this.user = builder.user;
this.rooms = [];
this.socket.on('disconnect', () => {
connectionPool.removeConnection(this);
})
}
/**
* Get user associated with this connection.
* @returns {*|RemoteUser} The user.
*/
getUser() {
return this.user;
}
/**
* Get socket instance.
* @returns {*|socket|{type, describe, group}|null}
*/
getSocket() {
return this.socket;
}
/**
* get a list of rooms.
* @returns {Array}
*/
getRooms() {
return this.rooms;
}
/**
* Join a new room.
* @param roomName
*/
join(roomName) {
// Only join if not already joined.
if(this.rooms.indexOf(roomName) < 0) {
this.rooms.push(roomName);
this.socket.join(roomName);
}
}
/**
* Link handler.
* @param eventName
* @returns {{invoke: function}}
*/
onEvent(eventName) {
return {
/**
* Upon receiving the event, fire handler.
* @param {function} handler
*/
invoke: (handler) => {
this.socket.on(eventName, handler(this));
}
}
}
/**
* Disconnect the socket, and remove self from pool.
*/
disconnectAndRemoveFromPool() {
this.socket.disconnect();
connectionPool.removeConnection(this);
}
/**
* Emit an event to this connection.
* @param event
* @param data
*/
emit(event, data) {
this.socket.emit(event, data);
}
} |
JavaScript | class FeatureCollection {
constructor(url) {
let that = this
let request = new XMLHttpRequest()
request.open("GET", url, false) // async = false
request.onload = function() {
if ((this.status >= 200 && this.status < 400) || (this.status == 0)) {
that.fc = JSON.parse(this.response)
} else {
console.warn("FeatureCollection::request.onload", this)
}
}
request.onerror = function() {
console.error("FeatureCollection::request.onerror")
}
request.send()
console.log("FeatureCollection::constructor: loaded", url, this.fc)
}
get collection() {
return this.fc
}
get features() {
return this.fc.features
}
find(n, k) { // note: find returns the first match only
return this.fc.features.find(f => f.properties[n] == k)
}
filter(n, k) { // note: find returns all matches (array of Features)
return this.fc.features.filter(f => f.properties[n] == k)
}
count(n, k) {
let r = this.filter(n, k)
return r.length
}
distinct(n) { // note: find all values of a property
let ret = []
this.fc.features.forEach( (f) => {
if(ret.indexOf(f.properties[n]) == -1) {
ret.push(f.properties[n])
}
})
return ret
}
filterAndSort(n, k, s, rev = false) { // note: find returns all matches (array of Features)
let a = this.fc.features.filter(f => f.properties[n] == k)
a = a.sort( (a,b) => (a[s] > b[s]))
return rev ? a.reverse() : a
}
/* Returns features that contain the supplied point
*/
contains(point) {
return this.fc.features.filter(f => booleanPointInPolygon(point.coordinates, f))
}
/* Returns features that are inside the bbox feature (a polygon)
*/
inside(bbox) {
return this.fc.features.filter(f =>
booleanWithin(f, bbox))
}
addProperties(props) {
this.fc.features.forEach( (f) => {
f.properties = deepExtend(f.properties, props)
})
}
} |
JavaScript | class SCNPhysicsField extends NSObject {
/**
* constructor
* @access public
* @constructor
*/
constructor() {
super()
// Specifying a Field’s Area of Effect
/**
* A location marking the end of the field’s area of effect.
* @type {SCNVector3}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388138-halfextent
*/
this.halfExtent = null
/**
* The area affected by the field, either inside or outside its region.
* @type {SCNPhysicsFieldScope}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388136-scope
*/
this.scope = null
/**
* A Boolean value that determines whether the field’s area of effect is shaped like a box or ellipsoid.
* @type {boolean}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388158-usesellipsoidalextent
*/
this.usesEllipsoidalExtent = false
/**
* The offset of the field’s center within its area of effect.
* @type {SCNVector3}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388154-offset
*/
this.offset = null
/**
* The field’s directional axis.
* @type {SCNVector3}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388128-direction
*/
this.direction = null
// Specifying a Field’s Behavior
/**
* A multiplier for the force that the field applies to objects in its area of effect.
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388132-strength
*/
this.strength = 0
/**
* An exponent that determines how the field’s strength diminishes with distance.
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388146-falloffexponent
*/
this.falloffExponent = 0
/**
* The minimum value for distance-based effects.
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388148-minimumdistance
*/
this.minimumDistance = 0
/**
* A Boolean value that determines whether the field’s effect is enabled.
* @type {boolean}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388117-isactive
*/
this.isActive = false
/**
* A Boolean value that determines whether the field overrides other fields whose areas of effect it overlaps.
* @type {boolean}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388126-isexclusive
*/
this.isExclusive = false
// Choosing Physics Bodies to Be Affected by the Field
/**
* A mask that defines which categories this physics field belongs to.
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388119-categorybitmask
*/
this.categoryBitMask = 0
}
// Creating Physics Fields
/**
* Creates a field that slows any object in its area of effect with a force proportional to the object’s velocity.
* @access public
* @returns {SCNPhysicsField} -
* @desc Like the damping and angularDamping properties of a physics body, drag fields can simulate effects such as fluid friction or air resistance. Unlike those properties, drag fields can simulate different intensities of fluid friction in different areas of your scene. For example, you can use a drag field to represent underwater areas.The default falloffExponent value for a drag field is 0.0, indicating that the field’s effect is constant throughout its area of effect.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388164-drag
*/
static drag() {
return null
}
/**
* Creates a field whose forces circulate around an axis.
* @access public
* @returns {SCNPhysicsField} -
* @desc The force on an object in a vortex field is tangential to the line from the object’s position to the field’s axis and proportional to the object’s mass. (The field’s axis is a line that is parallel to its direction vector and that passes through its center. For details, see the offset property.) For example, when a vortex field’s area of effect contains many objects, the resulting scene resembles a tornado: The objects simultaneously revolve around and fly away from the field’s center.By default, a vortex circulates counterclockwise relative to its direction vector. To make it circulate clockwise, set the field’s strength property to a negative value.The default falloffExponent value for a vortex field is 0.0, indicating that the field’s effect is constant throughout its area of effect.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388160-vortex
*/
static vortex() {
return null
}
/**
* Creates a field that accelerates objects toward its center.
* @access public
* @returns {SCNPhysicsField} -
* @desc Because the force of gravity on an object is proportional to the object’s mass, this force accelerates all objects at the same distance from the field’s center by the same amount. The field’s strength property measures this acceleration in meters per second per second.By default, a radial gravity field attracts objects toward its center. To make it repel objects instead, set the field’s strength property to a negative value.The default falloffExponent value for a radial gravity field is 2.0, indicating that the field’s effect diminishes with the square of distance from its center.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388115-radialgravity
*/
static radialGravity() {
return null
}
/**
* Creates a field that accelerates objects in a specific direction.
* @access public
* @returns {SCNPhysicsField} -
* @desc Because the force of gravity on an object is proportional to the object’s mass, this force accelerates all objects in the field’s area of affect by the same amount. The field’s strength property measures this acceleration in meters per second per second.By default, a linear gravity field accelerates objects in along its direction vector. To make it accelerate objects in the opposite direction, set the field’s strength property to a negative value.The default falloffExponent value for a linear gravity field is 0.0, indicating that the field’s effect is constant throughout its area of effect.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388130-lineargravity
*/
static linearGravity() {
return null
}
/**
* Creates a field that applies random forces to objects in its area of effect.
* @access public
* @param {number} smoothness - The amount of randomness in the field. A value of 0.0 specifies maximum noise, and a value of 1.0 specifies no noise at all.
* @param {number} speed - The field’s variation over time. Specify 0.0 for a static field.
* @returns {SCNPhysicsField} -
* @desc Use this field type to simulate effects involving random motion, such as fireflies or gently falling snow.In calculating the direction and strength of the field’s effect on an object, SceneKit uses a Perlin simplex noise function. This function produces a velocity field that varies over time.The default falloffExponent value for a noise field is 0.0, indicating that the field’s effect is constant throughout its area of effect. This field type ignores the field’s direction property.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388150-noisefield
*/
static noiseFieldAnimationSpeed(smoothness, speed) {
return null
}
/**
* Creates a field that applies random forces to objects in its area of effect, with magnitudes proportional to those objects’ velocities.
* @access public
* @param {number} smoothness - The amount of randomness in the field. A value of 0.0 specifies maximum noise, and a value of 1.0 specifies no noise at all.
* @param {number} speed - The field’s variation over time. Specify 0.0 for a static field.
* @returns {SCNPhysicsField} -
* @desc Like a noise field, a turbulence field applies forces in random directions to the objects that it affects. Unlike a noise field, a turbulence field applies a force whose magnitude is proportional to the speed of each affected object. For example, an object passing through a noise field shakes as it travels through the field, but an object passing through a turbulence field shakes more violently the faster it travels. The field’s strength property scales the magnitude of the turbulence effect.The default falloffExponent value for a turbulence field is 0.0, indicating that the field’s effect is constant throughout its area of effect.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388162-turbulencefield
*/
static turbulenceFieldAnimationSpeed(smoothness, speed) {
return null
}
/**
* Creates a field that pulls objects toward its center with a spring-like force.
* @access public
* @returns {SCNPhysicsField} -
* @desc The force a spring field applies to objects in its area of effect is linearly proportional to the distance from the object to the center of the field. (That is, the field behaves according to Hooke’s Law of real-world spring forces.) An object placed at the center of the field and moved away will oscillate around the center, with a period of oscillation that is proportional to the object’s mass. The field’s strength property scales the magnitude of the spring effect—a larger strength simulates a stiffer spring.The default falloffExponent value for a spring field is 1.0, indicating that the field’s effect diminishes linearly with distance from its center.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388134-spring
*/
static spring() {
return null
}
/**
* Creates a field that attracts or repels objects based on their electrical charge and on their distance from the field’s center.
* @access public
* @returns {SCNPhysicsField} -
* @desc Use this field type to make objects behave differently from one another when they enter a region, or to make an object's behavior different from its mass-based behavior. An electric field behaves according to the first part of the Lorentz force equation modeling real-world electromagnetic forces—the field applies a force whose magnitude is proportional to electric charge and distance.By default, physics bodies and particle systems have no electric charge, so they are unaffected by electric and magnetic fields. Use the charge property of a physics body or the particleCharge property of a particle system to add charge-based behavior.When the field’s strength value is positive (the default), it attracts bodies whose charge is negative and repels bodies whose charge is positive. To reverse this behavior, set the field’s strength property to a negative value.The default falloffExponent value for an electric field is 2.0, indicating that the field’s effect diminishes with the square of its distance from its center.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388152-electric
*/
static electric() {
return null
}
/**
* Creates a field that attracts or repels objects based on their electrical charge, velocity, and distance from the field’s axis.
* @access public
* @returns {SCNPhysicsField} -
* @desc Use this field type to make objects behave differently from one another when they enter a region, or to make an object's behavior different from its mass based behavior. A magnetic field behaves according to the second part of the Lorentz force equation modeling real-world electromagnetic forces—the field applies a force determined by the cross product of an object’s velocity vector and the magnetic field vector at the object’s location, with magnitude proportional to the object’s electric charge. By default, physics bodies and particle systems have no electric charge, so they are unaffected by electric and magnetic fields. Use the charge property of a physics body or the particleCharge property of a particle system to add charge-based behavior.When the field’s strength value is positive (the default), the magnetic field vectors circulate counterclockwise relative to the field’s direction vector. (That is, the magnetic field models a real-world magnetic field created by current in a wire oriented in the field’s direction.) To make field vectors circulate clockwise, set the field’s strength property to a negative value.NoteThis SCNPhysicsField option models the real-world physics effect of magnetic fields on moving, electrically charged bodies, not the behavior of permanent magnets or electromagnets. To make objects in your scene simply attract or repel one another, use a different field type. For example, a field created by the radialGravity() method attracts or repels all dynamic bodies near it according to its strength property, and a field created by the electric() method selectively attracts or repels bodies according to their electric charge.The default falloffExponent value for a magnetic field is 2.0, indicating that the field’s effect diminishes with the square of distance from its center.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388168-magnetic
*/
static magnetic() {
return null
}
// Creating Custom Physics Fields
/**
* Creates a field that runs the specified block to determine the force a field applies to each object in its area of effect.
* @access public
* @param {SCNFieldForceEvaluator} block - A block that SceneKit runs for each object in the field’s area of effect. See SCNFieldForceEvaluator.
* @returns {SCNPhysicsField} -
* @desc For custom physics fields, SceneKit ignores the direction, strength, falloffExponent, and minimumDistance properties. Instead, SceneKit calls your block to determine the direction and magnitude of force to apply to each physics body or particle in the field’s area of effect.
* @see https://developer.apple.com/documentation/scenekit/scnphysicsfield/1388140-customfield
*/
static customFieldEvaluationBlock(block) {
return null
}
} |
JavaScript | class DirectoryResource extends implementationOf(SelfCheckingResourceInterface) {
/**
* @param {string} resource The file path to the resource
* @param {null|RegExp} [pattern] A pattern to restrict monitored files
*
* @throws {InvalidArgumentException}
*/
__construct(resource, pattern = null) {
/**
* @type {string|boolean}
*
* @private
*/
this._resource = existsSync(resource) ? realpathSync(resource) : false;
/**
* @type {null|RegExp}
*
* @private
*/
this._pattern = pattern;
if (false === this._resource || ! statSync(this._resource).isDirectory()) {
throw new InvalidArgumentException(__jymfony.sprintf('The directory "%s" does not exist.', resource));
}
}
/**
* @inheritdoc
*/
toString() {
const hash = createHash('md5');
hash.update(__jymfony.serialize([ this._resource, this._pattern ]));
return hash.digest().toString('hex');
}
/**
* @returns {string} The file path to the resource
*/
get resource() {
return this._resource;
}
/**
* Returns the pattern to restrict monitored files.
*
* @returns {string|null}
*/
get pattern() {
return this._pattern;
}
/**
* @inheritdoc
*/
isFresh(timestamp) {
let stat;
try {
stat = statSync(this._resource);
} catch (e) {
return false;
}
if (! stat.isDirectory()) {
return false;
}
if (timestamp < ~~(stat.mtimeMs / 1000)) {
return false;
}
for (const file of new RecursiveDirectoryIterator(this._resource)) {
const stat = statSync(file);
// If regex filtering is enabled only check matching files
if (null !== this._pattern && stat.isFile() && ! basename(file).match(this._pattern)) {
continue;
}
// Always monitor directories for changes, except the .. entries
// (otherwise deleted files wouldn't get detected)
if (stat.isDirectory() && '/..' === file.substr(-3)) {
continue;
}
const fileMTime = ~~(stat.mtimeMs / 1000);
// Early return if a file's mtime exceeds the passed timestamp
if (timestamp < fileMTime) {
return false;
}
}
return true;
}
} |
JavaScript | class TopicDeleteTransaction extends Transaction {
/**
* @param {object} props
* @param {TopicId | string} [props.topicId]
*/
constructor(props = {}) {
super();
/**
* @private
* @type {?TopicId}
*/
this._topicId = null;
if (props.topicId != null) {
this.setTopicId(props.topicId);
}
}
/**
* @internal
* @param {HashgraphProto.proto.ITransaction[]} transactions
* @param {HashgraphProto.proto.ISignedTransaction[]} signedTransactions
* @param {TransactionId[]} transactionIds
* @param {AccountId[]} nodeIds
* @param {HashgraphProto.proto.ITransactionBody[]} bodies
* @returns {TopicDeleteTransaction}
*/
static _fromProtobuf(
transactions,
signedTransactions,
transactionIds,
nodeIds,
bodies
) {
const body = bodies[0];
const topicDelete =
/** @type {HashgraphProto.proto.IConsensusDeleteTopicTransactionBody} */ (
body.consensusDeleteTopic
);
return Transaction._fromProtobufTransactions(
new TopicDeleteTransaction({
topicId:
topicDelete.topicID != null
? TopicId._fromProtobuf(topicDelete.topicID)
: undefined,
}),
transactions,
signedTransactions,
transactionIds,
nodeIds,
bodies
);
}
/**
* @returns {?TopicId}
*/
get topicId() {
return this._topicId;
}
/**
* Set the topic ID which is being deleted in this transaction.
*
* @param {TopicId | string} topicId
* @returns {TopicDeleteTransaction}
*/
setTopicId(topicId) {
this._requireNotFrozen();
this._topicId =
typeof topicId === "string"
? TopicId.fromString(topicId)
: topicId.clone();
return this;
}
/**
* @param {Client} client
*/
_validateChecksums(client) {
if (this._topicId != null) {
this._topicId.validateChecksum(client);
}
}
/**
* @override
* @internal
* @param {Channel} channel
* @param {HashgraphProto.proto.ITransaction} request
* @returns {Promise<HashgraphProto.proto.ITransactionResponse>}
*/
_execute(channel, request) {
return channel.consensus.deleteTopic(request);
}
/**
* @override
* @protected
* @returns {NonNullable<HashgraphProto.proto.TransactionBody["data"]>}
*/
_getTransactionDataCase() {
return "consensusDeleteTopic";
}
/**
* @override
* @protected
* @returns {HashgraphProto.proto.IConsensusDeleteTopicTransactionBody}
*/
_makeTransactionData() {
return {
topicID: this._topicId != null ? this._topicId._toProtobuf() : null,
};
}
/**
* @returns {string}
*/
_getLogId() {
const timestamp = /** @type {import("../Timestamp.js").default} */ (
this._transactionIds.current.validStart
);
return `TopicDeleteTransaction:${timestamp.toString()}`;
}
} |
JavaScript | class SliderControlsPlugin extends Plugin {
/**
* @memberof Vevet.SliderControlsPlugin
* @typedef {object} Properties
* @augments Vevet.Plugin.Properties
*
* @property {boolean} [on=true] - If enabled.
*/
/**
* @alias Vevet.SliderControlsPlugin
*
* @param {Vevet.SliderControlsPlugin.Properties} [data]
*/
constructor(data) {
super(data, false);
}
/**
* @readonly
* @type {Vevet.SliderControlsPlugin.Properties}
*/
get defaultProp() {
return merge(super.defaultProp, {
on: true
});
}
/**
* @member Vevet.SliderControlsPlugin#prop
* @memberof Vevet.SliderControlsPlugin
* @readonly
* @type {Vevet.SliderControlsPlugin.Properties}
*/
/**
* @member Vevet.SliderControlsPlugin#_prop
* @memberof Vevet.SliderControlsPlugin
* @protected
* @type {Vevet.SliderControlsPlugin.Properties}
*/
/**
* @function Vevet.SliderControlsPlugin#changeProp
* @memberof Vevet.SliderControlsPlugin
* @param {Vevet.SliderControlsPlugin.Properties} [prop]
*/
/**
* @member Vevet.SliderControlsPlugin#_m
* @memberof Vevet.SliderControlsPlugin
* @protected
* @type {Vevet.SliderModule}
*/
// Extra Constructor
_extra() {
super._extra();
// get module
let module = this._m,
prefix = module.prefix,
outer = module._outer;
// vars
let controlClass = `${prefix}__control`;
/**
* @description Module events IDs.
* @protected
* @member {Array<string>}
*/
this._me = [];
// create controls
let prev = dom({
selector: 'button',
styles: `${controlClass} ${controlClass}_prev`
});
outer.appendChild(prev);
let next = dom({
selector: 'button',
styles: `${controlClass} ${controlClass}_next`
});
outer.appendChild(next);
/**
* @description Previous control button.
* @protected
* @member {HTMLElement}
*/
this._prev = prev;
/**
* @description Next control button.
* @protected
* @member {HTMLElement}
*/
this._next = next;
// set classes
this._classes();
}
// Set events
_setEvents() {
let module = this._m;
// controls
this.listener(this._prev, 'click', () => {
module.prev('control');
});
this.listener(this._next, 'click', () => {
module.next('control');
});
// events
this._me.push(module.on("changeProp", this._classes.bind(this)));
this._me.push(module.on("show", this._classes.bind(this)));
this._me.push(module.on("hide", this._classes.bind(this)));
this._me.push(module.on("start", this._classes.bind(this)));
}
// When properties are changed.
_changeProp() {
// set classes
this._classes();
}
/**
* @description Set classes.
* @protected
*/
_classes() {
let prop = this._prop,
module = this._m,
outer = module._outer,
prefix = module.prefix,
hiddenClass = `${prefix}_controls-hidden`,
active = module.active,
moduleProp = module.prop,
disabledAttr = "disabled";
// show & hide
if (!prop.on) {
outer.classList.add(hiddenClass);
}
else {
outer.classList.remove(hiddenClass);
}
// if disabled
if ((active === 0 & !moduleProp.loop) || !moduleProp.prev) {
this._prev.setAttribute(disabledAttr, true);
}
else{
this._prev.removeAttribute(disabledAttr);
}
if ((active === (module.total - 1) & !moduleProp.loop) || !moduleProp.next) {
this._next.setAttribute(disabledAttr, true);
}
else{
this._next.removeAttribute(disabledAttr);
}
}
// Destroy events
_destroy() {
super._destroy();
// get module
let module = this._m;
// remove elements
this._prev.remove();
this._next.remove();
// remove events
this._me.forEach(id => {
module.remove(id);
});
}
} |
JavaScript | class ServerQueue {
/**
*
* @param {VoiceChannel} channel
*/
static async create (channel) {
const queue = new ServerQueue();
await queue.setup(channel);
console.log(`Setting server queue for guild ${channel.guild.id} \n`, queue);
serverQueues.set(channel.guild.id, queue);
return queue;
}
/**
*
* @param {VoiceChannel} channel
*/
async setup (channel) {
this.guildId = channel.guild.id;
this.connection = await getConnection(channel);
this.audioPlayer = audioPlayers.get(this.guildId);
this.audioPlayer.on("stateChange", (prev, state) => {
console.log(`Finished audio, changing state from ${prev.status} to ${state.status}`);
if (prev.status == AudioPlayerStatus.Playing && state.status == AudioPlayerStatus.Idle) {
if (this.hasNext()) this.start();
else {
this.playing = false;
this.paused = false;
}
}
});
/**
* @type {ytsr.Item[]}
*/
this.playlist = [];
this.playing = false;
this.paused = false;
/**
* @type {ReadableStream}
*/
this.currentStream = null;
/**
* @type {AudioResource}
*/
this.currentResource = null;
/**
* @type {ytsr.Item}
*/
this.lastPlayed = null;
this.volumePercent = 1.0;
}
getVolumeDecibels () {
return this.currentResource.volume.volumeDecibels;
}
setVolume (percent) {
this.volumePercent = Math.max(Math.min(percent, 4.0), 0.25);
this.currentResource.volume.setVolume(this.volumePercent);
}
async addSong (query) {
if (!query.length) return;
const filters = await ytsr.getFilters(query);
const videoFilter = filters.get("Type").get("Video");
const videoUrl = videoFilter.url;
const searchResults = await ytsr(videoUrl, {
limit: 1
});
if (!searchResults.items.length) return;
const song = searchResults.items[0];
this.playlist.push(song);
return song;
}
hasNext () {
return this.playlist.length > 0;
}
nextSong () {
if (!this.hasNext()) return null;
return this.playlist.shift();
}
clearQueue () {
this.playlist.length = 0;
}
async start () {
const song = this.nextSong();
this.lastPlayed = song;
const url = song.url;
const info = await ytdl.getInfo(url);
console.log(info.formats);
const readStream = ytdl.downloadFromInfo(info, {
highWaterMark: 1 << 25,
filter: format => format.mimeType.startsWith("audio/mp4"),
dlChunkSize: 0,
format: ytdl.chooseFormat(info.formats, { "filter": "audioonly" })
});
// TODO: Stream buffer
const resource = createAudioResource(readStream, {
inlineVolume: true
});
/*
if (this.currentStream) {
await this.currentStream.cancel();
}
*/
this.currentResource = resource;
this.currentResource.volume.setVolume(this.volumePercent);
this.audioPlayer.play(resource);
this.playing = true;
this.currentStream = readStream;
}
pause () {
if (!this.playing) return;
this.audioPlayer.pause();
this.paused = true;
}
unpause () {
if (!this.playing) return;
this.audioPlayer.unpause();
this.paused = false;
}
stop () {
this.paused = false;
this.playing = false;
this.audioPlayer.stop();
}
} |
JavaScript | class Icon extends Element {
constructor(...classNames) {
super('i');
this.addClass(...classNames);
}
} |
JavaScript | class CarStructure {
constructor() {
this.Maximum_Length = 0; // mm
this.Maximum_Width = 0; // mm
this.Curb_Weight = 0; // kg
this.Driver_Included = false; //
this.Luggage_Capacity = 0; // l
if(new.target === CarStructure) {
var msg = "Cannot create an instance of "
+ "an abstract class";
throw new TypeError(msg);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.