language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class MeteorManager {
/**
* @param {MeteorDesktop} $ - context
* @constructor
*/
constructor($) {
this.log = new Log('meteorManager');
this.$ = $;
}
/**
* Looks for specified packages in .meteor/packages. In other words checks if the project has
* specified packages added.
* @param {Array} packages
* @returns {boolean}
*/
checkPackages(packages) {
const usedPackages = fs
.readFileSync(this.$.env.paths.meteorApp.packages, 'UTF-8')
.replace(/\r/gm, '')
.split('\n')
.filter(line => !line.trim().startsWith('#'));
return !packages.some(
packageToFind =>
!usedPackages.some(meteorPackage => ~meteorPackage.indexOf(packageToFind))
);
}
/**
* Looks for specified packages in .meteor/packages. In other words checks if the project has
* specified packages added.
* @param {Array} packages
* @returns {boolean}
*/
checkPackagesVersion(packages) {
const usedPackages = fs.readFileSync(this.$.env.paths.meteorApp.versions, 'UTF-8')
.replace(/\r/gm, '')
.split('\n');
return !packages.some(
packageToFind => !usedPackages.some(meteorPackage => meteorPackage === packageToFind)
);
}
/**
* Ensures certain packages are added to meteor project and in correct version.
* @param {Array} packages
* @param {Array} packagesWithVersion
* @param {string} who - name of the entity that requests presence of thos packages (can be the
* integration itself or a plugin)
* @returns {Promise.<void>}
*/
async ensurePackages(packages, packagesWithVersion, who) {
if (!this.checkPackages(packages)) {
this.log.warn(`${who} requires some packages that are not added to project, will try to add them now`);
try {
await this.addPackages(packages, packagesWithVersion);
} catch (e) {
throw new Error(e);
}
}
if (!this.checkPackagesVersion(packagesWithVersion)) {
this.log.warn(`${who} required packages version is different, fixing it`);
try {
await this.addPackages(packages, packagesWithVersion);
} catch (e) {
throw new Error(e);
}
}
}
/**
* Removes packages from the meteor app.
* @param {Array} packages - array with names of the packages to remove
*/
deletePackages(packages) {
this.log.warn('removing packages from meteor project', ...packages);
return new Promise((resolve, reject) => {
spawn(
'meteor',
['remove'].concat(packages), {
cwd: this.$.env.paths.meteorApp.root,
stdio: ['pipe', 'pipe', process.stderr],
env: Object.assign(
{ METEOR_PRETTY_OUTPUT: 0, METEOR_NO_RELEASE_CHECK: 1 }, process.env
)
}
).on('exit', (code) => {
if (code !== 0 || this.checkPackages(packages)) {
reject('removing packages failed');
} else {
resolve();
}
});
});
}
/**
* Adds packages to the meteor app.
* @param {Array} packages - array with names of the packages to add
* @param {Array} packagesWithVersion - array with names and versions of the packages to add
*/
addPackages(packages, packagesWithVersion) {
this.log.info('adding packages to meteor project', ...packagesWithVersion);
return new Promise((resolve, reject) => {
spawn(
'meteor',
['add'].concat(
packagesWithVersion.map(packageName => packageName.replace('@', '@='))
),
{
cwd: this.$.env.paths.meteorApp.root,
stdio: ['pipe', 'pipe', process.stderr],
env: Object.assign(
{ METEOR_PRETTY_OUTPUT: 0, METEOR_NO_RELEASE_CHECK: 1 }, process.env
)
}
).on('exit', (code) => {
if (code !== 0 || !this.checkPackages(packages)) {
reject('adding packages failed');
} else {
resolve();
}
});
});
}
} |
JavaScript | class Bookings {
/**
* @description Creates the bookings, trips,
* users and buses Model instance
*/
static bookModel() {
return new Model('bookings');
}
static tripModel() {
return new Model('trips');
}
static userModel() {
return new Model('users');
}
static busModel() {
return new Model('buses');
}
/**
* @description Creates a booking on a trip
* @param {object} req request object
* @param {object} res response object
* @returns {object} JSON response
*/
static async bookTrip(req, res) {
let { trip_id, seat_number } = req.body;
const { id, email } = req.user;
trip_id = Number(trip_id);
seat_number = Number(seat_number);
const tripColumns = 'id, bus_id, trip_date';
const bookClause = `WHERE trip_id=${trip_id}`;
const seatClause = `WHERE trip_id=${trip_id} AND seat_number=${seat_number}`;
const mbColumns = 'trip_id, user_id, seat_number';
const mbValues = `${trip_id}, ${id}, ${seat_number}`;
const mbClause = 'RETURNING id, trip_id, user_id, seat_number';
const userColumn = 'first_name, last_name';
try {
// Check if the trip exists
const trip = await Bookings.tripModel().select(tripColumns, `WHERE id=${trip_id}`);
if (!trip[0]) {
return nullResponse(res, 'Trip is unavailable');
}
const { bus_id, trip_date } = trip[0];
const bookExists = await Bookings.bookModel().select('*', bookClause);
const booked = bookExists.find(el => el.user_id === id);
if (booked) {
return conflictResponse(res, 'You have a current booking for this trip');
}
const user = await Bookings.userModel().select(userColumn, `WHERE id=${id}`);
const { first_name, last_name } = user[0];
switch (false) {
case !seat_number: {
const seatExists = await Bookings.bookModel().select('*', seatClause);
if (!booked && seatExists[0]) {
const occupiedSeats = bookExists.map(book => book.seat_number);
const busCap = await Bookings.busModel().select('capacity', `WHERE id=${bus_id}`);
const { capacity } = busCap[0];
const availableSeats = getFreeSeats(occupiedSeats, capacity);
if (availableSeats.length === 0) {
return nullResponse(res, 'All seats on this bus have been occupied');
}
return conflictResponse(res, `Seat is already occupied. Available seat(s): (${availableSeats.join(', ')})`);
}
const booking = await Bookings.bookModel().insert(mbColumns, mbValues, mbClause);
const data = {
id: booking[0].id,
user_id: id,
trip_id,
bus_id,
trip_date,
seat_number,
first_name,
last_name,
email,
};
return successResponse(res, 200, data);
}
default: {
const seats = await Bookings.bookModel().select('seat_number', `WHERE trip_id=${trip_id}`);
seat_number = seats.length + 1;
const defaultValues = `${trip_id}, ${id}, ${seat_number}`;
const booking = await Bookings.bookModel().insert(mbColumns, defaultValues, mbClause);
const data = {
id: booking[0].id,
user_id: id,
trip_id,
bus_id,
trip_date,
seat_number,
first_name,
last_name,
email,
};
return successResponse(res, 200, data);
}
}
} catch (error) {
return internalErrREesponse(res, error.stack);
}
}
/**
* @description Get bookings
* @param {object} req request object
* @param {object} res response object
* @returns {object} JSON response
*/
static async getBookings(req, res) {
const { id, is_admin } = req.user;
const columns = `b.id AS booking_id, trip_id, user_id, seat_number,
bus_id, trip_date, first_name, last_name, email`;
const clause = `b
join trips t ON t.id = trip_id
join users u ON u.id = user_id`;
try {
if (!is_admin) {
const data = await Bookings.bookModel().select(columns, `${clause} WHERE user_id=${id}`);
if (!data[0]) {
return nullResponse(res, 'You have no active bookings');
}
return successResponse(res, 200, data);
}
const data = await Bookings.bookModel().select(columns, clause);
return successResponse(res, 200, data);
} catch (error) {
return internalErrREesponse(res);
}
}
/**
* @description Delete a booking
* @param {object} req request object
* @param {object} res response object
* @returns {object} JSON response
*/
static async deleteBooking(req, res) {
const { booking_id } = req.params;
const { id } = req.user;
const clause = `WHERE id=${booking_id} AND user_id=${id}`;
try {
const data = await Bookings.bookModel().select('*', clause);
if (data[0]) {
await Bookings.bookModel().delete(clause);
return successResponse(res, 200, { message: 'Booking deleted successfully' });
}
return nullResponse(res, 'You have no active booking with that ID');
} catch (error) {
return internalErrREesponse(res);
}
}
/**
* @description Change booked seat
* @param {object} req request object
* @param {object} res response object
* @returns {object} JSON response
*/
static async changeSeat(req, res) {
const { booking_id } = req.params;
const { seat_number } = req.body;
const { id } = req.user;
const column = 'b.id AS booking_id, trip_id, user_id, seat_number, bus_id';
const clause = `b JOIN trips t ON t.id = trip_id
WHERE b.id=${booking_id} AND user_id=${id}`;
const seatClause = `WHERE id=${booking_id} AND user_id=${id}`;
try {
const data = await Bookings.bookModel().select(column, clause);
if (data[0]) {
const { trip_id, bus_id } = data[0];
const trip = await Bookings.bookModel().select('*', `WHERE trip_id=${trip_id}`);
const booked = trip.find(el => el.seat_number === seat_number);
if (booked) {
// Get all already booked seats
const occupiedSeats = trip.map(book => book.seat_number);
// Get the capacity of the bus been used for the trip
const busCap = await Bookings.busModel().select('capacity', `WHERE id=${bus_id}`);
const { capacity } = busCap[0];
// Get the number of free seats left on a bus for a particular trip
const availableSeats = getFreeSeats(occupiedSeats, capacity);
return conflictResponse(res, `Seat is already occupied. Available seat(s): (${availableSeats.join(', ')})`);
}
await Bookings.bookModel().update(`seat_number=${seat_number}`, seatClause);
return successResponse(res, 200, { message: 'Seat number updated successfully' });
}
return nullResponse(res, 'You have no active booking with that ID');
} catch (error) {
return internalErrREesponse(res);
}
}
} |
JavaScript | class EnumItem {
/**
* Public constructor.
*
* @param {number} typeId - Id of the Ignite enum type.
*
* @return {EnumItem} - new EnumItem instance
*
* @throws {IgniteClientError} if error.
*/
constructor(typeId) {
this.setTypeId(typeId);
this._ordinal = null;
this._name = null;
this._value = null;
}
/**
* Returns Id of the Ignite enum type.
*
* @return {number} - Id of the enum type.
*/
getTypeId() {
return this._typeId;
}
/**
* Updates Id of the Ignite enum type.
*
* @param {number} typeId - new Id of the Ignite enum type.
*
* @return {EnumItem} - the same instance of EnumItem
*
* @throws {IgniteClientError} if error.
*/
setTypeId(typeId) {
ArgumentChecker.isInteger(typeId, 'typeId');
this._typeId = typeId;
return this;
}
/**
* Returns ordinal of the item in the Ignite enum type
* or null if ordinal is not set.
*
* @return {number} - ordinal of the item in the Ignite enum type.
*/
getOrdinal() {
return this._ordinal;
}
/**
* Sets or updates ordinal of the item in the Ignite enum type.
*
* @param {number} ordinal - ordinal of the item in the Ignite enum type.
*
* @return {EnumItem} - the same instance of EnumItem
*
* @throws {IgniteClientError} if error.
*/
setOrdinal(ordinal) {
ArgumentChecker.isInteger(ordinal, 'ordinal');
this._ordinal = ordinal;
return this;
}
/**
* Returns name of the item
* or null if name is not set.
*
* @return {string} - name of the item.
*/
getName() {
return this._name;
}
/**
* Sets or updates name of the item.
*
* @param {string} name - name of the item.
*
* @return {EnumItem} - the same instance of EnumItem
*
* @throws {IgniteClientError} if error.
*/
setName(name) {
ArgumentChecker.notEmpty(name, 'name');
this._name = name;
return this;
}
/**
* Returns value of the item
* or null if value is not set.
*
* @return {number} - value of the item.
*/
getValue() {
return this._value;
}
/**
* Sets or updates value of the item.
*
* @param {number} value - value of the item.
*
* @return {EnumItem} - the same instance of EnumItem
*
* @throws {IgniteClientError} if error.
*/
setValue(value) {
ArgumentChecker.isInteger(value, 'value');
this._value = value;
return this;
}
/** Private methods */
/**
* @ignore
*/
async _write(communicator, buffer) {
const type = await this._getType(communicator, this._typeId);
if (!type || !type._isEnum) {
throw Errors.IgniteClientError.enumSerializationError(
true, Util.format('enum type id "%d" is not registered', this._typeId));
}
buffer.writeInteger(this._typeId);
if (this._ordinal !== null) {
buffer.writeInteger(this._ordinal);
return;
}
else if (this._name !== null || this._value !== null) {
if (type._enumValues) {
for (let i = 0; i < type._enumValues.length; i++) {
if (this._name === type._enumValues[i][0] ||
this._value === type._enumValues[i][1]) {
buffer.writeInteger(i);
return;
}
}
}
}
throw Errors.IgniteClientError.illegalArgumentError(
'Proper ordinal, name or value must be specified for EnumItem');
}
/**
* @ignore
*/
async _read(communicator, buffer) {
this._typeId = buffer.readInteger();
this._ordinal = buffer.readInteger();
const type = await this._getType(communicator, this._typeId);
if (!type || !type._isEnum) {
throw Errors.IgniteClientError.enumSerializationError(
false, Util.format('enum type id "%d" is not registered', this._typeId));
}
else if (!type._enumValues || type._enumValues.length <= this._ordinal) {
throw Errors.IgniteClientError.enumSerializationError(false, 'type mismatch');
}
this._name = type._enumValues[this._ordinal][0];
this._value = type._enumValues[this._ordinal][1];
}
/**
* @ignore
*/
async _getType(communicator, typeId) {
return await communicator.typeStorage.getType(typeId);
}
} |
JavaScript | class Static extends _react.Component {
constructor(...args) {
super(...args);
_defineProperty(this, "state", {
lastIndex: null
});
}
render() {
const _this$props = this.props,
{
children
} = _this$props,
otherProps = _objectWithoutProperties(_this$props, ["children"]);
const {
lastIndex
} = this.state;
let newChildren = children;
if (typeof lastIndex === 'number') {
newChildren = childrenToArray(children).slice(lastIndex);
}
return _react.default.createElement("div", {
unstable__static: true,
style: _objectSpread({
position: 'absolute',
flexDirection: 'column'
}, otherProps)
}, newChildren);
}
componentDidMount() {
this.saveLastIndex(this.props.children);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.lastIndex === this.state.lastIndex) {
this.saveLastIndex(this.props.children);
}
}
saveLastIndex(children) {
const nextIndex = childrenToArray(children).length;
if (this.state.lastIndex !== nextIndex) {
this.setState({
lastIndex: nextIndex
});
}
}
} |
JavaScript | class Node {
constructor(data, next) {
this._data = data;
this._next = next;
}
get data() {
return this._data
}
set data(d) {
this._data = d;
}
get next() {
return this._next;
}
set next(next) {
this._next = next
}
} |
JavaScript | class LinkedList {
constructor() {
this._head = null;
}
get head() {
return this._head;
}
printList() {
var current = this._head;
while(current) {
console.log(current.data);
current = current.next;
}
return this;
}
insertAtEnd(node) {
if(this._head === null || this._head === undefined) {
this._head = node;
}
else {
var current = this._head;
while(current.next) {
current = current.next;
}
current.next = node;
}
}
} |
JavaScript | class RuleCsvDeserializer extends CsvDeserializer {
constructor() {
super();
}
parseRow(currentRowIndex, source, columnMap, headerRow, currentRow) {
let SimpleDominantRecessiveMap = [
{ dominant: "Wings", recessive: "No wings", "Q":"W", "q":"w", characterisiticName: {dominant: "wings", recessive: "wingless"}},
{ dominant: "Forelimbs", recessive: "No forelimbs", "Q":"Fl", "q":"fl", characterisiticName: {dominant: "arms", recessive: "armless"}},
{ dominant: "Hindlimbs", recessive: "No hindlimbs", "Q":"Hl", "q":"hl", characterisiticName: {dominant: "legs", recessive: "legless"}},
{ dominant: "Hornless", recessive: "Horns", "Q":"H", "q":"h", characterisiticName: {dominant: "hornless", recessive: "horns"}},
{ dominant: "Metallic", recessive: "Nonmetallic", "Q":"M", "q":"m", characterisiticName: {dominant: "shiny", recessive: "dull"}},
{ dominant: "Colored", recessive: "Albino", "Q":"C", "q":"c", characterisiticName: {dominant: "colored", recessive: "albino"}},
{ dominant: "Gray", recessive: "Orange", "Q":"B", "q":"b", characterisiticName: {dominant: "gray", recessive: "orange"}},
{ dominant: "Deep", recessive: "Faded", "Q":"D", "q":"d", characterisiticName: {dominant: "deep", recessive: "faded"}}
];
let SexLinkedDominantRecessiveMap = [
{ dominant: "Nose spike", recessive: "No nose spike", "Q":"Rh", "q":"rh", characterisiticName: {dominant: "spiked", recessive: "spikeless"}},
];
let isSexLinked = this._isSexLinkedRules(headerRow);
if (this._isDominantRecessiveRule(currentRow)) {
let substitutionMap = (isSexLinked ? SexLinkedDominantRecessiveMap : SimpleDominantRecessiveMap);
var rules = [];
substitutionMap.forEach((traitMap) => {
var clonedRow = currentRow.slice();
var targetCharacterisitic = this._getTraitTarget(traitMap, clonedRow, columnMap, headerRow);
var isTargetTraitDominant = targetCharacterisitic === "dominant";
for (var i = 0; i < clonedRow.length; ++i) {
var columnName = this._getColumnName(columnMap, i);
var value = clonedRow[i];
if (!value) {
continue;
}
if (columnName.includes("trait")) {
if (value.toLowerCase() === "dominant") {
value = traitMap.dominant;
} else if (value.toLowerCase() === "recessive") {
value = traitMap.recessive;
} else {
// Don't change the value since it is a specific trait
}
clonedRow[i] = value;
}
if (columnName.includes("alleles")) {
value = value.replace(/Q/g, traitMap["Q"])
.replace(/q/g, traitMap["q"]);
clonedRow[i] = value;
}
}
rules.push(this._createRule(currentRowIndex, source, columnMap, headerRow, clonedRow));
});
return rules;
} else {
return [
this._createRule(currentRowIndex, source, columnMap, headerRow, currentRow)
];
}
}
_getTraitTarget(traitInfo, row, columnMap, headerRow) {
// The characteristic is specified as target in the rule
var characterisitcColumnName = "target-characteristics";
if (columnMap.hasOwnProperty(characterisitcColumnName)) {
return row[columnMap[characterisitcColumnName]].toLowerCase();
}
//console.warn("Unable to identify characteristic row for Dominant/Recessive generic rule");
// TODO rgtaylor 2018-02-27 Return and gracefully handle null as 'indeterminate' value
// Default to dominant
return "dominant";
}
_createRule(ruleId, source, columnMap, headerRow, currentRow) {
var conditions = [];
conditions = conditions.concat(this._extractConditions("context.target", "target", headerRow, currentRow));
conditions = conditions.concat(this._extractConditions("context.selected","selected", headerRow, currentRow));
conditions = conditions.concat(this._extractConditions("context.previous","previous", headerRow, currentRow));
conditions = conditions.concat(this._extractConditions("context","condition", headerRow, currentRow));
if (conditions.length == 0) {
throw new Error("Missing conditions in CSV. Unable to find columns with condition prefixes: Target-, Selected-, or Condition-");
}
return new GenericRule(
source,
ruleId,
conditions,
this._asBoolean(this._getCell(currentRow, columnMap, "correct", false)),
this._extractConcepts(headerRow, currentRow),
this._extractSubstitutionVariables(headerRow, currentRow));
}
_isBreedingRule(headerRow) {
for (let header of headerRow) {
let columnName = header.toLowerCase();
if (columnName.includes("mother-alleles")
|| columnName.includes("father-alleles")) {
return true;
}
}
return false;
}
_isDominantRecessiveRule(row) {
for (var i = 0; i < row.length; ++i) {
var value = row[i];
if (value) {
value = value.trim().toLowerCase();
if (value === "dominant" || value === "recessive") {
return true;
}
}
}
return false;
}
_isSexLinkedRules(headerRow) {
let targetSex = false;
let targetTrait = false;
for (var i = 0; i < headerRow.length; ++i) {
var value = headerRow[i];
if (value) {
value = value.trim().toLowerCase();
if (value === "target-sex") {
targetSex = true;
}
if (value === "target-trait") {
targetTrait = true;
}
}
}
return targetSex && targetTrait;
}
_extractConditions(basePropertyPath, prefix, headerRow, currentRow) {
let conditions = [];
for (let i = 0; i < headerRow.length; ++i) {
if (this._isColumnOfType(prefix, headerRow[i])) {
let targetValue = currentRow[i].trim();
if (targetValue) {
let columnName = headerRow[i];
let ruleType = this._extractRuleTypeFromColumnName(columnName);
let propertyPath = basePropertyPath + "." + this._extractProprtyPathFromColumnName(columnName);
conditions.push(this._createCondition(ruleType, targetValue, propertyPath, columnName));
}
}
}
return conditions;
}
// Assume last word specifies the type of rule
// E.g., Target-Sex -> Sex
_extractRuleTypeFromColumnName(columnName) {
var columnNameWithoutSibling = columnName.replace(/-Sibling\d+$/, "");
var words = columnNameWithoutSibling.split("-");
return words[words.length - 1];
}
// Assume last word specifies the type of rule
// E.g., Selected-Offspring-Sex -> offspringSex
_extractProprtyPathFromColumnName(columnName) {
let value = columnName.trimThroughFirst("-");
value = value.replace("-", "");
return value.lowerCaseFirstChar();
}
_createCondition(type, value, propertyPath, columnName) {
let displayVariable = columnName.toCamelCase();
// The last word indicates the type of condition (e.g., sex or trait)
let condition = null;
switch(type.toLowerCase()) {
case "alleles":
condition = new RuleCondition.AllelesCondition(propertyPath, value, displayVariable);
break;
case "sex":
condition = new RuleCondition.SexCondition(propertyPath, value, displayVariable);
break;
case "trait":
condition = new RuleCondition.TraitCondition(propertyPath, value, displayVariable);
break;
case "challengeid":
condition = new RuleCondition.StringCondition(propertyPath, value, displayVariable, true);
break;
case "correct":
condition = new RuleCondition.BoolCondition(propertyPath, value, displayVariable);
break;
default:
throw new Error("Unknown RuleCondition type: " + type);
}
return condition;
}
_extractConcepts(headerRow, currentRow) {
var concepts = [];
for (var i = 0; i < headerRow.length; ++i) {
if (this._isConceptId(headerRow[i])) {
var value = currentRow[i].trim();
if (value && this._asBoolean(value) === true) {
var conceptId = this._extractHeadingValue(headerRow[i]);
concepts.push(conceptId);
}
}
}
return concepts;
}
_isConceptId(text) {
return this._isColumnOfType("concept", text);
}
_extractSubstitutionVariables(headerRow, currentRow) {
var variableMap = {};
for (var i = 0; i < headerRow.length; ++i) {
if (this._isSubstitutionVariable(headerRow[i])) {
var value = currentRow[i].trim();
if (value) {
var substitutionVariable = this._extractProprtyPathFromColumnName(headerRow[i]);
variableMap[substitutionVariable] = value;
}
}
}
return variableMap;
}
_isSubstitutionVariable(text) {
return this._isColumnOfType("substitution", text);
}
} |
JavaScript | class Element {
constructor(element){
this.element = create(element);
}
setAttr(name, value){
this.element.setAttribute(name, value);
return this;
}
setClass(classname){
if (typeof(classname) !== "object") return console.warn("type of classname must be object (Array)");
for (const classes of classname) {
this.element.classList.add(classes);
}
return this;
}
insert(...element){
this.element.append(...element);
return this;
}
insertBefore(...element){
this.element.prepend(...element);
return this;
}
insertHTML(element){
this.element.innerHTML = element;
return this;
}
removeAttr(name){
this.element.removeAttribute(name);
return this;
}
removeClass(classname){
this.element.classList.remove(classname);
return this;
}
} |
JavaScript | class Select extends Component {
/**
* List of possible props
* @type {Object}
*/
static propTypes = {
/**
* Select options
* @type {array}
*/
options: PropTypes.arrayOf(
PropTypes.shape({
/**
* ID for the option
* @type {string}
*/
id: PropTypes.string.isRequired,
/**
* Optional text to be displayed as the option text instead of the value
* @type {string}
*/
label: PropTypes.string.isRequired,
/**
* The value for the select field
* @type {string|number}
*/
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
/**
* Flag indicating if a the specific option is disabled
*/
isDisabled: PropTypes.bool,
})
).isRequired,
/**
* ID for the default selected option.
* @type {string|number}
*/
selected: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Flag indicating if the select is in a disabled state
* @type {boolean}
*/
isDisabled: PropTypes.bool,
/**
* Flag indicating if the select is in an error state
*@type {boolean}
*/
isError: PropTypes.bool,
/**
* Optional callback function to trigger after the select value changes
*/
onChange: PropTypes.func,
/**
* ref for the select element
* @type {function | string}
*/
selectRef: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
/**
* Class name for the component
* @type {string | Array}
*/
className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
/**
* The id for the select. This should only be used if the field will be associated with a label
* @type {string}
*/
id: PropTypes.string,
};
/**
* Default prop values
*/
static defaultProps = {
selected: null,
isDisabled: false,
isError: false,
id: null,
onChange: null,
selectRef: null,
};
/**
* Class constructor
* @param {Object} [props] - The component props
*/
constructor(props) {
super(props);
this.state = {
selected: this.getDefaultSelected(this.props.options, this.props.selected),
};
}
/**
* Updates state variables that are initialized based on props if the props change at some point
* @param {Object} nextProps - The upcoming props
*/
componentWillReceiveProps(nextProps) {
const { selected, options } = this.props;
const nextOpts = nextProps.options;
if (selected !== nextProps.selected || !shallowCompareOptionsArray(options, nextOpts)) {
this.setState({
selected: this.getDefaultSelected(nextProps.options, nextProps.selected),
});
}
}
/**
* Finds the default option value for the select
* @param {Array} options - Array of option objects
* @param {string} selected - ID for the selected option
*
* @return {String|null} The id of the selected element or null
*/
getDefaultSelected = (options, selected) => {
let selectedIndex = 0;
options.some((o, i) => {
if (o.id === selected) {
selectedIndex = i;
return true;
}
});
return options[selectedIndex].value;
};
/**
* Updates the state with the currently selected option
* @param {Event} [evt] - The triggered event
*/
updateSelected = evt => {
evt.persist();
this.setState(
{
selected: evt.target.value,
},
() => {
if (this.props.onChange) {
this.props.onChange(evt);
}
}
);
};
/**
* Sanitizes the component props by removing all custom props so the rest can be assigned to the
* input element
*
* @return {Object} - The sanitized props
*/
getProps = () => {
const props = Object.assign({}, this.props);
delete props.options;
delete props.selected;
delete props.isDisabled;
delete props.isError;
delete props.selectRef;
delete props.id;
delete props.onChange;
return props;
};
/**
* The render method for the component
* @return {JSX} The component's markup
*/
render() {
const { className, isDisabled, isError, options, selectRef } = this.props;
const componentClassNames = classNames(
'gooey-select',
{
'gooey-select--disabled': isDisabled,
'gooey-select--error': isError,
},
className
);
const props = this.getProps();
return (
<div className={componentClassNames}>
<select
className="gooey-select__select"
disabled={isDisabled}
onChange={this.updateSelected}
value={this.state.selected}
ref={selectRef}
{...props}
>
{options.map(option => (
<option
key={option.id}
disabled={option.isDisabled || null}
value={option.value}
label={option.label}
className="gooey-select__option"
>
{option.label}
</option>
))}
</select>
</div>
);
}
} |
JavaScript | class NoFilter$5 extends stream$3.Transform {
/**
* Create an instance of NoFilter.
*
* @param {string|Buffer} [input] - Source data
* @param {string} [inputEncoding=null] - Encoding name for input,
* ignored if input is not a String
* @param {Object} [options={}] - Other options
* @param {string|Buffer} [options.input=null] - Input source data
* @param {string} [options.inputEncoding=null] - Encoding name for input,
* ignored if input is not a String
* @param {number} [options.highWaterMark=16384] - The maximum number of bytes
* to store in the internal buffer before ceasing to read from the
* underlying resource. Default=16kb, or 16 for objectMode streams
* @param {string} [options.encoding=null] - If specified, then buffers will
* be decoded to strings using the specified encoding
* @param {boolean} [options.objectMode=false] - Whether this stream should
* behave as a stream of objects. Meaning that stream.read(n) returns a
* single value instead of a Buffer of size n
* @param {boolean} [options.decodeStrings=true] - Whether or not to decode
* strings into Buffers before passing them to _write()
* @param {boolean} [options.watchPipe=true] - Whether to watch for 'pipe'
* events, setting this stream's objectMode based on the objectMode of the
* input stream
* @param {boolean} [options.readError=false] - If true, when a read()
* underflows, throw an error.
*/
constructor(input, inputEncoding, options) {
if (options == null) {
options = {};
}
let inp = null;
let inpE = null;
switch (typeof(input)) {
case 'object':
if (Buffer$8.isBuffer(input)) {
inp = input;
if ((inputEncoding != null) && (typeof(inputEncoding) === 'object')) {
options = inputEncoding;
}
} else {
options = input;
}
break
case 'string':
inp = input;
if ((inputEncoding != null) && (typeof(inputEncoding) === 'object')) {
options = inputEncoding;
} else {
inpE = inputEncoding;
}
break
}
if ((options == null)) {
options = {};
}
if (inp == null) {
inp = options.input;
}
if (inpE == null) {
inpE = options.inputEncoding;
}
delete options.input;
delete options.inputEncoding;
const watchPipe = options.watchPipe != null ? options.watchPipe : true;
delete options.watchPipe;
const readError = !! options.readError;
delete options.readError;
super(options);
this.readError = readError;
if (watchPipe) {
this.on('pipe', readable => {
const om = readable._readableState.objectMode;
if ((this.length > 0) && (om !== this._readableState.objectMode)) {
throw new Error(
'Do not switch objectMode in the middle of the stream'
)
}
this._readableState.objectMode = om;
this._writableState.objectMode = om;
});
}
if (inp != null) {
this.end(inp, inpE);
}
}
/**
* Is the given object a {NoFilter}?
*
* @param {Object} obj The object to test.
* @returns {boolean} true if obj is a NoFilter
*/
static isNoFilter(obj) {
return obj instanceof this
}
/**
* The same as nf1.compare(nf2). Useful for sorting an Array of NoFilters.
*
* @param {NoFilter} nf1 - The first object to compare
* @param {NoFilter} nf2 - The second object to compare
* @returns {number} -1, 0, 1 for less, equal, greater
*
* @example
* const arr = [new NoFilter('1234'), new NoFilter('0123')];
* arr.sort(NoFilter.compare);
*/
static compare(nf1, nf2) {
if (!(nf1 instanceof this)) {
throw new TypeError('Arguments must be NoFilters')
}
if (nf1 === nf2) {
return 0
}
return nf1.compare(nf2)
}
/**
* Returns a buffer which is the result of concatenating all the
* NoFilters in the list together. If the list has no items, or if
* the totalLength is 0, then it returns a zero-length buffer.
*
* If length is not provided, it is read from the buffers in the
* list. However, this adds an additional loop to the function, so
* it is faster to provide the length explicitly if you already know it.
*
* @param {Array<NoFilter>} list Inputs. Must not be all either in object
* mode, or all not in object mode.
* @param {number} [length=null] Number of bytes or objects to read
* @returns {Buffer|Array} The concatenated values as an array if in object
* mode, otherwise a Buffer
*/
static concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
if ((list.length === 0) || (length === 0)) {
return Buffer$8.alloc(0)
}
if ((length == null)) {
length = list.reduce((tot, nf) => {
if (!(nf instanceof NoFilter$5)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
return tot + nf.length
}, 0);
}
let allBufs = true;
let allObjs = true;
const bufs = list.map(nf => {
if (!(nf instanceof NoFilter$5)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
const buf = nf.slice();
if (Buffer$8.isBuffer(buf)) {
allObjs = false;
} else {
allBufs = false;
}
return buf
});
if (allBufs) {
return Buffer$8.concat(bufs, length)
}
if (allObjs) {
return [].concat(...bufs).slice(0, length)
}
// TODO: maybe coalesce buffers, counting bytes, and flatten in arrays
// counting objects? I can't imagine why that would be useful.
throw new Error('Concatenating mixed object and byte streams not supported')
}
/**
* @private
*/
_transform(chunk, encoding, callback) {
if (!this._readableState.objectMode && !Buffer$8.isBuffer(chunk)) {
chunk = Buffer$8.from(chunk, encoding);
}
this.push(chunk);
callback();
}
/**
* @private
*/
_bufArray() {
let bufs = this._readableState.buffer;
// HACK: replace with something else one day. This is what I get for
// relying on internals.
if (!Array.isArray(bufs)) {
let b = bufs.head;
bufs = [];
while (b != null) {
bufs.push(b.data);
b = b.next;
}
}
return bufs
}
/**
* Pulls some data out of the internal buffer and returns it.
* If there is no data available, then it will return null.
*
* If you pass in a size argument, then it will return that many bytes. If
* size bytes are not available, then it will return null, unless we've
* ended, in which case it will return the data remaining in the buffer.
*
* If you do not specify a size argument, then it will return all the data in
* the internal buffer.
*
* @param {number} [size=null] - Number of bytes to read.
* @returns {string|Buffer|null} If no data or not enough data, null. If
* decoding output a string, otherwise a Buffer
* @throws Error - if readError is true and there was underflow
* @fires NoFilter#read
*/
read(size) {
const buf = super.read(size);
if (buf != null) {
/*
* Read event. Fired whenever anything is read from the stream.
*
* @event NoFilter#read
* @type {Buffer|string|Object}
*
*/
this.emit('read', buf);
if (this.readError && (buf.length < size)) {
throw new Error(`Read ${buf.length}, wanted ${size}`)
}
} else if (this.readError) {
throw new Error(`No data available, wanted ${size}`)
}
return buf
}
/**
* Return a promise fulfilled with the full contents, after the 'finish'
* event fires. Errors on the stream cause the promise to be rejected.
*
* @param {function} [cb=null] - finished/error callback used in *addition*
* to the promise
* @returns {Promise<Buffer|String>} fulfilled when complete
*/
promise(cb) {
let done = false;
return new Promise((resolve, reject) => {
this.on('finish', () => {
const data = this.read();
if ((cb != null) && !done) {
done = true;
cb(null, data);
}
resolve(data);
});
this.on('error', er => {
if ((cb != null) && !done) {
done = true;
cb(er);
}
reject(er);
});
})
}
/**
* Returns a number indicating whether this comes before or after or is the
* same as the other NoFilter in sort order.
*
* @param {NoFilter} other - The other object to compare
* @returns {Number} -1, 0, 1 for less, equal, greater
*/
compare(other) {
if (!(other instanceof NoFilter$5)) {
throw new TypeError('Arguments must be NoFilters')
}
if (this === other) {
return 0
}
const buf1 = this.slice();
const buf2 = other.slice();
// these will both be buffers because of the check above.
if (Buffer$8.isBuffer(buf1) && Buffer$8.isBuffer(buf2)) {
return buf1.compare(buf2)
}
throw new Error('Cannot compare streams in object mode')
}
/**
* Do these NoFilter's contain the same bytes? Doesn't work if either is
* in object mode.
*
* @param {NoFilter} other
* @returns {boolean} Equal?
*/
equals(other) {
return this.compare(other) === 0
}
/**
* Read bytes or objects without consuming them. Useful for diagnostics.
* Note: as a side-effect, concatenates multiple writes together into what
* looks like a single write, so that this concat doesn't have to happen
* multiple times when you're futzing with the same NoFilter.
*
* @param {Number} [start=0] - beginning offset
* @param {Number} [end=length] - ending offset
* @returns {Buffer|Array} if in object mode, an array of objects. Otherwise,
* concatenated array of contents.
*/
slice(start, end) {
if (this._readableState.objectMode) {
return this._bufArray().slice(start, end)
}
const bufs = this._bufArray();
switch (bufs.length) {
case 0: return Buffer$8.alloc(0)
case 1: return bufs[0].slice(start, end)
default: {
const b = Buffer$8.concat(bufs);
// TODO: store the concatented bufs back
// @_readableState.buffer = [b]
return b.slice(start, end)
}
}
}
/**
* Get a byte by offset. I didn't want to get into metaprogramming
* to give you the `NoFilter[0]` syntax.
*
* @param {Number} index - The byte to retrieve
* @returns {Number} 0-255
*/
get(index) {
return this.slice()[index]
}
/**
* Return an object compatible with Buffer's toJSON implementation, so
* that round-tripping will produce a Buffer.
*
* @returns {Object}
*
* @example output for 'foo'
* { type: 'Buffer', data: [ 102, 111, 111 ] }
*/
toJSON() {
const b = this.slice();
if (Buffer$8.isBuffer(b)) {
return b.toJSON()
}
return b
}
/**
* Decodes and returns a string from buffer data encoded using the specified
* character set encoding. If encoding is undefined or null, then encoding
* defaults to 'utf8'. The start and end parameters default to 0 and
* NoFilter.length when undefined.
*
* @param {String} [encoding='utf8'] - Which to use for decoding?
* @param {Number} [start=0] - Start offset
* @param {Number} [end=length] - End offset
* @returns {String}
*/
toString(encoding, start, end) {
const buf = this.slice(start, end);
if (!Buffer$8.isBuffer(buf)) {
return JSON.stringify(buf)
}
if (!encoding || (encoding === 'utf8')) {
return td.decode(buf)
}
return buf.toString(encoding, start, end)
}
/**
* @private
* @deprecated
*/
inspect(depth, options) {
return this[customInspect](depth, options)
}
/**
* @private
*/
[customInspect](depth, options) {
const bufs = this._bufArray();
const hex = bufs.map(b => {
if (Buffer$8.isBuffer(b)) {
if ((options != null ? options.stylize : undefined)) {
return options.stylize(b.toString('hex'), 'string')
}
return b.toString('hex')
}
if (util$1) {
return util$1.inspect(b, options)
}
return b.toString()
}).join(', ');
return `${this.constructor.name} [${hex}]`
}
/**
* Current readable length, in bytes.
*
* @member {number}
* @readonly
*/
get length() {
return this._readableState.length
}
/**
* Write a JavaScript BigInt to the stream. Negative numbers will be
* written as their 2's complement version.
*
* @param {bigint} val - The value to write
* @returns {boolean} true on success
*/
writeBigInt(val) {
let str = val.toString(16);
if (val < 0) {
// two's complement
// Note: str always starts with '-' here.
const sz = BigInt(Math.floor(str.length / 2));
const mask = BigInt(1) << (sz * BigInt(8));
val = mask + val;
str = val.toString(16);
}
if (str.length % 2) {
str = '0' + str;
}
return this.push(Buffer$8.from(str, 'hex'))
}
/**
* Read a variable-sized JavaScript unsigned BigInt from the stream.
*
* @param {number} [len=null] - number of bytes to read or all remaining
* if null
* @returns {bigint}
*/
readUBigInt(len) {
const b = this.read(len);
if (!Buffer$8.isBuffer(b)) {
return null
}
return BigInt('0x' + b.toString('hex'))
}
/**
* Read a variable-sized JavaScript signed BigInt from the stream in 2's
* complement format.
*
* @param {number} [len=null] - number of bytes to read or all remaining
* if null
* @returns {bigint}
*/
readBigInt(len) {
const b = this.read(len);
if (!Buffer$8.isBuffer(b)) {
return null
}
let ret = BigInt('0x' + b.toString('hex'));
// negative?
if (b[0] & 0x80) {
// two's complement
const mask = BigInt(1) << (BigInt(b.length) * BigInt(8));
ret = ret - mask;
}
return ret
}
} |
JavaScript | class BinaryParseStream$1 extends TransformStream {
constructor(options) {
super(options);
// doesn't work to pass these in as opts, for some reason
this['_writableState'].objectMode = false;
this['_readableState'].objectMode = true;
this.bs = new NoFilter$4();
this.__restart();
}
_transform(fresh, encoding, cb) {
this.bs.write(fresh);
while (this.bs.length >= this.__needed) {
let ret = null;
const chunk = (this.__needed === null) ?
undefined :
this.bs.read(this.__needed);
try {
ret = this.__parser.next(chunk);
} catch (e) {
return cb(e)
}
if (this.__needed) {
this.__fresh = false;
}
if (!ret.done) {
this.__needed = ret.value || Infinity;
} else {
this.push(ret.value);
this.__restart();
}
}
return cb()
}
/**
* @abstract
* @protected
* @returns {Generator<number, undefined, Buffer>}
*/
/* istanbul ignore next */
*_parse() { // eslint-disable-line class-methods-use-this, require-yield
throw new Error('Must be implemented in subclass')
}
__restart() {
this.__needed = null;
this.__parser = this._parse();
this.__fresh = true;
}
_flush(cb) {
cb(this.__fresh ? null : new Error('unexpected end of input'));
}
} |
JavaScript | class Tagged$1 {
/**
* Creates an instance of Tagged.
*
* @param {number} tag - the number of the tag
* @param {any} value - the value inside the tag
* @param {Error} [err] - the error that was thrown parsing the tag, or null
*/
constructor(tag, value, err) {
this.tag = tag;
this.value = value;
this.err = err;
if (typeof this.tag !== 'number') {
throw new Error('Invalid tag type (' + (typeof this.tag) + ')')
}
if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) {
throw new Error('Tag must be a positive integer: ' + this.tag)
}
}
toJSON() {
if (this[INTERNAL_JSON]) {
return this[INTERNAL_JSON]()
}
const ret = {
tag: this.tag,
value: this.value
};
if (this.err) {
ret.err = this.err;
}
return ret
}
/**
* Convert to a String
*
* @returns {string} string of the form '1(2)'
*/
toString() {
return `${this.tag}(${JSON.stringify(this.value)})`
}
/**
* Push the simple value onto the CBOR stream
*
* @param {Object} gen The generator to push onto
*/
encodeCBOR(gen) {
gen._pushTag(this.tag);
return gen.pushAny(this.value)
}
/**
* If we have a converter for this type, do the conversion. Some converters
* are built-in. Additional ones can be passed in. If you want to remove
* a built-in converter, pass a converter in whose value is 'null' instead
* of a function.
*
* @param {Object} converters - keys in the object are a tag number, the value
* is a function that takes the decoded CBOR and returns a JavaScript value
* of the appropriate type. Throw an exception in the function on errors.
* @returns {any} - the converted item
*/
convert(converters) {
let f = converters != null ? converters[this.tag] : undefined;
if (typeof f !== 'function') {
f = Tagged$1['_tag_' + this.tag];
if (typeof f !== 'function') {
f = TYPED_ARRAY_TAGS[this.tag];
if (typeof f === 'function') {
f = this._toTypedArray;
} else {
return this
}
}
}
try {
return f.call(this, this.value)
} catch (error) {
if (error && error.message && (error.message.length > 0)) {
this.err = error.message;
} else {
this.err = error;
}
return this
}
}
_toTypedArray(val) {
const {tag} = this;
// see https://tools.ietf.org/html/rfc8746
const TypedClass = TYPED_ARRAY_TAGS[tag];
if (!TypedClass) {
throw new Error(`Invalid typed array tag: ${tag}`)
}
const little = tag & 0b00000100;
const float = (tag & 0b00010000) >> 4;
const sz = 2 ** (float + (tag & 0b00000011));
if ((!little !== utils$u.isBigEndian()) && (sz > 1)) {
swapEndian(val.buffer, sz, val.byteOffset, val.byteLength);
}
const ab = val.buffer.slice(val.byteOffset, val.byteOffset + val.byteLength);
return new TypedClass(ab)
}
// Standard date/time string; see Section 3.4.1
static _tag_0(v) {
return new Date(v)
}
// Epoch-based date/time; see Section 3.4.2
static _tag_1(v) {
return new Date(v * 1000)
}
// Positive bignum; see Section 3.4.3
static _tag_2(v) {
// (note: replaced by bigint version in decoder.js when bigint on)
return utils$u.bufferToBignumber(v) // throws if no BigNumber
}
// Negative bignum; see Section 3.4.3
static _tag_3(v) {
// (note: replaced by bigint version in decoder.js when bigint on)
const pos = utils$u.bufferToBignumber(v); // throws if no BigNumber
return constants$6.BN.MINUS_ONE.minus(pos)
}
// Decimal fraction; see Section 3.4.4
static _tag_4(v) {
if (!constants$6.BigNumber) {
throw new Error('No bignumber.js')
}
return new constants$6.BigNumber(v[1]).shiftedBy(v[0])
}
// Bigfloat; see Section 3.4.4
static _tag_5(v) {
if (!constants$6.BigNumber) {
throw new Error('No bignumber.js')
}
return constants$6.BN.TWO.pow(v[0]).times(v[1])
}
// Expected conversion to base64url encoding; see Section 3.4.5.2
static _tag_21(v) {
if (utils$u.isBufferish(v)) {
this[INTERNAL_JSON] = () => utils$u.base64url(v);
} else {
setBuffersToJSON(v, function b64urlThis() { // no =>, honor `this`
// eslint-disable-next-line no-invalid-this
return utils$u.base64url(this)
});
}
return this
}
// Expected conversion to base64 encoding; see Section 3.4.5.2
static _tag_22(v) {
if (utils$u.isBufferish(v)) {
this[INTERNAL_JSON] = () => utils$u.base64(v);
} else {
setBuffersToJSON(v, function b64this() { // no =>, honor `this`
// eslint-disable-next-line no-invalid-this
return utils$u.base64(this)
});
}
return this
}
// Expected conversion to base16 encoding; see Section Section 3.4.5.2
static _tag_23(v) {
if (utils$u.isBufferish(v)) {
this[INTERNAL_JSON] = () => v.toString('hex');
} else {
setBuffersToJSON(v, function hexThis() { // no =>, honor `this`
// eslint-disable-next-line no-invalid-this
return this.toString('hex')
});
}
return this
}
// URI; see Section 3.4.5.3
static _tag_32(v) {
return new URL(v)
}
// base64url; see Section 3.4.5.3
static _tag_33(v) {
// If any of the following apply:
// - the encoded text string contains non-alphabet characters or
// only 1 alphabet character in the last block of 4 (where
// alphabet is defined by Section 5 of [RFC4648] for tag number 33
// and Section 4 of [RFC4648] for tag number 34), or
if (!v.match(/^[a-zA-Z0-9_-]+$/)) {
throw new Error('Invalid base64url characters')
}
const last = v.length % 4;
if (last === 1) {
throw new Error('Invalid base64url length')
}
// - the padding bits in a 2- or 3-character block are not 0, or
if (last === 2) {
// The last 4 bits of the last character need to be zero.
if ('AQgw'.indexOf(v[v.length - 1]) === -1) {
throw new Error('Invalid base64 padding')
}
} else if (last === 3) {
// The last 2 bits of the last character need to be zero.
if ('AEIMQUYcgkosw048'.indexOf(v[v.length - 1]) === -1) {
throw new Error('Invalid base64 padding')
}
}
// or
// - the base64url encoding has padding characters,
// (caught above)
// the string is invalid.
return this
}
// base64; see Section 3.4.5.3
static _tag_34(v) {
// If any of the following apply:
// - the encoded text string contains non-alphabet characters or
// only 1 alphabet character in the last block of 4 (where
// alphabet is defined by Section 5 of [RFC4648] for tag number 33
// and Section 4 of [RFC4648] for tag number 34), or
const m = v.match(/^[a-zA-Z0-9+/]+(={0,2})$/);
if (!m) {
throw new Error('Invalid base64url characters')
}
if ((v.length % 4) !== 0) {
throw new Error('Invalid base64url length')
}
// - the padding bits in a 2- or 3-character block are not 0, or
if (m[1] === '=') {
// The last 4 bits of the last character need to be zero.
if ('AQgw'.indexOf(v[v.length - 2]) === -1) {
throw new Error('Invalid base64 padding')
}
} else if (m[1] === '==') {
// The last 2 bits of the last character need to be zero.
if ('AEIMQUYcgkosw048'.indexOf(v[v.length - 3]) === -1) {
throw new Error('Invalid base64 padding')
}
}
// - the base64 encoding has the wrong number of padding characters,
// (caught above)
// the string is invalid.
return this
}
// Regular expression; see Section 2.4.4.3
static _tag_35(v) {
return new RegExp(v)
}
// https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
static _tag_258(v) {
return new Set(v)
}
} |
JavaScript | class Simple$1 {
/**
* Creates an instance of Simple.
*
* @param {number} value - the simple value's integer value
*/
constructor(value) {
if (typeof value !== 'number') {
throw new Error('Invalid Simple type: ' + (typeof value))
}
if ((value < 0) || (value > 255) || ((value | 0) !== value)) {
throw new Error('value must be a small positive integer: ' + value)
}
this.value = value;
}
/**
* Debug string for simple value
*
* @returns {string} simple(value)
*/
toString() {
return 'simple(' + this.value + ')'
}
/**
* Debug string for simple value (backward-compatibility version)
*
* @returns {string} simple(value)
*/
inspect(depth, opts) {
return 'simple(' + this.value + ')'
}
/**
* Push the simple value onto the CBOR stream
*
* @param {Object} gen The generator to push onto
*/
encodeCBOR(gen) {
return gen._pushInt(this.value, MT$5.SIMPLE_FLOAT)
}
/**
* Is the given object a Simple?
*
* @param {any} obj - object to test
* @returns {boolean} - is it Simple?
*/
static isSimple(obj) {
return obj instanceof Simple$1
}
/**
* Decode from the CBOR additional information into a JavaScript value.
* If the CBOR item has no parent, return a "safe" symbol instead of
* `null` or `undefined`, so that the value can be passed through a
* stream in object mode.
*
* @param {number} val - the CBOR additional info to convert
* @param {boolean} [has_parent=true] - Does the CBOR item have a parent?
* @param {boolean} [parent_indefinite=false] - Is the parent element
* indefinitely encoded?
* @returns {(null|undefined|boolean|Symbol|Simple)} - the decoded value
*/
static decode(val, has_parent = true, parent_indefinite = false) {
switch (val) {
case SIMPLE$1.FALSE:
return false
case SIMPLE$1.TRUE:
return true
case SIMPLE$1.NULL:
if (has_parent) {
return null
}
return SYMS$4.NULL
case SIMPLE$1.UNDEFINED:
if (has_parent) {
return undefined
}
return SYMS$4.UNDEFINED
case -1:
if (!has_parent || !parent_indefinite) {
throw new Error('Invalid BREAK')
}
return SYMS$4.BREAK
default:
return new Simple$1(val)
}
}
} |
JavaScript | class Decoder$2 extends BinaryParseStream {
/**
* Create a parsing stream.
*
* @param {DecoderOptions} [options={}]
*/
constructor(options = {}) {
const {
tags = {},
max_depth = -1,
bigint = true,
preferWeb = false,
required = false,
encoding = 'hex',
extendedResults = false,
...superOpts
} = options;
super({defaultEncoding: encoding, ...superOpts});
this.running = true;
this.max_depth = max_depth;
this.tags = tags;
this.preferWeb = preferWeb;
this.extendedResults = extendedResults;
this.bigint = bigint;
this.required = required;
if (extendedResults) {
this.bs.on('read', this._onRead.bind(this));
this.valueBytes = new NoFilter$3();
}
if (bigint) {
if (this.tags[2] == null) {
this.tags[2] = _tag_2;
}
if (this.tags[3] == null) {
this.tags[3] = _tag_3;
}
}
}
/**
* Check the given value for a symbol encoding a NULL or UNDEFINED value in
* the CBOR stream.
*
* @static
* @param {any} val - the value to check
* @returns {any} the corrected value
*
* @example
* myDecoder.on('data', function(val) {
* val = Decoder.nullcheck(val);
* ...
* });
*/
static nullcheck(val) {
switch (val) {
case SYMS$3.NULL:
return null
case SYMS$3.UNDEFINED:
return undefined
// Leaving this in for now as belt-and-suspenders, but I'm pretty sure
// it can't happen.
/* istanbul ignore next */
case NOT_FOUND:
/* istanbul ignore next */
throw new Error('Value not found')
default:
return val
}
}
/**
* Decode the first CBOR item in the input, synchronously. This will throw
* an exception if the input is not valid CBOR, or if there are more bytes
* left over at the end (if options.extendedResults is not true).
*
* @static
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input - If a Readable stream, must have
* received the `readable` event already, or you will get an error
* claiming "Insufficient data"
* @param {DecoderOptions|string} [options={}] Options or encoding for input
* @returns {any} - the decoded value
*/
static decodeFirstSync(input, options = {}) {
if (input == null) {
throw new TypeError('input required')
}
({options} = normalizeOptions$2(options));
const {encoding = 'hex', ...opts} = options;
const c = new Decoder$2(opts);
const s = utils$t.guessEncoding(input, encoding);
// for/of doesn't work when you need to call next() with a value
// generator created by parser will be "done" after each CBOR entity
// parser will yield numbers of bytes that it wants
const parser = c._parse();
let state = parser.next();
while (!state.done) {
const b = s.read(state.value);
if ((b == null) || (b.length !== state.value)) {
throw new Error('Insufficient data')
}
if (c.extendedResults) {
c.valueBytes.write(b);
}
state = parser.next(b);
}
let val = null;
if (!c.extendedResults) {
val = Decoder$2.nullcheck(state.value);
if (s.length > 0) {
const nextByte = s.read(1);
s.unshift(nextByte);
throw new UnexpectedDataError(nextByte[0], val)
}
} else {
val = state.value;
val.unused = s.read();
}
return val
}
/**
* Decode all of the CBOR items in the input into an array. This will throw
* an exception if the input is not valid CBOR; a zero-length input will
* return an empty array.
*
* @static
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input
* @param {DecoderOptions|string} [options={}] Options or encoding
* for input
* @returns {Array} - Array of all found items
*/
static decodeAllSync(input, options = {}) {
if (input == null) {
throw new TypeError('input required')
}
({options} = normalizeOptions$2(options));
const {encoding = 'hex', ...opts} = options;
const c = new Decoder$2(opts);
const s = utils$t.guessEncoding(input, encoding);
const res = [];
while (s.length > 0) {
const parser = c._parse();
let state = parser.next();
while (!state.done) {
const b = s.read(state.value);
if ((b == null) || (b.length !== state.value)) {
throw new Error('Insufficient data')
}
if (c.extendedResults) {
c.valueBytes.write(b);
}
state = parser.next(b);
}
res.push(Decoder$2.nullcheck(state.value));
}
return res
}
/**
* Decode the first CBOR item in the input. This will error if there are
* more bytes left over at the end (if options.extendedResults is not true),
* and optionally if there were no valid CBOR bytes in the input. Emits the
* {Decoder.NOT_FOUND} Symbol in the callback if no data was found and the
* `required` option is false.
*
* @static
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input
* @param {DecoderOptions|decodeCallback|string} [options={}] - options, the
* callback, or input encoding
* @param {decodeCallback} [cb] callback
* @returns {Promise<any>} returned even if callback is specified
*/
static decodeFirst(input, options = {}, cb = null) {
if (input == null) {
throw new TypeError('input required')
}
({options, cb} = normalizeOptions$2(options, cb));
const {encoding = 'hex', required = false, ...opts} = options;
const c = new Decoder$2(opts);
/** @type {any} */
let v = NOT_FOUND;
const s = utils$t.guessEncoding(input, encoding);
const p = new Promise((resolve, reject) => {
c.on('data', val => {
v = Decoder$2.nullcheck(val);
c.close();
});
c.once('error', er => {
if (c.extendedResults && (er instanceof UnexpectedDataError)) {
v.unused = c.bs.slice();
return resolve(v)
}
if (v !== NOT_FOUND) {
er['value'] = v;
}
v = ERROR;
c.close();
return reject(er)
});
c.once('end', () => {
switch (v) {
case NOT_FOUND:
if (required) {
return reject(new Error('No CBOR found'))
}
return resolve(v)
// Pretty sure this can't happen, but not *certain*.
/* istanbul ignore next */
case ERROR:
/* istanbul ignore next */
return undefined
default:
return resolve(v)
}
});
});
if (typeof cb === 'function') {
p.then(val => cb(null, val), cb);
}
s.pipe(c);
return p
}
/**
* @callback decodeAllCallback
* @param {Error} error - if one was generated
* @param {Array} value - all of the decoded values, wrapped in an Array
*/
/**
* Decode all of the CBOR items in the input. This will error if there are
* more bytes left over at the end.
*
* @static
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input
* @param {DecoderOptions|decodeAllCallback|string} [options={}] -
* Decoding options, the callback, or the input encoding.
* @param {decodeAllCallback} [cb] callback
* @returns {Promise<Array>} even if callback is specified
*/
static decodeAll(input, options = {}, cb = null) {
if (input == null) {
throw new TypeError('input required')
}
({options, cb} = normalizeOptions$2(options, cb));
const {encoding = 'hex', ...opts} = options;
const c = new Decoder$2(opts);
const vals = [];
c.on('data', val => vals.push(Decoder$2.nullcheck(val)));
const p = new Promise((resolve, reject) => {
c.on('error', reject);
c.on('end', () => resolve(vals));
});
if (typeof cb === 'function') {
p.then(v => cb(undefined, v), er => cb(er, undefined));
}
utils$t.guessEncoding(input, encoding).pipe(c);
return p
}
/**
* Stop processing
*/
close() {
this.running = false;
this.__fresh = true;
}
/**
* Only called if extendedResults is true
* @ignore
*/
_onRead(data) {
this.valueBytes.write(data);
}
/**
* @ignore
* @returns {Generator<number, any, Buffer>}
*/
*_parse() {
let parent = null;
let depth = 0;
let val = null;
while (true) {
if ((this.max_depth >= 0) && (depth > this.max_depth)) {
throw new Error('Maximum depth ' + this.max_depth + ' exceeded')
}
const [octet] = yield 1;
if (!this.running) {
this.bs.unshift(Buffer$7.from([octet]));
throw new UnexpectedDataError(octet)
}
const mt = octet >> 5;
const ai = octet & 0x1f;
const parent_major = (parent != null) ? parent[MAJOR] : undefined;
const parent_length = (parent != null) ? parent.length : undefined;
switch (ai) {
case NUMBYTES$2.ONE:
this.emit('more-bytes', mt, 1, parent_major, parent_length)
;[val] = yield 1;
break
case NUMBYTES$2.TWO:
case NUMBYTES$2.FOUR:
case NUMBYTES$2.EIGHT: {
const numbytes = 1 << (ai - 24);
this.emit('more-bytes', mt, numbytes, parent_major, parent_length);
const buf = yield numbytes;
val = (mt === MT$4.SIMPLE_FLOAT) ?
buf :
utils$t.parseCBORint(ai, buf, this.bigint);
break
}
case 28:
case 29:
case 30:
this.running = false;
throw new Error('Additional info not implemented: ' + ai)
case NUMBYTES$2.INDEFINITE:
switch (mt) {
case MT$4.POS_INT:
case MT$4.NEG_INT:
case MT$4.TAG:
throw new Error(`Invalid indefinite encoding for MT ${mt}`)
}
val = -1;
break
default:
val = ai;
}
switch (mt) {
case MT$4.POS_INT:
// val already decoded
break
case MT$4.NEG_INT:
if (val === Number.MAX_SAFE_INTEGER) {
if (this.bigint) {
val = BI$1.NEG_MAX;
} else if (constants$5.BigNumber) {
val = constants$5.BN.NEG_MAX;
} else {
throw new Error('No bigint and no bignumber.js')
}
} else if (constants$5.BigNumber &&
(val instanceof constants$5.BigNumber)) {
val = constants$5.BN.MINUS_ONE.minus(val);
} else {
val = (typeof val === 'bigint') ? BI$1.MINUS_ONE - val : -1 - val;
}
break
case MT$4.BYTE_STRING:
case MT$4.UTF8_STRING:
switch (val) {
case 0:
this.emit('start-string', mt, val, parent_major, parent_length);
if (mt === MT$4.UTF8_STRING) {
val = '';
} else {
val = this.preferWeb ? new Uint8Array(0) : Buffer$7.allocUnsafe(0);
}
break
case -1:
this.emit('start', mt, SYMS$3.STREAM, parent_major, parent_length);
parent = parentBufferStream(parent, mt);
depth++;
continue
default:
this.emit('start-string', mt, val, parent_major, parent_length);
val = yield val;
if (mt === MT$4.UTF8_STRING) {
val = utils$t.utf8(val);
} else if (this.preferWeb) {
val = new Uint8Array(val.buffer, val.byteOffset, val.length);
}
}
break
case MT$4.ARRAY:
case MT$4.MAP:
switch (val) {
case 0:
val = (mt === MT$4.MAP) ? {} : [];
break
case -1:
this.emit('start', mt, SYMS$3.STREAM, parent_major, parent_length);
parent = parentArray(parent, mt, -1);
depth++;
continue
default:
this.emit('start', mt, val, parent_major, parent_length);
parent = parentArray(parent, mt, val * (mt - 3));
depth++;
continue
}
break
case MT$4.TAG:
this.emit('start', mt, val, parent_major, parent_length);
parent = parentArray(parent, mt, 1);
parent.push(val);
depth++;
continue
case MT$4.SIMPLE_FLOAT:
if (typeof val === 'number') {
if ((ai === NUMBYTES$2.ONE) && (val < 32)) {
throw new Error(
`Invalid two-byte encoding of simple value ${val}`
)
}
const hasParent = (parent != null);
val = Simple.decode(
val,
hasParent,
hasParent && (parent[COUNT] < 0)
);
} else {
val = utils$t.parseCBORfloat(val);
}
}
this.emit('value', val, parent_major, parent_length, ai);
let again = false;
while (parent != null) {
switch (false) {
case val !== SYMS$3.BREAK:
parent[COUNT] = 1;
break
case !Array.isArray(parent):
parent.push(val);
break
case !(parent instanceof NoFilter$3): {
const pm = parent[MAJOR];
if ((pm != null) && (pm !== mt)) {
this.running = false;
throw new Error('Invalid major type in indefinite encoding')
}
parent.write(val);
}
}
if ((--parent[COUNT]) !== 0) {
again = true;
break
}
--depth;
delete parent[COUNT];
if (Array.isArray(parent)) {
switch (parent[MAJOR]) {
case MT$4.ARRAY:
val = parent;
break
case MT$4.MAP: {
let allstrings = true;
if ((parent.length % 2) !== 0) {
throw new Error('Invalid map length: ' + parent.length)
}
for (let i = 0, len = parent.length; i < len; i += 2) {
if ((typeof parent[i] !== 'string') ||
(parent[i] === '__proto__')) {
allstrings = false;
break
}
}
if (allstrings) {
val = {};
for (let i = 0, len = parent.length; i < len; i += 2) {
val[parent[i]] = parent[i + 1];
}
} else {
val = new Map();
for (let i = 0, len = parent.length; i < len; i += 2) {
val.set(parent[i], parent[i + 1]);
}
}
break
}
case MT$4.TAG: {
const t = new Tagged(parent[0], parent[1]);
val = t.convert(this.tags);
break
}
}
} else /* istanbul ignore else */ if (parent instanceof NoFilter$3) {
// only parent types are Array and NoFilter for (Array/Map) and
// (bytes/string) respectively.
switch (parent[MAJOR]) {
case MT$4.BYTE_STRING:
val = parent.slice();
if (this.preferWeb) {
val = new Uint8Array(val.buffer, val.byteOffset, val.length);
}
break
case MT$4.UTF8_STRING:
val = parent.toString('utf-8');
break
}
}
this.emit('stop', parent[MAJOR]);
const old = parent;
parent = parent[SYMS$3.PARENT];
delete old[SYMS$3.PARENT];
delete old[MAJOR];
}
if (!again) {
if (this.extendedResults) {
const bytes = this.valueBytes.slice();
const ret = {
value: Decoder$2.nullcheck(val),
bytes,
length: bytes.length
};
this.valueBytes = new NoFilter$3();
return ret
}
return val
}
}
}
} |
JavaScript | class Commented extends stream$2.Transform {
/**
* Create a CBOR commenter.
*
* @param {CommentOptions} [options={}] - Stream options
*/
constructor(options = {}) {
const {
depth = 1,
max_depth = 10,
no_summary = false,
// decoder options
tags = {},
bigint,
preferWeb,
encoding,
// stream.Transform options
...superOpts
} = options;
super({
...superOpts,
readableObjectMode: false,
writableObjectMode: false
});
this.depth = depth;
this.max_depth = max_depth;
this.all = new NoFilter$2();
if (!tags[24]) {
tags[24] = this._tag_24.bind(this);
}
this.parser = new Decoder$1({
tags,
max_depth,
bigint,
preferWeb,
encoding
});
this.parser.on('value', this._on_value.bind(this));
this.parser.on('start', this._on_start.bind(this));
this.parser.on('start-string', this._on_start_string.bind(this));
this.parser.on('stop', this._on_stop.bind(this));
this.parser.on('more-bytes', this._on_more.bind(this));
this.parser.on('error', this._on_error.bind(this));
if (!no_summary) {
this.parser.on('data', this._on_data.bind(this));
}
this.parser.bs.on('read', this._on_read.bind(this));
}
/**
* @private
*/
_tag_24(v) {
const c = new Commented({depth: this.depth + 1, no_summary: true});
c.on('data', b => this.push(b));
c.on('error', er => this.emit('error', er));
c.end(v);
}
_transform(fresh, encoding, cb) {
this.parser.write(fresh, encoding, cb);
}
_flush(cb) {
// TODO: find the test that covers this, and look at the return value
return this.parser._flush(cb)
}
/**
* Comment on an input Buffer or string, creating a string passed to the
* callback. If callback not specified, a promise is returned.
*
* @static
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input
* @param {CommentOptions|commentCallback|string|number} [options={}]
* encoding, max_depth, or callback
* @param {commentCallback} [cb] - called on completion
* @returns {Promise} if cb not specified
*/
static comment(input, options = {}, cb = null) {
if (input == null) {
throw new Error('input required')
}
({options, cb} = normalizeOptions$1(options, cb));
const bs = new NoFilter$2();
const {encoding = 'hex', ...opts} = options;
const d = new Commented(opts);
let p = null;
if (typeof cb === 'function') {
d.on('end', () => {
cb(null, bs.toString('utf8'));
});
d.on('error', cb);
} else {
p = new Promise((resolve, reject) => {
d.on('end', () => {
resolve(bs.toString('utf8'));
});
d.on('error', reject);
});
}
d.pipe(bs);
utils$s.guessEncoding(input, encoding).pipe(d);
return p
}
/**
* @private
*/
_on_error(er) {
this.push('ERROR: ');
this.push(er.toString());
this.push('\n');
}
/**
* @private
*/
_on_read(buf) {
this.all.write(buf);
const hex = buf.toString('hex');
this.push(new Array(this.depth + 1).join(' '));
this.push(hex);
let ind = ((this.max_depth - this.depth) * 2) - hex.length;
if (ind < 1) {
ind = 1;
}
this.push(new Array(ind + 1).join(' '));
return this.push('-- ')
}
/**
* @private
*/
_on_more(mt, len, parent_mt, pos) {
let desc = '';
this.depth++;
switch (mt) {
case MT$3.POS_INT:
desc = 'Positive number,';
break
case MT$3.NEG_INT:
desc = 'Negative number,';
break
case MT$3.ARRAY:
desc = 'Array, length';
break
case MT$3.MAP:
desc = 'Map, count';
break
case MT$3.BYTE_STRING:
desc = 'Bytes, length';
break
case MT$3.UTF8_STRING:
desc = 'String, length';
break
case MT$3.SIMPLE_FLOAT:
if (len === 1) {
desc = 'Simple value,';
} else {
desc = 'Float,';
}
break
}
return this.push(desc + ' next ' + len + ' byte' + (plural(len)) + '\n')
}
/**
* @private
*/
_on_start_string(mt, tag, parent_mt, pos) {
let desc = '';
this.depth++;
switch (mt) {
case MT$3.BYTE_STRING:
desc = 'Bytes, length: ' + tag;
break
case MT$3.UTF8_STRING:
desc = 'String, length: ' + (tag.toString());
break
}
return this.push(desc + '\n')
}
/**
* @private
*/
_on_start(mt, tag, parent_mt, pos) {
this.depth++;
switch (parent_mt) {
case MT$3.ARRAY:
this.push(`[${pos}], `);
break
case MT$3.MAP:
if (pos % 2) {
this.push(`{Val:${Math.floor(pos / 2)}}, `);
} else {
this.push(`{Key:${Math.floor(pos / 2)}}, `);
}
break
}
switch (mt) {
case MT$3.TAG:
this.push(`Tag #${tag}`);
if (tag === 24) {
this.push(' Encoded CBOR data item');
}
break
case MT$3.ARRAY:
if (tag === SYMS$2.STREAM) {
this.push('Array (streaming)');
} else {
this.push(`Array, ${tag} item${plural(tag)}`);
}
break
case MT$3.MAP:
if (tag === SYMS$2.STREAM) {
this.push('Map (streaming)');
} else {
this.push(`Map, ${tag} pair${plural(tag)}`);
}
break
case MT$3.BYTE_STRING:
this.push('Bytes (streaming)');
break
case MT$3.UTF8_STRING:
this.push('String (streaming)');
break
}
return this.push('\n')
}
/**
* @private
*/
_on_stop(mt) {
return this.depth--
}
/**
* @private
*/
_on_value(val, parent_mt, pos, ai) {
if (val !== SYMS$2.BREAK) {
switch (parent_mt) {
case MT$3.ARRAY:
this.push(`[${pos}], `);
break
case MT$3.MAP:
if (pos % 2) {
this.push(`{Val:${Math.floor(pos / 2)}}, `);
} else {
this.push(`{Key:${Math.floor(pos / 2)}}, `);
}
break
}
}
const str = utils$s.cborValueToString(val, -Infinity);
if ((typeof val === 'string') ||
(Buffer$6.isBuffer(val))) {
if (val.length > 0) {
this.push(str);
this.push('\n');
}
this.depth--;
} else {
this.push(str);
this.push('\n');
}
switch (ai) {
case NUMBYTES$1.ONE:
case NUMBYTES$1.TWO:
case NUMBYTES$1.FOUR:
case NUMBYTES$1.EIGHT:
this.depth--;
}
}
/**
* @private
*/
_on_data() {
this.push('0x');
this.push(this.all.read().toString('hex'));
return this.push('\n')
}
} |
JavaScript | class Diagnose extends stream$1.Transform {
/**
* Creates an instance of Diagnose.
*
* @param {DiagnoseOptions} [options={}] - options for creation
*/
constructor(options = {}) {
const {
separator = '\n',
stream_errors = false,
// decoder options
tags,
max_depth,
bigint,
preferWeb,
encoding,
// stream.Transform options
...superOpts
} = options;
super({
...superOpts,
readableObjectMode: false,
writableObjectMode: false
});
this.float_bytes = -1;
this.separator = separator;
this.stream_errors = stream_errors;
this.parser = new Decoder({
tags,
max_depth,
bigint,
preferWeb,
encoding
});
this.parser.on('more-bytes', this._on_more.bind(this));
this.parser.on('value', this._on_value.bind(this));
this.parser.on('start', this._on_start.bind(this));
this.parser.on('stop', this._on_stop.bind(this));
this.parser.on('data', this._on_data.bind(this));
this.parser.on('error', this._on_error.bind(this));
}
_transform(fresh, encoding, cb) {
return this.parser.write(fresh, encoding, cb)
}
_flush(cb) {
return this.parser._flush(er => {
if (this.stream_errors) {
if (er) {
this._on_error(er);
}
return cb()
}
return cb(er)
})
}
/**
* Convenience function to return a string in diagnostic format.
*
* @param {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray
* |DataView|stream.Readable} input - the CBOR bytes to format
* @param {DiagnoseOptions |diagnoseCallback|string} [options={}] -
* options, the callback, or the input encoding
* @param {diagnoseCallback} [cb] - callback
* @returns {Promise} if callback not specified
*/
static diagnose(input, options = {}, cb = null) {
if (input == null) {
throw new Error('input required')
}
({options, cb} = normalizeOptions(options, cb));
const {encoding = 'hex', ...opts} = options;
const bs = new NoFilter$1();
const d = new Diagnose(opts);
let p = null;
if (typeof cb === 'function') {
d.on('end', () => cb(null, bs.toString('utf8')));
d.on('error', cb);
} else {
p = new Promise((resolve, reject) => {
d.on('end', () => resolve(bs.toString('utf8')));
d.on('error', reject);
});
}
d.pipe(bs);
utils$r.guessEncoding(input, encoding).pipe(d);
return p
}
_on_error(er) {
if (this.stream_errors) {
return this.push(er.toString())
}
return this.emit('error', er)
}
_on_more(mt, len, parent_mt, pos) {
if (mt === MT$2.SIMPLE_FLOAT) {
this.float_bytes = {
2: 1,
4: 2,
8: 3
}[len];
}
}
_fore(parent_mt, pos) {
switch (parent_mt) {
case MT$2.BYTE_STRING:
case MT$2.UTF8_STRING:
case MT$2.ARRAY:
if (pos > 0) {
this.push(', ');
}
break
case MT$2.MAP:
if (pos > 0) {
if (pos % 2) {
this.push(': ');
} else {
this.push(', ');
}
}
}
}
_on_value(val, parent_mt, pos) {
if (val === SYMS$1.BREAK) {
return
}
this._fore(parent_mt, pos);
const fb = this.float_bytes;
this.float_bytes = -1;
this.push(utils$r.cborValueToString(val, fb));
}
_on_start(mt, tag, parent_mt, pos) {
this._fore(parent_mt, pos);
switch (mt) {
case MT$2.TAG:
this.push(`${tag}(`);
break
case MT$2.ARRAY:
this.push('[');
break
case MT$2.MAP:
this.push('{');
break
case MT$2.BYTE_STRING:
case MT$2.UTF8_STRING:
this.push('(');
break
}
if (tag === SYMS$1.STREAM) {
this.push('_ ');
}
}
_on_stop(mt) {
switch (mt) {
case MT$2.TAG:
this.push(')');
break
case MT$2.ARRAY:
this.push(']');
break
case MT$2.MAP:
this.push('}');
break
case MT$2.BYTE_STRING:
case MT$2.UTF8_STRING:
this.push(')');
break
}
}
_on_data() {
this.push(this.separator);
}
} |
JavaScript | class Encoder extends stream.Transform {
/**
* Creates an instance of Encoder.
*
* @param {EncodingOptions} [options={}] - options for the encoder
*/
constructor(options = {}) {
const {
canonical = false,
encodeUndefined,
disallowUndefinedKeys = false,
dateType = 'number',
collapseBigIntegers = false,
detectLoops = false,
omitUndefinedProperties = false,
genTypes = [],
...superOpts
} = options;
super({
...superOpts,
readableObjectMode: false,
writableObjectMode: true
});
this.canonical = canonical;
this.encodeUndefined = encodeUndefined;
this.disallowUndefinedKeys = disallowUndefinedKeys;
this.dateType = parseDateType(dateType);
this.collapseBigIntegers = this.canonical ? true : collapseBigIntegers;
this.detectLoops = detectLoops;
if (typeof detectLoops === 'boolean') {
if (detectLoops) {
this.detectLoops = new WeakSet();
}
} else if (!(detectLoops instanceof WeakSet)) {
throw new TypeError('detectLoops must be boolean or WeakSet')
}
this.omitUndefinedProperties = omitUndefinedProperties;
this.semanticTypes = {
Array: this._pushArray,
Date: this._pushDate,
Buffer: this._pushBuffer,
[Buffer$5.name]: this._pushBuffer, // might be mangled
Map: this._pushMap,
NoFilter: this._pushNoFilter,
[NoFilter.name]: this._pushNoFilter, // might be mangled
RegExp: this._pushRegexp,
Set: this._pushSet,
ArrayBuffer: this._pushArrayBuffer,
Uint8ClampedArray: this._pushTypedArray,
Uint8Array: this._pushTypedArray,
Uint16Array: this._pushTypedArray,
Uint32Array: this._pushTypedArray,
Int8Array: this._pushTypedArray,
Int16Array: this._pushTypedArray,
Int32Array: this._pushTypedArray,
Float32Array: this._pushTypedArray,
Float64Array: this._pushTypedArray,
URL: this._pushURL,
Boolean: this._pushBoxed,
Number: this._pushBoxed,
String: this._pushBoxed
};
if (constants$4.BigNumber) {
this.semanticTypes[constants$4.BigNumber.name] = this._pushBigNumber;
}
// Safari needs to get better.
if (typeof BigUint64Array !== 'undefined') {
this.semanticTypes[BigUint64Array.name] = this._pushTypedArray;
}
if (typeof BigInt64Array !== 'undefined') {
this.semanticTypes[BigInt64Array.name] = this._pushTypedArray;
}
if (Array.isArray(genTypes)) {
for (let i = 0, len = genTypes.length; i < len; i += 2) {
this.addSemanticType(genTypes[i], genTypes[i + 1]);
}
} else {
for (const [k, v] of Object.entries(genTypes)) {
this.addSemanticType(k, v);
}
}
}
_transform(fresh, encoding, cb) {
const ret = this.pushAny(fresh);
// Old transformers might not return bool. undefined !== false
return cb((ret === false) ? new Error('Push Error') : undefined)
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_flush(cb) {
return cb()
}
/**
* @callback encodeFunction
* @param {Encoder} encoder - the encoder to serialize into. Call "write"
* on the encoder as needed.
* @return {bool} - true on success, else false
*/
/**
* Add an encoding function to the list of supported semantic types. This is
* useful for objects for which you can't add an encodeCBOR method
*
* @param {any} type
* @param {any} fun
* @returns {encodeFunction}
*/
addSemanticType(type, fun) {
const typeName = (typeof type === 'string') ? type : type.name;
const old = this.semanticTypes[typeName];
if (fun) {
if (typeof fun !== 'function') {
throw new TypeError('fun must be of type function')
}
this.semanticTypes[typeName] = fun;
} else if (old) {
delete this.semanticTypes[typeName];
}
return old
}
_pushUInt8(val) {
const b = Buffer$5.allocUnsafe(1);
b.writeUInt8(val, 0);
return this.push(b)
}
_pushUInt16BE(val) {
const b = Buffer$5.allocUnsafe(2);
b.writeUInt16BE(val, 0);
return this.push(b)
}
_pushUInt32BE(val) {
const b = Buffer$5.allocUnsafe(4);
b.writeUInt32BE(val, 0);
return this.push(b)
}
_pushFloatBE(val) {
const b = Buffer$5.allocUnsafe(4);
b.writeFloatBE(val, 0);
return this.push(b)
}
_pushDoubleBE(val) {
const b = Buffer$5.allocUnsafe(8);
b.writeDoubleBE(val, 0);
return this.push(b)
}
_pushNaN() {
return this.push(BUF_NAN)
}
_pushInfinity(obj) {
const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS;
return this.push(half)
}
_pushFloat(obj) {
if (this.canonical) {
// TODO: is this enough slower to hide behind canonical?
// It's certainly enough of a hack (see utils.parseHalf)
// From section 3.9:
// If a protocol allows for IEEE floats, then additional canonicalization
// rules might need to be added. One example rule might be to have all
// floats start as a 64-bit float, then do a test conversion to a 32-bit
// float; if the result is the same numeric value, use the shorter value
// and repeat the process with a test conversion to a 16-bit float. (This
// rule selects 16-bit float for positive and negative Infinity as well.)
// which seems pretty much backwards to me.
const b2 = Buffer$5.allocUnsafe(2);
if (utils$q.writeHalf(b2, obj)) {
// I have convinced myself that there are no cases where writeHalf
// will return true but `utils.parseHalf(b2) !== obj)`
return this._pushUInt8(HALF) && this.push(b2)
}
}
if (Math.fround(obj) === obj) {
return this._pushUInt8(FLOAT) && this._pushFloatBE(obj)
}
return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj)
}
_pushInt(obj, mt, orig) {
const m = mt << 5;
switch (false) {
case !(obj < 24):
return this._pushUInt8(m | obj)
case !(obj <= 0xff):
return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj)
case !(obj <= 0xffff):
return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj)
case !(obj <= 0xffffffff):
return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj)
case !(obj <= Number.MAX_SAFE_INTEGER):
return this._pushUInt8(m | NUMBYTES.EIGHT) &&
this._pushUInt32BE(Math.floor(obj / SHIFT32)) &&
this._pushUInt32BE(obj % SHIFT32)
default:
if (mt === MT$1.NEG_INT) {
return this._pushFloat(orig)
}
return this._pushFloat(obj)
}
}
_pushIntNum(obj) {
if (Object.is(obj, -0)) {
return this.push(BUF_NEG_ZERO)
}
if (obj < 0) {
return this._pushInt(-obj - 1, MT$1.NEG_INT, obj)
}
return this._pushInt(obj, MT$1.POS_INT)
}
_pushNumber(obj) {
switch (false) {
case !isNaN(obj):
return this._pushNaN()
case isFinite(obj):
return this._pushInfinity(obj)
case Math.round(obj) !== obj:
return this._pushIntNum(obj)
default:
return this._pushFloat(obj)
}
}
_pushString(obj) {
const len = Buffer$5.byteLength(obj, 'utf8');
return this._pushInt(len, MT$1.UTF8_STRING) && this.push(obj, 'utf8')
}
_pushBoolean(obj) {
return this._pushUInt8(obj ? TRUE : FALSE)
}
_pushUndefined(obj) {
switch (typeof this.encodeUndefined) {
case 'undefined':
return this._pushUInt8(UNDEFINED)
case 'function':
return this.pushAny(this.encodeUndefined.call(this, obj))
case 'object': {
const buf = utils$q.bufferishToBuffer(this.encodeUndefined);
if (buf) {
return this.push(buf)
}
}
}
return this.pushAny(this.encodeUndefined)
}
_pushNull(obj) {
return this._pushUInt8(NULL)
}
// TODO: make this static, and not-private
// eslint-disable-next-line class-methods-use-this
_pushArray(gen, obj, opts) {
opts = {
indefinite: false,
...opts
};
const len = obj.length;
if (opts.indefinite) {
if (!gen._pushUInt8((MT$1.ARRAY << 5) | NUMBYTES.INDEFINITE)) {
return false
}
} else if (!gen._pushInt(len, MT$1.ARRAY)) {
return false
}
for (let j = 0; j < len; j++) {
if (!gen.pushAny(obj[j])) {
return false
}
}
if (opts.indefinite) {
if (!gen.push(BREAK)) {
return false
}
}
return true
}
_pushTag(tag) {
return this._pushInt(tag, MT$1.TAG)
}
// TODO: make this static, and consider not-private
// eslint-disable-next-line class-methods-use-this
_pushDate(gen, obj) {
switch (gen.dateType) {
case 'string':
return gen._pushTag(TAG.DATE_STRING) &&
gen._pushString(obj.toISOString())
case 'int':
case 'integer':
return gen._pushTag(TAG.DATE_EPOCH) &&
gen._pushIntNum(Math.round(obj / 1000))
case 'float':
// force float
return gen._pushTag(TAG.DATE_EPOCH) &&
gen._pushFloat(obj / 1000)
case 'number':
default:
// if we happen to have an integral number of seconds,
// use integer. Otherwise, use float.
return gen._pushTag(TAG.DATE_EPOCH) &&
gen.pushAny(obj / 1000)
}
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushBuffer(gen, obj) {
return gen._pushInt(obj.length, MT$1.BYTE_STRING) && gen.push(obj)
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushNoFilter(gen, obj) {
return gen._pushBuffer(gen, obj.slice())
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushRegexp(gen, obj) {
return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source)
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushSet(gen, obj) {
if (!gen._pushTag(TAG.SET)) {
return false
}
if (!gen._pushInt(obj.size, MT$1.ARRAY)) {
return false
}
for (const x of obj) {
if (!gen.pushAny(x)) {
return false
}
}
return true
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushURL(gen, obj) {
return gen._pushTag(TAG.URI) && gen.pushAny(obj.toString())
}
// TODO: make static?
// eslint-disable-next-line class-methods-use-this
_pushBoxed(gen, obj) {
return gen._pushAny(obj.valueOf())
}
/**
* @param {constants.BigNumber} obj
* @private
*/
_pushBigint(obj) {
let m = MT$1.POS_INT;
let tag = TAG.POS_BIGINT;
if (obj.isNegative()) {
obj = obj.negated().minus(1);
m = MT$1.NEG_INT;
tag = TAG.NEG_BIGINT;
}
if (this.collapseBigIntegers &&
obj.lte(constants$4.BN.MAXINT64)) {
// special handiling for 64bits
if (obj.lte(constants$4.BN.MAXINT32)) {
return this._pushInt(obj.toNumber(), m)
}
return this._pushUInt8((m << 5) | NUMBYTES.EIGHT) &&
this._pushUInt32BE(
obj.dividedToIntegerBy(constants$4.BN.SHIFT32).toNumber()
) &&
this._pushUInt32BE(
obj.mod(constants$4.BN.SHIFT32).toNumber()
)
}
let str = obj.toString(16);
if (str.length % 2) {
str = '0' + str;
}
const buf = Buffer$5.from(str, 'hex');
return this._pushTag(tag) && this._pushBuffer(this, buf)
}
/**
* @param {bigint} obj
* @private
*/
_pushJSBigint(obj) {
let m = MT$1.POS_INT;
let tag = TAG.POS_BIGINT;
// BigInt doesn't have -0
if (obj < 0) {
obj = -obj + BI.MINUS_ONE;
m = MT$1.NEG_INT;
tag = TAG.NEG_BIGINT;
}
if (this.collapseBigIntegers &&
(obj <= BI.MAXINT64)) {
// special handiling for 64bits
if (obj <= 0xffffffff) {
return this._pushInt(Number(obj), m)
}
return this._pushUInt8((m << 5) | NUMBYTES.EIGHT) &&
this._pushUInt32BE(Number(obj / BI.SHIFT32)) &&
this._pushUInt32BE(Number(obj % BI.SHIFT32))
}
let str = obj.toString(16);
if (str.length % 2) {
str = '0' + str;
}
const buf = Buffer$5.from(str, 'hex');
return this._pushTag(tag) && this._pushBuffer(this, buf)
}
// TODO: make static
// eslint-disable-next-line class-methods-use-this
_pushBigNumber(gen, obj) {
if (obj.isNaN()) {
return gen._pushNaN()
}
if (!obj.isFinite()) {
return gen._pushInfinity(obj.isNegative() ? -Infinity : Infinity)
}
if (obj.isInteger()) {
return gen._pushBigint(obj)
}
if (!(gen._pushTag(TAG.DECIMAL_FRAC) &&
gen._pushInt(2, MT$1.ARRAY))) {
return false
}
const dec = obj.decimalPlaces();
const slide = obj.shiftedBy(dec);
if (!gen._pushIntNum(-dec)) {
return false
}
if (slide.abs().isLessThan(constants$4.BN.MAXINT)) {
return gen._pushIntNum(slide.toNumber())
}
return gen._pushBigint(slide)
}
// TODO: make static
// eslint-disable-next-line class-methods-use-this
_pushMap(gen, obj, opts) {
opts = {
indefinite: false,
...opts
};
let entries = [...obj.entries()];
if (gen.omitUndefinedProperties) {
entries = entries.filter(([k, v]) => v !== undefined);
}
if (opts.indefinite) {
if (!gen._pushUInt8((MT$1.MAP << 5) | NUMBYTES.INDEFINITE)) {
return false
}
} else if (!gen._pushInt(entries.length, MT$1.MAP)) {
return false
}
// memoizing the cbor only helps in certain cases, and hurts in most
// others. Just avoid it.
if (gen.canonical) {
// keep the key/value pairs together, so we don't have to do odd
// gets with object keys later
const enc = new Encoder({
genTypes: gen.semanticTypes,
canonical: gen.canonical,
detectLoops: !!gen.detectLoops, // give enc its own loop detector
dateType: gen.dateType,
disallowUndefinedKeys: gen.disallowUndefinedKeys,
collapseBigIntegers: gen.collapseBigIntegers
});
const bs = new NoFilter({highWaterMark: gen.readableHighWaterMark});
enc.pipe(bs);
entries.sort(([a], [b]) => {
// a, b are the keys
enc.pushAny(a);
const a_cbor = bs.read();
enc.pushAny(b);
const b_cbor = bs.read();
return a_cbor.compare(b_cbor)
});
for (const [k, v] of entries) {
if (gen.disallowUndefinedKeys && (typeof k === 'undefined')) {
throw new Error('Invalid Map key: undefined')
}
if (!(gen.pushAny(k) && gen.pushAny(v))) {
return false
}
}
} else {
for (const [k, v] of entries) {
if (gen.disallowUndefinedKeys && (typeof k === 'undefined')) {
throw new Error('Invalid Map key: undefined')
}
if (!(gen.pushAny(k) && gen.pushAny(v))) {
return false
}
}
}
if (opts.indefinite) {
if (!gen.push(BREAK)) {
return false
}
}
return true
}
// TODO: make static
// eslint-disable-next-line class-methods-use-this
_pushTypedArray(gen, obj) {
// see https://tools.ietf.org/html/rfc8746
let typ = 0b01000000;
let sz = obj.BYTES_PER_ELEMENT;
const {name} = obj.constructor;
if (name.startsWith('Float')) {
typ |= 0b00010000;
sz /= 2;
} else if (!name.includes('U')) {
typ |= 0b00001000;
}
if (name.includes('Clamped') || ((sz !== 1) && !utils$q.isBigEndian())) {
typ |= 0b00000100;
}
typ |= {
1: 0b00,
2: 0b01,
4: 0b10,
8: 0b11
}[sz];
if (!gen._pushTag(typ)) {
return false
}
return gen._pushBuffer(
gen,
Buffer$5.from(obj.buffer, obj.byteOffset, obj.byteLength)
)
}
// TODO: make static
// eslint-disable-next-line class-methods-use-this
_pushArrayBuffer(gen, obj) {
return gen._pushBuffer(gen, Buffer$5.from(obj))
}
/**
* Remove the loop detector WeakSet for this Encoder.
*
* @returns {boolean} - true when the Encoder was reset, else false
*/
removeLoopDetectors() {
if (!this.detectLoops) {
return false
}
this.detectLoops = new WeakSet();
return true
}
_pushObject(obj, opts) {
if (!obj) {
return this._pushNull(obj)
}
opts = {
indefinite: false,
skipTypes: false,
...opts
};
if (!opts.indefinite) {
// this will only happen the first time through for indefinite encoding
if (this.detectLoops) {
if (this.detectLoops.has(obj)) {
throw new Error(`\
Loop detected while CBOR encoding.
Call removeLoopDetectors before resuming.`)
} else {
this.detectLoops.add(obj);
}
}
}
if (!opts.skipTypes) {
const f = obj.encodeCBOR;
if (typeof f === 'function') {
return f.call(obj, this)
}
const converter = this.semanticTypes[obj.constructor.name];
if (converter) {
return converter.call(obj, this, obj)
}
}
const keys = Object.keys(obj).filter(k => {
const tv = typeof obj[k];
return (tv !== 'function') &&
(!this.omitUndefinedProperties || (tv !== 'undefined'))
});
const cbor_keys = {};
if (this.canonical) {
// note: this can't be a normal sort, because 'b' needs to sort before
// 'aa'
keys.sort((a, b) => {
// Always strings, so don't bother to pass options.
// hold on to the cbor versions, since there's no need
// to encode more than once
const a_cbor = cbor_keys[a] || (cbor_keys[a] = Encoder.encode(a));
const b_cbor = cbor_keys[b] || (cbor_keys[b] = Encoder.encode(b));
return a_cbor.compare(b_cbor)
});
}
if (opts.indefinite) {
if (!this._pushUInt8((MT$1.MAP << 5) | NUMBYTES.INDEFINITE)) {
return false
}
} else if (!this._pushInt(keys.length, MT$1.MAP)) {
return false
}
let ck = null;
for (let j = 0, len2 = keys.length; j < len2; j++) {
const k = keys[j];
if (this.canonical && ((ck = cbor_keys[k]))) {
if (!this.push(ck)) { // already a Buffer
return false
}
} else if (!this._pushString(k)) {
return false
}
if (!this.pushAny(obj[k])) {
return false
}
}
if (opts.indefinite) {
if (!this.push(BREAK)) {
return false
}
} else if (this.detectLoops) {
this.detectLoops.delete(obj);
}
return true
}
/**
* Push any supported type onto the encoded stream
*
* @param {any} obj
* @returns {boolean} true on success
*/
pushAny(obj) {
switch (typeof obj) {
case 'number':
return this._pushNumber(obj)
case 'bigint':
return this._pushJSBigint(obj)
case 'string':
return this._pushString(obj)
case 'boolean':
return this._pushBoolean(obj)
case 'undefined':
return this._pushUndefined(obj)
case 'object':
return this._pushObject(obj)
case 'symbol':
switch (obj) {
case SYMS.NULL:
return this._pushNull(null)
case SYMS.UNDEFINED:
return this._pushUndefined(undefined)
// TODO: Add pluggable support for other symbols
default:
throw new Error('Unknown symbol: ' + obj.toString())
}
default:
throw new Error(
'Unknown type: ' + typeof obj + ', ' +
(!!obj.toString ? obj.toString() : '')
)
}
}
/* backwards-compat wrapper */
_pushAny(obj) {
// TODO: write deprecation warning
return this.pushAny(obj)
}
_encodeAll(objs) {
const bs = new NoFilter({ highWaterMark: this.readableHighWaterMark });
this.pipe(bs);
for (const o of objs) {
this.pushAny(o);
}
this.end();
return bs.read()
}
/**
* Encode the given object with indefinite length. There are apparently
* some (IMO) broken implementations of poorly-specified protocols that
* REQUIRE indefinite-encoding. Add this to an object or class as the
* `encodeCBOR` function to get indefinite encoding:
* @example
* const o = {
* a: true,
* encodeCBOR: cbor.Encoder.encodeIndefinite
* }
* const m = []
* m.encodeCBOR = cbor.Encoder.encodeIndefinite
* cbor.encodeOne([o, m])
*
* @param {Encoder} gen - the encoder to use
* @param {String|Buffer|Array|Map|Object} [obj] - the object to encode. If
* null, use "this" instead.
* @param {EncodingOptions} [options={}] - Options for encoding
* @returns {boolean} - true on success
*/
static encodeIndefinite(gen, obj, options = {}) {
if (obj == null) {
if (this == null) {
throw new Error('No object to encode')
}
obj = this;
}
// TODO: consider other options
const { chunkSize = 4096 } = options;
let ret = true;
const objType = typeof obj;
let buf = null;
if (objType === 'string') {
// TODO: make sure not to split surrogate pairs at the edges of chunks,
// since such half-surrogates cannot be legally encoded as UTF-8.
ret = ret && gen._pushUInt8((MT$1.UTF8_STRING << 5) | NUMBYTES.INDEFINITE);
let offset = 0;
while (offset < obj.length) {
const endIndex = offset + chunkSize;
ret = ret && gen._pushString(obj.slice(offset, endIndex));
offset = endIndex;
}
ret = ret && gen.push(BREAK);
} else if (buf = utils$q.bufferishToBuffer(obj)) {
ret = ret && gen._pushUInt8((MT$1.BYTE_STRING << 5) | NUMBYTES.INDEFINITE);
let offset = 0;
while (offset < buf.length) {
const endIndex = offset + chunkSize;
ret = ret && gen._pushBuffer(gen, buf.slice(offset, endIndex));
offset = endIndex;
}
ret = ret && gen.push(BREAK);
} else if (Array.isArray(obj)) {
ret = ret && gen._pushArray(gen, obj, {
indefinite: true
});
} else if (obj instanceof Map) {
ret = ret && gen._pushMap(gen, obj, {
indefinite: true
});
} else {
if (objType !== 'object') {
throw new Error('Invalid indefinite encoding')
}
ret = ret && gen._pushObject(obj, {
indefinite: true,
skipTypes: true
});
}
return ret
}
/**
* Encode one or more JavaScript objects, and return a Buffer containing the
* CBOR bytes.
*
* @param {...any} objs - the objects to encode
* @returns {Buffer} - the encoded objects
*/
static encode(...objs) {
return new Encoder()._encodeAll(objs)
}
/**
* Encode one or more JavaScript objects canonically (slower!), and return
* a Buffer containing the CBOR bytes.
*
* @param {...any} objs - the objects to encode
* @returns {Buffer} - the encoded objects
*/
static encodeCanonical(...objs) {
return new Encoder({
canonical: true
})._encodeAll(objs)
}
/**
* Encode one JavaScript object using the given options.
*
* @static
* @param {any} obj - the object to encode
* @param {EncodingOptions} [options={}] - passed to the Encoder constructor
* @returns {Buffer} - the encoded objects
*/
static encodeOne(obj, options) {
return new Encoder(options)._encodeAll([obj])
}
/**
* Encode one JavaScript object using the given options in a way that
* is more resilient to objects being larger than the highWaterMark
* number of bytes. As with the other static encode functions, this
* will still use a large amount of memory. Use a stream-based approach
* directly if you need to process large and complicated inputs.
*
* @param {any} obj - the object to encode
* @param {EncodingOptions} [options={}] - passed to the Encoder constructor
*/
static encodeAsync(obj, options) {
return new Promise((resolve, reject) => {
const bufs = [];
const enc = new Encoder(options);
enc.on('data', buf => bufs.push(buf));
enc.on('error', reject);
enc.on('finish', () => resolve(Buffer$5.concat(bufs)));
enc.pushAny(obj);
enc.end();
})
}
} |
JavaScript | class CborMap extends Map {
/**
* Creates an instance of CborMap.
* @param {Iterable<any>} [iterable] An Array or other iterable
* object whose elements are key-value pairs (arrays with two elements, e.g.
* <code>[[ 1, 'one' ],[ 2, 'two' ]]</code>). Each key-value pair is added
* to the new CborMap; null values are treated as undefined.
*/
constructor(iterable) {
super(iterable);
}
/**
* @private
*/
static _encode(key) {
return encoder.encodeCanonical(key).toString('base64')
}
/**
* @private
*/
static _decode(key) {
return decoder.decodeFirstSync(key, 'base64')
}
/**
* Retrieve a specified element.
*
* @param {any} key The key identifying the element to retrieve.
* Can be any type, which will be serialized into CBOR and compared by
* value.
* @returns {any} The element if it exists, or <code>undefined</code>.
*/
get(key) {
return super.get(CborMap._encode(key))
}
/**
* Adds or updates an element with a specified key and value.
*
* @param {any} key The key identifying the element to store.
* Can be any type, which will be serialized into CBOR and compared by
* value.
* @param {any} val The element to store
*/
set(key, val) {
return super.set(CborMap._encode(key), val)
}
/**
* Removes the specified element.
*
* @param {any} key The key identifying the element to delete.
* Can be any type, which will be serialized into CBOR and compared by
* value.
* @returns {boolean}
*/
delete(key) {
return super.delete(CborMap._encode(key))
}
/**
* Does an element with the specified key exist?
*
* @param {any} key The key identifying the element to check.
* Can be any type, which will be serialized into CBOR and compared by
* value.
* @returns {boolean}
*/
has(key) {
return super.has(CborMap._encode(key))
}
/**
* Returns a new Iterator object that contains the keys for each element
* in the Map object in insertion order. The keys are decoded into their
* original format.
*
* @returns {IterableIterator<any>}
*/
*keys() {
for (const k of super.keys()) {
yield CborMap._decode(k);
}
}
/**
* Returns a new Iterator object that contains the [key, value] pairs for
* each element in the Map object in insertion order.
*
* @returns {IterableIterator}
*/
*entries() {
for (const kv of super.entries()) {
yield [CborMap._decode(kv[0]), kv[1]];
}
}
/**
* Returns a new Iterator object that contains the [key, value] pairs for
* each element in the Map object in insertion order.
*
* @returns {IterableIterator}
*/
[Symbol.iterator]() {
return this.entries()
}
/**
* Executes a provided function once per each key/value pair in the Map
* object, in insertion order.
*
* @param {function(any, any, Map): undefined} fun Function to execute for
* each element, which takes a value, a key, and the Map being traversed.
* @param {any} thisArg Value to use as this when executing callback
*/
forEach(fun, thisArg) {
if (typeof(fun) !== 'function') {
throw new TypeError('Must be function')
}
for (const kv of super.entries()) {
fun.call(this, kv[1], CborMap._decode(kv[0]), this);
}
}
/**
* Push the simple value onto the CBOR stream
*
* @param {Object} gen The generator to push onto
* @returns {boolean} true on success
*/
encodeCBOR(gen) {
if (!gen._pushInt(this.size, MT.MAP)) {
return false
}
if (gen.canonical) {
const entries = Array.from(super.entries())
.map(kv => [Buffer$4.from(kv[0], 'base64'), kv[1]]);
entries.sort((a, b) => a[0].compare(b[0]));
for (const kv of entries) {
if (!(gen.push(kv[0]) && gen.pushAny(kv[1]))) {
return false
}
}
} else {
for (const kv of super.entries()) {
if (!(gen.push(Buffer$4.from(kv[0], 'base64')) && gen.pushAny(kv[1]))) {
return false
}
}
}
return true
}
} |
JavaScript | class DivbloxDatabaseConnector {
/**
* Takes the config array (example of which can be seen in test.js) and sets up the relevant connection information
* for later use
* @param {{}} databaseConfig The database configuration object for each module. Each module is a separate
* database. An example is shown below:
* "mainModule": {
"host": "localhost",
"user": "dbuser",
"password": "123",
"database": "local_dx_db",
"port": 3306,
"ssl": false
},
"secondaryModule": {
"host": "localhost",
"user": "dbuser",
"password": "123",
"database": "local_dx_db",
"port": 3306,
"ssl": {
ca: "Contents of __dirname + '/certs/ca.pem'",
key: "Contents of __dirname + '/certs/client-key.pem'",
cert: "Contents of __dirname + '/certs/client-cert.pem'"
}
},
*/
constructor(databaseConfig = {}) {
this.databaseConfig = {};
this.connectionPools = {};
this.errorInfo = [];
this.moduleArray = Object.keys(databaseConfig);
for (const moduleName of this.moduleArray) {
this.databaseConfig[moduleName] = databaseConfig[moduleName];
this.connectionPools[moduleName] = mysql.createPool(databaseConfig[moduleName]);
}
}
/**
* Does all the required work to ensure that database communication is working correctly before continuing
* @returns {Promise<void>}
*/
async init() {
try {
await this.checkDBConnection();
} catch (error) {
this.errorInfo.push("Error checking db connection: "+error);
}
}
/**
* Whenever Divblox encounters an error, the errorInfo array is populated with details about the error. This
* function simply returns that errorInfo array for debugging purposes
* @returns {[]}
*/
getError() {
return this.errorInfo;
}
/**
* Returns a connection from the connection pool
* @param {string} moduleName The name of the module, corresponding to the module defined in dxconfig.json
* @return {Promise<*>}
*/
async getPoolConnection(moduleName) {
return util.promisify(this.connectionPools[moduleName].getConnection)
.call(this.connectionPools[moduleName]);
}
/**
* Connect to a configured database, based on the provided module name
* @param {string} moduleName The name of the module, corresponding to the module defined in dxconfig.json
* @returns {null|{rollback(): any, beginTransaction(): any, query(*=, *=): any, commit(): any, close(): any}|*}
*/
async connectDB(moduleName) {
if (typeof moduleName === undefined) {
this.errorInfo.push("Invalid module name provided");
return null;
}
try {
const connection = await this.getPoolConnection(moduleName);
return {
query(sql, args) {
return util.promisify(connection.query)
.call(connection, sql, args);
},
beginTransaction() {
return util.promisify(connection.beginTransaction)
.call(connection);
},
commit() {
return util.promisify(connection.commit)
.call(connection);
},
rollback() {
return util.promisify(connection.rollback)
.call(connection);
},
close() {
return connection.release();
}
};
} catch (error) {
this.errorInfo.push(error);
return null;
}
}
/**
* Executes a single query on the configured database, based on the provided module name
* @param {string} query The query to execute
* @param {string} moduleName The name of the module, corresponding to the module defined in dxconfig.json
* @param {[]} values Any values to insert into placeholders in sql. If not provided, it is assumed that the query
* can execute as is
* @returns {Promise<{}|null>} Returns null when an error occurs. Call getError() for more information
*/
async queryDB(query, moduleName, values) {
if ((typeof query === undefined)) {
this.errorInfo.push("Invalid query provided");
}
if ((typeof moduleName === undefined)) {
this.errorInfo.push("Invalid module name provided");
}
const database = await this.connectDB(moduleName);
if (database === null) {
return null;
}
let queryResult = {};
try {
queryResult = await database.query(query, values);
} catch (error) {
// handle the error
queryResult = {"error":error};
} finally {
try {
database.close();
} catch (error) {
queryResult = {"error":error};
}
}
return queryResult;
}
/**
* A wrapper for queryDB which takes an array of queries to execute
* @param {[{sql:string,values:[]}]} queryArray The array of queries to execute. Each query is an object
* containing the sql and possible placeholder values to process. If values is not provided, it is assumed that the
* query can execute as is
* @param {string} moduleName The name of the module, corresponding to the module defined in dxconfig.json
* @returns {Promise<{}|null>} Returns null when an error occurs. Call getError() for more information
*/
async queryDBMultiple(queryArray = [], moduleName = null) {
const database = await this.connectDB(moduleName);
if (database === null) {
return null;
}
let queryResult = {};
try {
await queryWithTransaction(database, async () => {
let tempData = [];
for (const query of queryArray) {
tempData.push(await database.query(query.sql, query.values));
}
queryResult = tempData;
} );
} catch (error) {
queryResult = {"error":error};
}
return queryResult;
}
/**
* Allows for executing a group of queries with potential rollback support
* @param {*} database The local database instance
* @param {function} callback The function called on completion
* @returns {Promise<null>} Returns null when an error occurs. Call getError() for more information
*/
async queryWithTransaction(database, callback) {
if (database === null) {
this.errorInfo.push("Tried to call queryWithTransaction, but database was NULL");
return null;
}
try {
await database.beginTransaction();
await callback();
await database.commit();
} catch (error) {
await database.rollback();
throw error;
} finally {
database.close();
}
}
/**
* Simply checks whether we can connect to the relevant database for each defined module
* @returns {Promise<boolean>}
*/
async checkDBConnection() {
for (const moduleName of this.moduleArray) {
try {
const database = await this.connectDB(moduleName);
if (database === null) {
throw new Error("Error connecting to database: "+JSON.stringify(this.getError(),null,2));
}
database.close();
} catch (error) {
throw new Error("Error connecting to database: "+error);
}
}
return true;
}
} |
JavaScript | class Persons extends PureComponent {
// static getDerivedStateFromProps(props, state){
// console.log('[Persons.js] getDerivedStateFromProps');
// return state;
// }
// shouldComponentUpdate(nextProps, nextState){
// console.log('[Persons.js] shouldComponentUpdate');
// if(nextProps.persons !== this.props.persons){
// return true;
// } else {
// return false;
// }
// }
getSnapshotBeforeUpdate(prevProps, prevState){
console.log('[Persons.js] getSnapshotBeforeUpdate');
return { message: 'Snapshot!!'};
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log('[Persons.js] componentDidUpdate');
console.log(snapshot);
}
/*For operations like cleanup that we need to execute before destroy or unmount
a component, we have componentWillUnmount in class-based components*/
componentWillUnmount(){
console.log('[App.js] componentWillUnmount');
}
render(){
return this.props.persons.map((person, index) => {
console.log('rendering...');
return <Person
click={() => this.props.clicked(index)}
name={person.name}
age={person.age}
key={person.id}
changed = {(event) => this.props.changed(event, person.id)}
isAuth={this.props.isAuthenticated}/>
});
}
} |
JavaScript | class NeDBManager {
/**
* NeDBManager constructor
* @param {Object} options The options as a JSON object.
* @constructor
*/
constructor(options) {
options = options || {};
let filename = DEFAULT_DATA_FOLDER + '/' + DEFAULT_STORY_DB;
this.database = new nedb({ filename: filename, autoload: true });
}
/**
* Insert a document in the database.
* @param {Object} doc The document to insert.
* @param {function} callback Function to call on completion.
*/
insert(doc, callback) {
this.database.insert(doc, callback);
}
/**
* Find all documents that match the query in the database, observing the
* given projection.
* @param {Object} query The database query.
* @param {Object} projection The projection to observe.
* @param {function} callback Function to call on completion.
*/
find(query, projection, callback) {
this.database.find(query, projection, callback);
}
/**
* Update all documents that match the query in the database.
* @param {Object} query The database query.
* @param {Object} update The update to apply.
* @param {Object} options The update options.
* @param {function} callback Function to call on completion.
*/
update(query, update, options, callback) {
this.database.update(query, update, options, callback);
}
/**
* Remove all documents that match the query in the database.
* @param {Object} query The database query.
* @param {Object} options The removal options.
* @param {function} callback Function to call on completion.
*/
remove(query, options, callback) {
this.database.remove(query, options, callback);
}
} |
JavaScript | class OAuth2Server extends HttpServer {
/**
* Creates a new instance of OAuth2Server.
*/
constructor() {
const iss = new OAuth2Issuer();
const serv = new OAuth2Service(iss);
super(serv.requestHandler);
this[issuer] = iss;
this[service] = serv;
}
/**
* Returns the OAuth2Issuer instance used by the server.
* @type {OAuth2Issuer}
*/
get issuer() {
return this[issuer];
}
/**
* Returns the OAuth2Service instance used by the server.
* @type {OAuth2Service}
*/
get service() {
return this[service];
}
/**
* Returns a value indicating whether or not the server is listening for connections.
* @type {Boolean}
*/
get listening() {
return super.listening;
}
/**
* Returns the bound address, family name and port where the server is listening,
* or null if the server has not been started.
* @returns {AddressInfo} The server bound address information.
*/
address() {
return super.address();
}
/**
* Starts the server.
* @param {Number} [port] Port number. If omitted, it will be assigned by the operating system.
* @param {String} [host] Host name.
* @returns {Promise<void>} A promise that resolves when the server has been started.
*/
async start(port, host) {
await super.start(port, host);
/* istanbul ignore else */
if (!this.issuer.url) {
this.issuer.url = buildIssuerUrl(host, this.address().port);
}
}
/**
* Stops the server.
* @returns {Promise} Resolves when the server has been stopped.
*/
async stop() {
await super.stop();
this[issuer].url = null;
}
} |
JavaScript | class Threat {
static get TYPE_ENEMY() {
return 'enemy';
}
static get TYPE_ASTEROID() {
return 'asteroid';
}
static get TYPE_LEECH() {
return 'leech';
}
static get TYPE_BLACKHOLE() {
return 'blackhole';
}
get X() {
return this.sprite.position.x;
}
get Y() {
return this.sprite.position.y;
}
set X(val) {
this.sprite.position.x = val;
}
set Y(val) {
this.sprite.position.y = val;
}
get complete() {
return this.requirements && this.requirements.length === 0;
}
get expired() {
return this.remainingTime <= 0;
}
get elapsedTime() {
return Date.now() - this._startTime;
}
get remainingTime() {
return this._duration - this.elapsedTime;
}
get remainingSeconds() {
return (this.remainingTime / 1000.0).toFixed(1);
}
static sortFn(left, right) {
if (left.remainingTime < right.remainingTime) {
return -1;
}
if (left.remainingTime > right.remainingTime) {
return 1;
}
return 0;
}
constructor(type) {
if (!threatGroupMidnight) {
threatGroupMidnight = game.add.group();
threatGroupMidnight.position.set(5, 5);
threatGroupMidnight.fixedToCamera = true;
HUDGROUP.add(threatGroupMidnight);
}
this.type = type;
this._group = game.add.group();
this.sprite = this._group.create(0, 0, 'threats');
this.sprite.animations.add('base', Threat.getFrames(type), 4, true);
this.sprite.play('base');
this.text = game.add.bitmapText(this.sprite.right + 1, this._group.y + 1, 'visitor', this.type, 8);
this.text.alpha = 0.15;
this._group.add(this.text);
threatGroupMidnight.add(this._group);
this.requirements = this.makeRequirements();
// in milliseconds
this._duration = this.makeDuration();
this.bones = this.calculateBones();
this.damage = this.calculateDamage();
console.log(`Created new threat of type ${type} with ${this.damage} damage / ${this.bones} bones`)
this._startTime = Date.now();
this.signals = {
complete: new Phaser.Signal(),
expired: new Phaser.Signal(),
};
}
acceptStationInput(stationType) {
const stationStr = getStationStr(stationType);
const idx = this.requirements.indexOf(stationType);
if (idx !== -1) {
this.requirements.splice(idx);
console.log(`Removed ${stationStr} from ${this.type}`);
} else {
console.log(`Not accepting inputs from ${stationStr} from ${this.type}`);
}
return idx !== -1;
}
update() {
if (this.elapsedTime > this.remainingTime * 2) {
this.sprite.animations.currentAnim.speed = 12;
} else if (this.elapsedTime > this.remainingTime) {
this.sprite.animations.currentAnim.speed = 8;
}
if (this.complete) {
this.signals.complete.dispatch(this);
} else if (this.expired) {
this.signals.expired.dispatch(this);
}
}
render() {}
makeRequirements() {
throw new Error('Not Implemented');
}
makeDuration() {
throw new Error('Not Implemented');
}
calculateBones() {
throw new Error('Not Implemented');
}
calculateDamage() {
throw new Error('Not Implemented');
}
static getFrames(type) {
switch (type) {
case Threat.TYPE_ENEMY:
return [0, 1, 2, 3];
case Threat.TYPE_ASTEROID:
return [4, 5, 6, 7];
case Threat.TYPE_LEECH:
return [8, 9, 10, 11];
case Threat.TYPE_BLACKHOLE:
return [12, 13, 14, 15];
}
console.error(`Type ${type} not accounted for in getFrames`);
return [];
}
static randomThreat() {
const _threats = [
Threat.TYPE_ASTEROID,
Threat.TYPE_ENEMY,
Threat.TYPE_LEECH,
Threat.TYPE_BLACKHOLE,
];
const randIdx = Math.floor(Math.random() * _threats.length);
return _threats[randIdx];
}
static makeThreat(type = undefined) {
if (!type) {
type = Threat.randomThreat();
}
let result;
switch (type) {
case Threat.TYPE_ASTEROID:
result = new AsteroidThreat();
break;
case Threat.TYPE_ENEMY:
result = new EnemyThreat();
break;
case Threat.TYPE_LEECH:
result = new LeechThreat();
break;
case Threat.TYPE_BLACKHOLE:
result = new BlackHoleThreat();
break;
default:
console.warn(`Attempted to make threat of type ${type} and did not`);
}
return result;
}
destroy() {
this._group.destroy();
}
resolve() {
if (this.complete) {
this.text.tint = TINT_SUCCESS;
const tween = game.add.tween(this._group).to({
y: this.sprite.y - 20,
},
TWEENS.THREAT_FAILURE,
Phaser.Easing.Default,
true);
tween.onComplete.add(() => {
this.destroy();
}, this);
} else if (this.expired) { // failed
this.text.tint = TINT_FAILURE;
game.camera.shake(0.001, 150, 0.001);
game.camera.flash(0xff0000, 150, 0.001, 0.2);
const tween = game.add.tween(this._group).to({
y: this.sprite.y - 20,
},
TWEENS.THREAT_FAILURE,
Phaser.Easing.Default,
true);
tween.onComplete.add(() => {
this.destroy();
}, this);
}
}
} |
JavaScript | class QueuesService extends Service {
/**
* Shifts the first two players from the queue.
* @todo refactor using redis
* @param {object} query query object
* @return {Promise<Object|undefined>} the first player or undefined
*/
async shiftTwo() {
const { data } = await super.find({
$limit: 2,
$sort: {
id: 1
}
});
const enoughPlayers = this._shiftPlayers(data);
return enoughPlayers ? data : [];
}
/**
* Shifts the first two players.
* @param {Array<Object>} data array of first two players on queue
* @return {Boolean}
*/
_shiftPlayers(data) {
if (data.length === 2) {
super.remove(data[0].id);
super.remove(data[1].id);
return true;
}
return false;
}
} |
JavaScript | class AddItemScreen {
constructor(rl, state) {
this.rl = rl;
this.state = state;
}
printChoiceUi() {
console.clear();
console.log("********************************************");
console.log("* CREATE AN ITEM (c) 1987 *");
console.log("********************************************");
console.log();
console.log("What kind of to-do item do you want to");
console.log("create?");
console.log();
console.log("1. Note");
console.log("2. Task");
console.log();
console.log('Type the number and hit "Enter".');
console.log();
}
printNoteUi() {
console.clear();
console.log("********************************************");
console.log("* CREATE A NOTE (c) 1987 *");
console.log("********************************************");
console.log();
console.log('(Type your text and hit "Enter" to return to');
console.log("the to-do list screen, 300 characters max.)");
console.log();
console.log("What is the note?");
console.log();
}
printTaskUi1() {
console.clear();
console.log("********************************************");
console.log("* CREATE A TASK (c) 1987 *");
console.log("********************************************");
console.log();
console.log("What is the title?");
console.log();
}
printTaskUi2(title) {
console.clear();
console.log("********************************************");
console.log("* CREATE A TASK (c) 1987 *");
console.log("********************************************");
console.log();
console.log(`TITLE: ${title}`);
console.log();
console.log("What is the category?");
console.log();
for (let i = 0; i < this.state.getCategoryCount(); i += 1) {
console.log(`${i + 1}. ${this.state.getCategoryByIndex(i)}`);
}
console.log();
}
printTaskUi3(title, categoryIndex) {
console.clear();
console.log("********************************************");
console.log("* CREATE A TASK (c) 1987 *");
console.log("********************************************");
console.log();
console.log(`TITLE: ${title}`);
console.log(`CATEGORY: ${this.state.getCategoryByIndex(categoryIndex)}`);
console.log();
console.log('(Type your text and hit "Enter" to return to');
console.log("the to-do list screen, 300 characters max.)");
console.log();
console.log("What is the description?");
console.log();
}
show() {
this.printChoiceUi();
this.rl.question("> ", (answer) => {
if (answer === "1") {
this.printNoteUi();
this.rl.question("> ", (answer) => {
this.state.addNote(answer);
this.state.save();
const screen = new ManageTasksScreen(this.rl, this.state);
screen.show();
});
} else if (answer === "2") {
this.printTaskUi1();
this.rl.question("> ", (title) => {
this.printTaskUi2(title);
this.rl.question("> ", (categoryIndex) => {
categoryIndex = Number.parseInt(categoryIndex) - 1;
this.printTaskUi3(title, categoryIndex);
this.rl.question("> ", (description) => {
this.state.addTask(title, description, categoryIndex);
this.state.save();
const screen = new ManageTasksScreen(this.rl, this.state);
screen.show();
});
});
});
} else {
this.show();
}
});
}
} |
JavaScript | class ManualBackupStep3 extends PureComponent {
static navigationOptions = ({ navigation }) => getTransparentOnboardingNavbarOptions(navigation);
constructor(props) {
super(props);
this.steps = props.route.params?.steps;
}
state = {
currentStep: 4,
showHint: false,
hintText: '',
};
static propTypes = {
/**
/* navigation object required to push and pop other views
*/
navigation: PropTypes.object,
/**
* Object that represents the current route info like params passed to it
*/
route: PropTypes.object,
};
componentWillUnmount = () => {
BackHandler.removeEventListener(HARDWARE_BACK_PRESS, hardwareBackPress);
};
componentDidMount = async () => {
const currentSeedphraseHints = await AsyncStorage.getItem(SEED_PHRASE_HINTS);
const parsedHints = currentSeedphraseHints && JSON.parse(currentSeedphraseHints);
const manualBackup = parsedHints?.manualBackup;
this.setState({
hintText: manualBackup,
});
BackHandler.addEventListener(HARDWARE_BACK_PRESS, hardwareBackPress);
};
toggleHint = () => {
this.setState((state) => ({ showHint: !state.showHint }));
};
learnMore = () =>
this.props.navigation.navigate('Webview', {
screen: 'SimpleWebview',
params: {
url: 'https://support.metamask.io',
title: strings('drawer.metamask_support'),
},
});
isHintSeedPhrase = (hintText) => {
const words = this.props.route.params?.words;
if (words) {
const lower = (string) => String(string).toLowerCase();
return lower(hintText) === lower(words.join(' '));
}
return false;
};
saveHint = async () => {
const { hintText } = this.state;
if (!hintText) return;
if (this.isHintSeedPhrase(hintText)) {
Alert.alert('Error!', strings('manual_backup_step_3.no_seedphrase'));
return;
}
this.toggleHint();
const currentSeedphraseHints = await AsyncStorage.getItem(SEED_PHRASE_HINTS);
const parsedHints = JSON.parse(currentSeedphraseHints);
await AsyncStorage.setItem(SEED_PHRASE_HINTS, JSON.stringify({ ...parsedHints, manualBackup: hintText }));
};
done = async () => {
const onboardingWizard = await DefaultPreference.get(ONBOARDING_WIZARD);
// Check if user passed through metrics opt-in screen
const metricsOptIn = await DefaultPreference.get(METRICS_OPT_IN);
if (!metricsOptIn) {
this.props.navigation.navigate('OptinMetrics');
} else if (onboardingWizard) {
this.props.navigation.reset({ routes: [{ name: 'HomeNav' }] });
} else {
this.props.navigation.reset({ routes: [{ name: 'HomeNav' }] });
}
};
handleChangeText = (text) => this.setState({ hintText: text });
renderHint = () => {
const { showHint, hintText } = this.state;
return (
<HintModal
onConfirm={this.saveHint}
onCancel={this.toggleHint}
modalVisible={showHint}
onRequestClose={Keyboard.dismiss}
value={hintText}
onChangeText={this.handleChangeText}
/>
);
};
render() {
return (
<View style={styles.mainWrapper}>
<Confetti />
{this.steps ? (
<View style={styles.onBoardingWrapper}>
<OnboardingProgress currentStep={this.state.currentStep} steps={this.steps} />
</View>
) : null}
<ActionView
confirmTestID={'manual-backup-step-3-done-button'}
confirmText={strings('manual_backup_step_3.done')}
onConfirmPress={this.done}
showCancelButton={false}
confirmButtonMode={'confirm'}
style={styles.actionView}
>
<View style={styles.wrapper} testID={'import-congrats-screen'}>
<Emoji name="tada" style={styles.emoji} />
<Text style={styles.congratulations}>{strings('manual_backup_step_3.congratulations')}</Text>
<Text style={[styles.baseText, styles.successText]}>
{strings('manual_backup_step_3.success')}
</Text>
<TouchableOpacity onPress={this.toggleHint}>
<Text style={[styles.baseText, styles.hintText]}>
{strings('manual_backup_step_3.hint')}
</Text>
</TouchableOpacity>
<Text style={[styles.baseText, styles.recoverText]}>
{strings('manual_backup_step_3.recover')}
</Text>
<TouchableOpacity onPress={this.learnMore}>
<Text style={[styles.baseText, styles.learnText]}>
{strings('manual_backup_step_3.learn')}
</Text>
</TouchableOpacity>
</View>
</ActionView>
{Device.isAndroid() && <AndroidBackHandler customBackPress={this.props.navigation.pop} />}
{this.renderHint()}
</View>
);
}
} |
JavaScript | class Colorizer extends Component {
static get displayName() { return "Default"; }
static get description() {
return "Doesn't apply any coloration to points";
}
apply(context, vertex) { return vertex; }
reset() { }
} |
JavaScript | class SemanticChess {
/**
* @param {Object} options: options to initialize the chess game
* @param {null|string} options.chess: Chess game from chess.js
* @param {null|string} options.startPosition: start position of the game, using FEN
* @param {string} options.url: url that represents the game
* @param {string} options.userWebId: WebId of the user
* @param {string} options.opponentWebId: WebId of the opponent
* @param {string|function(): string} options.moveBaseUrl: base url used to create urls for new moves
* @param {null|string} options.name: name of the game
* @param {null|Object} options.lastMove: latest move made in the game
* @param {null|Object} options.lastUserMove: last move made by the use in the game
* @param {null|string} options.colorOfUser: color of the user ('w' or 'b', default is 'w')
* @param {null|function()} options.uniqid: function that will return a unique id for the moves
* @param {null|string} options.givenUpBy: WebId of the player that gave up
*/
constructor(options) {
if (options.chess) {
this.chess = options.chess;
this.startPosition = options.startPosition; // FEN
} else {
if (options.startPosition) {
// if there is start position we se the chess game to that
this.chess = new Chess(options.startPosition);
} else {
// else use default start position
this.chess = new Chess();
}
this.startPosition = this.chess.fen();
}
this.url = options.url;
this.userWebId = options.userWebId;
this.opponentWebId = options.opponentWebId;
this.name = options.name;
this.lastMove = options.lastMove;
this.lastUserMove = options.lastUserMove;
this.moveBaseUrl = options.moveBaseUrl;
this.realTime = !!options.realTime;
// if move base url is a string create function that returns this string
// else a function so we leave it
if (typeof this.moveBaseUrl === 'string') {
const t = this.moveBaseUrl;
this.moveBaseUrl = function() {
return t;
}
}
// the default color of the user is white
if (!options.colorOfUser) {
this.colorOfUser = 'w';
} else {
this.colorOfUser = options.colorOfUser;
}
// set the color of the opponent opposite of the user
if (this.colorOfUser === 'w') {
this.colorOfOpponent = 'b';
} else {
this.colorOfOpponent = 'w';
}
// an empty string as name does not make much sense
if (this.name === '') {
this.name = null;
}
// if we don't have a last move, the game just started so we can check who which color started the game
if (!this.lastMove) {
this.colorOfFirstTurn = this.chess.turn();
}
// set the default uniqid function to the function of the package 'uniqid'
if (!options.uniqid) {
this.uniqid = require('uniqid');
} else {
this.uniqid = options.uniqid;
}
this.givenUpWebId = options.givenUpBy ? options.givenUpBy : null;
}
/**
* The method returns true if the next half move has to be made by the opponent.
* @returns {boolean}: true if the next half move has to be made by the opponent
*/
isOpponentsTurn() {
return this.chess.turn() === this.colorOfOpponent;
}
/**
* This method returns true if the game is over because someone gave up.
* @returns {boolean}: true if someone give up on the game
*/
isGivenUp() {
return this.givenUpWebId !== null;
}
/**
* This method returns the WebId of the player that gave up.
* @returns {string|null}: WebId of the player that gave up or null if nobody gave up
*/
givenUpBy() {
return this.givenUpWebId;
}
/**
* This method is called to give up to game by a player.
* @param webId: the WebId of the player that gives up on the game
* @returns {{sparqlUpdate: string, notification: string}}: corresponding SPARQL update and (inbox) notification
* that is generated by giving up
*/
giveUpBy(webId) {
if ((webId === this.userWebId || webId === this.opponentWebId) && this.givenUpWebId === null) {
this.givenUpWebId = webId;
const giveUpActionUrl = this.moveBaseUrl() + `#` + this.uniqid();
//todo use existing class
const sparqlUpdate = `<${giveUpActionUrl}> a <${namespaces.schema}GiveUpAction>;
<${namespaces.schema}agent> <${webId}>;
<${namespaces.schema}object> <${this.url}>.
<${this.url}> <${namespaces.chess}givenUpBy> <${webId}>.`;
const notification = `<${giveUpActionUrl}> a <${namespaces.schema}GiveUpAction>.`;
return {sparqlUpdate, notification};
} else {
return null;
}
}
/**
* This methods loads the giving up of a player.
* @param webId: the WebId of the player that gives up on the game
*/
loadGiveUpBy(webId) {
if ((webId === this.userWebId || webId === this.opponentWebId) && this.givenUpWebId === null) {
this.givenUpWebId = webId;
}
}
/**
* This method does the next move, which specified via the san and the options.
* It returns the corresponding SPARQL update and inbox notification if the move is valid.
* It returns null if the move was invalid. For example, when the san is invalid or
* when it's the opponents turn.
* Note that opponents turns can only be added via the method loadMove.
* @param {string|Object} move: new move either via SAN (string) or object (inherited from chess.js)
* @param {Object} options: the options of the move, inherited from Chess from chess.js
* @returns {null|{sparqlUpdate: string, notification: string}}: corresponding SPARQL update and inbox notification
* that is generated by doing the move
*/
doMove(move, options) {
// check if it's the user's turn
if (!this.isOpponentsTurn()) {
// save the current turn for later
const currentTurn = this.chess.turn();
const createdMove = this.chess.move(move, options);
// check if the move is valid
if (createdMove) {
// if the color of the first turn has not been set that means that this move is the first move
if (!this.colorOfFirstTurn) {
this.colorOfFirstTurn = currentTurn;
}
return this._addUserMove(createdMove.san);
} else {
// invalid mode
return null;
}
} else {
// not the user's turn
return null;
}
}
/**
* This method load a user's or opponent's move.
* This method returns {url, san}, where `url` is the url of the newly loaded move and
* `san` is the SAN of the newly loaded move.
* This method returns null if the SAN of the move is invalid.
* When multiple moves need to be loaded, they have to be loaded in the order that they are played.
* @param {string} san: SAN of the new move
* @param {Object} options: is inherited from Chess.move() from chess.js extended with the key url that represents the move
* @returns {null|{url: string, san:string}}: null if the move is invalid or the url and san of the move if valid
*/
loadMove(san, options) {
const currentTurn = this.chess.turn();
const createdMove = this.chess.move(san, options);
// check if the move is valid
if (createdMove) {
if (!this.colorOfFirstTurn) {
this.colorOfFirstTurn = currentTurn;
}
// check if the current turn is made by the user
if (currentTurn === this.colorOfUser) {
this.lastUserMove = {url: options.url, san};
}
this.lastMove = {url: options.url, san};
return this.lastMove;
} else {
// invalid move
return null;
}
}
/**
* This method returns the RDF (Turtle) representation of the game, without any moves.
* @returns {string}: RDF representation of the game
*/
getMinimumRDF() {
if (!this.minimumRDF) {
const userAgentRole = this.moveBaseUrl() + `#` + this.uniqid();
const opponentAgentRole = this.moveBaseUrl() + `#` + this.uniqid();
let whiteWebId;
let blackWebId;
// determine the WebIds per color
if (this.colorOfUser === 'w') {
whiteWebId = this.userWebId;
blackWebId = this.opponentWebId;
} else {
whiteWebId = this.opponentWebId;
blackWebId = this.userWebId;
}
this.minimumRDF = `<${this.url}> <${namespaces.rdf}type> <${namespaces.chess}ChessGame>;\n` +
`<${namespaces.chess}providesAgentRole> <${userAgentRole}>, <${opponentAgentRole}>.\n\n` +
`<${userAgentRole}> <${namespaces.rdf}type> <${namespaces.chess}WhitePlayerRole>;\n` +
`<${namespaces.chess}performedBy> <${whiteWebId}>.\n\n` +
`<${opponentAgentRole}> <${namespaces.rdf}type> <${namespaces.chess}BlackPlayerRole>;\n` +
`<${namespaces.chess}performedBy> <${blackWebId}>.\n\n` +
`<${this.url}> <${namespaces.chess}isRealTime> ${this.realTime}.\n\n`;
if (this.name) {
this.minimumRDF += `<${this.url}> <http://schema.org/name> "${this.name}".\n`;
}
if (this.startPosition) {
this.minimumRDF += `<${this.url}> <${namespaces.chess}startPosition> "${this.startPosition}".\n`;
}
if (this.colorOfFirstTurn === 'w') {
this.minimumRDF += `<${this.url}> <${namespaces.chess}starts> <${userAgentRole}>.\n`;
} else if (this.colorOfFirstTurn === 'b') {
this.minimumRDF += `<${this.url}> <${namespaces.chess}starts> <${opponentAgentRole}>.\n`;
}
}
return this.minimumRDF;
}
/**
* This method returns {san, url} of the last move made, where `san` is the SAN of the move and
* `url` is the url of the move.
* @returns {null|{url: string, san: string}}: url that represents the move and SAN that describes the move
*/
getLastMove() {
return this.lastMove;
}
/**
* This method returns {san, url} of the last move made by the user, where `san` is the SAN of the move and
* `url` is the url of the move.
* @returns {null|{url: string, san: string}}: url that represents the move and SAN that describes the move
*/
getLastUserMove() {
return this.lastUserMove;
}
/**
* This method returns the color of the user, where 'w' is white and 'b' is black.
* @returns {string}: 'w' (white) or 'b' (black)
*/
getUserColor() {
return this.colorOfUser;
}
/**
* This method returns the color of the opponent, where 'w' is white and 'b' is black.
* @returns {string}: 'w' (white) or 'b' (black)
*/
getOpponentColor() {
return this.colorOfOpponent;
}
/**
* This method returns chess.js game that is used.
* @returns {Chess}: Chess from chess.js
*/
getChess() {
return this.chess;
}
/**
* This method return the WebId of the opponent.
* @returns {string}: WebId of the opponent
*/
getOpponentWebId() {
return this.opponentWebId;
}
/**
* This method returns the URL of the game.
* @returns {string}: URL of the game
*/
getUrl() {
return this.url;
}
/**
* This method returns the function that generates the base url for a new move.
* @returns {function(): string}: function that generates the base url for a new move
*/
geMoveBaseUrl() {
return this.moveBaseUrl;
}
/**
* This method returns the name of the game.
* @returns {string|null}: name of the game
*/
getName() {
return this.name;
}
/**
* This method returns the start position (using FEN) of the game.
* @returns {string|null}: starting position of the game
*/
getStartPosition() {
return this.startPosition;
}
/**
* This method returns true if the game is played real time.
* @returns {boolean}: true if the game is played real time, else false
*/
isRealTime() {
return this.realTime;
}
/**
* This method adds a new move for the user and generates the corresponding SPARQL update and notification.
* @param {string} san: SAN of the new move
* @returns {{sparqlUpdate: string, notification: string}}: sparqlUpdate is the SPARQL update representing this move
* and the corresponding inbox notification that should be send to the opponent
* @private
*/
_addUserMove(san) {
// generate URL for move
const moveURL = this.moveBaseUrl() + `#` + this.uniqid();
let sparqlUpdate = 'INSERT DATA {\n';
let notification = null;
sparqlUpdate +=
`<${this.url}> <${namespaces.chess}hasHalfMove> <${moveURL}>.
<${moveURL}> <${namespaces.rdf}type> <${namespaces.chess}HalfMove>;
<${namespaces.schema}subEvent> <${this.url}>;
<${namespaces.chess}hasSANRecord> "${san}"^^<${namespaces.xsd}string>;
<${namespaces.chess}resultingPosition> "${this.chess.fen()}".\n`;
if (this.lastMove) {
sparqlUpdate += `<${this.lastMove.url}> <${namespaces.chess}nextHalfMove> <${moveURL}>.\n`;
notification = `<${this.lastMove.url}> <${namespaces.chess}nextHalfMove> <${moveURL}>.`;
} else {
sparqlUpdate += `<${this.url}> <${namespaces.chess}hasFirstHalfMove> <${moveURL}>.\n`;
notification = `<${this.url}> <${namespaces.chess}hasFirstHalfMove> <${moveURL}>.`;
}
// if we have a checkmate we also say that this move is the last move
if (this.chess.in_checkmate()) {
sparqlUpdate += `<${this.url}> <${namespaces.chess}hasLastHalfMove> <${moveURL}>.\n`;
notification += `<${this.url}> <${namespaces.chess}hasLastHalfMove> <${moveURL}>.`;
}
sparqlUpdate += `}`;
this.lastMove = {
url: moveURL,
san
};
// because this method is only called when a move is done by the user, so we can set the lastUserMove
this.lastUserMove = this.lastMove;
return {
sparqlUpdate,
notification
}
}
} |
JavaScript | class MnistData {
constructor() {}
async load() {
// Make a request for the MNIST sprited image.
const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imgRequest = new Promise((resolve, reject) => {
img.crossOrigin = '';
img.onload = () => {
img.width = img.naturalWidth;
img.height = img.naturalHeight;
const datasetBytesBuffer =
new ArrayBuffer(NUM_DATASET_ELEMENTS * IMAGE_SIZE * 4);
const chunkSize = 1000;
canvas.width = img.width;
canvas.height = chunkSize;
for (let i = 0; i < NUM_DATASET_ELEMENTS / chunkSize; i++) {
const datasetBytesView = new Float32Array(
datasetBytesBuffer, i * IMAGE_SIZE * chunkSize * 4,
IMAGE_SIZE * chunkSize);
ctx.drawImage(
img, 0, i * chunkSize, img.width, chunkSize, 0, 0, img.width,
chunkSize);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (let j = 0; j < imageData.data.length / 4; j++) {
// All channels hold an equal value since the image is grayscale, so
// just read the red channel.
datasetBytesView[j] = imageData.data[j * 4] / 255;
}
}
this.datasetImages = new Float32Array(datasetBytesBuffer);
resolve();
};
img.src = MNIST_IMAGES_SPRITE_PATH;
});
// const labelsRequest = fetch(MNIST_LABELS_PATH);
// const [imgResponse, labelsResponse] =
// await Promise.all([imgRequest, labelsRequest]);
this.datasetLabels = new Array(2384).fill(0); //new Uint8Array(await labelsResponse.arrayBuffer());
// Slice the the images and labels into train and test sets.
this.trainImages =
this.datasetImages.slice(0, IMAGE_SIZE * NUM_TRAIN_ELEMENTS);
// this.testImages = this.datasetImages.slice(IMAGE_SIZE * NUM_TRAIN_ELEMENTS);
this.trainLabels =
this.datasetLabels.slice(0, NUM_CLASSES * NUM_TRAIN_ELEMENTS);
// this.testLabels =
// this.datasetLabels.slice(NUM_CLASSES * NUM_TRAIN_ELEMENTS);
}
/**
* Get all training data as a data tensor and a labels tensor.
*
* @returns
* xs: The data tensor, of shape `[numTrainExamples, 28, 28, 1]`.
* labels: The one-hot encoded labels tensor, of shape
* `[numTrainExamples, 10]`.
*/
getTrainData() {
const xs = tf.tensor4d(
this.trainImages,
[this.trainImages.length / IMAGE_SIZE, IMAGE_H, IMAGE_W, 1]);
const labels = tf.tensor2d(
this.trainLabels, [this.trainLabels.length / NUM_CLASSES, NUM_CLASSES]);
return {xs, labels};
}
/**
* Get all test data as a data tensor a a labels tensor.
*
* @param {number} numExamples Optional number of examples to get. If not
* provided,
* all test examples will be returned.
* @returns
* xs: The data tensor, of shape `[numTestExamples, 28, 28, 1]`.
* labels: The one-hot encoded labels tensor, of shape
* `[numTestExamples, 10]`.
*/
// getTestData(numExamples) {
// let xs = tf.tensor4d(
// this.testImages,
// [this.testImages.length / IMAGE_SIZE, IMAGE_H, IMAGE_W, 1]);
// let labels = tf.tensor2d(
// this.testLabels, [this.testLabels.length / NUM_CLASSES, NUM_CLASSES]);
// if (numExamples != null) {
// xs = xs.slice([0, 0, 0, 0], [numExamples, IMAGE_H, IMAGE_W, 1]);
// labels = labels.slice([0, 0], [numExamples, NUM_CLASSES]);
// }
// return {xs, labels};
// }
} |
JavaScript | class PdfResponse {
/**
* Creates an instance of PdfResponse.
* @param {object} [values={}]
* @memberof PdfResponse
*
* values = {
* url: // The request url
* options: // The request options
* method: // The response headers
* wrapper: // The RequestWrapper instance originating this object
* content: // The pdf document stream (request stream)
* };
*/
constructor(values = {}) {
this._url = values.url;
this._options = values.options;
this._headers = values.headers;
this._content = values.content;
this._wrapper = values.wrapper;
this._uuid = uuidv1();
this._defaultFilename = this._uuid + '.pdf';
}
/**
* Returns the pdf stream
*
* @readonly
* @memberof PdfResponse
*/
get stream() {
return this._content;
}
/**
* Returns the url
*
* @readonly
* @memberof PdfResponse
*/
get url() {
return this._url;
}
/**
* Returns the filename
*
* @readonly
* @memberof PdfResponse
*/
get fileName() {
return (this._headers['content-disposition'] || this._defaultFilename).split('filename=').pop() || this._defaultFilename;
}
/**
* Returns the pdf content length in bytes
*
* @readonly
* @memberof PdfResponse
*/
get size() {
return (this._headers['content-length'] || 0) * 1;
}
/**
* Returns the response headers
*
* @readonly
* @memberof PdfResponse
*/
get headers() {
return this._headers;
}
/**
* Require a new Pdf using the same options and wrapper. returns a new instance of PdfResponse;
*
* @returns {PdfResponse} the new instance of PdfResponse
* @memberof PdfResponse
*/
refresh() {
return this._wrapper.request(this._options);
}
} |
JavaScript | class GlideRenderer {
constructor(len) {
this._len = len;
this._strokeColor = 0;
this._fillColor = 150;
this._stretch = true;
this._currLen = len;
}
render(mover) {
if (mover.isMoving()) {
this.calculateCurrentLength();
}
rectMode(CENTER);
push();
translate(mover._location.x, mover._location.y);
rotate(mover._angle);
this.renderBody();
pop();
}
calculateCurrentLength() {
if (this._stretch) {
this._currLen += (this._len * GlideRenderer.INCREMENT);
if (this._currLen >= this._len * GlideRenderer.MULTIPLIER) {
this._stretch = false;
}
} else {
this._currLen -= (this._len * GlideRenderer.INCREMENT);
if (this._currLen <= this._len) {
this._stretch = true;
}
}
}
/**
* The body is bunch of connected segments, first one representing the head with a circle
* and consecutive segments gradually tapering out.
* The movement is squash and stretch (hence the name) like earthworms?
*/
renderBody() {
let headPos = (this._currLen - this._len) + this._len/2;
let segments = this._len / GlideRenderer.SEGMENT_SIZE;
let segDist = this._currLen / segments;
let wid = this._len * 0.3;
stroke(this._strokeColor);
strokeWeight(2);
line(headPos, 0, headPos-this._currLen, 0);
for (let i=0; i<segments; i++) {
if (i === 0) {
this.renderHead(headPos - (i*segDist), wid*0.8);
} else {
this.renderSegment(
(headPos - (i*segDist)),
(this._len*0.8/segments),
map(i,0,segments-1, wid*0.9, wid*0.3));
}
}
}
renderHead(x, r) {
strokeWeight(1);
stroke(this._strokeColor);
fill(this._fillColor);
circle(x, 0, r);
}
renderSegment(x, len, wid) {
strokeWeight(1);
stroke(this._strokeColor);
fill(this._fillColor);
rect(x, 0, len, wid);
}
} |
JavaScript | class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
};
} finally {
sheet.seal();
}
}
// render() {
// return (
// <Html>
// <Head>
// <title>Niyon</title>
// <link rel="shortcut icon" href="/static/favicon.ico" />
// <link
// href="https://cdn.jsdelivr.net/npm/[email protected]/inter.min.css"
// rel="stylesheet"
// />
// <link rel="stylesheet" type="text/css" href="/static/nprogrss.css" />
// <script src="https://kit.fontawesome.com/51283197d2.js" />
// </Head>
// <body style={bodyStyles}>
// <Main />
// <NextScript />
// </body>
// </Html>
// );
// }
} |
JavaScript | class ClConstraint {
/* FIELDS:
var _strength
var _weight
var _attachedObject
var _times_added
*/
constructor(strength, weight) {
this.hash_code = ClConstraint.iConstraintNumber++;
this._strength = strength || ClStrength.required;
this._weight = weight || 1.0;
this._times_added = 0;
}
// abstract expression()
hashCode() {
return this.hash_code;
}
isEditConstraint() {
return false;
}
isInequality() {
return false;
}
isRequired() {
return this._strength.isRequired();
}
isStayConstraint() {
return false;
}
strength() {
return this._strength;
}
weight() {
return this._weight;
}
toString() {
// this is abstract -- it intentionally leaves the
// parens unbalanced for the subclasses to complete
// (e.g., with ' = 0', etc.
return this._strength + ' {' + this._weight + '} (' +
this.expression() + ')';
}
setAttachedObject(o /*Object*/) {
this._attachedObject = o;
}
getAttachedObject() {
return this._attachedObject;
}
changeStrength(strength) {
if (this._times_added == 0) {
this.setStrength(strength);
} else {
throw new ExCLTooDifficult();
}
}
addedTo(solver) {
++this._times_added;
}
removedFrom(solver) {
--this._times_added;
}
setStrength(strength) {
this._strength = strength;
}
setWeight(weight) {
this._weight = weight;
}
// Babelsberg
get isConstraintObject() { return true }
enable(strength) {
if (strength) {
this.setStrength(strength);
}
this.solver.addConstraint(this);
}
disable() {
this.solver.removeConstraint(this);
}
cnOr(other) {
return this;
}
get solver() {
return this._solver || ClSimplexSolver.getInstance();
}
set solver(value) {
this._solver = value;
}
} |
JavaScript | class CL {
static debugprint(s) {
if (CL.fVerboseTraceOn) {
print(s);
}
}
static traceprint(s) {
if (CL.fVerboseTraceOn) {
print(s);
}
}
static fnenterprint(s /*String*/) {
print('* ' + s);
}
static fnexitprint(s) {
print('- ' + s);
}
static Assert(f, description) {
if (!f) {
throw new ExCLInternalError('Assertion failed:' + description);
}
}
static Plus(e1, e2) {
if (!(e1 instanceof ClLinearExpression)) {
e1 = new ClLinearExpression(e1);
}
if (!(e2 instanceof ClLinearExpression)) {
e2 = new ClLinearExpression(e2);
}
return e1.plus(e2);
}
static Minus(e1, e2) {
if (!(e1 instanceof ClLinearExpression)) {
e1 = new ClLinearExpression(e1);
}
if (!(e2 instanceof ClLinearExpression)) {
e2 = new ClLinearExpression(e2);
}
return e1.minus(e2);
}
static Times(e1, e2) {
if (e1 instanceof ClLinearExpression &&
e2 instanceof ClLinearExpression) {
return e1.times(e2);
} else if (e1 instanceof ClLinearExpression &&
e2 instanceof ClVariable) {
return e1.times(new ClLinearExpression(e2));
} else if (e1 instanceof ClVariable &&
e2 instanceof ClLinearExpression) {
return (new ClLinearExpression(e1)).times(e2);
} else if (e1 instanceof ClLinearExpression &&
typeof(e2) == 'number') {
return e1.times(new ClLinearExpression(e2));
} else if (typeof(e1) == 'number' &&
e2 instanceof ClLinearExpression) {
return (new ClLinearExpression(e1)).times(e2);
} else if (typeof(e1) == 'number' &&
e2 instanceof ClVariable) {
return (new ClLinearExpression(e2, e1));
} else if (e1 instanceof ClVariable &&
typeof(e2) == 'number') {
return (new ClLinearExpression(e1, e2));
} else if (e1 instanceof ClVariable &&
e2 instanceof ClLinearExpression) {
return (new ClLinearExpression(e2, n));
}
}
static Divide(e1, e2) {
return e1.divide(e2);
}
static approx(a, b) {
if (a instanceof ClVariable) {
a = a.value();
}
if (b instanceof ClVariable) {
b = b.value();
}
var epsilon = 1.0e-8;
if (a == 0.0) {
return (Math.abs(b) < epsilon);
} else if (b == 0.0) {
return (Math.abs(a) < epsilon);
} else {
return (Math.abs(a - b) < Math.abs(a) * epsilon);
}
}
static hashToString(h) {
var answer = '';
CL.Assert(h instanceof Hashtable);
h.each(function(k, v) {
answer += k + ' => ';
if (v instanceof Hashtable) {
answer += CL.hashToString(v);
} else if (v instanceof HashSet) {
answer += CL.setToString(v);
} else {
answer += v + '\n';
}
});
return answer;
}
static setToString(s) {
CL.Assert(s instanceof HashSet);
var answer = s.size() + ' {';
var first = true;
s.each(function(e) {
if (!first) {
answer += ', ';
} else {
first = false;
}
answer += e;
});
answer += '}\n';
return answer;
}
} |
JavaScript | class PlainReporter extends consola.BasicReporter {
formatArgs(args) {
const _args = args.map(arg => {
if (arg && typeof arg.stack === 'string') {
return arg.message + '\n' + this.formatStack(arg.stack)
}
return arg
})
return util.format(..._args)
}
formatLogObj(logObj) {
const message = this.formatArgs(logObj.args)
return this.filterAndJoin([message])
}
} |
JavaScript | class ActorItemHelper {
constructor(actorId, tokenId, sceneId, options = {}) {
this.actorId = actorId;
this.tokenId = tokenId;
this.sceneId = sceneId;
if (tokenId) {
this.token = canvas.tokens?.placeables.find(x => x.id === tokenId);
if (!this.token) {
this.token = game.scenes.get(sceneId).data.tokens.find(x => x.id === tokenId);
}
if (this.token) {
this.scene = this.token.scene || game.scenes.get(sceneId);
this.actor = this.token.actor;
}
}
if (!this.actor && actorId) {
this.actor = game.actors.get(actorId);
}
if (options?.debug) {
console.trace();
console.log([actorId, tokenId, sceneId]);
console.log([this.actor, this.token, this.scene]);
}
}
/**
* Parses a new ActorItemHelper out of an object containing actorId, tokenId, and sceneId.
* @param {Object} actorReferenceObject
*/
static FromObject(actorReferenceObject, options = {}) {
return new ActorItemHelper(actorReferenceObject.actorId, actorReferenceObject.tokenId, actorReferenceObject.sceneId, options);
}
toObject() {
return {actorId: this.actorId, tokenId: this.tokenId, sceneId: this.sceneId};
}
static IsValidHelper(object) {
return (object && object instanceof ActorItemHelper && object.isValid());
}
isValid() {
return (this.actor);
}
/**
* Wrapper around actor.items.get.
* @param {String} itemId ID of item to get.
*/
getItem(itemId) {
if (!this.actor) return null;
return this.actor.items.get(itemId);
}
/**
* Wrapper around actor.createOwnedItem.
* @param {Object} itemData Data for item to create.
* @returns An array of newly created items.
*/
async createItem(itemData) {
if (!this.actor) return null;
const dataToCreate = itemData instanceof Array ? itemData : [itemData];
const createResult = await this.actor.createEmbeddedDocuments("Item", dataToCreate, {});
const newItem = createResult instanceof Array ? createResult : [createResult];
return newItem;
}
/**
* Wrapper around actor.updateEmbeddedDocuments.
* @param {Object} update Data to update with. Must have an id field.
*/
async updateItem(itemId, update) {
if (!this.actor) return null;
return this.actor.updateEmbeddedDocuments("Item", [{ "_id": itemId, data: update}]);
}
/**
* Wrapper around actor.deleteEmbeddedDocuments, also removes the item cleanly from its container, if applicable.
* @param {String} itemId ID of item to delete.
* @param {Boolean} recursive (Optional) Set to true to also delete contained items. Defaults to false.
*/
async deleteItem(itemId, recursive = false) {
if (!this.actor) return null;
const itemIdsToDelete = (itemId instanceof Array) ? itemId : [itemId];
if (recursive) {
let idsToTest = [itemId];
while (idsToTest.length > 0) {
let idToTest = idsToTest.shift();
let item = this.getItem(idToTest);
if (item && item.data.data.container?.contents) {
for (let containedItem of item.data.data.container.contents) {
itemIdsToDelete.push(containedItem.id);
idsToTest.push(containedItem.id);
}
}
}
}
/** Clean up parent container, if deleted from container. */
const promises = [];
const container = this.actor.items.find(x => x.data.data?.container?.contents?.find(y => y.id === itemId) !== undefined);
if (container) {
const newContents = container.data.data.container.contents.filter(x => x.id !== itemId);
promises.push(this.actor.updateEmbeddedDocuments("Item", [{"_id": container.id, "data.container.contents": newContents}]));
}
promises.push(this.actor.deleteEmbeddedDocuments("Item", itemIdsToDelete, {}));
return Promise.all(promises);
}
/**
* Wrapper around actor.items.find().
* @param {Function} fn Method used to search the item.
* @returns The first item matching fn. Null if nothing is found or invalid helper.
*/
findItem(fn) {
if (!ActorItemHelper.IsValidHelper(this)) {
return null;
}
return this.actor.items.find(fn);
}
/**
* Wrapper around actor.items.filter().
* @param {*} fn Method used to filter the items.
* @returns Array of items matching fn. Null if invalid helper.
*/
filterItems(fn) {
if (!ActorItemHelper.IsValidHelper(this)) {
return null;
}
return this.actor.items.filter(fn);
}
/**
* Function that migrates actor items to the new data format, using some rough guesstimations.
* Returns null if no migrations are performed, or a Promise if there is.
*/
migrateItems() {
if (!this.isValid()) return null;
const propertiesToTest = ["contents", "storageCapacity", "contentBulkMultiplier", "acceptedItemTypes", "fusions", "armor.upgradeSlots", "armor.upgrades"];
const migrations = [];
for (const item of this.actor.items) {
const itemData = duplicate(item.data.data);
let isDirty = false;
// Migrate original format
const migrate = propertiesToTest.filter(x => itemData.hasOwnProperty(x));
if (migrate.length > 0) {
//console.log(migrate);
const container = {
contents: (itemData.contents || []).map(x => { return { id: x, index: 0 }; }),
storage: []
};
if (item.type === "container") {
container.storage.push({
type: "bulk",
subtype: "",
amount: itemData.storageCapacity || 0,
acceptsType: itemData.acceptedItemTypes ? Object.keys(itemData.acceptedItemTypes) : [],
affectsEncumbrance: itemData.contentBulkMultiplier === 0 ? false : true,
weightProperty: "bulk"
});
} else if (item.type === "weapon") {
container.storage.push({
type: "slot",
subtype: "fusion",
amount: itemData.level,
acceptsType: ["fusion"],
affectsEncumbrance: false,
weightProperty: "level"
});
} else if (item.type === "equipment") {
container.storage.push({
type: "slot",
subtype: "armorUpgrade",
amount: itemData.armor?.upgradeSlots || 0,
acceptsType: ["upgrade", "weapon"],
affectsEncumbrance: true,
weightProperty: "slots"
});
container.storage.push({
type: "slot",
subtype: "weaponSlot",
amount: itemData.weaponSlots || 0,
acceptsType: ["weapon"],
affectsEncumbrance: true,
weightProperty: "slots"
});
}
itemData["container"] = container;
delete itemData.contents;
delete itemData.storageCapacity;
delete itemData.acceptedItemTypes;
delete itemData.contentBulkMultiplier;
delete itemData.containedItemIds;
delete itemData.fusions;
if (itemData.armor) {
delete itemData.armor.upgradeSlots;
delete itemData.armor.upgrades;
}
}
// Migrate intermediate format
if (itemData.container?.contents?.length > 0) {
let isDirty = false;
if (itemData.container.contents[0] instanceof String) {
for (let i = 0; i<itemData.container.contents.length; i++) {
itemData.container.contents[i] = {id: itemData.container.contents[0], index: 0};
}
isDirty = true;
}
if (itemData.container.itemWeightMultiplier) {
delete itemData.container.itemWeightMultiplier;
isDirty = true;
}
}
if (itemData.container?.storage && itemData.container.storage.length > 0) {
for (let storage of itemData.container.storage) {
if (storage.hasOwnProperty("weightMultiplier")) {
storage["affectsEncumbrance"] = storage.weightMultiplier === 0 ? false : true;
delete storage.weightMultiplier;
isDirty = true;
}
}
}
/** Ensure deleted items are cleaned up. */
const newContents = itemData.container?.contents?.filter(x => this.actor.items.find(ownedItem => ownedItem.id === x.id));
if (newContents?.length !== itemData.container?.contents?.length) {
//console.log([`Actor ${this.actor.name} has deleted item(s) for ${item.name}`, item, itemData.container.contents, newContents]);
itemData.container.contents = newContents;
isDirty = true;
}
// Test for ammunition slots
if (item.type === "weapon" && itemData.capacity && itemData.capacity.max > 0) {
const ammunitionStorageSlot = itemData.container.storage.find(x => x.acceptsType.includes("ammunition"));
if (!ammunitionStorageSlot) {
itemData.container.storage.push({
type: "slot",
subtype: "ammunitionSlot",
amount: 1,
acceptsType: ["ammunition"],
affectsEncumbrance: true,
weightProperty: ""
});
isDirty = true;
}
}
if (isDirty) {
console.log("> Migrating " + item.name);
migrations.push({ _id: item.id, data: itemData});
}
}
if (migrations.length > 0) {
console.log(`Starfinder | Executing migration of ${migrations.length} items for actor ${this.actor.name}.`);
return this.actor.updateEmbeddedDocuments("Item", migrations);
}
return null;
}
} |
JavaScript | class RedirectToChannelMiddleware extends Middleware {
/**
* Creates a new middleware that redirects the reply to a different text channel.
* @param {Bot} bot - The bot instance.
* @param {DiscordCommand} command - The Discord command.
* @param {Object<string,* >} [options] - Additional options for the middleware.
*/
constructor(bot, command, options) {
super(bot, 'redirectToChannel', command, options);
this._defaultOptions = {
channel: undefined,
leaveRedirectMessage: true,
removeOriginalMessage: 300 // Time in seconds for both the request and the redirect response; use undefined to disable
};
}
async onCommand(response) {
const options = this.getOptions();
if (options.leaveRedirectMessage) {
// Leave a message to let the user know the response can be found elsewhere
if (options.removeOriginalMessage) {
await deleteIgnoreErrors(response.getRequest().getMessage(), options.removeOriginalMessage * 1000);
}
let redirectMessage = this.getBot().getLocalizer().t('middleware.defaults:redirect-to-channel.redirect-message');
const mentions = [response.getRequest().getMessage().author];
if (response.getTargetChannel().type === 'dm') {
redirectMessage = this.getBot().getLocalizer().t('middleware.defaults:reply-with-mentions.response-dm', { mentions, message: redirectMessage });
} else {
redirectMessage = this.getBot().getLocalizer().t('middleware.defaults:reply-with-mentions.response-public', { mentions, message: redirectMessage });
}
const message = await response.getTargetChannel().send(redirectMessage);
await deleteIgnoreErrors(message, options.removeOriginalMessage * 1000);
}
if (options.channel) {
// This breaks the possibility of running the bot on more than one server
// Might have to look into this later
response.setTargetChannel(options.channel);
}
return response;
}
} |
JavaScript | class Sites extends Commands {
accounts = new Accounts()
/**
* Fetches a list of sites from users wpengine account
* @param {*} limit
* @returns an object
* @since 1.0.0
*/
getSites = async (limit) => {
if (limit < 1) {
const data = await fetch(`https://api.wpengineapi.com/v1/sites`, {
method: 'GET',
headers: { 'Authorization': this.auth.authorization },
})
const json = await data.json();
const sites = json.results.map(data => {
return {
name: data.name,
value: data.id
};
})
return sites;
} else {
const data = await fetch(`https://api.wpengineapi.com/v1/sites?limit=${limit}`, {
method: 'GET',
headers: { 'Authorization': this.auth.authorization },
})
const json = await data.json();
const sites = json.results.map(data => {
return {
name: data.name,
value: data.id
};
})
return sites;
}
console.log('something went wrong')
}
/**
* Fetches a site by its ID
* @param {*} id
* @returns JSON
* @since 1.0.0
*/
getSiteById = async (id) => {
const data = await fetch(`https://api.wpengineapi.com/v1/sites/${id}`, {
method: 'GET',
headers: { 'Authorization': this.auth.authorization },
})
const json = await data.json();
return json;
}
/**
* Adds a site to the users wpengine account.
* @param {*} body
* @since 1.0.0
*/
addSite = async (body) => {
const response = await fetch(`https://api.wpengineapi.com/v1/sites`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Authorization': this.auth.authorization,
'Content-Type': 'application/json',
'accept': 'application/json'
},
})
const data = await response.json();
console.log("Site successfully created!", data);
}
updateSite(id, {options}) {
}
deleteSite(id) {
}
/**
* Executes the sites CLI.
* @since 1.0.0
*/
sites = () => {
if (this.auth.authenticated()) {
inquirer
.prompt([
{
type: 'list',
message: chalk.blue('Select an action'),
name: 'actions',
choices: [
'add site',
'show all',
'get by ID',
'update site',
'delete site'
]
}
])
.then((answers) => {
if (answers.actions === 'show all') {
inquirer
.prompt([
{
type: 'number',
message: chalk.blue('How many sites would you like to list'),
name: 'siteLimit',
default: 100
}
])
.then((limit) => {
this.getSites(limit.siteLimit).then(
data => {
inquirer
.prompt([
{
type: 'list',
message: chalk.blue('Select a site'),
name: 'siteList',
choices: data
}
])
.then((siteId) => {
this.getSiteById(siteId.siteList).then(
data => {
inquirer
.prompt([
{
type: 'list',
message: chalk.blue('Select a site'),
name: 'options',
choices: [
"View installs",
"Edit site",
"Delete site"
]
}
])
.then((siteId) => {
if (siteId.options[0]) {
console.log(data.installs);
} else if (siteId.options[1]) {
// Edit site
} else if (siteId.options[2]) {
// Remove site
}
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
}
)
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
}
)
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
} else if (answers.actions === 'get by ID') {
inquirer
.prompt([
{
type: 'input',
message: chalk.blue('Enter the sites unique ID'),
name: 'site_by_id'
}
])
.then((id) => {
this.getSiteById(id.site_by_id).then(
data => {
console.log(data);
}
)
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
} else if (answers.actions === 'add site') {
this.accounts.listAccounts().then(
accounts => {
inquirer
.prompt([
{
type: 'list',
message: chalk.blue('Choose an account'),
name: 'accountId',
choices: accounts
},
{
type: 'input',
name: 'siteName',
message: chalk.blue('Enter a site name'),
validate(value) {
const pass = value.match(
/([\w\-\s]*)/g
);
if (pass) {
return true;
}
return 'Please enter a valid name';
},
}
])
.then((answers) => {
this.addSite(
{
name: answers.siteName,
account_id: answers.accountId
}
)
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
}
)
}
})
} else {
console.log(chalk.bgRedBright("Please authenticate first"));
this.auth.signin();
}
}
} |
JavaScript | class StudentReviews{
//Create the constructor and enter in an appropriate value to be passed through
constructor(imgFaces){
//Sets element to the iterated item
this.imgFaces = imgFaces;
//This sets the image to be the first child element that is an image
this.img = this.imgFaces.querySelector('img')
//This assigns the data value of the img faces current div to this.data
this.data = this.imgFaces.dataset.img;
//This line associates the HTML element that has the same number of data-rev as this.data's data-img value
this.review = document.querySelector(`.fc-column[data-rev='${this.data}']`)
//This line creates an event listener that occurs whenever a designated image is clicked, the corresponding students text block is then displayed via the "select" method
this.img.addEventListener('click', () => {
this.select()
})
}
//This is the nested method for this object
select(){
//Create a variable that is assignged to a nodelist of all the student reviews
const studentReviews = document.querySelectorAll('.fc-column')
//Use the forEach method on the new nodelist to remove the .active class from all elements in the nodelist
studentReviews.forEach(rev => rev.classList.remove('active'));
//Once an image is clicked, set that corresponding student review to have the active class
this.review.classList.add('active');
}
} |
JavaScript | class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
chosenDate: new Date(),
showIOSDatePicker: false
};
}
setDate(newDate) {
this.setState({chosenDate: newDate});
this.props.onDateChange(newDate);
}
getDateString() {
return this.state.chosenDate ? this.state.chosenDate.toLocaleString() : "";
}
displayDatePicker() {
if (Platform.OS === 'android') {
this.pickAndroidDate();
}
else if (Platform.OS === 'ios') {
this.setState((prevState) => {
return {showIOSDatePicker: !prevState.showIOSDatePicker};
});
}
}
async pickAndroidDate() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
date: this.state.chosenDate
});
if (action !== DatePickerAndroid.dismissedAction) {
this.setDate(new Date(
year,
month,
day,
this.state.chosenDate.getHours(),
this.state.chosenDate.getMinutes()
));
this.pickAndroidTime();
}
}
catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}
async pickAndroidTime() {
try {
const {action, hour, minute} = await TimePickerAndroid.open({
hour: this.state.chosenDate.hour,
minute: this.state.chosenDate.minute,
is24Hour: false
});
if (action !== TimePickerAndroid.dismissedAction) {
this.setDate(new Date(
this.state.chosenDate.getFullYear(),
this.state.chosenDate.getMonth(),
this.state.chosenDate.getDate(),
hour,
minute
));
}
}
catch ({code, message}) {
console.warn('Cannot open time picker', message);
}
}
render() {
const customStyle = {
buttonContainer: [styles.buttonContainer, {
backgroundColor: this.props.color_theme.APP_BACKGROUND,
shadowColor: this.props.color_theme.APP_UNFOCUS
}]
};
let iOSDatePicker;
if (Platform.OS === 'ios' && this.state.showIOSDatePicker) {
iOSDatePicker = (
<View style={styles.TimeDateWrapper}>
<DatePickerIOS
date={this.state.chosenDate}
onDateChange={(date) => this.setDate(date)}
/>
</View>);
}
return (
<View style={styles.container}>
<View style={customStyle.buttonContainer}>
<Button
onPress={()=> this.displayDatePicker()}
title={this.getDateString()}/>
</View>
{iOSDatePicker}
</View>
);
}
} |
JavaScript | class TileChart {
/**
* Initializes the svg elements required to lay the tiles
* and to populate the legend.
*/
constructor(){
let divTiles = d3.select("#tiles").classed("content", true);
this.margin = {top: 30, right: 20, bottom: 30, left: 50};
//Gets access to the div element created for this chart and legend element from HTML
let svgBounds = divTiles.node().getBoundingClientRect();
this.svgWidth = svgBounds.width - this.margin.left - this.margin.right;
this.svgHeight = this.svgWidth/2;
let legendHeight = 150;
//add the svg to the div
let legend = d3.select("#legend").classed("content",true);
//creates svg elements within the div
this.legendSvg = legend.append("svg")
.attr("width",this.svgWidth)
.attr("height",legendHeight)
.attr("transform", "translate(" + this.margin.left + ",0)")
this.svg = divTiles.append("svg")
.attr("width",this.svgWidth)
.attr("height",this.svgHeight)
.attr("transform", "translate(" + this.margin.left + ",0)")
};
/**
* Returns the class that needs to be assigned to an element.
*
* @param party an ID for the party that is being referred to.
*/
chooseClass (party) {
if (party == "R"){
return "republican";
}
else if (party== "D"){
return "democrat";
}
else if (party == "I"){
return "independent";
}
}
/**
* Renders the HTML content for tool tip.
*
* @param tooltip_data information that needs to be populated in the tool tip
* @return text HTML content for tool tip
*/
tooltip_render(tooltip_data) {
let text = "<h2 class =" + this.chooseClass(tooltip_data.winner) + " >" + tooltip_data.state + "</h2>";
text += "Electoral Votes: " + tooltip_data.electoralVotes;
text += "<ul>"
tooltip_data.result.forEach((row)=>{
//text += "<li>" + row.nominee+":\t\t"+row.votecount+"("+row.percentage+"%)" + "</li>"
text += "<li class = " + this.chooseClass(row.party)+ ">" + row.nominee+":\t\t"+row.votecount+"("+row.percentage+"%)" + "</li>"
});
text += "</ul>";
return text;
}
/**
* Creates tiles and tool tip for each state, legend for encoding the color scale information.
*
* @param electionResult election data for the year selected
* @param colorScale global quantile scale based on the winning margin between republicans and democrats
*/
update (electionResult, colorScale){
//Calculates the maximum number of columns to be laid out on the svg
this.maxColumns = d3.max(electionResult,function(d){
return parseInt(d["Space"]);
});
//Calculates the maximum number of rows to be laid out on the svg
this.maxRows = d3.max(electionResult,function(d){
return parseInt(d["Row"]);
});
//Creates a legend element and assigns a scale that needs to be visualized
this.legendSvg.append("g")
.attr("class", "legendQuantile")
.attr("transform", "translate(0,50)");
/*let legendQuantile = d3.legendColor()
.shapeWidth(100)
.cells(10)
.orient('horizontal')
.scale(colorScale);*/
let rectWidth = (this.svgWidth - this.maxColumns * 6) / this.maxColumns;
let rectHeight = (this.svgHeight - this.maxRows * 8) / this.maxRows;
/*this.legendSvg.select(".legendQuantile")
.call(legendQuantile);*/
let range = ["#063e78", "#08519c", "#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#fcbba1", "#fc9272", "#fb6a4a", "#de2d26", "#a50f15", "#860308"];
let domain = [-60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60];
let widthOfOne = this.svgWidth / range.length;
d3.select("#legend svg").selectAll("rect").data(range)
.enter()
.append("rect")
.attr("width", widthOfOne)
.attr("height", widthOfOne/4)
.attr("x", function(d, i){return i*widthOfOne})
.attr("y", 5)
.attr("fill", function(d){return d});
d3.select("#legend svg").selectAll("text").data(domain)
.enter()
.append("text")
.attr("x", function(d, i){return i*widthOfOne})
.attr("y", 20 + widthOfOne/4)
.text(function(d, i){
if (i != 12) {
return `${domain[i]} - ${domain[i+1]}`
}
});
let tip = d3.tip().attr('class', 'd3-tip')
.direction('se')
.offset(function() {
return [0,0];
})
.html((d)=>{
let allVoices = +d.D_Votes + +d.R_Votes + +d.I_Votes;
if (d.I_Nominee_prop != " ") {
return `<div>
<h2 class = ${d.State_Winner}>${d.State}</h2>
<p class = "green">${d.I_Nominee_prop}: ${d.I_Votes}(${d3.format(".0%")(d.I_Votes/allVoices)})</p>
<p class = "blue">${d.D_Nominee_prop}: ${d.D_Votes}(${d3.format(".0%")(d.D_Votes/allVoices)})</p>
<p class = "red">${d.R_Nominee_prop}: ${d.R_Votes}(${d3.format(".0%")(d.R_Votes/allVoices)})</p>
</div>`;
}
return `<div>
<h2 class = ${d.State_Winner}>${d.State}</h2>
<p class = "blue">${d.D_Nominee_prop}: ${d.D_Votes}(${d3.format(".0%")(d.D_Votes/allVoices)})</p>
<p class = "red">${d.R_Nominee_prop}: ${d.R_Votes}(${d3.format(".0%")(d.R_Votes/allVoices)})</p>
</div>`;
});
this.svg.selectAll("rect").remove();
this.svg.call(tip);
this.svg.selectAll("rect")
.data(electionResult)
.enter()
.append("rect")
.attr("width", rectWidth)
.attr("height", rectHeight)
.attr("x", function(d) {return parseInt(d["Space"]) * rectWidth + 2})
.attr("y", function(d) {return parseInt(d["Row"]) * rectHeight + 2})
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
this.svg.selectAll("rect")
.append("rect")
.attr("width", rectWidth)
.attr("height", rectHeight);
this.svg.selectAll("rect")
.transition()
.duration(500)
.attr("fill", function(d) {
if (d.State_Winner == "I") {
return "#45AD6A"
}
return colorScale(d.RD_Difference);
});
this.svg.selectAll("text").remove();
this.svg.selectAll("text")
.data(electionResult)
.enter()
.append("text");
this.svg.selectAll("text").each(function(){
let cur = d3.select(this);
cur.append('tspan').text(function(d) { return `${d.Abbreviation}` })
.attr("x", function(d) {return (parseInt(d["Space"]) * rectWidth + 2) + ((rectWidth - this.getComputedTextLength()) / 2)})
.attr("y", function(d) {return (parseInt(d["Row"]) * rectHeight + 2) + rectHeight / 2});
cur.append('tspan').text(function(d) { return `${d.Total_EV}` })
.attr("x", function(d) {return (parseInt(d["Space"]) * rectWidth + 2) + ((rectWidth - this.getComputedTextLength()) / 2)})
.attr("y", function(d) {return (parseInt(d["Row"]) * rectHeight + 2) + rectHeight / 2 + 20});
});
// ******* TODO: PART IV *******
//Tansform the legend element to appear in the center and make a call to this element for it to display.
//Lay rectangles corresponding to each state according to the 'row' and 'column' information in the data.
//Display the state abbreviation and number of electoral votes on each of these rectangles
//Use global color scale to color code the tiles.
//HINT: Use .tile class to style your tiles;
// .tilestext to style the text corresponding to tiles
//Call the tool tip on hover over the tiles to display stateName, count of electoral votes
//then, vote percentage and number of votes won by each party.
//HINT: Use the .republican, .democrat and .independent classes to style your elements.
};
} |
JavaScript | class SuperContainer extends React.PureComponent {
render() {
return <Container {...this.props} />;
}
} |
JavaScript | class FormObjectMapper {
/**
* @param {jQuery} $form - Form element to attach the mapper to
* @param {Object} modelMapping - Structure mapping a model to form names
* @param {EventEmitter} eventEmitter
* @param {Object} [config] - Event names
* @param {Object} [config.updateModel] - Name of the event to listen to trigger a refresh of the model update
* @param {Object} [config.modelUpdated] - Name of the event emitted each time the model is updated
* @param {Object} [config.modelFieldUpdated] - Name of the event emitted each time a field is updated
* @return {Object}
*/
constructor($form, modelMapping, eventEmitter, config) {
this.$form = $form;
this.fullModelMapping = modelMapping;
this.eventEmitter = eventEmitter;
const inputConfig = config || {};
// This event is registered so when it is triggered it forces the form mapping and object update,
// it can be useful when some new inputs have been added in the DOM (or removed) so that the model
// acknowledges the update
this.updateModelEventName = inputConfig.updateModel || 'updateModel';
// This event is emitted each time the object is updated (from both input change and external event)
this.modelUpdatedEventName = inputConfig.modelUpdated || 'modelUpdated';
// This event is emitted each time an object field is updated (from both input change and external event)
this.modelFieldUpdatedEventName = inputConfig.modelFieldUpdated || 'modelFieldUpdated';
// Contains callbacks identified by model keys
this.watchedProperties = {};
this.initFormMapping();
this.updateFullObject();
this.watchUpdates();
return {
/**
* Returns the model mapped to the form (current live state)
*
* @returns {*|{}}
*/
getModel: () => this.model,
/**
* Returns all inputs associated to a model field.
*
* @param {string} modelKey
*
* @returns {undefined|jQuery}
*/
getInputsFor: (modelKey) => {
if (!Object.prototype.hasOwnProperty.call(this.fullModelMapping, modelKey)) {
return undefined;
}
const inputNames = this.fullModelMapping[modelKey];
// We must loop manually to keep the order in configuration, if we use jQuery multiple selectors the collection
// will be filled respecting the order in the DOM
const inputs = [];
const domForm = this.$form.get(0);
inputNames.forEach((inputName) => {
const inputsByName = domForm.querySelectorAll(`[name="${inputName}"]`);
if (inputsByName.length) {
inputsByName.forEach((input) => {
inputs.push(input);
});
}
});
return inputs.length ? $(inputs) : undefined;
},
/**
* Set a value to a field of the object based on the model key, the object itself is updated
* of course but the mapped inputs are also synced (all of them if multiple). Events are also
* triggered to indicate the object has been updated (the general and the individual field ones).
*
* @param {string} modelKey
* @param {*|{}} value
*/
set: (modelKey, value) => {
if (!Object.prototype.hasOwnProperty.call(this.modelMapping, modelKey) || value === this.getValue(modelKey)) {
return;
}
// First update the inputs then the model, so that the event is sent at last
this.updateInputValue(modelKey, value);
this.updateObjectByKey(modelKey, value);
this.eventEmitter.emit(this.modelUpdatedEventName, this.model);
},
/**
* Alternative to the event listening, you can watch a specific field of the model and assign a callback.
* When the specified model field is updated the event is still thrown but additionally any callback assigned
* to this specific value is also called, the parameter is the same event.
*
* @param {string} modelKey
* @param {function} callback
*/
watch: (modelKey, callback) => {
if (!Object.prototype.hasOwnProperty.call(this.watchedProperties, modelKey)) {
this.watchedProperties[modelKey] = [];
}
this.watchedProperties[modelKey].push(callback);
},
};
}
/**
* Get a field from the object based on the model key, you can even get a sub part of the whole model,
* this internal method is used by both get and set public methods.
*
* @param {string} modelKey
*
* @returns {*|{}|undefined} Returns any element from the model, undefined if not found
* @private
*/
getValue(modelKey) {
const modelKeys = modelKey.split('.');
return $.serializeJSON.deepGet(this.model, modelKeys);
}
/**
* Watches if changes happens from the form or via an event.
*
* @private
*/
watchUpdates() {
this.$form.on('keyup change dp.change', ':input', _.debounce(
(event) => this.inputUpdated(event),
350,
{maxWait: 1500},
));
this.eventEmitter.on(this.updateModelEventName, () => this.updateFullObject());
}
/**
* Triggered when a form input has been changed.
*
* @param {jQuery.Event} event
*
* @private
*/
inputUpdated(event) {
const target = event.currentTarget;
// All inputs changes are watched, but not all of them are part of the mapping so we ignore them
if (!Object.prototype.hasOwnProperty.call(this.formMapping, target.name)) {
return;
}
const updatedValue = $(target).val();
const updatedModelKey = this.formMapping[target.name];
// Update the mapped input fields
this.updateInputValue(updatedModelKey, updatedValue, target.name);
// Then update model and emit event
this.updateObjectByKey(updatedModelKey, updatedValue);
this.eventEmitter.emit(this.modelUpdatedEventName, this.model);
}
/**
* Update all the inputs mapped to a model key
*
* @param {string} modelKey
* @param {*|{}} value
* @param {string|undefined} sourceInputName Source of the change (no need to update it)
*
* @private
*/
updateInputValue(modelKey, value, sourceInputName = undefined) {
const modelInputs = this.fullModelMapping[modelKey];
// Update linked inputs (when there is more than one input associated to the model field)
if (Array.isArray(modelInputs)) {
modelInputs.forEach((inputName) => {
if (sourceInputName === inputName) {
return;
}
this.updateInputByName(inputName, value);
});
} else if (sourceInputName !== modelInputs) {
this.updateInputByName(modelInputs, value);
}
}
/**
* Update individual input based on its name
*
* @param {string} inputName
* @param {*|{}} value
*
* @private
*/
updateInputByName(inputName, value) {
const $input = $(`[name="${inputName}"]`, this.$form);
if (!$input.length) {
console.error(`Input with name ${inputName} is not present in form.`);
return;
}
// This check is important to avoid infinite loops, we don't use strict equality on purpose because it would result
// into a potential infinite loop if type don't match, which can easily happen with a number value and a text input.
// eslint-disable-next-line eqeqeq
if ($input.val() != value) {
$input.val(value);
if ($input.data('toggle') === 'select2') {
// This is required for select2, because only changing the val doesn't update the wrapping component
$input.trigger('change');
}
}
}
/**
* Serializes and updates the object based on form content and the mapping configuration, finally
* emit an event for external components that may need the update.
*
* This method is called when this component initializes or when triggered by an external event.
*
* @private
*/
updateFullObject() {
const serializedForm = this.$form.serializeJSON();
this.model = {};
Object.keys(this.modelMapping).forEach((modelKey) => {
const formMapping = this.modelMapping[modelKey];
const formKeys = $.serializeJSON.splitInputNameIntoKeysArray(formMapping);
const formValue = $.serializeJSON.deepGet(serializedForm, formKeys);
this.updateObjectByKey(modelKey, formValue);
});
this.eventEmitter.emit(this.modelUpdatedEventName, this.model);
}
/**
* Update a specific field of the object.
*
* @param {string} modelKey
* @param {*|{}} value
*
* @private
*/
updateObjectByKey(modelKey, value) {
const modelKeys = modelKey.split('.');
const previousValue = $.serializeJSON.deepGet(this.model, modelKeys);
// This check has two interests, there is no point in modifying a value or emit an event for a value that did not
// change, and it avoids infinite loops when the object field are co-dependent and need to be updated dynamically
// (ex: update price tax included when price tax excluded is updated and vice versa, without this check an infinite
// loop would happen)
if (previousValue === value) {
return;
}
$.serializeJSON.deepSet(this.model, modelKeys, value);
const updateEvent = {
object: this.model,
modelKey,
value,
previousValue,
};
this.eventEmitter.emit(this.modelFieldUpdatedEventName, updateEvent);
if (Object.prototype.hasOwnProperty.call(this.watchedProperties, modelKey)) {
const propertyWatchers = this.watchedProperties[modelKey];
propertyWatchers.forEach((callback) => {
callback(updateEvent);
});
}
}
/**
* Reverse the initial mapping Model->Form to the opposite Form->Model
* This simplifies the sync in when data updates.
*
* @private
*/
initFormMapping() {
// modelMapping is a light version of the fullModelMapping, it only contains one input name which is considered
// as the default one (when full object is updated, only the default input is used)
this.modelMapping = {};
// formMapping is the inverse of modelMapping for each input name it associated the model key, it is generated for
// performance and convenience, this allows to get mapping data faster in other functions
this.formMapping = {};
Object.keys(this.fullModelMapping).forEach((modelKey) => {
const formMapping = this.fullModelMapping[modelKey];
if (Array.isArray(formMapping)) {
formMapping.forEach((aliasFormMapping) => {
this.addFormMapping(aliasFormMapping, modelKey);
});
} else {
this.addFormMapping(formMapping, modelKey);
}
});
}
/**
* @param {string} formName
* @param {string} modelMapping
*
* @private
*/
addFormMapping(formName, modelMapping) {
if (Object.prototype.hasOwnProperty.call(this.formMapping, formName)) {
console.error(`The form element ${formName} is already mapped to ${this.formMapping[formName]}`);
return;
}
this.formMapping[formName] = modelMapping;
this.modelMapping[modelMapping] = formName;
}
} |
JavaScript | class ScheduleInfo {
/**
* @private
* @param {object} props
* @param {ScheduleId} props.scheduleId;
* @param {?AccountId} props.creatorAccountID;
* @param {?AccountId} props.payerAccountID;
* @param {?HashgraphProto.proto.ISchedulableTransactionBody} props.schedulableTransactionBody;
* @param {?Key} props.adminKey
* @param {?KeyList} props.signers;
* @param {?string} props.scheduleMemo;
* @param {?Timestamp} props.expirationTime;
* @param {?Timestamp} props.executed;
* @param {?Timestamp} props.deleted;
* @param {?TransactionId} props.scheduledTransactionId;
*/
constructor(props) {
/**
*
* @readonly
*/
this.scheduleId = props.scheduleId;
/**
*
* @readonly
*/
this.creatorAccountId = props.creatorAccountID;
/**
*
* @readonly
*/
this.payerAccountId = props.payerAccountID;
/**
*
* @readonly
*/
this.schedulableTransactionBody = props.schedulableTransactionBody;
/**
*
* @readonly
*/
this.signers = props.signers;
/**
*
* @readonly
*/
this.scheduleMemo = props.scheduleMemo;
/**
*
* @readonly
*/
this.adminKey = props.adminKey != null ? props.adminKey : null;
/**
*
* @readonly
*/
this.expirationTime = props.expirationTime;
/**
*
* @readonly
*/
this.executed = props.executed;
/**
*
* @readonly
*/
this.deleted = props.deleted;
this.scheduledTransactionId = props.scheduledTransactionId;
Object.freeze(this);
}
/**
* @internal
* @param {HashgraphProto.proto.IScheduleInfo} info
* @returns {ScheduleInfo}
*/
static _fromProtobuf(info) {
return new ScheduleInfo({
scheduleId: ScheduleId._fromProtobuf(
/** @type {HashgraphProto.proto.IScheduleID} */ (
info.scheduleID
)
),
creatorAccountID:
info.creatorAccountID != null
? AccountId._fromProtobuf(
/** @type {HashgraphProto.proto.IAccountID} */ (
info.creatorAccountID
)
)
: null,
payerAccountID:
info.payerAccountID != null
? AccountId._fromProtobuf(
/** @type {HashgraphProto.proto.IAccountID} */ (
info.payerAccountID
)
)
: null,
schedulableTransactionBody:
info.scheduledTransactionBody != null
? info.scheduledTransactionBody
: null,
adminKey:
info.adminKey != null
? Key._fromProtobufKey(info.adminKey)
: null,
signers:
info.signers != null
? KeyList.__fromProtobufKeyList(info.signers)
: null,
scheduleMemo: info.memo != null ? info.memo : null,
expirationTime:
info.expirationTime != null
? Timestamp._fromProtobuf(
/** @type {HashgraphProto.proto.ITimestamp} */ (
info.expirationTime
)
)
: null,
executed:
info.executionTime != null
? Timestamp._fromProtobuf(
/** @type {HashgraphProto.proto.ITimestamp} */ (
info.executionTime
)
)
: null,
deleted:
info.deletionTime != null
? Timestamp._fromProtobuf(
/** @type {HashgraphProto.proto.ITimestamp} */ (
info.deletionTime
)
)
: null,
scheduledTransactionId:
info.scheduledTransactionID != null
? TransactionId._fromProtobuf(info.scheduledTransactionID)
: null,
});
}
/**
* @returns {HashgraphProto.proto.IScheduleInfo}
*/
_toProtobuf() {
return {
scheduleID:
this.scheduleId != null ? this.scheduleId._toProtobuf() : null,
creatorAccountID:
this.creatorAccountId != null
? this.creatorAccountId._toProtobuf()
: null,
payerAccountID:
this.payerAccountId != null
? this.payerAccountId._toProtobuf()
: null,
scheduledTransactionBody:
this.schedulableTransactionBody != null
? this.schedulableTransactionBody
: null,
adminKey:
this.adminKey != null ? this.adminKey._toProtobufKey() : null,
signers:
this.signers != null
? this.signers._toProtobufKey().keyList
: null,
memo: this.scheduleMemo != null ? this.scheduleMemo : "",
expirationTime:
this.expirationTime != null
? this.expirationTime._toProtobuf()
: null,
scheduledTransactionID:
this.scheduledTransactionId != null
? this.scheduledTransactionId._toProtobuf()
: null,
};
}
/**
* @returns {Transaction}
*/
get scheduledTransaction() {
if (this.schedulableTransactionBody == null) {
throw new Error("Scheduled transaction body is empty");
}
const scheduled = new proto.SchedulableTransactionBody(
this.schedulableTransactionBody
);
const data =
/** @type {NonNullable<HashgraphProto.proto.SchedulableTransactionBody["data"]>} */ (
scheduled.data
);
return Transaction.fromBytes(
proto.TransactionList.encode({
transactionList: [
{
signedTransactionBytes: proto.SignedTransaction.encode({
bodyBytes: proto.TransactionBody.encode({
transactionFee:
this.schedulableTransactionBody
.transactionFee,
memo: this.schedulableTransactionBody.memo,
[data]: scheduled[data],
}).finish(),
}).finish(),
},
],
}).finish()
);
}
} |
JavaScript | class BaseService extends EventEmitter {
constructor (options) {
super()
this.options = { ...defaultOptions, options }
this.started = false
}
/**
* Returns the name of this service.
* @return {string} Name of the service.
*/
get name () {
throw new Error('Classes that extend BaseService must implement this method')
}
/**
* Starts the service.
*/
async start () {
throw new Error('Classes that extend BaseService must implement this method')
}
/**
* Stops the service.
*/
async stop () {
throw new Error('Classes that extend BaseService must implement this method')
}
} |
JavaScript | class TextWithRecommendedLengthCounter {
constructor() {
$(document).on('input', '.js-recommended-length-input', (event) => {
const $input = $(event.currentTarget);
$($input.data('recommended-length-counter')).find('.js-current-length').text($input.val().length);
});
}
} |
JavaScript | class Or16 extends BuiltInGate {
/**
* IN a[16], b[16];
* OUT out[16];
*
* for i = 0..15: out[i] = (a[i] | b[i])
*
* Abstract:
*
* Or(a=a[0], b=b[0], out=out[0]);
* Or(a=a[1], b=b[1], out=out[1]);
* ...
*
* Technically use JS bitwise operations at needed index.
*/
eval() {
const a = this.getInputPins()[0].getValue();
const b = this.getInputPins()[1].getValue();
// In JS implementation doesn't differ from the simple `Or` gate.
// Use 16-bit values with 0xFFFF mask.
this.getOutputPins()[0].setValue((a | b) & 0xffff);
}
} |
JavaScript | class WheelSlider extends UI5Element {
static get metadata() {
return metadata;
}
static get render() {
return litRender;
}
static get styles() {
return WheelSliderCss;
}
static get template() {
return WheelSliderTemplate;
}
constructor() {
super();
this._currentElementIndex = 0;
this._itemCellHeight = 0;
this._itemsToShow = [];
this._scroller = new ScrollEnablement(this);
this._scroller.attachEvent("scroll", this._updateScrolling.bind(this));
this._scroller.attachEvent("mouseup", this._handleScrollTouchEnd.bind(this));
this._scroller.attachEvent("touchend", this._handleScrollTouchEnd.bind(this));
}
onBeforeRendering() {
if (!this._expanded && this.cyclic) {
const index = this._currentElementIndex % this._items.length;
this._currentElementIndex = (this._timesMultipliedOnCyclic() / 2) * this._items.length + index;
}
if (!this.value) {
this.value = this._items[0];
}
this._buildItemsToShow();
this._updateItemCellHeight();
}
static async onDefine() {
await Button.define();
}
onAfterRendering() {
if (!this._scroller.scrollContainer) {
this._scroller.scrollContainer = this.shadowRoot.querySelector(`#${this._id}--wrapper`);
}
if (!this._expanded) {
this._scroller.scrollTo(0, 0);
}
if (this._expanded) {
const elements = this.shadowRoot.querySelectorAll(".ui5-wheelslider-item");
for (let i = 0; i < elements.length; i++) {
if (elements[i].textContent === this.value) {
this._selectElementByIndex(Number(elements[i].dataset.itemIndex) + this._getCurrentRepetition() * this._items.length);
return true;
}
}
this._selectElement(elements[0]);
}
}
get classes() {
return {
root: {
"ui5-wheelslider-root": true,
"ui5-phone": isPhone(),
},
};
}
expandSlider() {
this._expanded = true;
this.fireEvent("expand", {});
}
collapseSlider() {
this._expanded = false;
this.fireEvent("collapse", {});
}
_updateItemCellHeight() {
if (this.shadowRoot.querySelectorAll(".ui5-wheelslider-item").length) {
const itemComputedStyle = getComputedStyle(this.shadowRoot.querySelector(".ui5-wheelslider-item"));
const itemHeightValue = itemComputedStyle.getPropertyValue("--_ui5_wheelslider_item_height");
const onlyDigitsValue = itemHeightValue.replace("rem", "");
this._itemCellHeight = Number(onlyDigitsValue);
}
}
_updateScrolling() {
const sizeOfOneElementInPixels = this._itemCellHeight * 16,
scrollWhere = this._scroller.scrollContainer.scrollTop;
let offsetIndex;
if (!scrollWhere) {
return;
}
offsetIndex = Math.round(scrollWhere / sizeOfOneElementInPixels);
if (this.value === this._itemsToShow[offsetIndex]) {
return;
}
if (this.cyclic) {
const newIndex = this._handleArrayBorderReached(offsetIndex);
if (offsetIndex !== newIndex) {
offsetIndex = newIndex;
}
}
this.value = this._itemsToShow[offsetIndex];
this._currentElementIndex = offsetIndex;
}
_handleScrollTouchEnd() {
if (this._expanded) {
this._selectElementByIndex(this._currentElementIndex);
}
}
_selectElement(element) {
if (element && this._items.indexOf(element.textContent) > -1) {
this._currentElementIndex = Number(element.dataset.itemIndex);
this._selectElementByIndex(this._currentElementIndex);
}
}
_getCurrentRepetition() {
if (this._currentElementIndex) {
return Math.floor(this._currentElementIndex / this._items.length);
}
return 0;
}
_selectElementByIndex(currentIndex) {
let index = currentIndex;
const itemsCount = this._itemsToShow.length;
const sizeOfCellInCompactInRem = 2;
const sizeOfCellInCozyInRem = 2.875;
const sizeOfCellInCompactInPixels = sizeOfCellInCompactInRem * 16;
const sizeOfCellInCozyInPixels = sizeOfCellInCozyInRem * 16;
const scrollBy = this.isCompact ? sizeOfCellInCompactInPixels * index : sizeOfCellInCozyInPixels * index;
if (this.cyclic) {
index = this._handleArrayBorderReached(index);
}
if (index < itemsCount && index > -1) {
this._scroller.scrollTo(0, scrollBy);
this._currentElementIndex = index;
this.value = this._items[index - (this._getCurrentRepetition() * this._items.length)];
this.fireEvent("valueSelect", { value: this.value });
}
}
_timesMultipliedOnCyclic() {
const minElementsInCyclicWheelSlider = 70;
const repetitionCount = Math.round(minElementsInCyclicWheelSlider / this._items.length);
const minRepetitionCount = 3;
return Math.max(minRepetitionCount, repetitionCount);
}
_buildItemsToShow() {
this._itemsToShow = this._items;
if (this.cyclic) {
if (this._itemsToShow.length < this._items.length * this._timesMultipliedOnCyclic()) {
for (let i = 0; i < this._timesMultipliedOnCyclic(); i++) {
this._itemsToShow = this._itemsToShow.concat(this._items);
}
}
}
}
_handleArrayBorderReached(currentIndex) {
const arrayLength = this._itemsToShow.length;
const maxVisibleElementsOnOneSide = 7;
let index = currentIndex;
if (maxVisibleElementsOnOneSide > index) {
index += this._items.length * 2;
} else if (index > arrayLength - maxVisibleElementsOnOneSide) {
index -= this._items.length * 2;
}
return index;
}
_handleWheel(e) {
if (!e) {
return;
}
e.stopPropagation();
e.preventDefault();
if (e.timeStamp === this._prevWheelTimestamp || !this._expanded) {
return;
}
if (e.deltaY > 0) {
this._itemUp();
} else if (e.deltaY < 0) {
this._itemDown();
}
this._prevWheelTimestamp = e.timeStamp;
}
_onclick(e) {
if (!e.target.classList.contains("ui5-wheelslider-item")) {
return;
}
if (this._expanded) {
this.value = e.target.textContent;
this._selectElement(e.target);
this.fireEvent("valueSelect", { value: this.value });
} else {
this._expanded = true;
}
}
_onArrowDown(e) {
e.preventDefault();
this._itemDown();
}
_onArrowUp(e) {
e.preventDefault();
this._itemUp();
}
_itemDown() {
const nextElementIndex = this._currentElementIndex + 1;
this._selectElementByIndex(nextElementIndex);
}
_itemUp() {
const nextElementIndex = this._currentElementIndex - 1;
this._selectElementByIndex(nextElementIndex);
}
_onkeydown(Π΅) {
if (!this._expanded) {
return;
}
if (isUp(Π΅)) {
this._onArrowUp(Π΅);
}
if (isDown(Π΅)) {
this._onArrowDown(Π΅);
}
}
_onfocusin(e) {
e.preventDefault();
this.expandSlider();
}
_onfocusout(e) {
e.preventDefault();
this.collapseSlider();
}
} |
JavaScript | class PdfElement extends (0, _schemaBehaviors.SchemaBehaviors)(_polymerElement.PolymerElement) {
constructor() {
super();
new Promise((res, rej) => _require.default(["../../@polymer/paper-card/paper-card.js"], res, rej));
new Promise((res, rej) => _require.default(["../../@polymer/app-layout/app-toolbar/app-toolbar.js"], res, rej));
new Promise((res, rej) => _require.default(["../../@polymer/paper-spinner/paper-spinner.js"], res, rej));
}
static get template() {
return (0, _polymerElement.html)`
<style>
:host {
display: block;
width: 100%;
height: 100%;
}
app-toolbar.pdf-toolbar {
--app-toolbar-background: #323639;
}
.pdf-viewer {
text-align: center;
border: 1px solid #4d4d4d;
}
.pdf-viewport-out {
overflow: auto;
background-color: #525659;
position: relative;
width: 100%;
height: 100%;
}
.pdf-viewport {
display: block;
position: relative;
border: 1px solid #eeeeee;
transition: all 200ms ease-in-out;
width: 100%;
height: 100%;
}
.sidebar {
background-color: gray;
float: left;
height: 0px;
overflow: scroll;
margin-left: -25%;
visibility: hidden;
}
.main {
margin-left: 0%;
}
.pageselector {
width: 3ch;
background-color: black;
font-size: 17px;
background-color: transparent;
border: 0px solid;
}
.pageselector:focus {
outline: none;
}
#input {
-webkit-margin-start: -3px;
color: #fff;
line-height: 18px;
padding: 3px;
text-align: end;
}
#input:focus,
#input:hover {
background-color: rgba(0, 0, 0, 0.5);
border-radius: 2px;
}
#slash {
padding: 0 3px;
}
paper-spinner {
position: absolute;
left: 50%;
}
.textLayer {
transition: all 200ms ease-in-out;
}
.positionRelative {
position: relative;
}
</style>
<paper-material elevation="{{elevation}}">
<div class="card-content" style="width: {{width}}px">
<paper-card class="paperCard" style="width: {{width}}px">
<div class="pdf-viewer">
<app-toolbar class="pdf-toolbar">
<paper-icon-button
icon="menu"
on-click="sideBar"
></paper-icon-button>
<paper-icon-button
icon="arrow-back"
on-click="showPrev"
></paper-icon-button>
<input
class="pageselector"
id="input"
is="iron-input"
value="{{currentPage}}"
prevent-invalid-input=""
allowed-pattern="\\d"
on-change="pageNumSearch"
/>
<span id="slash">/</span><span id="totalPages"></span>
<paper-icon-button
icon="arrow-forward"
on-click="showNext"
></paper-icon-button>
<span class="title" hidden="{{!showFileName}}">Testing</span>
<span class="title" hidden="{{showFileName}}"></span>
<span class="pageRendering"></span>
<paper-icon-button
icon="zoom-in"
on-click="zoomIn"
></paper-icon-button>
<paper-icon-button
icon="zoom-out"
on-click="zoomOut"
></paper-icon-button>
<paper-icon-button
id="zoomIcon"
icon="fullscreen"
on-click="zoomFit"
></paper-icon-button>
<paper-icon-button
icon="file-download"
hidden\$="{{!downloadable}}"
on-click="download"
></paper-icon-button>
</app-toolbar>
<div id="container" class="sidebar" style="width:25%"></div>
<div id="main">
<div id="test" class="pdf-viewport-out">
<canvas class="pdf-viewport"></canvas>
<div
id="text-layer"
class="textLayer"
hidden\$="{{!enableTextSelection}}"
></div>
</div>
<paper-spinner
class="spinner"
hidden\$="{{!showSpinner}}"
></paper-spinner>
</div>
</div>
</paper-card>
</div>
</paper-material>
`;
}
static get tag() {
return "pdf-element";
}
static get properties() {
return { ...super.properties,
/**
* Source of a PDF file.
*/
src: {
type: String,
reflectToAttribute: true
},
/**
* The z-depth of this element, from 0-5. Setting to 0 will remove the shadow, and each increasing number greater than 0 will be "deeper" than the last.
*/
elevation: {
type: Number,
value: 1
},
/**
* If provided then download icon will appear on the toolbar to download file.
*/
downloadable: {
type: Boolean,
value: false
},
/**
* If provided then file name will be shown on the toolbar.
*/
showFileName: {
type: Boolean,
value: false
},
/*
* If provided then during page rendering loading spinner will be shown.
* Maybe used for documents with many images for example.
*/
showSpinner: {
type: Boolean,
value: false
},
/*
* If provided then text selection will be enabled.
*/
enableTextSelection: {
type: Boolean,
value: false
},
/*
* If provided then the document will be zoomed to maximum width initially.
*/
fitWidth: {
type: Boolean,
value: false
},
/*
* If provided then the width will be set.
*/
width: {
type: Number,
value: 500
}
};
}
connectedCallback() {
super.connectedCallback();
this.src = this.getAttribute("src");
this._initializeReader();
if (this.src) this.instance.loadPDF();
this._setFitWidth();
}
static get haxProperties() {
return {
canScale: true,
canPosition: true,
canEditSource: false,
gizmo: {
title: "PDF viewer",
descrption: "This can nicely present a PDF in a standard inplace, cross browser way.",
icon: "image:picture-as-pdf",
color: "red",
groups: ["Presentation", "PDF", "Data"],
handles: [{
type: "pdf",
url: "src",
source: "src"
}, {
type: "document",
url: "src",
source: "src"
}],
meta: {
author: "ELMS:LN"
}
},
settings: {
quick: [{
property: "src",
title: "File",
description: "The URL for the pdf",
inputMethod: "textfield",
icon: "link",
required: true
}],
configure: [{
property: "src",
title: "Source",
description: "The URL for this csv file",
inputMethod: "textfield",
icon: "link",
required: true
}, {
property: "downloadable",
title: "Downloadable",
description: "User can download this",
inputMethod: "boolean",
icon: "file-download"
}, {
property: "enableTextSelection",
title: "Text Selection",
description: "User can select text in this element.",
inputMethod: "boolean",
icon: "file-download"
}, {
property: "elevation",
title: "Elevation",
description: "Visual elevation of the element",
inputMethod: "number",
icon: "flip-to-front"
}],
advanced: []
}
};
}
/*
* For the first time the pdf is loaded.
* The inital page is set to 1 and it sets the total Pages
*/
loadPDF() {
if (!this.getAttribute("src")) return;
this.instance.changePDFSource(this.getAttribute("src"));
this.currentPage = 1;
this.totalPages = this.instance.totalPages;
this.fileName = this.src.split("/").pop();
this._setFitWidth();
this.shadowRoot.querySelector("#zoomIcon").icon = "fullscreen";
}
/*
* When a new pdf is selected and loaded, this sets the properties for the switch
*/
attributeChanged(name, type) {
if (name === "src") {
if (typeof this.instance == "undefined") this._initializeReader();else {
this.loadPDF();
this.changedSideBar = true;
this.fromChange = true;
this.sideBar();
}
} else if (name === "fitWidth") {
this._setFitWidth();
}
}
_initializeReader() {
this.instance = new Reader(this);
if (this.src != null) this.fileName = this.src.split("/").pop();
this.currentPage = 1;
}
_setFitWidth() {
this.instance.setFitWidth(this.fitWidth);
}
/*
* Is called from zoomIn function to control the zoom in
*/
zoomInOut(step) {
if (this.instance.currentZoomVal >= 2) {
this.instance.currentZoomVal = 2;
} else if (this.instance.currentZoomVal <= 0.1) {
this.instance.currentZoomVal = 0.1;
} else {
this.shadowRoot.querySelector("#zoomIcon").icon = "fullscreen";
this.instance.zoomInOut(step);
}
}
/*
* Zoom in to the pdf as long as it is loaded
*/
zoomIn() {
if (this.instance.pdfExists) {
this.zoomInOut(0.1);
}
}
/*
* Zoom out of the pdf as long as it is loaded
*/
zoomOut() {
if (this.instance.pdfExists) {
this.instance.zoomInOut(-0.1);
}
}
/*
* When the zoom in/out button is selected. Reformats the pdf to the original display
*/
zoomFit() {
if (this.instance.pdfExists) {
if (this.instance.currentZoomVal == this.instance.widthZoomVal) {
this.instance.zoomPageFit();
this.shadowRoot.querySelector("#zoomIcon").icon = "fullscreen";
} else {
this.instance.zoomWidthFit();
this.shadowRoot.querySelector("#zoomIcon").icon = "fullscreen-exit";
}
}
}
/*
* Controls the page search functionality.
* When a number is input it checks to see if it is a valid page
* If it is valid then it will change the view to that page
* as well as update the page number
*/
pageNumSearch() {
var page = parseInt(this.shadowRoot.querySelector("#input").value);
if (1 <= page && page <= this.instance.totalPagesNum) {
this.instance.currentPage = page;
this.instance.queueRenderPage(this.instance.currentPage);
this.currentPage = page;
this.shadowRoot.querySelector("#input").blur();
} else {
this.shadowRoot.querySelector("#input").value = this.currentPage;
this.shadowRoot.querySelector("#input").blur();
}
}
/*
* Is called when a page is selected from the sidebar
* Checks to make sure a valid page is selected, then changes the page
* The currentInstance is passed in to make sure it is changing the proper pdf if multiple are loaded
*/
sideBarClick(page, currentInstance, currentThis) {
//this.instance = currentInstance;
var parsedFileName = currentThis.src.split("/").pop();
var self = currentInstance;
currentThis.sidebarOpen = true;
if (1 <= page && page <= currentInstance.totalPagesNum) {
self.currentPage = page;
self.queueRenderPage(self.currentPage);
currentInstance.currentPage = page;
currentThis.currentPage = page;
this.shadowRoot.querySelector("#input").blur();
} else {
this.shadowRoot.querySelector("#input").value = self.currentPage;
this.shadowRoot.querySelector("#input").blur();
}
}
/*
* Is called to show the previous page and update page number
*/
showPrev() {
if (1 < this.instance.currentPage) {
this.instance.currentPage--;
this.instance.queueRenderPage(this.instance.currentPage);
this.currentPage--;
}
}
/*
* Is called to show the next page and update page number
*/
showNext() {
if (this.instance.totalPagesNum > this.instance.currentPage) {
this.instance.currentPage++;
this.instance.queueRenderPage(this.instance.currentPage);
this.currentPage++;
}
}
/*
* The sidebar is a scrollable bar on the side of the page that allows you to scroll and select a page to change to
* Checks if the pdf loaded changed
* Then checks if the sidebar is open or not
* If it is open, close. Else open sidebar. Set sidebarOpen to either T or F
*/
sideBar() {
if (this.instance.pdfExists) {
if (!this.fromChange) {
this.shadowRoot.querySelector("#container").style.height = this.shadowRoot.querySelector("#test").style.height;
this.shadowRoot.querySelector("#container").style.width = this.shadowRoot.querySelector("#test").style.width;
if (this.shadowRoot.querySelector("#main").style.marginLeft == "25%") {
this.sidebarOpen = false;
this.instance.setViewportPos(false);
this.shadowRoot.querySelector("#main").style.marginLeft = "0%";
this.shadowRoot.querySelector("#container").style.marginLeft = "-25%";
this.shadowRoot.querySelector("#container").style.visibility = "hidden";
} else {
this.sidebarOpen = true;
this.shadowRoot.querySelector("#main").style.marginLeft = "25%";
this.shadowRoot.querySelector("#container").style.marginLeft = "0%";
this.shadowRoot.querySelector("#container").style.visibility = "visible";
this.instance.setViewportPos(true);
}
}
this.fromChange = false;
this.instance.sidebarSetup(this);
this.changedSideBar = false;
}
}
/*
* Is called when the download pdf button is selected
*/
download() {
if (this.instance.pdfExists) {
this.instance.download();
}
}
} |
JavaScript | class Parametrics {
/**
* Returns the voronoi data (check https://github.com/gorhill/Javascript-Voronoi#usage) for details
* @param {object} origin - {x,y} point representing the top right corner of the
* @param {number} w width of the voronoi area
* @param {number} h height of the voronoi area
* @param {number} sites list of {x,y} points representing the initial cell centers
*/
static voronoi (origin, w, h, sites) {
let bbox = {xl:origin.x, xr:origin.x + w, yt:origin.y, yb:origin.y + h}
return new voronoi().compute(sites, bbox)
}
/**
* Returns the points generated by a Butterfly curve
* @param {object} origin - xymap with coordinates
* @param {number} scale - value to scale the points
* @param {number} loops - number of loops to iterate
* @param {number} lambda - lambda parameter of the curve
*/
static butterflyCurve(origin, scale, loops, lambda) {
let points = [];
let stepSize = 0.025;
let upperLimit = loops * Math.PI;
for (let t = 0.0; t < upperLimit; t += stepSize) {
let e = (Math.exp(Math.cos(t)) - 2 * Math.cos(lambda * t) - Math.pow(Math.sin(t / 12), 5));
let x = Math.sin(t) * e;
let y = Math.cos(t) * e;
points.push(createVector(x * scale + origin.x, y * scale + origin.y))
}
return points;
}
/**
* Returns the points generated by a Hypocycloid curve
* @param {object} origin - xymap with starting coordinates
* @param {number} r - minor circle radio
* @param {number} R - major circle radio
* @param {number} loops - number of loops to iterate
*/
static hypocycloid(origin, scale, loops, r, R) {
let points = [];
let stepSize = 0.025;
let upperLimit = loops * Math.PI;
for (let th = 0.0; th < upperLimit; th += stepSize) {
let x = (R - r) * Math.cos(th) + r * Math.cos(((R - r) / r) * th);
let y = (R - r) * Math.sin(th) - r * Math.sin(((R - r) / r) * th);
points.push(createVector(x * scale + origin.x, y * scale + origin.y))
}
return points;
}
/**
* Returns the points generated by a Rose curve.
* The k parameter can be expressed as (n/d), being both integer values
* @param {object} origin - xymap with starting coordinates
* @param {number} k - k factor of the Rose curve (n/d)
* @param {number} loops - number of loops to iterate
*/
static rose(origin, scale, loops, k) {
let points = [];
let stepSize = 0.025;
let upperLimit = loops * Math.PI;
for (let th = 0.0; th < upperLimit; th += stepSize) {
let x = Math.cos(k * th) * Math.cos(th);
let y = Math.cos(k * th) * Math.sin(th);
points.push(createVector(x, y));
}
return points;
}
/**
* Returns the points from the Rossler attractor
* @param {object} origin - xy coordinates to center the attractor
* @param {number} scale - scale factor
* @param {number} loops - number of iterations
* @param {number} a a value
* @param {number} b b value
* @param {number} c c value
* @param {number} h h value
* @return a list of xy points
*
* Rossler Attractor code.
* http://paulbourke.net/fractals/rossler/
*/
static rossler(origin, scale, loops, a, b, c, h) {
function rosslerPoint(x, y, z, a, b, c) {
let dx = -(y + z);
let dy = x + a * y;
let dz = b + z * (x - c);
return {
x: dx,
y: dy,
z: dz
};
};
let center = {
x: origin.x,
y: origin.y
}; // center in the screen
let x = 0.1,
y = 0.1,
z = 0.1;
let tmpx = 0,
tmpy = 0,
tmpz = 0;
let points = [];
for (let i = 0; i < loops; i++) {
let dt = rosslerPoint(x, y, z, a, b, c);
tmpx = x + h * dt.x;
tmpy = y + h * dt.y;
tmpz = z + h * dt.z;
let point = createVector(tmpx * scale + center.x, tmpy * scale + center.y, tmpz)
x = tmpx;
y = tmpy;
z = tmpz;
}
return points;
}
/**
* Returns the Lorent attractor points
* @param {object} origin - xy coordinates
* @param {number} scale - scale factor
* @param {number} loops - iterations
* @param {number} z - value
* @param {number} a - value
* @param {number} b - value
* @param {number} c - value
* @param {number} h - value
* @return a list of xypoints
Lorentz Attractor code.
http://www.algosome.com/articles/lorenz-attractor-programming-code.html
*/
static lorentz(origin, scale, loops, x, y, z, a, b, c, h) {
function lorentzPoint(x, y, z, a, b, c) {
let dx = a * (y - x);
let dy = x * (b - z) - y;
let dz = x * y - c * z;
return {
x: dx,
y: dy,
z: dz
};
};
//var x = 0.1, y = 0.1, z = 0.1;
let tmpx = 0,
tmpy = 0,
tmpz = 0;
let points = [];
for (let i = 0; i < loops; i++) {
let dt = lorentzPoint(x, y, z, a, b, c);
tmpx = x + h * dt.x;
tmpy = y + h * dt.y;
tmpz = z + h * dt.z;
points.push(createVector(tmpx * scale + origin.x, tmpy * scale + origin.y, tmpz))
x = tmpx;
y = tmpy;
z = tmpz;
}
return points;
}
/**
* Returns the points from an attractor
* http://struct.cc/blog/2011/08/15/strange-attractors/
* @param {number} numPoints number of points to generate
* @param {string} entryString initial configuration string
* @return a list of xy points
*/
static attractor(origin, loops, entryString) {
// Fractal pattern and coefficients.
let a = [];
let points = [];
// Parameters.
let x = 0.1,
y = 0.1;
let r = 360 % entryString.length;
// Initialize coefficients.
for (let i = 0; i < entryString.length; i++) {
a[i] = (entryString.charCodeAt(i) - 65 - 12) / 10;
}
points.push({
x: origin.x + 50 * Math.cos(r),
y: origin.y + 58 * Math.sin(r),
r: 0
});
for (let i = 0; i < loops; i++) {
let nx = a[0] + a[1] * x + a[2] * x * x +
a[3] * x * y + a[4] * y + a[5] * y * y;
let ny = a[6] + a[7] * x + a[8] * x * x +
a[9] * x * y + a[10] * y + a[11] * y * y;
let xvalue = (origin.x) * nx + origin.x;
let yvalue = (origin.y) * ny + origin.y;
points.push(createVector(Math.abs(xvalue), Math.abs(yvalue)))
x = nx;
y = ny;
}
return points;
}
/*a = -2.24, b = 0.43, c = -0.65, d = -2.43
a = 2.01, b = -2.53, c = 1.61, d = -0.33
a = -2, b = -2, c = -1.2, d = 2
a = 2.01, b = -2.53, c = 1.61, d = -0.33
a = -2, b = -2, c = -1.2, d = 2
*/
static dejon(origin, a, b, c, d, scale = 100, loops = 10) {
let points = []
let xt = 1, yt = 1
for (let i = 0; i < loops; i++) {
let nextx = (Math.sin(a * yt) - Math.cos(b * xt))
let nexty = (Math.sin(c * xt) - Math.cos(d * yt))
points.push(createVector(scale * xt + origin.x + scale, scale * yt + origin.y - scale))
xt = nextx
yt = nexty
}
return points
}
} |
JavaScript | class Route {
/**
* Constructor for Route class.
*
* @param {module:workbox-routing~matchCallback} match
* A callback function that determines whether the route matches a given
* `fetch` event by returning a non-falsy value.
* @param {module:workbox-routing~handlerCallback} handler A callback
* function that returns a Promise resolving to a Response.
* @param {string} [method='GET'] The HTTP method to match the Route
* against.
*/
constructor(match, handler, method = defaultMethod) {
if (process.env.NODE_ENV !== 'production') {
assert.isType(match, 'function', {
moduleName: 'workbox-routing',
className: 'Route',
funcName: 'constructor',
paramName: 'match',
});
if (method) {
assert.isOneOf(method, validMethods, { paramName: 'method' });
}
}
// These values are referenced directly by Router so cannot be
// altered by minificaton.
this.handler = normalizeHandler(handler);
this.match = match;
this.method = method;
}
} |
JavaScript | class LinkedBuffer {
static from(buffer, start, end) {
const chain = new LinkedBuffer();
return init(chain, buffer, start, end);
}
append(buffer, start, end) {
const chain = this;
if (chain.buffer) {
last(chain).next = LinkedBuffer.from(buffer, start, end);
return chain;
} else {
return init(chain, buffer, start, end);
}
}
clear() {
return reset(this);
}
toBuffer() {
const chain = this;
return chain.next ? combineBuffer(chain) : getBuffer(chain);
}
} |
JavaScript | class Plugin extends PuppeteerExtraPlugin {
constructor(opts = {}) {
super(opts)
}
get name() {
return 'stealth/evasions/navigator.hardwareConcurrency'
}
async onPageCreated(page) {
await page.evaluateOnNewDocument(opts => {
Object.defineProperty(
Object.getPrototypeOf(navigator),
'hardwareConcurrency',
{
value: opts.hardwareConcurrency || 4,
writable: false
}
)
}, this.opts)
}
} |
JavaScript | class IconButton extends Component {
render() {
return (
<div className={classNames("button icon-only", this.props.className,
{"is-small": this.props.small})}
title={this.props.title}
onClick={this.props.onClick}>
<div className="control-icon">
<SvgSymbol viewBox='0 0 20 20' sym={this.props.spriteName}
className={classNames({"is-primary": this.props.primary,
"is-danger": this.props.danger})} />
</div>
</div>
)
}
} |
JavaScript | class Adder extends CircuitElement {
constructor(x, y, scope = globalScope, dir = 'RIGHT', bitWidth = 1) {
super(x, y, scope, dir, bitWidth);
/* this is done in this.baseSetup() now
this.scope['Adder'].push(this);
*/
this.setDimensions(20, 20);
this.inpA = new Node(-20, -10, 0, this, this.bitWidth, 'A');
this.inpB = new Node(-20, 0, 0, this, this.bitWidth, 'B');
this.carryIn = new Node(-20, 10, 0, this, 1, 'Cin');
this.sum = new Node(20, 0, 1, this, this.bitWidth, 'Sum');
this.carryOut = new Node(20, 10, 1, this, 1, 'Cout');
}
/**
* @memberof Adder
* fn to create save Json Data of object
* @return {JSON}
*/
customSave() {
const data = {
constructorParamaters: [this.direction, this.bitWidth],
nodes: {
inpA: findNode(this.inpA),
inpB: findNode(this.inpB),
carryIn: findNode(this.carryIn),
carryOut: findNode(this.carryOut),
sum: findNode(this.sum),
},
};
return data;
}
/**
* @memberof Adder
* Checks if the element is resolvable
* @return {boolean}
*/
isResolvable() {
return this.inpA.value !== undefined && this.inpB.value !== undefined;
}
/**
* @memberof Adder
* function to change bitwidth of the element
* @param {number} bitWidth - new bitwidth
*/
newBitWidth(bitWidth) {
this.bitWidth = bitWidth;
this.inpA.bitWidth = bitWidth;
this.inpB.bitWidth = bitWidth;
this.sum.bitWidth = bitWidth;
}
/**
* @memberof Adder
* resolve output values based on inputData
*/
resolve() {
if (this.isResolvable() === false) {
return;
}
let carryIn = this.carryIn.value;
if (carryIn === undefined) carryIn = 0;
const sum = this.inpA.value + this.inpB.value + carryIn;
this.sum.value = ((sum) << (32 - this.bitWidth)) >>> (32 - this.bitWidth);
this.carryOut.value = +((sum >>> (this.bitWidth)) !== 0);
simulationArea.simulationQueue.add(this.carryOut);
simulationArea.simulationQueue.add(this.sum);
}
} |
JavaScript | class LocalizationRead {
/**
* Constructs a new <code>LocalizationRead</code>.
* localization metadata and latest revision for associated template
* @alias module:dyspatch-client/LocalizationRead
*/
constructor() {
LocalizationRead.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>LocalizationRead</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:dyspatch-client/LocalizationRead} obj Optional instance to populate.
* @return {module:dyspatch-client/LocalizationRead} The populated <code>LocalizationRead</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new LocalizationRead();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('languages')) {
obj['languages'] = ApiClient.convertToType(data['languages'], ['String']);
}
if (data.hasOwnProperty('url')) {
obj['url'] = ApiClient.convertToType(data['url'], 'String');
}
if (data.hasOwnProperty('template')) {
obj['template'] = ApiClient.convertToType(data['template'], 'String');
}
if (data.hasOwnProperty('compiled')) {
obj['compiled'] = CompiledRead.constructFromObject(data['compiled']);
}
if (data.hasOwnProperty('createdAt')) {
obj['createdAt'] = ApiClient.convertToType(data['createdAt'], 'Date');
}
if (data.hasOwnProperty('updatedAt')) {
obj['updatedAt'] = ApiClient.convertToType(data['updatedAt'], 'Date');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('localeGroup')) {
obj['localeGroup'] = ApiClient.convertToType(data['localeGroup'], 'String');
}
}
return obj;
}
} |
JavaScript | class FinancialDispositionMonitor {
disposed_ = null;
regulator_ = null;
lastVehicleModificationTime_ = null;
constructor(regulator, NativeCallsConstructor = FinancialNativeCalls) {
this.disposed_ = false;
this.regulator_ = regulator;
this.nativeCalls_ = new NativeCallsConstructor();
this.lastVehicleModificationTime_ = new WeakMap();
server.vehicleManager.addObserver(this);
}
// Spins until the disposition monitor gets disposed of. At the configured interval, will check
// the amount of cash each player has, and align that with the financial regulator.
async monitor() {
await wait(kDispositionMonitorSpinDelay);
while (!this.disposed_) {
const currentTime = server.clock.monotonicallyIncreasingTime();
for (const player of server.playerManager) {
const expectedCash = this.regulator_.getPlayerCashAmount(player);
const actualCash = this.nativeCalls_.getPlayerMoney(player);
if (expectedCash === actualCash)
continue;
const difference = actualCash - expectedCash;
const absoluteDifference = Math.abs(difference);
const lastVehicleModificationTime = this.lastVehicleModificationTime_.get(player);
const lastVehicleModificationValid =
lastVehicleModificationTime >= (currentTime - kModShopSignalExpirationMs);
if (lastVehicleModificationValid &&
difference >= -kModShopMaximumDifference && difference < 0) {
this.regulator_.setPlayerCashAmount(player, actualCash, true);
continue;
}
if (this.isInPayAndSprayShop(player) &&
difference >= -kPayAndSprayMaximumDifference && difference < 0) {
this.regulator_.setPlayerCashAmount(player, actualCash, true);
continue;
}
if (this.isInCasino(player) && absoluteDifference <= kCasinoMaximumDifference) {
this.regulator_.setPlayerCashAmount(player, actualCash, true);
continue;
}
this.nativeCalls_.givePlayerMoney(player, expectedCash - actualCash);
}
await wait(kDispositionMonitorSpinDelay);
}
}
// Returns whether the given |player| currently is in a casino.
isInCasino(player) {
return this.isInArea(player, kCasinoAreas);
}
// Returns whether the given |player| currently is in a Pay 'n Spray shop.
isInPayAndSprayShop(player) {
return this.isInArea(player, kPayAndSprayShops);
}
// Returns whether the |player| is currently in one of the |areas|.
isInArea(player, areas) {
const position = player.position;
for (const area of areas) {
if (position.x < area[0] || position.x > area[1])
continue;
if (position.y < area[2] || position.y > area[3])
continue;
return true;
}
return false;
}
onVehicleMod(player) {
this.lastVehicleModificationTime_.set(player, server.clock.monotonicallyIncreasingTime());
}
onVehiclePaintjob(player) {
this.lastVehicleModificationTime_.set(player, server.clock.monotonicallyIncreasingTime());
}
onVehicleRespray(player) {
this.lastVehicleModificationTime_.set(player, server.clock.monotonicallyIncreasingTime());
}
dispose() {
server.vehicleManager.removeObserver(this);
this.disposed_ = true;
}
} |
JavaScript | class World {
/**
* Constructs an instance of the world.
*
* @param {object} [options] - The initial systems, components, and context to setup in the world.
* Each one is optional. See below for registering these after world construction.
*
* @example
* const world = new World({
* components: { position, velocity },
* systems: [Input, Physics, Render],
* context: { state },
* })
*/
constructor(options) {
/** @ignore */
this._systems = new SystemStorage(this)
/** @ignore */
this.entities = new EntityStorage(this)
// Register components, context, and systems
if (options) {
if (options.components) {
this.components = options.components
}
if (options.context) {
this.context = options.context
}
if (options.systems) {
this.systems = options.systems
}
}
}
/**
* Removes all entities from the world.
* Does not affect any registered systems or components.
*
* @example
* world.clear()
*/
clear() {
this.entities.clear()
}
/**
* Registers a component type to the world. Components must be constructable. If the component has
* an onCreate(), it is passed all of the arguments from methods like entity.set(). Also, components
* can have an onRemove() method, which gets called when removing that component from an entity.
*
* @param {string} name - The name
* @param {function} componentClass - The component class, must be a constructable class or function
*
* @example
* world.component('myComponent', class {
* // It is highly recommended to use onCreate() over constructor(), because the component
* // will have already been added to the entity. In the constructor(), it is not safe to use
* // "entity" because it does not contain the current component while still in the constructor.
* onCreate(some, args) {
* this.some = some
* this.args = args
* this.entity.set('whatever') // this.entity is auto-injected, and this is safe to do here
* }
* })
* // entity === the new entity object
* // some === 10
* // args === 500
* world.entity().set('myComponent', 10, 500)
*
* @return {string} Registered component name on success, undefined on failure
*/
component(name, componentClass) {
this.entities.registerComponent(name, componentClass)
}
/**
* Registers all components in an object. Merges with existing registered components.
*
* @example
* world.components = { position: Position }
*/
set components(comps) {
for (let key in comps) {
this.entities.registerComponent(key, comps[key])
}
}
/**
* Returns currently registered components.
*
* @example
* const { position: Position } = world.components
*/
get components() {
return this.entities.componentClasses
}
/**
* Creates a new entity in the world
*
* @example
* world.entity()
*
* @return {Entity} The new entity created
*/
entity() {
return this.entities.createEntity()
}
/**
* Sets a context object that is automatically injected into all existing and new systems.
* Calling this multiple times will overwrite any previous contexts passed. One caveat is that
* you can only start to use the injected context in systems starting with init(). It is not
* available in the constructor.
*
* @param {Object} data - The object to use as context to pass to systems.
* All the keys inside the context object will be spread into the top-level of the system.
*
* @example
* const state = { app: new PIXI.Application() }
* const world = new World()
* world.context = state // new and existing systems can directly use this.app
* world.system(...)
*/
set context(data) {
this._systems.setContext(data)
}
/**
* Returns currently set context object.
*
* @example
* const { app } = world.context
*/
get context() {
return this._systems.context
}
/**
* Registers a system to the world.
* The order the systems get registered, is the order then run in.
*
* @example
* // Movement system (basic example)
* class MovementSystem {
* run(dt) {
* world.each('position', 'velocity', ({ position, velocity }) => {
* position.x += velocity.x * dt
* position.y += velocity.y * dt
* })
* }
* }
* // Input system (advanced example)
* class InputSystem {
* init(key) {
* // Have access to this.keyboard here, but not in constructor
* this.key = key
* }
* run(dt) {
* if (this.keyboard.isPressed(this.key)) {
* world.each('controlled', 'velocity', ({ velocity }, entity) => {
* // Start moving all controlled entities to the right
* velocity.x = 1
* velocity.y = 0
* // Can also use the full entity here, in this case to add a new component
* entity.set('useFuel')
* })
* }
* }
* }
* // Inject context (see world.context)
* world.context = { keyboard: new Keyboard() }
* // Register systems in order (this method)
* world.system(InputSystem, 'w') // pass arguments to init/constructor
* world.system(MovementSystem)
* // Run systems (can get dt or frame time)
* world.run(1000.0 / 60.0)
*
* @param {Function} systemClass - The system class to instantiate. Can contain a
* constructor(), init(), run(), or any other custom methods/properties.
*
* @param {...Object} [args] - The arguments to forward to the system's constructor and init.
* Note that it is recommended to use init if using context, see world.context.
* Passing args here is still useful, because it can be specific to each system, where
* the same context is passed to all systems.
*/
system(systemClass, ...args) {
this._systems.register(systemClass, ...args)
}
/**
* Registers additional systems, in the order specified. See world.system().
*
* @example
* world.systems = [inputSystem, movementSystem]
*/
set systems(values) {
for (const sys of values) {
this._systems.register(sys)
}
}
/**
* Returns currently added systems, in the order added.
*
* @example
* const [inputSystem, movementSystem] = world.systems
*/
get systems() {
return this._systems.systems
}
/**
* Calls run() on all systems. These methods can return true to cause an additional rerun of all systems.
* Reruns will not receive the args passed into run(), as a way to identify reruns.
*
* @example
* world.run(deltaTime)
*
* @example
* // Example flow of method call order:
* // Setup systems:
* world.system(systemA)
* world.system(systemB)
* // During world.run():
* // systemA.run()
* // systemB.run()
*
* @param {...Object} [args] - The arguments to forward to the systems' methods
*/
run(...args) {
this._systems.run(...args)
}
/**
* Iterate through components and entities with all of the specified component names
*
* @example
* // Use a callback to process entities one-by-one
* // This is the recommended way, as it is higher performance than allocating and
* // returning an array
* world.each('comp', ({ comp }) => { comp.value = 0 })
*
* @example
* // Get an array of entities
* const entities = world.each('comp')
* for (const entity of entities) {...}
*
* @example
* // Pass multiple components, arrays, use extra entity parameter,
* // and destructure components outside the query
* world.each('compA', ['more', 'comps'], 'compB', ({ compA, compC }, entity) => {
* if (compC) compC.foo(compC.bar)
* compA.foo = 'bar'
* entity.remove('compB')
* })
*
* @param {...Object} args - Can pass component names, arrays of component names, and a callback,
* in any order.
*
* **{...string}**: The component names to match entities with. This checks if the entity
* has ALL of the specified components, but does not check for additional components.
*
* **{Function}**: The callback to call for each matched entity. Takes (entity.data, entity).
* Entity data is an object of {[componentName]: [component]}, that can be destructured with syntax
* shown in the examples.
*
* @return {Entity[]} If no callback is specified, then returns an array of the entity results.
*/
each(...args) {
return this.entities.each(...args)
}
} |
JavaScript | class ElementHandler {
element(element) {
if (toBeRemovedTags.includes(element.tagName)) {
element.remove()
}
}
comments(comment) {
comment.remove()
}
} |
JavaScript | class EveParticleDirectForce extends Tw2ParticleForce
{
force = vec3.create();
/**
* Black definition
* @param {*} r
* @returns {*[]}
*/
static black(r)
{
return [
["force", r.vector3]
];
}
/**
* Identifies that the class is in staging
* @property {null|Number}
*/
static __isStaging = 4;
} |
JavaScript | class LinesLabel extends Component {
lineStyle(line) {
return {
color: line.label_font_color,
backgroundColor: line.color,
marginLeft: 0,
marginRight: 5
}
}
system() {
// If there are multiple lines,
// we assume that they all belong to the same systemm
return {
name: this.props.lines[0].system,
historic: this.props.lines[0].historic
};
}
render() {
return (
<li className="c-list__item line-label-li">
{this.props.lines.map(line =>
<span key={line.name} className="c-text--highlight line-label" style={this.lineStyle(line)}>{line.name}</span>
)}
<strong className="line-label-system">{this.system().name}</strong><SystemTags system={this.system()} />
{/* We loop through all lines, but we usually use showYears with only one line */}
{this.props.showYears && this.props.lines.map(line =>
validFeatureValue(line.from) &&
<span key={line.name} className="line-label-year">{`${line.from} - ${validOrToday(line.to)}`}</span>
)}
</li>
)
}
} |
JavaScript | class Message {
constructor() {
this._colorizer = null;
this._message = '<Empty Logger Message>';
this._timestamp = null;
this._level = 'info';
this._label = null;
this._from = null;
// this._template = '[{{timestamp}} {{level}}] {{message}}';
}
/**
*
* @param {Colorizer} colorizer
* @return {Message} Return instance
*/
setColorizer(colorizer) {
this._colorizer = colorizer;
return this;
}
/**
* This takes a configuration
* object like Winston's colors object.
*
* @param {Object} colors
*/
setColors(colors) {
this._colors = colors;
return this;
}
setColor(key, style) {
this._colors[key] = style;
return this;
}
setTextStyle(...style) {
/*
* We can use an array as argument:
* ['red', 'bold', 'white_bg']
*/
if (Array.isArray(style[0])) {
style = style[0];
}
if (style.length === 1 && typeof style[0] === 'string') {
style = style[0];
} else {
style = style.join('+');
}
// [
// 'bold', 'underline', 'blink',
// 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white',
// 'black_bg', 'red_bg', 'green_bg', 'yellow_bg', 'blue_bg', 'magenta_bg', 'cyan_bg', 'white_bg'
// ]
this._textStyle = style;
return this;
}
stylize(message, style) {
return _ansiStyle(message, style);
}
colorify(level, message, createColor) {
if (createColor) {
if (!this._colors[level]) {
this.setColor(level, ['bold']);
}
}
try {
return this._colorizer(level, message);
} catch (e) {
return message;
}
}
randomColor() {
// let colors = [
// 'bgBlack',
// 'bgRed',
// 'bgGreen',
// 'bgYellow',
// 'bgBlue',
// 'bgMagenta',
// 'bgCyan',
// 'bgWhite'];
let colors = [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
];
let c = colors[Math.floor(Math.random() * colors.length)];
return c;
}
/**
* Set the message of this instance.
*
* @param {String} message String to output
* @memberof Message
* @return {this}
*/
setMessage(message) {
if (message) {
this._message = message;
}
return this;
}
setLoggerName(name) {
if (name) {
this._loggerName = name;
}
return this;
}
/**
* @param {boolean|function} timestamp
* @return {Message}
*/
setTime(timestamp) {
if (typeof timestamp === 'function') {
this._timestamp = timestamp();
} else if (timestamp) {
var format = typeof timestamp === 'string' ? timestamp : 'hh:mm:ss';
this._timestamp = this.dateFormat(format);
}
return this;
}
/**
* @param {string|undefined} label
* @return {Message}
*/
setLabel(label) {
if (label) {
this._label = label;
}
return this;
}
/**
* @param {string|undefined} level
* @return {Message}
*/
setLevel(level) {
if (level) {
this._level = level.toLowerCase();
}
return this;
}
/**
* @param {string|undefined} from
* @return {Message}
*/
setFrom(from) {
if (from) {
this._from = from;
}
return this;
}
/*
* eg: format="YYYY-MM-DD hh:mm:ss";
*/
dateFormat(format) {
var date = new Date();
var o = {
'M+': date.getMonth() + 1, //month
'D+': date.getDate(), //day
'h+': date.getHours(), //hour
'm+': date.getMinutes(), //minute
's+': date.getSeconds(), //second
'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
'S': this.padRight(date.getMilliseconds(), 3, '0') //millisecond
};
if (/(Y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
}
}
return format;
}
padRight(str = '', len = 5, char = ' ') {
str = '' + str;
if (str.length >= len) return str;
return str + Array(len - str.length + 1).join(char);
}
padLeft(str = '', len = 5, char = ' ') {
if (str.length >= len) return str;
return Array(len - str.length + 1).join(char) + str;
}
pad(str = '', len = 10, char = '') {
if (str.length >= len) return str;
len = len - str.length;
let left = Array(Math.ceil(len / 2) + 1).join(char);
let right = Array(Math.floor(len / 2) + 1).join(char);
return left + str + right;
}
toString() {
let from = '';
let after = '';
let before = '';
let message = this._message;
if (this._label) {
before += `[${this._label}] `;
}
let level = this.pad(this._level.toUpperCase(), 8, ' ');
before += `${level}`;
before = this.colorify(this._level, before);
if (this._timestamp) {
before += `[${this._timestamp}] `;
}
if (this._loggerName) {
let loggername = this.padRight(this._loggerName, 12);
loggername = this.colorify(loggername, loggername, true);
before += `βββ ${loggername}`;
}
before += ' : ';
if (this._from) {
from += `${this._from} `;
after += '- ';
}
// let message = this._message;
if (['error', 'warn'].indexOf(this._level) !== -1) {
message = this.colorify(this._level + '-msg', message);
}
if (this._textStyle) {
message = this.stylize(message, this._textStyle);
}
message = enforceColumnWidth(message, this.columnWidth);
message = message.join(this.padRight('\n', LN) + ' ');
after += `${message}`;
return before + from + after;
}
} |
JavaScript | class BasicTool extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>basic tool</div>
)}
} |
JavaScript | class ComponentAdd extends React.Component {
render() {
// Count documents and sections in the project to which the element could be assigned to
const docs = defaultTo([], pathOr([], [ "documents" ], this.props.project))
const documentArray = uniq(this.props.selectionArray)
return (
<List className="document-section-list">
{documentArray.map((doc, index) => {
const key = index
const docum = compose(head, filter(propEq("_id", doc.documentId)))(docs)
if (!docum) return null
const sectionsCount = compose(head, map(d => d.data.sections.length), filter(propEq("_id", doc.documentId)))(this.props.selectedDocuments) || 1
return (
<ComponentAddSection
docItem={doc}
document={docum}
index={index}
key={`document-section-${doc.documentId}-${doc.sectionId}-${key}`}
sectionsCount={sectionsCount}
handleDeleteClick={this.props.handleDeleteClick}
handleSelectSection={this.props.handleSelectSection}
/>
)
})}
<ComponentAddDocument handleAddDocument={this.props.handleAddDocument} remainingDocs={this.props.remainingDocs} />
</List>
)
}
} |
JavaScript | @EdmMapping.entityType('Group')
class Group extends Account {
/**
* @constructor
*/
constructor() {
super();
}
} |
JavaScript | class Game {
constructor(canvas,GAME_OVER,leftArrow,rightArrow) {
this.cvs = canvas;
this.ctx = this.cvs.getContext("2d");
this.GAME_OVER = GAME_OVER;
this.leftArrow = leftArrow;
this.rightArrow= rightArrow;
}
start() {
let cvs = this.cvs;
let ctx = this.ctx;
this.bricks = new Bricks({
score: SCORE,
score_unit: SCORE_UNIT,
canvas: this.cvs,
ctx : this.ctx,
ball: this.ball
});
this.bricks.createBricks();
// this.bricks.drawBricks();
this.paddle = new Paddle({
x: cvs.width / 2 - PADDLE_WIDTH / 2,
y: cvs.height - PADDLE_MARGIN_BOTTOM - PADDLE_HEIGHT,
width: PADDLE_WIDTH,
height: PADDLE_HEIGHT,
dx: 5,
canvas: cvs,
ctx: ctx,
// rArrow: this.rightArrow,
// lArrow: this.leftArrow
});
// this.paddle.drawPaddle();
this.ball = new Ball({
x: cvs.width / 2,
y: this.paddle.y - BALL_RADIUS - 10,
radius: BALL_RADIUS,
speed: 4,
dx: 3 * (Math.random() * 2 - 1),
dy: -3,
canvas: cvs,
ctx: ctx,
rArrow:this. rightArrow,
lArrow: this.leftArrow
})
}
ballBrickCollision() {
for (let r = 0; r < brick.row; r++) {
for (let c = 0; c < brick.column; c++) {
let b = this.bricks.bricksMat[r][c];
// if the brick isn't broken
if (b.status) {
if (this.ball.x + this.ball.radius > b.x && this.ball.x - this.ball.radius < b.x + brick.width && this.ball.y + this.ball.radius > b.y && this.ball.y - this.ball.radius < b.y + brick.height) {
BRICK_HIT.play();
this.ball.dy = -this.ball.dy;
b.status = false; // the brick is broken
SCORE += SCORE_UNIT;
}
}
}
}
}
ballWallCollision(){
let ball = this.ball;
let cvs = this.cvs;
if(ball.x + ball.radius > cvs.width || ball.x - ball.radius < 0){
ball.dx = - ball.dx;
WALL_HIT.play();
}
if(ball.y - ball.radius < 0){
ball.dy = -ball.dy;
WALL_HIT.play();
}
if(ball.y + ball.radius > cvs.height){
LIFE--; // LOSE LIFE
LIFE_LOST.play();
this.resetBall();
}
}
resetBall(){
this.ball.x = this.cvs.width/2;
this.ball.y = this.paddle.y - BALL_RADIUS;
this.ball.dx = 3 * (Math.random() * 2 - 1);
this.ball.dy = -3;
}
ballPaddleCollision(){
let ball = this.ball;
let paddle = this.paddle;
if(ball.x < paddle.x + paddle.width && ball.x > paddle.x && paddle.y < paddle.y + paddle.height && ball.y > paddle.y){
// PLAY SOUND
PADDLE_HIT.play();
// CHECK WHERE THE BALL HIT THE PADDLE
let collidePoint = ball.x - (paddle.x + paddle.width/2);
// NORMALIZE THE VALUES
collidePoint = collidePoint / (paddle.width/2);
// CALCULATE THE ANGLE OF THE BALL
let angle = collidePoint * Math.PI/3;
ball.dx = ball.speed * Math.sin(angle);
ball.dy = - ball.speed * Math.cos(angle);
}
}
showGameStats(text, textX, textY, img, imgX, imgY){
let ctx = this.ctx;
// draw text
ctx.fillStyle = "#FFF";
ctx.font = "25px Germania One";
ctx.fillText(text, textX, textY);
// draw image
ctx.drawImage(img, imgX, imgY,25, 25);
}
gameOver(){
if(LIFE <= 0){
this.showYouLose();
this.GAME_OVER = true;
}
}
showYouWin(){
const gameover = document.getElementById("gameover");
gameover.style.display = "block";
const youwin = document.getElementById("youwon");
youwin.style.display = "block";
}
showYouLose(){
const gameover = document.getElementById("gameover");
gameover.style.display = "block";
const youlose = document.getElementById("youlose");
youlose.style.display = "block";
}
levelUp(){
let isLevelDone = true;
// check if all the bricks are broken
for(let r = 0; r < brick.row; r++){
for(let c = 0; c < brick.column; c++){
isLevelDone = isLevelDone && ! this.bricks.bricksMat[r][c].status;
}
}
if(isLevelDone){
WIN.play();
if(LEVEL >= MAX_LEVEL){
this.showYouWin();
this.GAME_OVER = true;
return;
}
brick.row++;
this.bricks.createBricks();
this.ball.speed += 0.5;
this.resetBall();
LEVEL++;
}
else{
isLevelDone = false;
this.gameOver();
}
}
movePaddle() {
if (this.rightArrow && this.paddle.x + this.paddle.width < this.paddle.cvs.width) {
this.paddle.x += this.paddle.dx;
// console.log("inside move condition");
} else if (this.leftArrow && this.paddle.x > 0) {
this.paddle.x -= this.paddle.dx;
// console.log("inside move condition");
}
}
onKeyDown(event){
// console.log("key pressed");
if(event.keyCode == 37){
this.leftArrow = true;
// console.log("left arrow true");
}else if(event.keyCode == 39){
this.rightArrow = true;
// console.log("right arrow true");
}
}
onKeyUp(event){
// console.log("key released");
if(event.keyCode == 37){
this.leftArrow = false;
// console.log("left arrow false");
}else if(event.keyCode == 39){
this.rightArrow = false;
// console.log("right arrow false");
}
}
update() {
this.movePaddle();
this.ball.moveBall();
this.ballWallCollision();
this.ballPaddleCollision();
this.ballBrickCollision();
this.gameOver();
this.levelUp();
}
draw() {
let cvs = this.cvs;
this.paddle.drawPaddle();
this.ball.drawBall();
// this.bricks.createBricks();
this.bricks.drawBricks();
this.showGameStats(SCORE, 35, 25, SCORE_IMG, 5, 5);
this.showGameStats(LIFE, cvs.width - 25, 25, LIFE_IMG, cvs.width - 55, 5);
this.showGameStats(LEVEL, cvs.width / 2, 25, LEVEL_IMG, cvs.width / 2 - 30, 5);
}
} |
JavaScript | class Request extends ValueEmitter {
/**
* @constructor
* @param {object} options Same options as `request` with additional:
* @param {number} options.interval
* @param {array} options.failStatus
*/
constructor (options) {
if (!options) {
throw new Error('Request requires the "options" argument');
}
super();
options = lodash.cloneDeep(options);
options.interval = options.interval || 0;
options.failStatus = options.failStatus || [/^[^2]/];
this.on('error', this._onError);
this.options = options;
this._poll = false;
this._timer = null;
this._predicate();
}
/**
* Validate current options object. To override in subclass.
*
* Default implementation always return true.
*
* @protected
* @returns {boolean}
*/
validate () {
return true;
}
/**
* Parse the response body. To override in subclass.
*
* Default implementation uses JSON.parse.
*
* @protected
* @param {string} body
* @returns {boolean}
*/
parse (body) {
return JSON.parse(body);
}
/**
* Fetch the URL.
*/
fetch (poll) {
// enable/disable polling if `poll` arg given
if (typeof poll !== 'undefined') {
this._poll = poll;
}
try {
// don't throw errors here, instead
// emit them as events because
// `fetch` might be called async-ly
this._predicate();
} catch (e) {
this.emit('error', e);
return false;
}
if (this.validate()) {
// always clear timer before sending request
// in case `fetch` is called while we are
// already waiting on a timeout (TODO test)
this._clear();
debug(this, 'fetching');
return Request.go(this.options, this._callback.bind(this));
}
return false;
}
/**
* Start polling the URL.
*/
poll (interval) {
if (typeof interval !== 'undefined') {
this.options.interval = interval;
}
this.fetch(true);
return this;
}
/**
* Stop polling the URL.
*/
stop () {
debug(this, 'stopping poll');
this._clear();
this._poll = false;
}
/**
* Returns true if in poll mode
*/
isPolling () {
return this._poll;
}
/**
* Get data
*/
getData () {
var data = this.getValue('data');
return lodash.isEmpty(data) ? null : data[0];
}
/**
* @private
*/
_clear () {
if (this._timer) {
debug(this, 'clearing timer');
clearTimeout(this._timer);
this._timer = null;
}
}
/**
* @private
*/
_predicate () {
debug(this, 'predicate: url');
if (!this.options.url) {
throw new Error('Request requires the "url" option');
}
return true;
}
/**
* @private
*/
_callback (err, resp, body) {
debug(this, 'response', err, resp && resp.statusCode, body && body.length);
if (resp) {
// always emit response, even on error
this.emit('response', resp);
// check for non-200 errors
if (!err && lodash.any(this.options.failStatus, match(resp.statusCode))) {
err = new Error('Request: request responded with ' + resp.statusCode);
}
}
if (!err) {
// parse body, catching any parse errors
try {
body = this.parse(body);
} catch (e) {
err = e;
}
}
if (err) {
// attach response to error object
err.response = resp;
this.emit('error', err);
} else {
// everything ok? emit parsed body
this.emit('data', body);
}
process.nextTick(() => {
// only setTimeout if in poll mode and interval > 0
// and got no error or stopOnError=true
var polling = this._poll && this.options.interval > 0;
var stopErr = err && this.options.stopOnError;
if (polling && !stopErr) {
debug(this, 'interval', this.options.interval);
this._timer = setTimeout(this.fetch.bind(this), this.options.interval);
}
});
}
/**
* @private
*/
_onError (err) {
if (this.options.stopOnError) {
debug(this, 'stop on error', err);
this.stop();
}
}
/**
* Util function to stringify query string objects.
*
* Difference from built-in `querystring` module is
* that the query keys are sorted before stringify,
* this allows the qs to be used as a unique key.
*
* @static
* @param {object} query
* @returns {string}
*/
static stringifyQuery (query) {
var keys = Object.keys(query).sort();
var pairs = keys.map((k) => qs.escape(k) + '=' + qs.escape(query[k]));
return pairs.join('&');
}
} |
JavaScript | class TodoView extends React.Component{
render(){
console.log('TodoView render');
const model = this.props.model
// just some HTML markup based of the ViewModel data.
return <MuiThemeProvider>
<div>
<h1>React & MobX Todo List!</h1>
<div>
<RaisedButton onClick={() => model.add()} primary={true} style={buttonStyle} label="New" />
<RaisedButton onClick={() => model.load()} secondary={true} style={buttonStyle} label="Load" />
<RaisedButton onClick={() => model.save()} style={buttonStyle} label="Save" />
</div>
<Table>
<TableHeader displaySelectAll={false}>
<TableRow>
<TableHeaderColumn>Done?</TableHeaderColumn>
<TableHeaderColumn>ID</TableHeaderColumn>
<TableHeaderColumn>Name</TableHeaderColumn>
<TableHeaderColumn>Actions</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
{model.todos.map((todo, i) => <SingleTodoView key={todo.id} model={model} todo={todo} />)}
</TableBody>
</Table>
</div>
</MuiThemeProvider>
}
} |
JavaScript | class SingleTodoView extends React.Component {
@observable todo = null;
constructor(props) {
super(props);
this.todo =Todo.deserialize(this.props.todo.serialize());
}
componentDidMount() {
document.getElementById(this.props.todo.id).value = this.todo.text;
document.getElementById('tablerow').striped = this.todo.done;
document.getElementById('checkbox').checked= this.todo.done;
}
// for if have the btn to update the todo at onces instead of use onCheck or onChange to change parameter of todo
updateProps() {
this.props.model.changeTodo(this.props.todo,this.todo);
}
render(){
const model = this.props.model;
var id = ""+ this.todo.id;
console.log('SingleTodoView render shouldn\'t been called when todo change');
return <TableRow id='tablerow' displayBorder={false}>
<TableRowColumn>
<Checkbox id='checkbox' onCheck={e => {
this.todo.done = e.target.checked;
this.updateProps();
}} />
</TableRowColumn>
<TableRowColumn>
#{id}
</TableRowColumn>
<TableRowColumn>
<TextField id= {id} name="text" type="text" onChange={e => {
this.todo.text = e.target.value;
this.updateProps();
}} />
</TableRowColumn>
<TableRowColumn>
<RaisedButton onClick={() => {}} label="Delete" />
</TableRowColumn>
</TableRow>
}
} |
JavaScript | class WelcomeController {
/**
* Constructor of WelcomeController
*
* @param $scope - type in module ng
* @param $state - service in module ui.router.state
* @param $timeout - service in module ngMock
* @param $interval - service in module ngMock
* @param AuthenticationService - service in module konko.authentication
* @constructs
*/
/*@ngInject;*/
constructor($scope, $state, $timeout, $interval, AuthenticationService) {
// other vars
this.user = AuthenticationService.currentUser();
$scope.countdown = 15;
// set listener
$timeout(() => {
let promise = $interval(() => {
$scope.countdown--;
}, 1000);
$scope.$watch('countdown', (_new, old) => {
if (_new === 0) {
$interval.cancel(promise);
$state.go($state.previous.state.name, $state.previous.params, { reload: true });
}
});
});
}
} |
JavaScript | class Banner extends Component {
constructor(props){
super(props);
let widthMediaQuery = window.matchMedia("(max-width: 1130px)");
this.state = {
isOpen: true,
mobile: widthMediaQuery.matches,
messageIndex: 0,
currentMessage: undefined,
messages: [],
seenMessages: JSON.parse(window.localStorage.getItem(localStorageKey)) || []
};
widthMediaQuery.addListener((ev) => {
this.setState({mobile: ev.matches});
});
/**
* Fetch the notificiation from the backend
* If the response is redirected link from firebase,
* push the new link without redirected param
*/
fetch(this.props.endpoint).then(resp => {
resp.json().then(json => {
let arr = [];
if(this.props.redirected){
arr = [redirectedNotif].concat(json);
const url = window.location.toString();
window.history.pushState({}, "", url.substr(0, url.indexOf("?")));
}else{
arr = json;
}
//Remove messages that have already been seen
arr = arr.filter( item => (this.state.seenMessages.indexOf(item._id) < 0) );
this.setState({messages: arr, currentMessage: arr[0]});
});
});
}
/**
* Handle when banner is close
*/
closeButtonClick = () => {
//Prevent notification redirects from being pushed to the ignore array
if(this.state.currentMessage._id !== -1){
this.state.seenMessages.push(
this.state.messages[this.state.messageIndex]._id
);
window.localStorage.setItem(localStorageKey,
JSON.stringify(this.state.seenMessages)
);
}
//Show the next banner if exists, close it otherwise.
if(this.state.messageIndex + 1 >= this.state.messages.length){
this.setState({isOpen: false});
}else{
this.setState({
messageIndex: this.state.messageIndex + 1,
currentMessage: this.state.messages[this.state.messageIndex + 1]
});
}
}
/**
* @returns Elements of buttons depends on device
*/
renderButtons = () => {
const style = {
closeButton: {
color: this.state.currentMessage.fontColor || "black"
},
linkButton: {
color: this.state.currentMessage.fontColor || "black",
borderColor: this.state.currentMessage.fontColor || "black"
},
desktop: {
marginTop: "8px",
paddingLeft: "36px",
paddingRight: "8px",
textAlign: "right"
},
mobile:{
paddingLeft: "8px",
alignItems: "center"
}
};
let linkButton = ( <></> );
if(this.state.currentMessage.link){
linkButton = (
<Button variant="outlined" href={this.state.currentMessage.link} target="_blank" rel="noopener noreferrer" style={style.linkButton}>
{this.state.currentMessage.linkText || "Details"}
</Button>
);
}
const closeButton = (
<IconButton onClick={this.closeButtonClick} style={style.closeButton}>
<Icon className="material-icons">close</Icon>
</IconButton>
);
return (this.state.mobile ?
<>
<Grid item xs={2} style={this.state.mobile ? style.mobile : style.desktop}>
{linkButton}
</Grid>
<Grid item xs={10} style={{textAlign: "right"}}>
{closeButton}
</Grid>
</>
:
<Grid item xs={3} style={style.desktop}>
{linkButton}
{closeButton}
</Grid>
);
}
/**
* @returns Elements to display messages
*/
renderMessage = () => {
const style = {
title: {
desktop:{
paddingLeft: "16px",
flexWrap: "nowrap"
},
mobile: {
alignSelf: "center"
}
},
message: {
mobile: {
paddingLeft: "8px",
paddingRight: "8px"
},
desktop: {
paddingLeft: "24px",
textAlign: "left",
flexShrink: "1"
}
}
};
let title = ( <></> );
if(this.state.currentMessage.title){
title = (
<Grid item
xs={1}
style={this.state.mobile ? style.title.mobile : style.title.desktop}>
<strong>{this.state.currentMessage.title}</strong>
</Grid>
);
}
return (this.state.mobile ?
<Grid container direction="column">
{title}
<Grid item style={style.message.mobile} xs={12}>{this.state.currentMessage.message}</Grid>
</Grid>
:
<>
{title}
<Grid item style={style.message.desktop} xs={10}>{this.state.currentMessage.message}</Grid>
</>
);
}
/**
* @returns Elements to display if user is accessing from desktop
*/
renderDesktop = () => {
return (
<Grid container direction="row" alignItems="center" wrap="nowrap" style={{paddingBottom: "8px"}}>
{this.renderMessage()}
{this.renderButtons()}
</Grid>
);
}
/**
* @returns Elements to display if user is accessing from mobile
*/
renderMobile = () => {
return (
<>
<Grid container direction="row" alignItems="center" wrap="nowrap" style={{paddingBottom: "8px"}}>
{this.renderMessage()}
</Grid>
<Grid container direction="row">
{this.renderButtons()}
</Grid>
</>
);
}
/**
* Create Banner
*/
render = () => {
return (this.state.isOpen && this.state.currentMessage ?
<div style={{
backgroundColor: this.state.currentMessage.color || "yellow",
color: this.state.currentMessage.fontColor || "black"
}}>
{this.state.mobile ?
this.renderMobile()
:
this.renderDesktop()
}
</div>
:
<></>);
}
} |
JavaScript | class PowerSchoolStudent {
constructor(api, id, firstName, middleName, lastName, dateOfBirth, ethnicity, gender, gradeLevel, currentGPA, currentTerm, photoDate = null, currentMealBalance = 0, startingMealBalance = 0) {
this.api = api;
/**
* The student's ID.
* @member {number}
*/
this.id = id;
/**
* The student's first/given name.
* @member {string}
*/
this.firstName = firstName;
/**
* The student's middle name.
* @member {string}
*/
this.middleName = middleName;
/**
* The student's last name/surname.
* @member {string}
*/
this.lastName = lastName;
/**
* The student's date of birth.
* @member {Date}
*/
this.dateOfBirth = dateOfBirth;
/**
* The student's ethnicity (can be one of many things determined by the school itself).
* @member {string}
*/
this.ethnicity = ethnicity;
/**
* The student's gender (can be one of many things determined by the school itself).
* @member {string}
*/
this.gender = gender;
/**
* The grade the student is currently in.
* @member {number}
*/
this.gradeLevel = gradeLevel;
/**
* The student's current GPA, if grades are available (null if not).
* @member {number}
*/
this.currentGPA = currentGPA;
/**
* The student's current term, if available (null if not).
* @member {number}
*/
this.currentTerm = currentTerm;
/**
* The date the student's photo was taken on.
* @member {Date}
*/
this.photoDate = photoDate;
/**
* The student's current meal balance, if supported.
* @member {number}
*/
this.currentMealBalance = currentMealBalance;
/**
* The student's starting meal balance, if supported.
* @member {number}
*/
this.startingMealBalance = startingMealBalance;
}
static fromData(data, api) {
return new PowerSchoolStudent(api, data.id, data.firstName, data.middleName, data.lastName, new Date(data.dob), data.ethnicity, data.gender, data.gradeLevel, data.currentGPA || null, data.currentTerm, data.photoDate ? new Date(data.photoDate) : null, data.currentMealBalance, data.startingMealBalance);
}
/**
* Get the parts making up a student's name.
* @param {boolean} [includeMiddleName] - Whether or not to include the student's middle name.
* @return {Array.<string>}
*/
getNameParts(includeMiddleName = false) {
if(includeMiddleName && this.middleName && this.middleName.length > 0) return [this.firstName, this.middleName, this.lastName];
return [this.firstName, this.lastName];
}
/**
* Get student's name formatted for display.
* @param {boolean} [includeMiddleName] - Whether or not to include the student's middle name.
* @return {string}
*/
getFormattedName(includeMiddleName = false) {
return this.getNameParts(includeMiddleName).join(" ");
}
/**
* Get the current reporting term the student is in.
* @return {PowerSchoolReportingTerm}
*/
getCurrentReportingTerm() {
// Why did they make this a title instead of ID?
return this.api._cachedInfo.reportingTerms.find((term) => term.title == this.currentTerm);
}
} |
JavaScript | class Boat extends Vehicle {
constructor(id, type, crew) {
super(id, 0, 'bwom');
this.type = type;
this.crew = crew;
}
useHorn() {
console.log(this.sound);
}
crewSoundOff() {
this.crew.forEach(member => {
console.log(`${member} reporting for duty!`);
});
}
} |
JavaScript | class ImageSet {
constructor(input, options={}, prefix='data-mh-image-set--') {
// Configure the options
this._options = {}
$.config(
this._options,
{
/**
* A comma separated list of file types that are accepted.
*/
'accept': 'image/*',
/**
* If true then the field will support users dropping files on
* to the acceptor to upload them.
*/
'allowDrop': false,
/**
* The aspect ratios to apply to the crop region for each
* version within the image set (the number of crop aspect
* ratios must match that number of versions).
*/
'cropAspectRatios': [],
/**
* The label displayed when the field is not populated and the
* user is dragging a file over the page.
*/
'dropLabel': 'Drop image here',
/**
* The image variation to display as the preview in the
* image editor (if applicable).
*/
'editing': 'editing',
/**
* Flag indicating if the aspect ratio of the crop region for
* the image versions should be fixed.
*/
'fixCropAspectRatio': false,
/**
* The label displayed when the field is not populated.
*/
'label': 'Select an image...',
/**
* The image variation to display as the preview in the
* viewer (if applicable).
*/
'preview': 'preview',
/**
* The image variation to display as the preview in the
* viewer (if applicable).
*/
'maxPreviewSize': [480, 480],
/**
* The URL that any file will be uploaded to.
*/
'uploadUrl': '/upload',
/**
* A list of labels for each version within the image set (the
* number of versions must match that number of versions).
*/
'versionLabels': [],
/**
* A list of named versions that this image set supports.
*/
'versions': []
},
options,
input,
prefix
)
// Convert `versions` option given as an attribute to a list
if (typeof this._options.versions === 'string') {
this._options.versions = this._options.versions.split(',')
}
// Convert `versionLabels` option given as an attribute to a list
if (typeof this._options.versionLabels === 'string') {
this._options.versionLabels = this._options.versionLabels.split(',')
if (this._options.versions.length
!== this._options.versionLabels.length) {
throw Error('Length of version labels must match versions')
}
}
// Convert `cropAspectRatios` option given as an attribute to a list
// of floats.
if (typeof this._options.cropAspectRatios === 'string') {
const cropAspectRatios = this._options.cropAspectRatios.split(',')
this._options.cropAspectRatios = []
for(let cropAspectRatio of cropAspectRatios) {
this
._options
.cropAspectRatios.push(parseFloat(cropAspectRatio))
}
}
if (this._options.cropAspectRatios.length > 0
&& this._options.versions.length
!== this._options.cropAspectRatios.length) {
throw Error('Length of crop aspect ratios must match versions')
}
// Conver `maxPreviewSize` option given as an attribute to a list of
// integers.
if (typeof this._options.maxPreviewSize === 'string') {
const maxPreviewSize = this._options.maxPreviewSize.split(',')
this._options.maxPreviewSize = [
parseInt(maxPreviewSize[0], 10),
parseInt(maxPreviewSize[1], 10)
]
}
// Configure the behaviours
this._behaviours = {}
$.config(
this._behaviours,
{
'alt': 'default',
'acceptor': 'default',
'assetProp': 'manhattan',
'asset': 'manhattan',
'formData': 'default',
'imageEditor': 'default',
'input': 'manhattan',
'uploader': 'default',
'viewer': 'default'
},
options,
input,
prefix
)
// A map of assets (for each version) currently being managed by the
// image set.
this._assets = null
// A map of transforms applied to each version of the image set
this._baseTransforms = null
// The base version of the
this._baseVersion = null
// The version of the image set currently being viewed
this._version = null
// The alt tag for the image set
this._alt = ''
// A map of preview URIs for each version generated by editing images
this._previewURIs = null
// The state of the image set (initializing, accepting, uploading,
// viewing).
this._state = 'initializing'
// Handles to the state components
this._acceptor = null
this._uploader = null
this._viewer = null
// Handle to the error message component
this._error = null
// Domain for related DOM elements
this._dom = {
'imageSet': null,
'input': null
}
// Store a reference to the input element
this._dom.input = input
}
// -- Getters & Setters --
get alt() {
return this._alt
}
set alt(value) {
const cls = this.constructor
// Set the alt value
this._alt = value
// Sync the input value with the image set
const inputBehaviour = this._behaviours.input
cls.behaviours.input[inputBehaviour](this, 'set')
// Trigger a change event against the input
$.dispatch(this.input, 'change')
}
get assets() {
if (this._assets) {
const assets = {}
for (let version in this._assets) {
assets[version] = Object.assign(this._assets[version], {})
}
return assets
}
return null
}
get baseTransforms() {
return Object.assign(this._baseTransforms || {}, {})
}
get baseVersion() {
return this._baseVersion || this._options.versions[0]
}
get imageSet() {
return this._dom.imageSet
}
get input() {
return this._dom.input
}
get previewURIs() {
return Object.assign(this._previewURIs || {}, {})
}
get state() {
return this._state
}
get version() {
return this._version
}
// -- Public methods --
/**
* Clear the field (transition to the accepting state).
*/
clear() {
const cls = this.constructor
// Clear the current state component
this._destroyStateComponent()
// Clear the asset input value
this._assets = {}
this._baseTransforms = {}
this._previewURIs = {}
this._alt = ''
// Set up the acceptor
const behaviour = this._behaviours.acceptor
this._acceptor = cls.behaviours.acceptor[behaviour](this)
this._acceptor.init()
// Set up event handlers for the acceptor
$.listen(
this._acceptor.acceptor,
{
'accepted': (event) => {
this.upload(this.baseVersion, event.files[0])
}
}
)
// Set the new state
this._state = 'accepting'
this._updateInput()
}
/**
* Clean the asset from a version of the image set.
*/
clearAsset(version, asset) {
delete this._assets[version]
delete this._baseTransforms[version]
delete this._previewURIs[version]
this._updateInput()
}
/**
* Clear any error from the field.
*/
clearError() {
if (this._error) {
this._error.destroy()
// Clear the error CSS modifier from the field
this.imageSet.classList.remove(this.constructor.css['hasError'])
}
}
/**
* Remove the image set.
*/
destroy() {
if (this._dom.imageSet) {
this._dom.imageSet.parentNode.removeChild(this._dom.imageSet)
this._dom.imageSet = null
}
// Remove the file field reference from the input
delete this._dom.input._mhImageSet
}
/**
* Return the value of the named property from the asset.
*/
getAssetProp(version, name) {
const behaviours = this.constructor.behaviours.assetProp
const behaviour = this._behaviours.assetProp
return behaviours[behaviour](this, 'get', version, name)
}
/**
* Get the crop aspect ratio for a version of the image set.
*/
getCropAspectRatio(version) {
return this
._options
.cropAspectRatios[this._options.versions.indexOf(version)]
}
/**
* Return a map of which versions have a unique asset (vs. using the base
* version asset).
*/
getOwnAssets() {
const ownImages = {}
for (const version of this._options.versions) {
ownImages[version] = this._assets.hasOwnProperty(version)
}
return ownImages
}
/**
* Return a preview URL/URI for a version of the image set.
*/
getPreview(version) {
if (this._previewURIs[version]) {
// Preview URI available for this version
return this._previewURIs[version]
}
if(this._assets[version]) {
// Preview URL available for this version
return this.getAssetProp(version, 'previewURL')
}
if (this._baseTransforms[version]) {
// Use the variation related to this version against the base
// version.
return this.getAssetProp(version, 'previewURL')
}
return this.getAssetProp(this.baseVersion, 'editingURL')
}
/**
* Return a map of preview URL/URIs for versions of the image set.
*/
getPreviews() {
const previews = {}
for (const version of this._options.versions) {
previews[version] = this.getPreview(version)
}
return previews
}
/**
* Initialize the image set.
*/
init() {
const cls = this.constructor
// Store a reference to the image set instance against the input
this.input._mhImageSet = this
// Create the image set element
this._dom.imageSet = $.create(
'div',
{'class': cls.css['imageSet']}
)
// Add the image set to the page
this.input.parentNode.insertBefore(
this._dom.imageSet,
this.input.nextSibling
)
if (this.input.value) {
const behaviour = this._behaviours.input
cls.behaviours.input[behaviour](this, 'get')
this.populate(this.baseVersion)
} else {
this.clear()
}
}
/**
* Populate the image set (transition to the viewing state).
*/
populate(version, asset) {
const cls = this.constructor
// Clear the current state component
this._destroyStateComponent()
if (asset) {
// Add the new asset to the image set (against its version)
this._assets[version] = asset
// Clear any existing base transforms and previews for this
// version.
delete this._baseTransforms[version]
delete this._previewURIs[version]
}
// Set up the viewer
const viewerBehaviour = this._behaviours.viewer
this._viewer = cls.behaviours.viewer[viewerBehaviour](this, version)
this._viewer.init()
// Set up event handlers for the viewer
$.listen(
this._viewer.viewer,
{
'accepted': (event) => {
this.upload(this._viewer.version, event.files[0])
},
'alt': () => {
const altBehaviour = this._behaviours.alt
const altModal = cls.behaviours.alt[altBehaviour](this)
altModal.init()
altModal.show()
$.listen(
altModal.overlay,
{
'okay': () => {
// Apply any changes to the alt tag
this.alt = altModal.props.alt || ''
// Hide the medata overlay
altModal.hide()
},
'cancel': () => {
altModal.hide()
},
'hidden': () => {
altModal.destroy()
}
}
)
},
'clear': (event) => {
this.clearAsset(this._viewer.version)
// Update the viewer with the new preview URI and own
// image flag.
this._viewer.setImageURL(
this._viewer.version,
this.getPreview(this._viewer.version)
)
this._viewer.setOwnImage(this._viewer.version, false)
},
'edit': () => {
const imageEditorBehaviour = this._behaviours.imageEditor
const imageEditor = cls.behaviours
.imageEditor[imageEditorBehaviour](
this,
this._viewer.version
)
imageEditor.init()
imageEditor.show()
$.listen(
imageEditor.overlay,
{
'okay': () => {
const {transforms} = imageEditor
const {previewDataURI} = imageEditor
previewDataURI.then(([dataURI, sizeInfo]) => {
// Set base transforms against the image
this.setBaseTransform(
this._viewer.version,
imageEditor.transforms
)
// Set the preview URI
this.setPreview(
this._viewer.version,
dataURI
)
// Update the image URLs for the viewer
for (const [v, imageURL]
of Object.entries(this.getPreviews())) {
this._viewer.setImageURL(v, imageURL)
}
imageEditor.hide()
})
},
'cancel': () => {
imageEditor.hide()
},
'hidden': () => {
imageEditor.destroy()
}
}
)
},
'remove': () => {
// Clear the image set
this.clear()
}
}
)
// Set the initial version in the viewer to the one we just populated
this._viewer.version = version
// Set the new state
this._state = 'viewing'
this._updateInput()
}
/**
* Post an error against the field.
*/
postError(message) {
// Clear any existing error
this.clearError()
// Post an error against the field
this._error = new ErrorMessage(this.field)
this._error.init(message)
// Add clear handler
$.listen(
this._error.error,
{
'clear': () => {
// Clear the error
this.clearError()
}
}
)
// Add the error CSS modifier to the field
this.imageSet.classList.add(this.constructor.css['hasError'])
}
/**
* Set the asset for a version of the image set.
*/
setAsset(version, asset) {
this._assets[version] = asset
this._updateInput()
}
/**
* Set the base transforms for a version of the image set.
*/
setBaseTransform(version, transforms) {
this._baseTransforms[version] = transforms
this._updateInput()
}
/**
* Set the preview URI for a version of the image set.
*/
setPreview(version, uri) {
this._previewURIs[version] = uri
this._updateInput()
}
/**
* Upload a file (transition to the uploading state).
*/
upload(version, file) {
const cls = this.constructor
// Clear the current state component
this._destroyStateComponent()
// Build the form data
const formData = cls.behaviours.formData[this._behaviours.formData](
this,
file,
version
)
// Set up the uploader
this._uploader = cls.behaviours.uploader[this._behaviours.uploader](
this,
this._options.uploadUrl,
formData
)
this._uploader.init()
// Set up event handlers for the uploader
$.dispatch(this.input, 'uploading')
$.listen(
this._uploader.uploader,
{
'aborted cancelled error': () => {
$.dispatch(this.input, 'uploadfailed')
this.clear()
},
'uploaded': (event) => {
$.dispatch(this.input, 'uploaded')
try {
// Extract the asset from the response
const behaviour = this._behaviours.asset
const asset = cls.behaviours.asset[behaviour](
this,
event.response
)
// Populate the field
this.populate(version, asset)
} catch (error) {
if (error instanceof ResponseError) {
// Clear the field
this.clear()
// Display the upload error
this.postError(error.message)
} else {
// Re-through any JS error
throw error
}
}
}
}
)
// Set the new state
this._state = 'uploading'
}
// -- Private methods --
/**
* Destroy the component for the current state (acceptor, uploader or
* viewer).
*/
_destroyStateComponent() {
// Clear any error
this.clearError()
// Clear the state component
switch (this.state) {
case 'accepting':
this._acceptor.destroy()
break
case 'uploading':
this._uploader.destroy()
break
case 'viewing':
this._viewer.destroy()
break
// no default
}
}
/**
* Update the input value to the current state of the image set.
*/
_updateInput() {
const cls = this.constructor
// Sync the input value with the image set
const inputBehaviour = this._behaviours.input
cls.behaviours.input[inputBehaviour](this, 'set')
// Trigger a change event against the input
$.dispatch(this.input, 'change')
}
} |
JavaScript | class CitrixCloud extends api_1.API {
constructor() {
super();
}
/**
* Generates auth code for login to Citrix Cloud
*
* @param {string} secretKey - SecretKey for generating the code
*/
async getAuthenticatorCode({ secretKey }) {
return otplib_1.authenticator.generate(secretKey);
}
/**
* Get Citrix Cloud Bearer Token
* @param {string} cwaAPI - Api Environmet
* @param {string} citrixCloudCustomerId - Customer Id
* @param {string} citrixCloudClientId - Client Id
* @param {string} citrixCloudClientSecret - Client Secret
*/
async getCCBearerToken({ cwaAPI, citrixCloudCustomerId, citrixCloudClientId, citrixCloudClientSecret, }) {
const response = await this.getCitrixCloudTokens({
cwaAPI,
citrixCloudCustomerId,
citrixCloudClientId,
citrixCloudClientSecret,
});
let token;
try {
token = response.data.token;
}
catch (error) {
console.log(error.stack);
throw new Error(await helpers_1.paramsCheck({
params: { token, response },
source: 'response',
}));
}
return token;
}
/**
* Create Authorized Instace
* @param {string} bearerToken - Access token
*/
async createAuthInstance({ bearerToken }) {
const authInstance = axios_1.default.create({});
authInstance.defaults.headers.common['Authorization'] = `CWSAuth bearer=${bearerToken}`;
authInstance.defaults.timeout = 90000;
return authInstance;
}
} |
JavaScript | class ManageContainerUsers extends Component {
constructor(props){
super(props)
this.state ={
totalMembers: 0,
members: [],
loadingMembers: false,
statesFilter: [],
reachableStates:[],
queryFilters: {
page: 0,
pageSize:20,
includeParentItems: false,
login: '',
state: '',
},
viewMode: 'viewList'
}
this.manageMembers = this.manageMembers.bind(this)
this.unsubscribe = this.unsubscribe.bind(this)
this.blockUser = this.blockUser.bind(this)
this.goToPage = this.goToPage.bind(this)
this.setLinkState = this.setLinkState.bind(this)
this.switchToView = this.switchToView.bind(this)
this.onPeopleDetailsChange = this.onPeopleDetailsChange.bind(this);
this.moreActions = this.moreActions.bind(this);
this.getRootObjectForDetailsId = this.getRootObjectForDetailsId.bind(this)
}
switchToView(e, name){
if(e) e.preventDefault()
this.setState({
viewMode: name
})
}
unsubscribe(userAccountId){
var members = [...this.state.members],
newMembers = [];
this.state.members.map(m => {
if(m.attributes.id !== userAccountId){
newMembers.push(m)
}
})
this.setState({
members: newMembers
})
}
blockUser(userAccountId){
var members = [...this.state.members],
newMembers = [];
this.state.members.map(m => {
if(m.attributes.id !== userAccountId){
newMembers.push(m)
}
})
this.setState({members: newMembers})
}
newPeople(wizardCloseFunction){
return <AddPeople
{...this.props}
fromConnectedUser={true}
onCreatePeopleSuccess={(id) => this.onCreatePeopleSuccess(wizardCloseFunction, id)}/>
}
onCreatePeopleSuccess(wizardCloseFunction, id){
if(wizardCloseFunction){
wizardCloseFunction()
}
setTimeout(() => {
this.setState({ showSuccessAlert: false });
}, 5000);
// reload list data and
//select newly created catalog
this.setState({
selectedAccountId: id,
showSuccessAlert: true
})
this.componentDidMount()
}
componentDidUpdate(prevProps, prevState){
if(prevState.viewMode !== this.props.viewMode){
this.setState({viewMode: this.props.viewMode})
}
}
getRootObjectForDetailsId(currentItemIdParam){
const queryUrlParams = queryString.parse(this.props.location.search);
let objectforDetailsId = queryUrlParams.rootId;
return objectforDetailsId
}
refreshView(){
this.setState({loadingMembers: true})
var queryFilters = {...this.state.queryFilters};
queryFilters.login = '';
this.loadDatas(queryFilters)
}
manageMembers(e){
e.preventDefault()
}
componentDidMount(){
var wc = this.props.containerId;
var queryFilters = {...this.state.queryFilters}
//queryFilters.state = 'VALID_MEMBER'
queryFilters.state = 'REQUEST_IN_PROGRESS'
this.setState({
queryFilters: queryFilters,
loadingMembers: true,
})
this.loadDatas(queryFilters)
}
onPeopleDetailsChange(id, wasRemoved){
var queryFilters = {...this.state.queryFilters}
if(wasRemoved === true){
this.setState({selectedAccountId: null})
}
this.loadDatas(queryFilters)
}
showDetailsView(){
return <div className="jsoagger-container">
<PeopleDetails
{...this.props}
pushBreadCrumb={this.props.pushBreadCrumb}
updatePeopleCallBack={(id, wasRemoved) => this.onPeopleDetailsChange(id, wasRemoved)}
accountId={this.state.selectedAccountId} />
</div>
}
loadDatas(queryFilters){
searchService
.searchContainerMemberByLoginLike2(queryFilters, this.props.containerId)
.then(response => {
if(response && response.data){
this.setState({
results: response.data,
metaData:response.metaData,
loadingMembers: false,
})
}
else {
this.setState({
results: [],
metaData: null,
loadingMembers: false,
reachableStates: []
})
}
})
.catch(error => {
console.log(error)
})
}
goToPage(i){
var queryFilters = {...this.state.queryFilters}
queryFilters.page = i
this.setState({queryFilters: queryFilters})
this.loadDatas(queryFilters)
}
nameOf(res, item){
var owner = item.attributes.ownerSummary
var type = item.businessType.type
if(type === 'person'){
return this.LinkToPeople(item.attributes, owner, "person")
}
else {
return this.LinkToPeople(item.attributes, owner, "org")
}
}
moreActions(val,item){
return <td className="dt-center">
<div className="btn-toolbar">
<Button onClick={e=>this.selectPerson(e, val.id)}>
<i className="fa fa-lg fa-eye"></i>
</Button>
</div>
</td>
}
lifecycleActions(v, i){
var actions = [], roleAid, roleBid,
id = i.attributes.id;
roleAid = this.props.containerId;
roleBid = i.attributes.id;
if(this.state.reachableStates.length > 0){
this.state.reachableStates.map(state => {
if(state !== ''){
actions.push(
<div className="float-right">
<Button size="sm" variant="outline-primary"
onClick={e =>this.setLinkState(roleAid, roleBid, state)}>{state}</Button>
</div>
)
}
})
}
return <td className="dt-center">
{actions}
</td>
}
setLinkState(roleAid, roleBid, state){
var linkClass = 'io.github.jsoagger.core.api.composite.ContainerMembershipLink'
this.setState({
loadingMembers: true
})
if(roleAid == undefined || roleBid == undefined ){
return;
}
lifecycleService
.setLinkState(roleAid, roleBid, state, linkClass, this.props.containerId)
.then(response => {
var queryFilters = {...this.state.queryFilters}
this.loadDatas(queryFilters)
})
}
LinkToPeople(item, owner, type){
var route
if(type !== "org"){
route = <Link className="table-link" onClick={e=>this.selectPerson(e, item.id)}>
{owner}
</Link>
} else {
route = <Link className="table-link" onClick={e=>this.selectPerson(e, item.id)}>
{owner}
</Link>
}
return (
<td className="dt-center" width="30%">
<HashRouter >
{route}
</HashRouter>
</td>
)
}
selectPerson(e, id){
if(e) e.preventDefault()
this.props.history.push(coreUri.profileAdminUri(id))
}
membersDatatable(){
const tableConfig = {
columnsConfig: [
//{ displayComponent: (v) => enIcon(v) },
{name:'Summary', dataField: 'attributes', displayComponent: (v, i) => this.nameOf(v, i)},
{name:'Email', dataField: 'attributes.login'},
{name:'Password expired', dataField: 'attributes.passwordExpirationDate', dateFormat: 'DD/MM/YYYY HH:mm'},
//{name:'Created', dataField: 'attributes.createDate', dateFormat: 'DD/MM/YYYY HH:mm'},
{name:'Last Updated', dataField: 'attributes.lastModifiedDate', dateFormat: 'DD/MM/YYYY'},
//{ displayComponent: (v,i) => this.moreActions(v,i), dataField: 'attributes'},
],
}
return <DataTable
tableClassName="data-table"
items={JSON.stringify(this.state.results)}
metaData={JSON.stringify(this.state.metaData)}
tableConfig={tableConfig}
displayTotalElements={true}
goToPage={this.goToPage}
paginate={true}/>
}
searchTermUpdated(e){
var queryFilters = {...this.state.queryFilters}
queryFilters.login = e.target.value
this.loadDatas(queryFilters)
this.setState({
queryFilters: queryFilters,
loadingMembers: true,
viewMode: 'viewList'
})
}
searchHeader(){
return <div className="admin-filters">
<Input type="text"
className="admin-hover-input"
name="input1-group2"
placeholder="Member email or nickname"
autocomplete="off"
defaultValue={this.state.searchTerm}
onChange={(e) => this.searchTermUpdated(e)}/>
</div>
}
updateStates(e){
var queryFilters = {...this.state.queryFilters}
queryFilters.state = e.target.value
this.setState({
queryFilters: queryFilters,
loadingMembers: true
})
this.loadDatas(queryFilters)
}
getStateFilterDisplay(){
var datas = []
this.state.statesFilter.map(m => {
var id = "defaultCheck__" + m;
var val = m.split(';')[0];
var key = m.split(';')[0]
var checked = this.state.queryFilters.state === key
datas.push(
<div className="">
<input class="form-check-input" checked={checked} type="radio" value={key} id={id} onChange={e => this.updateStates(e)}/>
<label class="form-check-label" for={id}>
{val}
</label>
</div>
)
})
return <div className="mx-4">{datas}</div>
}
render() {
var rootObjectForDetailsId = this.getRootObjectForDetailsId()
if(!rootObjectForDetailsId){
var datatable, currentContainerName = commons.getWorkingContainerName(this.props.userContext),
total = this.state.metaData !== null && this.state.metaData !== undefined ? this.state.metaData.totalElements : 0;
if(this.state.loadingMembers == true){
datatable = <WaitingPane waitingMessage='Loading members...'/>
}
else if(total > 0){
datatable = this.membersDatatable();
}
else {
datatable = <EmptyPane mainMessage='No members found' secondaryMessage='No members found with given criterias' />
}
var buttonIconComp = <RiUserLine size="1.2em"/>
var headerActions = <>
<Wizard buttonColor="secondary"
buttonIconComp={buttonIconComp}
dialogTitle="New member"
buttonTitle="NEW MEMBER"
hideFooter={true}
dialogSize="md"
dialogContentProvider={(wizardCloseFunction)=>this.newPeople(wizardCloseFunction)}/>
<Button className="" size="sm"
variant="link"
onClick={e=>this.refreshView()}>
<RiRefreshLine size="1.2em"/>
REFRESH
</Button>
</>
return <div className="portlet-box">
<div className="portlet-header">
{this.searchHeader()}
<div className="btn-toolbar footer-btn-toolbar">{headerActions}</div>
</div>
<div className="portlet-content table-list-admin-root">{datatable}</div>
</div>
}
return this.showDetailsView()
}
} |
JavaScript | class Programmer {
canCode() {
return true;
}
code() {
return 'Coding';
}
test() {
return 'Testing in localhost';
}
} |
JavaScript | class CustomError extends Error {
constructor(message) {
super(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
}
} |
JavaScript | class HTTPError extends CustomError {
constructor(message, status) {
super(message);
this.status = status;
if (status === 401) {
this.userMessage = 'Access was denied';
}
this.name = 'HTTPError';
}
} |
JavaScript | class NetworkConnectivityError extends CustomError {
constructor(message) {
super(message);
this.userMessage = 'Could not connect to server.';
this.name = 'NetworkConnectivityError';
}
} |
JavaScript | class ValidationError extends CustomError {
constructor(message) {
super(message);
this.userMessage = message;
this.name = 'ValidationError';
}
} |
JavaScript | class Cache {
constructor(key, _) {
const options = _ || {};
this.tmpdir = options.location|| tmpdir;
this.compression = options.compression || false;
this.supportBuffer = options.supportBuffer || false;
this.key = key || 'default-disk-cache';
this.root = path.join(this.tmpdir, 'if-you-need-to-delete-this-open-an-issue-async-disk-cache', this.key);
debug('new Cache { root: %s, compression: %s }', this.root, this.compression);
}
} |
JavaScript | class KeyboardInteractionTrap extends PureComponent {
handleFocus = (event) => {
this.updateMenu(event.target);
}
updateMenu(element) {
const enabled = ['INPUT', 'TEXTAREA'].includes(element.tagName);
const editMenu = [
[
{
role: 'undo',
enabled
},
{
role: 'redo',
enabled
},
],
[
{
role: 'copy',
enabled
},
{
role: 'cut',
enabled
},
{
role: 'paste',
enabled
},
{
role: 'selectAll',
enabled
}
]
];
this.props.triggerAction('update-menu', { editMenu });
}
componentDidMount() {
window.addEventListener('focus', this.handleFocus);
this.updateMenu(document.activeElement);
}
componentWillUnmount() {
window.removeEventListener('focus', this.handleFocus);
}
render() {
return this.props.children;
}
} |
JavaScript | class ServeStaleCache {
/* Create a ServeStaleCache:
* @param {Function} options.dispose: Function called when an item is evicted
* the underlying LRU cache
* default: () => {}
* @param {Number} options.capacity: The maximum capacity of this cache, once the
* cache reaches this limit, the least recently
* used items will be evicted.
* default: from config
* 'local_cache_capacity'
* @param {Number} options.defaultTTL: The default time to live in ms, for items in the cache,
* this is used if the create callback doesn't specify
* a ttl in it's return value.
* default: from config
* 'default_cache_ttl'
* @constructor
*/
constructor(options) {
const opts = options || {};
const dispose = opts.dispose || function() {};
const capacity = opts.capacity || config.local_cache_capacity;
this.cache = new LRUMap({
dispose: dispose,
max: capacity
});
this.defaultTTL = opts.defaultTTL || config.default_cache_ttl;
}
/*
* Clear all items from the cache
*/
clear() {
this.cache.reset();
}
/*
* Get an item from the cache using the given key.
* If the item does not exist in the cache, (or is
* expiring), `create` is called to create the cached value.
*
* @param {String} key
*
* @param {Function} createCallback: fn() -> { ttl, value }
* `createCallback` should be a function, that takes no arguments and returns
* an object containing at least a `value` property, and optionally
* a `ttl` property, to specify the time to live for this cache
* item.
*
* @returns {Promise} Returns a Promise resolving to the cached item, or erroring if not cached
* and `create` fails.
*/
get(key, createCallback) {
let cacheRecord = this.cache.get(key);
const that = this;
if (cacheRecord === undefined) {
// Cache is empty
cacheRecord = this._set(key, Promise.resolve(createCallback()));
} else {
const now = this._now();
// We should really use max-stale or
// stale-while-revalidate/stale-if-error
// TODO: for now only serve stale content for two hours
if (now - cacheRecord.expires > config.max_serve_stale) {
// Synchronously create the new cache item
const next = Promise.resolve(createCallback());
// Assign this new cache item as the current value.
return updateTTLForValue(next).then((cachedValue) => {
cacheRecord.value = next;
return cachedValue.value;
});
}
// If key in cache, but expired - serve stale and revalidate in the
// background
if (cacheRecord.expires < now) {
const next = Promise.resolve().then(() => {
return createCallback();
});
updateTTLForValue(next).then((cachedValue) => {
// Set new cached value.
cacheRecord.value = next;
return cachedValue;
});
}
}
function updateTTLForValue(valuePromise) {
return valuePromise.then((cachedValue) => {
if (!cachedValue) {
const msg = 'Cacheable item should return an object with at least a `value` property';
throw new Error(msg);
}
// If `createCallback` specified a ttl, update the expiry time of
// the cache record, or use the defaultTTL.
let _ttl = that.defaultTTL;
if (cachedValue.ttl) {
_ttl = cachedValue.ttl;
}
cacheRecord.expires = that._now() + _ttl;
return cachedValue;
});
}
return cacheRecord.value.then((value) => {
// Return only the inner value
return value.value;
});
}
/*
* Create a new item in the cache from the given promise.
*
* Usually, you'll only need to use 'get' with a `createCallback`.
*
* @param {String} key
* @param {Promise} promise
* @returns {Object} The cache record entry.
* @private
*/
_set(key, promise) {
const ttl = this.defaultTTL;
const now = this._now();
const cacheRecord = {
expires: now + ttl,
value: promise.then((value) => {
// If the promise returns an object with a 'ttl' value,
// update the cacheRecord's expiry using this new ttl.
// This allows for the ttl of the cached item to depend
// on a result computed from the creation of the cacheable
// item.
if (value.ttl) {
cacheRecord.expires = now + value.ttl;
}
return value;
})
};
this.cache.set(key, cacheRecord);
return cacheRecord;
}
/*
* Get a timestamp representing the time now.
*
* Useful for testing (can be overwritten in tests)
* @returns {Number} Current timestamp in millis
* @private
*/
_now() {
return Date.now();
}
} |
JavaScript | class DailyMetricDataProvider {
/**
* Creates an instance of daily metric data provider.
* @param d
*/
constructor(d) {
this._onDidChangeTreeData = new vscode_1.EventEmitter();
this.onDidChangeTreeData = this
._onDidChangeTreeData.event;
if (d == undefined) {
this.data = [
new DailyMetricItem(Constants_1.DAILY_METRIC_KEYSTROKES_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_LINES_CHANGED_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_TIME_INTERVAL_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_POINTS_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
];
}
else {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
this.data = [];
let tempList = [];
for (let key in d) {
if (key === "teamId") {
continue;
}
tempList.push(new DailyMetricItem(Constants_1.DAILY_METRIC_DISPLAY_HEADER_MAP_TREEVIEW[key], [
new DailyMetricItem("π Today: " + +d[key].toFixed(3) + " (Updated: " + time + ")"),
]));
}
this.data = tempList;
}
}
/**
* Refreshs daily metric data provider
* @returns refresh
*/
refresh() {
const ctx = Authentication_1.getExtensionContext();
if (ctx.globalState.get(Constants_1.GLOBAL_STATE_USER_ID) === undefined) {
this.data = [
new DailyMetricItem(Constants_1.DAILY_METRIC_KEYSTROKES_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_LINES_CHANGED_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_TIME_INTERVAL_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_POINTS_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
];
return;
}
else {
Firestore_1.retrieveUserUpdateDailyMetric().then((userDocument) => {
if (userDocument === undefined) {
this.data = [
new DailyMetricItem(Constants_1.DAILY_METRIC_KEYSTROKES_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_LINES_CHANGED_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_TIME_INTERVAL_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
new DailyMetricItem(Constants_1.DAILY_METRIC_POINTS_TREEVIEW, [
new DailyMetricItem("π Today: " + "0" + Constants_1.DAILY_METRIC_NO_DATA_YET_TREEVIEW),
]),
];
}
else {
var today = new Date();
var time = today.getHours() +
":" +
today.getMinutes() +
":" +
today.getSeconds();
this.data = [];
let tempList = [];
for (let key in userDocument) {
if (key === "teamId") {
continue;
}
tempList.push(new DailyMetricItem(Constants_1.DAILY_METRIC_DISPLAY_HEADER_MAP_TREEVIEW[key], [
new DailyMetricItem("π Today: " +
+userDocument[key].toFixed(3) +
" (Updated: " +
time +
")"),
]));
}
this.data = tempList;
}
});
}
this._onDidChangeTreeData.fire(null);
}
/**
* Gets children
* @param [task]
* @returns children
*/
getChildren(task) {
if (task === undefined) {
return this.data;
}
return task.children;
}
/**
* Gets tree item
* @param task
* @returns tree item
*/
getTreeItem(task) {
return task;
}
} |
JavaScript | class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
static getDerivedStateFromError(error) {
return {
error,
};
}
render() {
if (this.state.error != null) {
return (
<div>
<div>Error: {this.state.error.message}</div>
<div>
<pre>{JSON.stringify(this.state.error.source, null, 2)}</pre>
</div>
</div>
);
}
return this.props.children;
}
} |
JavaScript | class Command_1_68 extends Segment {
/**
* Set payload
*/
constructor() {
super();
/**
* Set payload fields
*/
this.fields = {
//Flag can be 0 (no records left in flash) or 1.
records_left: 1,
//Describes how many records are in buffer.
records_total: 1,
//Init record
record: {}
};
}
} |
JavaScript | class Detail {
/**
* CONSTRUCTOR CLASE
* @param quantity: Cantidad de producto
* @param detail: DescripciΓ³n del producto
* @param id: ID del detalle
* @param code: CΓ³digo de producto
* @param price: Precio unitario de producto
*/
constructor(quantity, detail, id, code, price) {
this.quantity = quantity;
this.detail = detail;
this.id = id;
this.price = price;
this.code = code;
}
/**
* Calcula el total de cada detalle de factura
* @returns {number}
*/
get total(){
return this.quantity*this.price;
}
/**
* funcion que retorna html configurado para imprimir tabla de detalles
* @returns {string}
*/
get render(){
return '<tr id="'+this.id+'" class="standar_row">'+
'<td>'+this.code+'</td>'+
'<td>'+this.detail+'</td>'+
'<td>Q'+number_format(this.price, 2)+'</td>'+
'<td><input type="number" id_detail="'+this.id+'" readonly value="'+
this.quantity+'" class="form-control">'+
'</td>'+
'<td>Q'+ number_format(this.total, 2)+'</td>'+
'<td class="hide detControl devolucion"><input type="text" min="0" id_detail="'+
this.id+'" maxQty="'+this.quantity+'" costItem="'+this.price+'" oldValue="0" value="0" onchange="change_devolucion(this)"' +
' class="form-control input_custom devolucion_input number">'+
'</td>'+
'<td class="hide detControl descuento"><input type="text" min="0" onchange="change_descuento(this)" id_detail="'+
this.id+'" maxAmount="'+this.total+'" oldValue="0" value="0" class="form-control input_custom descuento_input number">'+
'</td>'+
'</tr>';
}
/**
* Funcion que retorna html configurado para imprimir el detalle unico de descuento general para el documento
* @returns {string}
*/
get renderGd(){
return '<tr id="'+this.id+'" class="hide dsc_row">'+
'<td>'+this.code+'</td>'+
'<td>'+this.detail+'</td>'+
'<td>Q'+number_format(this.price, 2)+'</td>'+
'<td><input type="number" id_detail="'+this.id+'" readonly value="'+
this.quantity+'" class="form-control">'+
'</td>'+
'<td>Q'+ number_format(this.total, 2)+'</td>'+
'<td class="hide detControl devolucion"><input type="text" min="0" id_detail="'+
this.id+'" maxQty="'+this.quantity+'" costItem="'+this.price+'" oldValue="0" value="0" onchange="change_devolucion(this)" ' +
' class="form-control input_custom devolucion_input number">'+
'</td>'+
'<td class="detControl descuento"><input type="text" min="0" onchange="change_descuento(this)" id_detail="'+
this.id+'" maxAmount="'+this.total+'" oldValue="0" value="0" class="form-control input_custom descuento_input number">'+
'</td>'+
'</tr>';
}
} |
JavaScript | class Tensor {
/**
* Construct a Tensor object
* @param {Array} shape
* @param {Array} [data]
*/
constructor(shape, data = undefined) {
const size = shape.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
if (data !== undefined) {
if (size !== data.length) {
throw new Error('The length of array is invalid.');
}
this.data = data;
} else {
this.data = new Array(size).fill(0);
}
this.shape = shape;
this.rank = shape.length;
if (this.rank < 2) {
this.strides = [];
} else {
this.strides = new Array(this.rank - 1);
this.strides[this.rank - 2] = this.shape[this.rank - 1];
for (let i = this.rank - 3; i >= 0; --i) {
this.strides[i] = this.strides[i + 1] * this.shape[i + 1];
}
}
}
/**
* Get index in the flat array given the location.
* @param {Array} location
* @return {Number}
*/
indexFromLocation(location) {
if (location.length !== this.rank) {
throw new Error('The location is invalid.');
}
let index = 0;
for (let i = 0; i < location.length - 1; ++i) {
index += this.strides[i] * location[i];
}
index += location[location.length - 1];
return index;
}
locationFromIndex(index) {
const location = new Array(this.rank);
for (let i = 0; i < location.length - 1; ++i) {
location[i] = Math.floor(index / this.strides[i]);
index -= location[i] * this.strides[i];
}
location[location.length - 1] = index;
return location;
}
/**
* Set value given the location.
* @param {Array} location
* @param {Number} value
*/
setValue(location, value) {
this.data[this.indexFromLocation(location)] = value;
}
/**
* Get value given the location.
* @param {Array} location
* @return {Number}
*/
getValue(location) {
return this.data[this.indexFromLocation(location)];
}
} |
JavaScript | class Events extends Component {
constructor(props) {
super();
this.AuthService = new AuthenticationService();
this.classes = props.classes
this.state = {"rows": []};
}
state = {
editDialogOpen: false
};
componentDidMount() {
this.fetchData();
}
openAddDialog = () => {
this.setState({editDialogOpen: true});
}
closeAddDialog = () => {
this.setState({editDialogOpen: false});
}
onAdded = (event) => {
this.setState({editDialogOpen: false});
// display a notification indicating we have added a new user
let message = 'Added ' + event.name;
let actionUri = '/events/' + event.eventId;
displayActionMessage({message, actionUri});
// refetch the list on the current page/filters
this.fetchData();
}
fetchData = () => {
this.AuthService.fetch('/api/events', {})
.then(response => {
if(response.ok) {
return response.json().then((json) => {
var transformed = this.transformEventRows(json);
this.setState({"rows": transformed });
});
} else if (response.status === 401) {
this.setState({reauthenticate: true})
} else {
alert("Request failed with error code: " + response.status);
}
});
};
transformEventRows(rows) {
return rows.map(row => {
let url = '/events/' + row.eventId
return {
"id": <Button color="primary" size="small" component={Link} to={url}>{row.eventId}</Button>,
"name" : row.name,
"location": row.location,
"startDate": row.startDate,
"endDate": row.endDate,
"status": row.eventStatus,
"current": row.current
};
});
}
render() {
const { editDialogOpen } = this.state;
return (
<React.Fragment>
<HeadlineWithAction headline="Events" buttonLabel="Add new event" buttonOnClick={this.openAddDialog.bind(this)} />
<Paper className={this.classes.root}>
{this.state.reauthenticate && <ReauthenticateModal onReauthenticated={this.componentDidMount.bind(this)} />}
{editDialogOpen && <EventAdd
onClosed={this.closeAddDialog.bind(this)}
onAdded={this.onAdded.bind(this)} />
}
<Grid
rows={this.state.rows}
columns={[
{ name: 'id', title: 'ID' },
{ name: 'name', title: 'Name' },
{ name: 'location', title: 'Location' },
{ name: 'startDate', title: 'Start Date' },
{ name: 'endDate', title: 'End Date' },
{ name: 'status', title: 'Status' },
{ name: 'current', title: 'Current' },
]}>
<DateTypeProvider
for={['startDate', 'endDate']}
/>
<BooleanTypeProvider
for={['current']}
/>
<SortingState
defaultSorting={[{ columnName: 'startDate', direction: 'desc' }]}
/>
<IntegratedSorting />
<Table />
<TableHeaderRow showSortingControls />
</Grid>
</Paper>
</React.Fragment>
);
}
} |
JavaScript | class AbstractTransaction {
/**
* @param {BaseContext} context
*/
constructor(context) {
/**@type{*}*/this._id = null;
/**@type{BaseContext}*/this._context = context;
/**@type{null|{...}}*/this._config = null;
/**@type{boolean}*/this._new = false;
/**@type{number}*/this._state = TRANSACTION_STATE.INVALID;
/**@type{Object}*/this._source = null; // The original
/**@type{Object}*/this._target = null; // Copy of the original
}
/**@returns{null|{...}}*/get config() {return this._config;}
/**
* @param {Object} source
* @return {Promise<object>}
* @abstract
*/
async _objectify(source) {throw CelastrinaError.newError("Not Implemented.");}
/**
* @param {Object} source
* @return {Promise<object>}
* @abstract
*/
async _extract(source) {throw CelastrinaError.newError("Not Implemented.");}
/**
* @param {*} id
* @return {Promise<Object>}
* @abstract
*/
async _construct(id) {throw CelastrinaError.newError("Not Implemented.");}
/**
* @param {Object} _object
* @return {Promise<object>}
* @abstract
*/
async _create(_object) {throw CelastrinaError.newError("Not Implemented.");}
/**
* @return {Promise<Object>}
* @abstract
*/
async _read() {throw CelastrinaError.newError("Not Implemented.");}
/**
* @param {Object} _object
* @return {Promise<void>}
* @abstract
*/
async _update(_object) {throw CelastrinaError.newError("Not Implemented.");}
/**
* @return {Promise<void>}
* @abstract
*/
async _delete() {throw CelastrinaError.newError("Not Implemented.");}
/**
* @return {Promise<void>}
* @abstract
*/
async _rollback() {throw CelastrinaError.newError("Not Implemented.");}
/**
* @return {Promise<void>}
* @abstract
*/
async _abort() {throw CelastrinaError.newError("Not Implemented.");}
/**@returns{boolean}*/get isStarted() {return this._state === TRANSACTION_STATE.STARTED;}
/**@returns{boolean}*/get isUpdated() {return this._state === TRANSACTION_STATE.UPDATED;}
/**@returns{boolean}*/get isDeleted() {return this._state === TRANSACTION_STATE.DELETED;}
/**@returns{boolean}*/get isCommitted() {return this._state === TRANSACTION_STATE.COMITTED;}
/**@returns{boolean}*/get isRolledBack() {return this._state === TRANSACTION_STATE.ROLLED_BACK;}
/**@returns{boolean}*/get isAborted() {return this._state === TRANSACTION_STATE.ABORTED;}
/**@returns{number}*/get state() {return this._state;}
/**@returns{*}*/get id() {return this._id;}
/**@returns{boolean}*/get isNew() {return this._new;}
/**@returns{Object}*/get source() {return this._source;}
/**@returns{Object}*/get target() {return this._target;}
/**
* @param {*} id
* @param {Object} [config = null]
* @return {Promise<*>}
*/
async start(id = uuidv4(), config = null) {
return new Promise((resolve, reject) => {
if(typeof id === "undefined" || id == null)
reject(CelastrinaError.newError("Invalid Object Id.", 400));
else {
this._config = config;
this._new = false;
this._state = TRANSACTION_STATE.STARTED;
this._source = null;
this._target = null;
this._id = id;
resolve(this._id);
}
});
}
/**
* @return {Promise<Object>}
*/
async create() {
if(this._state === TRANSACTION_STATE.STARTED) {
let _object = await this._construct(this._id);
this._new = true;
this._source = _object;
let _extracted = await this._extract(this._source);
_extracted = await this._create(_extracted);
this._target = await this._objectify(JSON.parse(JSON.stringify(_extracted)));
return this._target;
}
else
throw CelastrinaError.newError("Invalid transaction state. Unable to create when '" +
this._state + "'.");
}
/**
* @return {Promise<Object>}
*/
async read() {
if(this._state === TRANSACTION_STATE.STARTED){
let _object = await this._read();
this._new = false;
this._source = await this._objectify(_object);
this._target = await this._objectify(JSON.parse(JSON.stringify(await this._extract(this._source))));
return this._target;
}
else
throw CelastrinaError.newError("Invalid transaction state. Unable to read when '" +
this._state + "'.");
}
/**
* @return {Promise<Object>}
*/
async readOrCreate() {
try {
return await this.read();
}
catch(exception) {
if(exception instanceof CelastrinaError) {
if(exception.code === 404)
return await this.create();
else
throw exception;
}
else throw exception;
}
}
/**
* @param {Object} _object
* @return {Promise<Object>}
*/
async update(_object) {
return new Promise((resolve, reject) => {
if(this._state === TRANSACTION_STATE.STARTED || this._state === TRANSACTION_STATE.UPDATED) {
this._state = TRANSACTION_STATE.UPDATED;
this._target = _object;
resolve(this._target);
}
else
reject(CelastrinaError.newError("Invalid transaction state. Unable to update when '" + this._state + "'."));
});
}
/**
* @return {Promise<Object>}
*/
async delete() {
return new Promise((resolve, reject) => {
if(this._state === TRANSACTION_STATE.STARTED || this._state === TRANSACTION_STATE.UPDATED) {
this._state = TRANSACTION_STATE.DELETED;
resolve();
}
else if(this._state === TRANSACTION_STATE.DELETED)
resolve();
else
reject(CelastrinaError.newError("Invalid transaction state. Unable to delete when '" +
this._state + "'."));
});
}
/**
* @return {Promise<void>}
*/
async rollback() {
if(this._state === TRANSACTION_STATE.COMITTED) {
await this._rollback();
this._state = TRANSACTION_STATE.ROLLED_BACK;
}
else
throw CelastrinaError.newError("Invalid transaction state. Unable to rollback when '" +
this._state + "'.");
}
/**
* @return {Promise<void>}
*/
async abort() {
await this._abort();
this._state = TRANSACTION_STATE.ABORTED;
}
/**
* @return {Promise<void>}
*/
async rollbackOrAbort() {
if (this._state === TRANSACTION_STATE.COMITTED)
await this.rollback();
else
await this.abort();
}
/**
* @return {Promise<void>}
*/
async commit() {
if(this._state === TRANSACTION_STATE.UPDATED) {
let object = await this._extract(this._target);
await this._update(object);
this._state = TRANSACTION_STATE.COMITTED;
}
else if(this._state === TRANSACTION_STATE.DELETED) {
await this._delete();
this._target = null;
this._state = TRANSACTION_STATE.COMITTED;
}
else
throw CelastrinaError.newError("Invalid transaction state. Unable to commit when '" +
this._state + "'.");
}
/**
* @param {Object} _object
* @return {Promise<Object>}
*/
async updateAndCommit(_object) {
await this.update(_object);
return this.commit();
}
/**
* @param {Object} _object
* @return {Promise<Object>}
*/
async deleteAndCommit(_object) {
await this.delete();
return this.commit();
}
} |
JavaScript | class AbstractBlobStorageTransaction extends AbstractTransaction {
/**
* @param {BaseContext} context
*/
constructor(context) {
super(context);
/**@type{BlobSemaphore}*/this._semaphore = null;
/**@type{null|string}*/this._blob = null;
this._storage = null;
this._container = null;
/**@type{null|string}*/this._endpoint = null;
/**@type{ResourceAuthorization}*/this._auth = null;
/**@type{number}*/this._lockStrategy = BLOB_LOCK_STRATEGY.COMMIT_LOCK;
/**@type{number}*/this._lockTimeout = 0;
}
/**@type{null|string}*/get blobName() {return this._blob;}
/**@type{number}*/get lockingStrategy() {return this._lockStrategy;}
/**@type{number}*/get lockTimeOut() {return this._lockTimeout;}
/**
* @param {{storage:string, container:string, path?:string, [lockStrategy]:number, [lockTimeOut]:number}} config
* @return {(null|string)}
* @private
*/
_getPath(config) {
if(typeof config.path === "undefined" || config.path == null)
return null;
else
return config.path;
}
/**
* @param {{storage:string, container:string, path?:string, [lockStrategy]:number, [lockTimeOut]:number}} config
* @private
*/
_setLockStrategy(config) {
if(typeof config.lockStrategy === "number")
this._lockStrategy = config.lockStrategy;
}
/**
* @param {{storage:string, container:string, path?:string, [lockStrategy]:number, [lockTimeOut]:number}} config
* @private
*/
_setLockTimeout(config) {
if(typeof config.lockTimeOut === "number")
this._lockTimeout = config.lockTimeOut;
}
/**
* @param {*} id
* @param {{blob:{storage:string, container:string, path?:string, [lockStrategy]:number, [lockTimeOut]:number}}} config
* @return {Promise<void>}
*/
async start(id, config) {
this._context.log("Starting transaction.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction.start(id, config)");
this._context.log(JSON.stringify(config), LOG_LEVEL.LEVEL_INFO, "AbstractBlobStorageTransaction.start(id, config)");
if(typeof config.blob === "undefined") {
this._context.log("Invalid configuration, missing blob.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction.start(id, config)");
throw CelastrinaError.newError("Missing blob configuration.");
}
else {
await super.start(id, config);
let blob = config.blob;
this._setLockStrategy(blob);
this._setLockTimeout(blob);
this._blob = id;
this._storage = blob.storage;
this._container = blob.container;
let path = this._getPath(blob);
this._context.log("Path set to '" + path + "'.", LOG_LEVEL.LEVEL_INFO, "AbstractBlobStorageTransaction.start(id, config)");
if(path != null)
this._blob = path + "/" + this._blob;
this._endpoint = "https://" + this._storage + ".blob.core.windows.net/" + this._container + "/" + this._blob;
this._auth = await this._context.authorizationContext.getAuthorization(
ManagedIdentityAuthorization.SYSTEM_MANAGED_IDENTITY);
this._semaphore = new BlobSemaphore(this._auth, this._storage, this._container, this._blob);
this._context.log("Transaction '" + this._endpoint + "' started.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction.start(id, config)");
}
}
/**
* @param {Object} _object
* @return {Promise<Object>}
*/
async _create(_object) {
/**@type{number}*/let _lock = this.lockingStrategy;
this._context.log("Creating '" + this._endpoint + "' using locking strategy " + _lock + ".", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._create()");
if(_lock < BLOB_LOCK_STRATEGY.NONE) {
let token = await this._auth.getToken("https://storage.azure.com/");
let response = await axios.put(this._endpoint, _object,
{headers: {
"Authorization": "Bearer " + token, "x-ms-version": "2020-06-12",
"Content-Type": "application/json", "x-ms-blob-content-type": "application/json",
"Content-Length": _object.length, "x-ms-blob-type": "BlockBlob"
}});
if(response.status === 201) {
this._context.log("Create '" + this._endpoint + " successful.", LOG_LEVEL.LEVEL_INFO,
"BlobStorageTransaction._create()");
try {
await this._semaphore.lock(this.lockTimeOut, this._context);
this._context.log("Lock of '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._create()");
return _object;
}
catch(err) {
token = await this._auth.getToken("https://storage.azure.com/");
await axios.delete(this._endpoint, {headers: {
"Authorization": "Bearer " + token, "x-ms-version": "2020-06-12",
"Content-Type": "application/json", "x-ms-blob-content-type": "application/json",
"x-ms-blob-type": "BlockBlob"
}});
throw CelastrinaError.newError("Unable to lock '" + this._endpoint + "', blob deleted.");
}
}
else
throw CelastrinaError.newError("Unable to create '" + this._endpoint + "'. Response code " +
response.status + ", " + response.statusText);
}
else {
this._context.log("Create successful.", LOG_LEVEL.LEVEL_INFO, "AbstractBlobStorageTransaction._create()");
return _object;
}
}
/**
* @return {Promise<Object>}
*/
async _read() {
let _lock = this.lockingStrategy;
this._context.log("Reading using locking strategy " + _lock + ".", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._read()");
if((_lock < BLOB_LOCK_STRATEGY.NONE) && !this._semaphore.isLocked) {
await this._semaphore.lock(this.lockTimeOut, this._context);
this._context.log("Lock of '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"BlobStorageTransaction._read()");
}
let token = await this._auth.getToken("https://storage.azure.com/");
let _headers = {"Authorization": "Bearer " + token, "x-ms-version": "2020-06-12",
"Accept": "application/json"};
if(this._semaphore.isLocked)
_headers["x-ms-lease-id"] = this._semaphore.leaseId;
let exception = null;
let response = null;
try {
try {
response = await axios.get(this._endpoint, {headers: _headers});
}
catch(error) {
exception = CelastrinaError.newError("Unable to read '" + this._endpoint + "'. Response code " +
error.response.status + ", " + error.response.statusText + ". ",
error.response.status, error);
}
if(exception != null)
throw exception;
else if(response == null)
throw CelastrinaError.newError("No response returned from '" + this._endpoint + "'.");
else if(response.status === 200) {
this._context.log("Read '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._read()");
return response.data;
}
else
throw CelastrinaError.newError("Unable to read '" + this._endpoint + "'. Response code " +
response.status + ", " + response.statusText);
}
finally {
if(_lock > BLOB_LOCK_STRATEGY.COMMIT_LOCK && this._semaphore.isLocked)
await this._semaphore.unlock();
}
}
/**
* @param {Object} _object
* @return {Promise<Object>}
*/
async _update(_object) {
let _lock = this.lockingStrategy;
this._context.log("Updating using locking strategy " + _lock + ".", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._update()");
if((_lock < BLOB_LOCK_STRATEGY.NONE) && !this._semaphore.isLocked) {
await this._semaphore.lock(this.lockTimeOut, this._context);
this._context.log("Lock of '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._update()");
}
let token = await this._auth.getToken("https://storage.azure.com/");
let __object = JSON.stringify(_object);
let header = {"Authorization": "Bearer " + token, "x-ms-version": "2020-06-12",
"Content-Type": "application/json", "x-ms-blob-content-type": "application/json",
"Content-Length": __object.length, "x-ms-blob-type": "BlockBlob"};
if(this._semaphore.isLocked)
header["x-ms-lease-id"] = this._semaphore.leaseId;
let exception = null;
let response = null;
try {
response = await axios.put(this._endpoint, __object, {headers: header});
}
catch(error) {
exception = CelastrinaError.newError("Unable to update '" + this._endpoint + "'. Response code " +
error.response.status + ", " + error.response.statusText + ". ");
}
if(exception != null)
throw exception;
else if(response == null)
throw CelastrinaError.newError("No response returned from '" + this._endpoint + "'.");
else if(response.status === 201) {
this._context.log("Update '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._update()");
if(this._semaphore.isLocked) {
await this._semaphore.unlock();
this._context.log("Ulock '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._update()");
}
}
else
throw CelastrinaError.newError("Unable to update '" + this._endpoint + "'. Response code " +
response.status + ", " + response.statusText);
}
/**
* @return {Promise<void>}
* @private
*/
async _delete() {
this._context.log("Delete " + this._endpoint, LOG_LEVEL.LEVEL_INFO, "AbstractBlobStorageTransaction._delete()");
let token = await this._auth.getToken("https://storage.azure.com/");
let header = {"Authorization": "Bearer " + token, "x-ms-version": "2020-06-12",
"Content-Type": "application/json", "x-ms-blob-content-type": "application/json",
"x-ms-blob-type": "BlockBlob"}
if(this._semaphore.isLocked)
header["x-ms-lease-id"] = this._semaphore.leaseId;
let response = await axios.delete(this._endpoint, {headers: header});
if(response.status === 202) {
this._context.log("Delete '" + this._endpoint + "' successful.", LOG_LEVEL.LEVEL_INFO, "" +
"AbstractBlobStorageTransaction._delete()");
}
throw CelastrinaError.newError("Unable to update '" + this._endpoint + "'. Response code " +
response.status + ", " + response.statusText);
}
/**
* @return {Promise<Object>}
* @private
*/
async _rollback() {
this._context.log("Rollback " + this._endpoint, LOG_LEVEL.LEVEL_INFO, "AbstractBlobStorageTransaction._rollback()");
if(!this._new) {
this._context.log("'" + this._endpoint + "' is not new, updating record.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._rollback()");
await this._update(this._source);
}
else {
this._context.log("'" + this._endpoint + " is a new Blob, deleting record.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._rollback()");
await this._delete();
this._source = null;
this._target = null;
this._context.log("Rollback of new Blob '" + this._endpoint + "' successful, Blob deleted.", LOG_LEVEL.LEVEL_INFO,
"AbstractBlobStorageTransaction._rollback()");
}
}
/**
* @return {Promise<void>}
* @private
*/
async _abort() {
if(this._semaphore.isLocked)
await this._semaphore.unlock(this._context);
}
} |
JavaScript | class NavBarOffset extends React.Component {
render() {
if(this.props.sticky) {
const style = {
"height": "100px"
};
return <div style={style}></div>
}
return null;
}
} |
JavaScript | class MTypeData {
constructor(type = null, bin = null, f = null) {
this.type = type;
this.bin = bin;
this.f = f;
}
} |
JavaScript | class ModalWrapper extends Component {
static setAppElement(element) {
Modal.setAppElement(element);
}
constructor() {
super();
this.onRequestClose = this.onRequestClose.bind(this);
}
onRequestClose(evt) {
const { onRequestClose, shouldCloseOnOverlayClick } = this.props;
if (shouldCloseOnOverlayClick || evt.type === 'keydown') {
onRequestClose();
} else if (this.closeButtonRef) {
this.closeButtonRef.focus();
} else {
this.modalRef.portal.refs.content.focus();
}
}
render() {
const { children, closeButton, shouldCloseOnOverlayClick, contentClass, ...props } = this.props;
return (
<Modal
{...props}
className={cls(props.className)}
onRequestClose={this.onRequestClose}
overlayClassName="modal__overlay"
shouldCloseOnOverlayClick
ref={(modalRef) => { this.modalRef = modalRef; }}
>
<section className={contentClass}>
{children}
</section>
{ closeButton &&
<Lukknapp
overstHjorne
className={classnames(shouldCloseOnOverlayClick || 'modal__lukkknapp--shake')}
onClick={props.onRequestClose}
ref={(closeButtonRef) => { this.closeButtonRef = closeButtonRef; }}
>Lukk modal</Lukknapp>
}
</Modal>
);
}
} |
JavaScript | class RoverButtonList extends Component {
constructor(props) {
super(props);
this.state = { rover : '' };
this.updateDetail = this.updateDetail.bind(this)
}
updateDetail(rover){
this.setState({ rover })
}
renderDetail() {
if(this.state.rover) {
return(
<div className="Detail">
<Detail rover= {this.state.rover} />
</div>
);
}
return(
<div className="Detail">
<div className="RoverCard">
<h2>
Choose a rover!
</h2>
<div className="CameraSwitcher">
</div>
<div className="carousel">
</div>
</div>
</div>
)
}
render() {
console.log("ButtonListIsRendering", this.props.rovers);
return (
<div className="MasterDetail">
<div className="Master">
<h3>
Rovers
</h3>
{
this.props.rovers.map((x) => {
return<RoverButton key={"item-" + x.id} info={x} updateDetail = {this.updateDetail}/>
})
}
</div>
{this.renderDetail()}
</div>)
}
} |
JavaScript | class BTJSONEditor extends BTBase {
static get properties() {
return {
model: { type: String },
readonly: { type: Boolean },
_errors: { type: Array },
};
}
constructor() {
super();
this._errors = [];
this.readonly = false;
}
render() {
return html` <div class=${this.readonly && "readonly"} id="editor"></div> `;
}
firstUpdated() {
const container = this._id("editor");
this._flask = new CodeFlask(container, {
language: "js",
lineNumbers: true,
styleParent: this.shadowRoot,
readonly: this.readonly,
});
this._flask.onUpdate((code) => {
this._silentUpdateModel = true;
this.model = code;
this._silentUpdateModel = false;
this.validate();
this._emit("model-change", { value: code });
});
}
updated(changed) {
if (changed.has("model")) {
if (!this._silentUpdateModel) {
this._flask.updateCode(this.model);
}
}
if (changed.has("readonly")) {
if (this.readonly) {
this._flask.enableReadonlyMode();
} else {
this._flask.disableReadonlyMode();
}
}
}
validate() {
const errors = [];
try {
const json = JSON.parse(this.model);
const isValid = typeof json === "object" && !isEmpty(json);
if (!isValid) {
errors.push(ErrorInvalidJSON);
}
} catch (e) {
errors.push(ErrorInvalidJSON);
}
this._errors = errors;
return errors.length === 0;
}
format() {
try {
const json = JSON.parse(this.model);
this.model = JSON.stringify(json, null, 4);
return true;
} catch (e) {
console.error("Error formatting");
}
return false;
}
static get styles() {
return [
super.styles,
css`
.readonly .codeflask {
opacity: 0.725;
}
`,
];
}
} |
JavaScript | class EncryptionType extends Enum {
constructor(code, keyLength, initializationVectorLength) {
super(code, code);
this._keyLength = keyLength;
this._initializationVectorLength = initializationVectorLength;
}
/**
* The byte length of the algorithm's key.
*
* @public
* @returns {Number}
*/
get keyLength() {
return this._keyLength;
}
/**
* The byte length of the algorithm's initialization vector.
*
* @public
* @returns {Number}
*/
get initializationVectorLength() {
return this._initializationVectorLength;
}
/**
* AES-192.
*
* @public
* @static
* @returns {EncryptionType}
*/
static get AES_192() {
return encryptionTypeAes192;
}
/**
* AES-256.
*
* @public
* @static
* @returns {EncryptionType}
*/
static get AES_256() {
return encryptionTypeAes256;
}
toString() {
return `[EncryptionType (code=${this.code})]`;
}
} |
JavaScript | class InMemoryProvider extends SyncKeyValueProvider {
name() { return InMemoryProvider.Name; }
constructor() {
super({ store: new InMemoryStore() });
}
/**
* Creates an InMemoryProvider instance.
*/
static Create(options, cb) {
cb(null, new InMemoryProvider());
}
} |
JavaScript | class TargetExposition {
/**
*
* @param {Target} target
* @param {Array} projection
*/
constructor(target, projection) {
this.target = target;
this.projection = projection;
this.sendTarget = false;
}
/**
* Sets `mutation` to be commited on exposed field change
* if `sendTarget` is `false`, `action` shall be called in format:
*
* `commit(mutation, { key, value })`
*
* otherwise, if `sendTarget` is set to `true`
*
* `commit(mutation, { target, key, value })`
*
* **Hint**: That's just syntax sugar for `hook()` method.
* @param {String} mutation name of mutation
* @param {Boolean} sendTarget send target to action
* @return {TargetExposition}
*/
commit(mutation, sendTarget = false) {
this.target.commit(mutation);
this.sendTarget = sendTarget || false;
return this;
}
/**
* Sets `action` to be dispatched on exposed field change.
* if `sendTarget` is `false`, `action` shall be called in format:
*
* `dispatch(action, { key, value })`
*
* otherwise, if `sendTarget` is set to `true`
*
* `dispatch(action, { target, key, value })`
*
* **Hint**: That's just syntax sugar for `hook()` method.
* @param {String} action name of action
* @param {Boolean} sendTarget send target to action
* @return {TargetExposition}
*/
dispatch(action, sendTarget = false) {
this.target.dispatch(action);
this.sendTarget = sendTarget || false;
return this;
}
/**
* set callback to be run on property change
*
* @param {TargetExposition~dispatcher} dispatcher
* @param {Boolean} sendTarget
* @return {TargetExposition}
*/
hook(dispatcher, sendTarget) {
this.target.hook(dispatcher);
this.sendTarget = sendTarget || false;
return this;
}
/**
* @callback TargetExposition~dispatcher
* @param {Store} store `vuex` store
* @param {*} value changed value
* @param {String} key key of changed field
* @param {*} target parent object of changed field
*/
/**
* generates map of getters or/and setters for specified projection
*
* @return {Object}
*/
map() {
const result = {};
const { target, sendTarget } = this;
this.projection.forEach(field => {
let camelCasedField = (field.indexOf('.') === -1) ? field : field.replace(/\.(.)/g, (all, matched) => matched.toUpperCase());
result[camelCasedField] = map_1(target, field, sendTarget);
});
if (target.inject) Object.assign(result, target.inject);
return result;
}
/**
* look [Target.use(plugin)](#Target+use)
*
* @param plugin
* @return {TargetExposition}
*/
use(plugin) {
this.target.use(plugin);
return this;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.