language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Sonny {
/**
* @param {String} option Parâmetro obrigatório - este parãmetro espera ser uma das opções: 'learn',
* 'update', ou null. Caso null por padrão será iniciada como 'learn'
* @param {Array<String>} intentTag Parâmetro obrigatório - o intentTag espera os nomes das tags na qual deve procurar
* no intents.json, as opções dependem exclusivamente dos nomes dados a cada tag. Determinará quantos arquivos
* de aprendizado serão criados
* @param {Number} [numberIterations] Parâmetro opcional - este parâmetro determina o número de iterações que
* o Sonny será treinado, como padrão será definido para 20000, caso nenhum valor do tipo número inteiro seja
* definido
* @param {String} [intentsDir] Parâmetro opcional - recebe o diretório onde Sonny deverá procurar se há intents
* que foram treinadas ou criar novas intents de aprendizado
* @returns {Object} Object
*/
constructor(option, intentTag, numberIterations, intentsDir) {
this.intentsDir = intentsDir == undefined ? './learnedIntents/' : intentsDir
this.Error = null
this.intentTag = null
this.numberIterations = numberIterations == undefined ? 20000 : parseInt(numberIterations)
this.option = option == undefined || option == null ? 'learn' : option;
numberIterations = this.numberIterations
option = this.option
if (typeof option != 'string')
this.Error = new Error('O parâmetro option deve ser uma String');
// else if (option != 'learn')
// this.Error = new Error('Opção inválida para o parâmetro option. opções disponíveis: "learn", "execute"');
if (!Array.isArray(intentTag)) {
this.Error = new Error('O parâmetro intentTag deve ser um Array ou não pode estar vazio');
} else {
this.intentTag = intentTag
}
if (typeof numberIterations != 'number')
this.Error = new Error('O parâmetro numberIterations deve ser um número');
// Retorna mensagem de erro caso exista
Sonny.prototype.checkError = (Error) => {
return console.log(Error)
}
/**
*
* @param {String} dir Parâmetro recebe o diretório onde serão gravadas as intents aprendidas por Sonny
* @param {Array<String>} intentTags Recebe as intents já filtradas para nomear os arquivos aprendidos
* por Sonny
*/
Sonny.prototype.trainMany = (dir, intentTags) => {
fs.readFile('testeIntents.json', (err, data) => {
let jsonFile = JSON.parse(data.toString())
for (let i = 0; i < jsonFile.intents.length; i++) {
let inouts = []
let trained = null
if (intentTags.indexOf(jsonFile.intents[i].tag) > -1) {
trained = jsonFile.intents[i].tag
for (let j = 0; j < jsonFile.intents[i].input.length; j++) {
inouts.push({
input: jsonFile.intents[i].input[j],
output: jsonFile.intents[i].output[j]
})
}
net.train(inouts, {
log: true,
iterations: this.numberIterations
});
fs.writeFileSync(dir + trained + '.json', JSON.stringify(net.toJSON()), (err, result) => {
if (err) return console.log(err)
})
console.log('Treinamento finalizado para', trained)
intentTags.unshift()
} else {
console.log('Uma ou mais intents não encontradas')
}
}
})
}
/**
* @param {String} task A task sempre deve ser igual ao valor da variável option
* @returns
*/
Sonny.ExecuteTask = (task, arrayOfIntents) => {
// Lista as intents novas a serem adicionadas através do nome da tag
let listOfIntents = Sonny.prototype.fileTypeAndExistChecker(this.intentTag).newIntentsToLearn
// Lista intents já existentes no diretório de intents aprendidas
let existingIntents = Sonny.prototype.fileTypeAndExistChecker(this.intentTag).existingIntents
Promise.resolve(Sonny.prototype.BlankFile(existingIntents)).then(() => {
switch (task) {
case 'learn':
Sonny.prototype.trainMany(this.intentsDir, listOfIntents)
break;
case 'update':
Sonny.prototype.RemoveExistingIntents(arrayOfIntents)
break;
default:
return console.log('Saindo...')
}
})
// return console.log('executando tarefa', task)
}
/**
*
* @param {String} intentsDir Recebe o diretório de onde se encontram as intents aprendidas por Sonny
* @returns {Array<String>} Retorna todos os arquivos dentro do diretório de intents aprendidas
*/
Sonny.FindLocalFiles = (intentsDir) => {
return fs.readdirSync(intentsDir)
}
/**
*
* @param {Array<String>} nameIntents Recebe uma lista com todos os nomes das tags que devem ser lidas e irão gerar
* um novo arquivo de intent aprendida
*/
Sonny.prototype.fileTypeAndExistChecker = (nameIntents) => {
let possibleExistingIntents = Sonny.FindLocalFiles(this.intentsDir)
let possibleExistingIntentsWithouExtension = []
let newIntentsAvailable = []
let blockedIntents = []
possibleExistingIntents.forEach((el) => { possibleExistingIntentsWithouExtension.push(el.split('.')[0]) })
for (let i = 0; i < nameIntents.length; i++) {
if (possibleExistingIntentsWithouExtension.indexOf(nameIntents[i]) > -1) {
blockedIntents.push(nameIntents[i])
} else {
newIntentsAvailable.push(nameIntents[i])
}
}
return {newIntentsToLearn: newIntentsAvailable, existingIntents: blockedIntents}
}
/**
*
* @param {Array<String>} arrayOfIntents Recebe um array com as intents a serem atualizadas
*/
Sonny.prototype.RemoveExistingIntents = (arrayOfIntents) => {
console.log('Atualizando intents... por favor aguarde isso pode demorar vários minutos')
let reboot = new Sonny(null, arrayOfIntents, this.numberIterations, this.intentsDir)
for (let i = 0; i < arrayOfIntents.length; i++) {
fs.unlinkSync(this.intentsDir + arrayOfIntents[i] + '.json')
reboot.train()
}
}
Sonny.prototype.BlankFile = async (file) => {
let arrayOfIntents = []
let learned = 0
if (file.length > 0) {
for (let i = 0; i < file.length; i++) {
let fileBuffer = fs.readFileSync(this.intentsDir + file[i] + '.json')
if (fileBuffer.toString() === '') {
arrayOfIntents.push(file[i])
} else {
learned ++
}
}
// if (learned > 0) {
// throw new Error(`Uma ou mais Intents selecionadas já foram aprendidas por Sonny '${file}',
// caso queira treiná-las novamente execute-as na função 'new Sonny(option, intentTag).reTeach()'`)
// }
} else {
return;
}
}
// Retorno principal da Class Sonny
return {
// Treina o Sonny com intentTag validas
train: () => {
if (this.Error) {
return Sonny.prototype.checkError(this.Error)
} else {
Sonny.ExecuteTask(this.option)
}
},
// Treina Sonny com intentTag já existentes apagando as antigas
updateIntents: () => {
if (this.Error) {
return Sonny.prototype.checkError(this.Error)
} else {
Sonny.ExecuteTask(this.option, this.intentTag)
}
},
};
}
} |
JavaScript | class PlantPage extends BasePage {
constructor(parentDiv, routeName) {
super(parentDiv, routeName);
this.parentDiv = parentDiv;
this.frameIntervalMS = 200;
this.swimUrl = 'ws://127.0.0.1:5620' // Fallback local service
this._alertStats = 0;
}
/**
* Store url variable, this url is to connect to websocket
* @param {string} url
*/
setSwimURL(newUrl) {
this.swimUrl = newUrl;
}
get alertStats() {
return this._alertStats;
}
/**
* Initialize range input function
* @param {string} url
*/
start(aggregateUrl) {
super.start(aggregateUrl);
//this.swimUrl = 'ws://192.168.0.212:5620'; // Testing
new Graphic(this.swimUrl, 'light', 'lx', '#fee54e');
new Graphic(this.swimUrl, 'soil', '%', '#4bc8ff');
new Graphic(this.swimUrl, 'temperatureCh1', '°', '#ff904e');
this._rangeLight = new PlantRange(this, this.parentDiv, 'light');
this._rangeSoil = new PlantRange(this, this.parentDiv, 'soil');
this._rangeTemp = new PlantRange(this, this.parentDiv, 'temperatureCh1');
// Connect to swim service and check for value
const alertOpenValue = swim.downlinkValue().hostUri(this.swimUrl).nodeUri('/sensor/light').laneUri('option')
.didSet(this.onAlertOpen.bind(this))
.open();
}
/**
* Check if the range inpput wrapper to show or not. Applying the wrapper with class
* @param {number} value between 0-1
*/
onAlertOpen(v) {
const className = 'alert-setting';
this._alertStats = v.numberValue();
if (this._alertStats === 1) {
this.parentDiv.classList.add(className)
this._rangeLight.rangeResize();
this._rangeSoil.rangeResize();
this._rangeTemp.rangeResize();
} else {
this.parentDiv.classList.remove(className);
}
}
/**
* Refresh page
*/
refreshPage() {
super.refreshPage();
}
/**
* Refresh data
*/
refreshData() {
super.refreshData();
this.refreshPage();
}
} |
JavaScript | class PlantRange {
constructor(parent, parentView, type) {
this._parent = parent;
this.parentView = parentView;
this.boxView = document.querySelector(`.box-${type}`);
this._type = type;
this.rangeClick = false;
this.barInterval = null;
this._nodeRef = swim.nodeRef(this._parent.swimUrl, `sensor/${type}`);
this.iconAlert = this.boxView.querySelector('.alert-wrap');
this.iconAlertValue = this.iconAlert.querySelector('.value');
this.iconAlert.addEventListener("click", this.onAlertClick.bind(this))
// Connect to swim service and check for value
const alertValue = this._nodeRef.downlinkValue().laneUri('alert')
.didSet(this.onAlertChange.bind(this))
.open();
this.inputRange = this.boxView.querySelector('.input-range');
this.inputRange.addEventListener('mouseup', this.onRangeMouseup.bind(this));
this.inputRange.addEventListener('input', this.onRangeMousedown.bind(this));
// Connect to swim service and check for value
const inputValue = this._nodeRef.downlinkValue().laneUri('threshold')
.didSet(this.onValueChange.bind(this))
.open();
this.rangeWrap = this.boxView.querySelector('.range-wrap');
this.rangeMeter = this.boxView.querySelector('.range-wrap .meter');
window.addEventListener('resize', this.rangeResize.bind(this));
this.rangeResize();
}
/**
* Dynamic height for range when range is vertical.
* Was not able to do this in css.
*/
rangeResize() {
const height = this.rangeWrap.offsetHeight;
this.inputRange.style.width = `${height + 20}px`;
}
/**
* Clicl event that send {0,1} to siwm service for alert
*/
onAlertClick() {
const value = (this._parent.alertStats === 0)? 1 : 0;
this.updateOption(value);
}
/**
* Check if there is an alert and apply class to parent view
* @stylesheeet .alert-box-{tyoe}
* @param {boolean}
*/
onAlertChange(value) {
(value.stringValue() === 'true')? this.parentView.classList.add(`alert-box-${this._type}`) : this.parentView.classList.remove(`alert-box-${this._type}`);
}
/**
* Change range input base on incoming value
* @param {number} range current state
*/
onValueChange(value) {
value = value.numberValue() || 0; // fallback if value is undefined
if(!this.rangeClick) {
this.inputRange.value = value;
this.onRangeBarChange(value);
}
}
/**
* Mouse down on range input,send the value to swim service
*/
onRangeMousedown() {
this.rangeClick = true;
this.value = this.inputRange.value;
this.onRangeBarChange(this.inputRange.value);
this.updateThreshold(this.inputRange.value);
}
/**
* Mouse up on range input, set click false
*/
onRangeMouseup() {
// set timeout is to prevent on value change to prevent input jumping
// We already set the new value no need to tigger onValueChange again. and prevent spaming
setTimeout(() => {
this.rangeClick = false;
}, 100);
}
/**
* Upadte text and range input
* @param {string} data value
*/
onRangeBarChange(value) {
let percent = value;
if(this._type === 'light' || this._type === 'soil') {
percent = value/10
}
if(this._type === 'soil') {
value = value/10
}
this.iconAlertValue.innerText = Math.round(value);
this.rangeMeter.style.height = `${percent}%`;
}
/**
* Update swim service for threshold
* @param {number} set option value
*/
updateThreshold(value) {
this._nodeRef.command('setThreshold', value);
}
/**
* Update swim service for option
* @param {number} set option value
*/
updateOption(value) {
const nodeRef = swim.nodeRef(this._parent.swimUrl, 'sensor/light');
nodeRef.command('setOption', value);
}
} |
JavaScript | class Context {
/**
* Construction
*/
constructor({ request, response }) {
this.request = request;
this.response = response;
}
} |
JavaScript | class StyleContainer {
constructor() {
this.selectors = new Map()
this.dynamics = new Map()
this._selector = 0
this._listener = new Set()
}
/**
* Adds a new selector with styles
* @param {string} selector - selector to reference the styles
* @param {Object} styles - styles that get added
*/
add(selector, styles) {
if (!this.selectors.has(selector) && !_.isEmpty(styles)) {
this.selectors.set(selector, styles)
this._emitChange()
}
}
/**
* Returns styles referenced by a selector
* @param {string} selector - selector to reference the styles
*/
get(selector) {
return this.selectors.get(selector)
}
/**
* Returns a valid unused selector
* @param {string?} prefix - prefix appended before the className
*/
requestSelector(prefix = 's') {
return prefix + (this._selector++).toString(36)
}
/**
* Adds an change listener
* Returns an instance with an unsubscribe method
* @param {Function} listener - event listener
*/
subscribe(listener) {
this._listener.add(listener)
return {
unsubscribe: () => this._listener.delete(listener)
}
}
/**
* Change emitter executes every single change listener
*/
_emitChange() {
this._listener.forEach(listener => listener())
}
/**
* Adds new dynamic styles referenced by a selector
* @param {string} selector - selector to reference the styles
* @param {Object} styles - styles that get added
*/
_addDynamic(selector, styles) {
if (!this.dynamics.has(selector) && !_.isEmpty(styles)) {
this.dynamics.set(selector, styles)
this._emitChange()
}
}
/**
* Returns dynamic styles referenced by a selector
* @param {string} selector - selector to reference the styles
*/
_getDynamic(selector) {
return this.dynamics.get(selector)
}
} |
JavaScript | class CategoryController {
/**
* Show a list of all categories.
* GET categories
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {TransformWith} ctx.transform
* @param { Object } ctx.pagination
*/
async index({ request, response, transform, pagination }) {
const title = request.input('title')
const query = Category.query()
if (title) {
query.where('title', 'LIKE', `%${title}%`)
}
var categories = await query.paginate(pagination.page, pagination.limit)
categories = await transform.paginate(categories, Transformer)
return response.send(categories)
}
/**
* Display a single category.
* GET categories/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show({ params: { id }, transform, response }) {
var category = await Category.findOrFail(id)
category = await transform.item(category, Transformer)
return response.send(category)
}
} |
JavaScript | class AnalyticsReporterService {
/**
* Report an analytics event
* @param {AnalyticsEvent} event
* @returns {boolean} whether the event was successfully reported
*/
report (event) {}
/**
* Enable or disable conversion tracking
* @param {boolean} isEnabled
*/
setConversionTrackingEnabled (isEnabled) {}
} |
JavaScript | class Hikes {
constructor(elementId) {
this.parentElement = document.getElementById(elementId);
// we need a back button to return back to the list. This will build it and hide it. When we need it we just need to remove the 'hidden' class
this.backButton = this.buildBackButton();
this.comments = new Comments('hikes', 'comments');
}
// why is this function necessary? hikeList is not exported, and so it cannot be seen outside of this module. I added this in case I ever need the list of hikes outside of the module. This also sets me up nicely if my data were to move. I can just change this method to the new source and everything will still work if I only access the data through this getter.
getAllHikes() {
return hikeList;
}
// For the first stretch we will need to get just one hike.
getHikeByName(hikeName) {
return this.getAllHikes().find(hike => hike.name === hikeName);
}
//show a list of hikes in the parentElement
showHikeList() {
this.parentElement.innerHTML = '';
// notice that we use our getter above to grab the list instead of getting it directly...this makes it easier on us if our data source changes...
renderHikeList(this.parentElement, this.getAllHikes());
this.addHikeListener();
// make sure the back button is hidden
this.backButton.classList.add('hidden');
this.comments.showCommentList();
}
// show one hike with full details in the parentElement
showOneHike(hikeName) {
const hike = this.getHikeByName(hikeName);
this.parentElement.innerHTML = '';
this.parentElement.appendChild(renderOneHikeFull(hike));
// show the back button
this.backButton.classList.remove('hidden');
// show the comments for just this hike
this.comments.showCommentList(hikeName);
}
// in order to show the details of a hike ontouchend we will need to attach a listener AFTER the list of hikes has been built. The function below does that.
addHikeListener() {
// We need to loop through the children of our list and attach a listener to each, remember though that children is a nodeList...not an array. So in order to use something like a forEach we need to convert it to an array.
const childrenArray = Array.from(this.parentElement.children);
childrenArray.forEach(child => {
child.addEventListener('click', e => {
// why currentTarget instead of target?
this.showOneHike(e.currentTarget.dataset.name);
});
});
}
buildBackButton() {
const backButton = document.createElement('button');
backButton.innerHTML = '<- All Hikes';
backButton.addEventListener('click', () => {
this.showHikeList();
});
backButton.classList.add('hidden');
this.parentElement.before(backButton);
return backButton;
}
} |
JavaScript | class ExtendedError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
} |
JavaScript | class RethrownError extends ExtendedError {
constructor(error, message) {
super(message);
if (!error) {
throw new Error('RethrownError requires a message and error');
}
this.original = error;
const messageLines = (this.message.match(/\n/g)||[]).length + 1;
// Remove all but the first line of this new stack and replace it with the old stack
// so only the new message appears on top of the entire old stack
this.stack = `${this.stack.split('\n').slice(0, messageLines + 1).join('\n')}\n${error.stack}`;
}
} |
JavaScript | class OAUTH2_CONST {
static get CLIENT_ID() {
return "9480ba15-fdf8-46ca-8745-5950e1d56b15"; //srt-client-app in willzhanad
//return "7eaede8d-6b12-4c81-9414-70309fec1e95"; //client-app-01 in willzhanoutlook.onmicrosoft.com
}
static get TENANT_ID() {
return "51641c40-ad65-4736-88fc-2f0e10072d85"; //willzhanad.onmicrosoft.com
//return "1aaaabcc-73b2-483c-a2c7-b9146631c677"; //willzhanoutlook.onmicrosoft.com
}
static get SCOPE() {
return "api://79b0c254-f7c2-49dd-9a43-97d15873ea1b/Files.Read offline_access";
}
//AAD, AAD B2C, ADFS use different IDP URLs.
static get IDENTITY_PROVIDER() {
return "https://login.microsoftonline.com/";
}
//for information only
static get MSAL_VERSION() {
return "@azure/msal-browser v 2.0.0-beta";
}
} |
JavaScript | class API_CONST {
static get API_LIST () {
return {
separator_0: {
display: "---------- Custom REST API (single-tenant)",
url: "",
method: "",
body: "",
info: "Not a test case. "
},
list: {
display: "Custom REST API - List all",
url: "https://lorentz-apimgmt.azure-api.net/nodes",
method: "GET",
body: "",
info: "List all data"
},
query: {
display: "Custom REST API - Filter, pagination, sort",
url: "https://lorentz-apimgmt.azure-api.net/nodes?customMetadata.vendor=Avid&skip=0&limit=3&sort=nodeName:desc",
method: "GET",
body: "",
info: "You can filter on any attribute, including customMetadata attributes. You can also paginate and sort."
},
delete: {
display: "Custom REST API - Delete",
url: "https://lorentz-apimgmt.azure-api.net/nodes/98ac6960-0d2b-45c1-bfb1-8b14cd18eff4",
method: "DELETE",
body: "",
info: "Make sure to replace the ID in the URL by the nodeId you want to delete."
},
create: {
display: "Custom REST API - Create",
url: "https://lorentz-apimgmt.azure-api.net/nodes",
method: "POST",
body: "",
info: "You may modify the attribute values and/or use any attributes/values in customMetadata."
},
update: {
display: "Custom REST API - Update",
url: "https://lorentz-apimgmt.azure-api.net/nodes/d0a65219-12ad-4334-afca-ec38014ae251",
method: "PUT",
body: "",
info: "Paste into the node content you want to update and modify its values. Also replace the nodeId in the URL."
},
get: {
display: "Custom REST API - Find one",
url: "https://lorentz-apimgmt.azure-api.net/nodes/d0a65219-12ad-4334-afca-ec38014ae251",
method: "GET",
body: "",
info: "Replace the ID by an existing nodeId to get one in response."
},
separator_1: {
display: "---------- Microsoft Graph (multi-tenant)",
url: "",
method: "",
body: "",
info: "Not a test case. "
},
graph_api_me: {
display: "Graph API - me",
url: "https://graph.microsoft.com/beta/me",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/profile"
},
graph_api_memberof: {
display: "Graph API - memberOf",
url: "https://graph.microsoft.com/beta/me/memberOf",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/profile"
},
graph_api_groups: {
display: "Graph API - groups",
url: "https://graph.microsoft.com/beta/groups",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/profile"
},
graph_api_serviceprincipals: {
display: "Graph API - service principals",
url: "https://graph.microsoft.com/beta/serviceprincipals",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/profile"
},
graph_api_presence: {
display: "Graph API - presence",
url: "https://graph.microsoft.com/beta/me/presence",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/Presence.Read. Presence API requires Teams deployment."
},
graph_api_profile: {
display: "Graph API - profile",
url: "https://graph.microsoft.com/beta/me/profile",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/Presence.Read. "
},
graph_api_users: {
display: "Graph API - users",
url: "https://graph.microsoft.com/beta/users",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/Presence.Read. "
},
graph_api_organization: {
display: "Graph API - organization",
url: "https://graph.microsoft.com/beta/organization",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/Presence.Read. "
},
graph_api_oauth2PermissionGrants: {
display: "Graph API - oauth2PermissionGrants",
url: "https://graph.microsoft.com/beta/me/oauth2PermissionGrants",
method: "GET",
body: "",
info: "Must use a Graph API scope such as https://graph.microsoft.com/Presence.Read. "
},
separator_2: {
display: "---------- Azure Media Services (multi-tenant)",
url: "",
method: "",
body: "",
info: "Not a test case. "
},
ams_drm: {
display: "Key Delivery API - DRM/AES-128",
url: "",
method: "GET",
body: "",
info: "This test case is done on AMS tab."
},
// separator_3: {
// display: "---------- Kafka REST Proxy (multi-tenant)",
// url: "",
// method: "",
// body: "",
// info: "Not a test case. "
// },
// kafka_topics: {
// display: "Kafka - topics",
// url: "https://clustkafka-kafkarest.azurehdinsight.net/v1/metadata/topics",
// method: "GET",
// body: "",
// info: "Get list of topics in Kafka"
// },
// kafka_partitions: {
// display: "Kafka - partitions",
// url: "https://clustkafka-kafkarest.azurehdinsight.net/v1/metadata/topics/nodeUpdate/partitions",
// method: "GET",
// body: "",
// info: "Get list of partitions of a topic"
// },
// kafka_produce: {
// display: "Kafka - produce",
// url: "https://clustkafka-kafkarest.azurehdinsight.net/v1/producer/topics/nodeUpdate",
// method: "POST",
// body: "",
// info: "Produce records"
// },
// kafka_consume: {
// display: "Kafka - consume",
// url: "https://clustkafka-kafkarest.azurehdinsight.net/v1/consumer/topics/nodeUpdate/partitions/0/offsets/0 ",
// method: "GET",
// body: "",
// info: "Consume records"
// },
} ;
}
} |
JavaScript | class RemoteControlClient extends BaseRemoteControlService {
/**
* Initializes a new {@code RemoteControlClient} instance.
*/
constructor() {
super();
/**
* Prevents from triggering more than one go to meeting actions at the same time.
*
* @type {Promise|null}
* @private
*/
this._goToMeetingPromise = null;
this._lastSpotState = null;
this._wirelessScreensharingConfiguration = null;
/**
* A timeout triggered in "no backend" mode which will trigger a disconnect if Spot TV presence does not arrive
* within 5 seconds since the MUC has been joined.
*
* @type {number|null}
* @private
*/
this._waitForSpotTvTimeout = null;
}
/**
* Requests the {@code RemoteControlServer} to change its audio level to a
* specific direction.
*
* @param {string} direction - The direction of the volume adjustment.
* One of 'up' or 'down'.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
adjustVolume(direction) {
return this.xmppConnection.sendCommand(
this._getSpotId(), COMMANDS.ADJUST_VOLUME, { direction });
}
/**
* Stores options related to wireless screensharing which will be to passed
* into the wireless screensharing service upon screenshare start.
*
* @param {Object} configuration - A configuration file for how the wireless
* screensharing should be captured.
* @param {Object} configuration.maxFps - The maximum number of frame per
* second which should be captured from the sharer's device.
* @returns {void}
*/
configureWirelessScreensharing(configuration = {}) {
this._wirelessScreensharingConfiguration = configuration;
}
/**
* Extends the connection promise with Spot Remote specific functionality.
*
* @param {ConnectOptions} options - Information necessary for creating the connection.
* @returns {Promise<RoomProfile>}
* @protected
*/
_createConnectionPromise(options) {
return super._createConnectionPromise(options)
.then(roomProfile => {
if (!options.backend) {
this._setWaitForSpotTvTimeout();
}
return roomProfile;
});
}
/**
* Stops any active {@code ScreenshareConnection}.
*
* @returns {void}
*/
destroyWirelessScreenshareConnections() {
if (this._screenshareConnection) {
this._screenshareConnection.stop();
this._screenshareConnection = null;
}
if (this._startWithScreenshare) {
this._startWithScreenshare.stop();
this._startWithScreenshare = null;
}
}
/**
* Stops the XMPP connection.
*
* @inheritdoc
* @override
*/
disconnect(event) {
this.destroyWirelessScreenshareConnections();
this._lastSpotState = null;
return super.disconnect(event);
}
/**
* Converts a join code to Spot-TV connection information so it can be connected to by
* a Spot-Remote.
*
* @param {string} code - The join code to exchange for connection information.
* @returns {Promise<RoomInfo>} Resolve with join information or an error.
*/
exchangeCodeWithXmpp(code) {
if (code.length === 6) {
return Promise.resolve({
roomName: code.substring(0, 3),
roomLock: code.substring(3, 6)
});
}
// The 'not-authorized' error is returned by the server if the code is wrong.
// Return the same error if it's known that the code is invalid before submitting to the server.
return Promise.reject('not-authorized');
}
/**
* Implements a way to get the current join code to connect to the
* {@code RemoteControlServer}.
*
* @inheritdoc
* @override
*/
getJoinCode() {
return (this._lastSpotState && this._lastSpotState.remoteJoinCode)
|| this._options.joinCode;
}
/**
* Requests a {@code RemoteControlServer} to join a meeting.
*
* @param {string} meetingName - The meeting to join.
* @param {GoToMeetingOptions} options - Additional details about how to join the
* meeting.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
goToMeeting(meetingName, options = {}) {
if (this._goToMeetingPromise) {
return Promise.reject('Another goToMeeting action is still in progress');
}
const { startWithScreensharing, ...otherOptions } = options;
let preGoToMeeting = Promise.resolve();
if (startWithScreensharing === 'wireless') {
const connection = this._createScreensharingService(otherOptions);
preGoToMeeting = connection.createTracks()
.then(() => {
this._startWithScreenshare = connection;
});
}
this._goToMeetingPromise
= preGoToMeeting
.then(() => this.xmppConnection.sendCommand(
this._getSpotId(),
COMMANDS.GO_TO_MEETING,
{
startWithScreensharing: startWithScreensharing === 'wired',
startWithVideoMuted: startWithScreensharing === 'wireless',
...otherOptions,
meetingName
})
)
.then(() => {
this._goToMeetingPromise = null;
}, error => {
this._goToMeetingPromise = null;
throw error;
});
return this._goToMeetingPromise;
}
/**
* Requests a {@code RemoteControlServer} to leave a meeting in progress.
*
* @param {boolean} skipFeedback - Whether or not to immediately navigate
* out of the meeting instead of display feedback entry.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
hangUp(skipFeedback = false) {
this.destroyWirelessScreenshareConnections();
return this.xmppConnection.sendCommand(
this._getSpotId(),
COMMANDS.HANG_UP,
{
skipFeedback
}
);
}
/**
* Requests a {@code RemoteControlServer} to change its audio mute status.
*
* @param {boolean} mute - Whether or not Spot should be audio muted.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
setAudioMute(mute) {
return this.xmppConnection.sendCommand(
this._getSpotId(), COMMANDS.SET_AUDIO_MUTE, { mute });
}
/**
* Requests a {@code RemoteControlServer} to change its screensharing status.
* Turning on the screensharing will enable wired screensharing, while
* turning off applies to both wired and wireless screensharing.
*
* @param {boolean} screensharing - Whether or not {@code RemoteControlServer}
* should start or stop screensharing.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
setScreensharing(screensharing) {
return this.xmppConnection.sendCommand(
this._getSpotId(),
COMMANDS.SET_SCREENSHARING,
{ on: screensharing }
);
}
/**
* Requests a {@code RemoteControlServer} to enter or exit tile view mode.
*
* @param {boolean} tileView - Whether or not {@code RemoteControlServer}
* should be in or not be in tile view.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
setTileView(tileView) {
return this.xmppConnection.sendCommand(
this._getSpotId(),
COMMANDS.SET_TILE_VIEW,
{ tileView }
);
}
/**
* Requests a {@code RemoteControlServer} to change its video mute status.
*
* @param {boolean} mute - Whether or not {@code RemoteControlServer} should
* be video muted.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
setVideoMute(mute) {
return this.xmppConnection.sendCommand(
this._getSpotId(), COMMANDS.SET_VIDEO_MUTE, { mute });
}
/**
* Logic specific to the "no backend" mode.
*
* This sets a timeout which will trigger a disconnect if Spot TV presence does not arrive
* within 5 seconds since the MUC was joined by Spot Remote.
*
* @returns {void}
* @private
*/
_setWaitForSpotTvTimeout() {
if (!this._getSpotId()) {
this._waitForSpotTvTimeout = setTimeout(() => {
logger.error('Spot TV never joined the MUC');
this._onDisconnect(CONNECTION_EVENTS.SERVER_DISCONNECTED);
}, 5 * 1000);
}
}
/**
* Begins or stops the process for a {@code RemoteControlClient} to connect
* to the Jitsi-Meet participant in order to directly share a local screen.
*
* @param {boolean} enable - Whether to start ot stop screensharing.
* @param {Object} options - Additional configuration to use for creating
* the screenshare connection.
* @returns {Promise}
*/
setWirelessScreensharing(enable, options) {
return enable
? this._startWirelessScreenshare(undefined, options)
: this._stopWirelessScreenshare();
}
/**
* Triggers any stored wireless screesharing connections to start the
* process of establishing a connection to a Jitsi-Meet meeting participant.
*
* @returns {void}
*/
startAnyDeferredWirelessScreenshare() {
if (!this._startWithScreenshare) {
// No wireless screenshare to start.
return;
}
this._startWirelessScreenshare(this._startWithScreenshare)
.then(() => logger.log('Start with screensharing successful'))
.catch(error => logger.error(
'Failed to start with screensharing', { error }));
this._startWithScreenshare = null;
}
/**
* Requests a {@code RemoteControlServer} to submit post-meeting feedback.
*
* @param {Object} feedback - The feedback to submit.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
submitFeedback(feedback) {
return this.xmppConnection.sendCommand(
this._getSpotId(), COMMANDS.SUBMIT_FEEDBACK, feedback);
}
/**
* Requests a {@code RemoteControlServer} to submit a password to attempt
* entry into a locked meeting.
*
* @param {string} password - The password to submit.
* @returns {Promise} Resolves if the command has been acknowledged.
*/
submitPassword(password) {
return this.xmppConnection.sendCommand(
this._getSpotId(), COMMANDS.SUBMIT_PASSWORD, password);
}
/**
* Initialize a new {@link ScreenshareService} instance.
*
* @param {Object} options - Additional configuration to use for creating
* the screenshare connection.
* @private
* @returns {ScreenshareService}
*/
_createScreensharingService(options = {}) {
return new ScreenshareService({
mediaConfiguration:
this._wirelessScreensharingConfiguration || {},
/**
* The {@code JitsiConnection} instance will be used to fetch TURN credentials.
*/
jitsiConnection: this.xmppConnection.getJitsiConnection(),
/**
* Callback invoked when the connection has been closed
* automatically. Triggers cleanup of {@code ScreenshareService}.
*
* @returns {void}
*/
onConnectionClosed: () => {
this._stopWirelessScreenshare();
options.onClose && options.onClose();
},
/**
* Callback invoked by {@code ScreenshareService} in order to
* communicate out to a {@code RemoteControlServer} an update about
* the screensharing connection.
*
* @param {string} to - The {@code RemoteControlServer} jid to send
* the message to.
* @param {Object} data - A payload to send along with the
* message.
* @returns {Promise}
*/
sendMessage: (to, data) =>
this.xmppConnection.sendMessage(
to,
MESSAGES.REMOTE_CONTROL_UPDATE,
data
).catch(error => logger.error(
'Failed to send screensharing message', { error }))
});
}
/**
* Get the {@code RemoteControlServer} jid for which to send commands and
* messages.
*
* @private
* @returns {string|null}
*/
_getSpotId() {
return this._lastSpotState && this._lastSpotState.spotId;
}
/**
* Implements {@link BaseRemoteControlService#_onPresenceReceived}.
*
* @inheritdoc
*/
_onPresenceReceived({ from, type, state }) {
if (type === 'unavailable') {
if (this._getSpotId() === from) {
logger.log('Spot TV left the MUC');
if (this._options.backend) {
// With backend it is okay for remote to sit in the MUC without Spot TV connected.
this._lastSpotState = {
spotId: undefined
};
this.emit(
SERVICE_UPDATES.SERVER_STATE_CHANGE,
{
updatedState: this._lastSpotState
}
);
} else {
this._onDisconnect(CONNECTION_EVENTS.SERVER_DISCONNECTED);
}
}
return;
}
if (type === 'error') {
logger.log(
'error presence received, interpreting as disconnect');
this._onDisconnect(CONNECTION_EVENTS.SERVER_DISCONNECTED);
return;
}
if (!state.isSpot) {
// Ignore presence from others not identified as a
// {@code RemoteControlServer}.
return;
}
// Redundantly update the known {@code RemoteControlServer} jid in case
// there are multiple due to ghosts left form disconnect, in which case
// the active {@code RemoteControlServer} should be emitting updates.
this._lastSpotState = {
...state,
spotId: from
};
// This is "no backend" specific logic
if (this._waitForSpotTvTimeout) {
clearTimeout(this._waitForSpotTvTimeout);
this._waitForSpotTvTimeout = null;
}
this.emit(
SERVICE_UPDATES.SERVER_STATE_CHANGE,
{
updatedState: this._lastSpotState
}
);
}
/**
* Processes screenshare related updates from the Jitsi-Meet participant.
*
* @override
* @inheritdoc
*/
_processMessage(messageType, from, data) {
switch (messageType) {
case MESSAGES.JITSI_MEET_UPDATE:
this._screenshareConnection
&& this._screenshareConnection.processMessage({
data,
from
});
break;
}
}
/**
* Begins the process of creating a direct connection to the Jitsi-Meet
* participant.
*
* @param {ScreenshareConnection} connection - Optionally use an existing
* instance of ScreenshareConnection instead of instantiating one. This
* would be used when creating a desktop track to stream first but the
* actual connection to the Jitsi participant must occur later.
* @param {Object} options - Additional configuration to use for creating
* the screenshare connection.
* @private
* @returns {Promise}
*/
_startWirelessScreenshare(connection, options) {
if (this._screenshareConnection) {
logger.error('Already started wireless screenshare');
return Promise.reject('Already started wireless screenshare');
}
this._screenshareConnection
= connection || this._createScreensharingService(options);
return this._screenshareConnection.startScreenshare(this._getSpotId())
.catch(error => {
logger.error(
'Could not establish wireless screenshare connection',
{ error }
);
this.destroyWirelessScreenshareConnections();
return Promise.reject(error);
});
}
/**
* Cleans up screensharing connections between the {@code RemoteControlClient}
* and Jitsi-Meet participant that are pending or have successfully been made.
*
* @private
* @returns {Promise}
*/
_stopWirelessScreenshare() {
this.destroyWirelessScreenshareConnections();
return this.setScreensharing(false);
}
} |
JavaScript | class PlainWithPillsSerializer {
/*
* @param {String} options.pillFormat - either 'md', 'plain', 'id'
*/
constructor(options = {}) {
const {
pillFormat = 'plain',
} = options;
this.pillFormat = pillFormat;
}
/**
* Serialize a Slate `value` to a plain text string,
* serializing pills as either MD links, plain text representations or
* ID representations as required.
*
* @param {Value} value
* @return {String}
*/
serialize = value => {
return this._serializeNode(value.document);
}
/**
* Serialize a `node` to plain text.
*
* @param {Node} node
* @return {String}
*/
_serializeNode = node => {
if (
node.object == 'document' ||
(node.object == 'block' && Block.isBlockList(node.nodes))
) {
return node.nodes.map(this._serializeNode).join('\n');
} else if (node.type == 'emoji') {
return node.data.get('emojiUnicode');
} else if (node.type == 'pill') {
const completion = node.data.get('completion');
// over the wire the @room pill is just plaintext
if (completion === '@room') return completion;
switch (this.pillFormat) {
case 'plain':
return completion;
case 'md':
return `[${ completion }](${ node.data.get('href') })`;
case 'id':
return node.data.get('completionId') || completion;
}
} else if (node.nodes) {
return node.nodes.map(this._serializeNode).join('');
} else {
return node.text;
}
}
} |
JavaScript | class Instructions {
constructor() {
this.scene;
this.video;
}
createScene() {
var scene = new BABYLON.Scene(engine);
this.scene = scene;
// Add a camera to the scene and attach it to the canvas
let camera = new BABYLON.UniversalCamera("UniversalCamera", new BABYLON.Vector3(0, 0, -6), scene);
camera.setTarget(BABYLON.Vector3.Zero());
var cvas = document.getElementById('renderCanvas');
var fov = camera.fov;
var aspectRatio = cvas.width / cvas.height;
var d = camera.position.length();
var y = d * Math.tan(fov);
var x = y * aspectRatio;
var plane = BABYLON.MeshBuilder.CreatePlane("plane", { width: x, height: y }, this.scene); // default plane
plane.material = new BABYLON.StandardMaterial("mat", this.scene);
plane.material.diffuseTexture = new BABYLON.VideoTexture("video", "videos/intro/walkerintro.m4v", this.scene, true);
plane.material.emissiveColor = new BABYLON.Color3(1, 1, 1);
var music = new BABYLON.Sound("Music", "audio/background_athmosphere.mp3", scene, null, {
loop: true,
autoplay: true,
volume: 0.66
});
scene.onKeyboardObservable.add(kbInfo => kbInfo.type == BABYLON.KeyboardEventTypes.KEYUP && this.onKeyUp(kbInfo));
this.hud = new Hud(this.scene);
this.hud.createTextElementAlign("whistleInfo", "#FFFFFF", "Whistle to skip.", "center", "bottom");
this.whistleHandler = new WhistleHandler();
this.whistleHandler.enableWhistleHandler((whistlePattern) => {
if (whistlePattern.length) {
setNewScene(menu);
}
});
}
onKeyUp(kbInfo) {
console.log(kbInfo.event.code);
switch (kbInfo.event.code) {
case "Esc":
setNewScene(menu)
break;
}
}
isReady() {
return (this.scene && this.scene.isReady());
}
onLoad() {
}
render() {
this.scene.render();
}
dispose() {
this.scene.dispose();
if (this.whistleHandler)
this.whistleHandler.disableWhistleHandler();
}
} |
JavaScript | class EventTimer extends Timer {
/**
* Instantiates an event timer object
* @param {object} httpServer
* @param {object} timerConfig
* @param {object} [oscConfig]
* @param {object} [httpConfig]
*/
constructor(httpServer, timerConfig, oscConfig, httpConfig) {
// call super constructor
super();
this.cycleState = {
/* idle: before it is initialised */
idle: 'idle',
/* onLoad: when a new event is loaded */
onLoad: 'onLoad',
/* armed: when a new event is loaded but hasn't started */
armed: 'armed',
onStart: 'onStart',
/* update: every update call cycle (1 x second) */
onUpdate: 'onUpdate',
onPause: 'onPause',
onStop: 'onStop',
onFinish: 'onFinish',
};
this.ontimeCycle = 'idle';
this.prevCycle = null;
// OSC Object
this.osc = null;
// HTTP Client Object
this.http = null;
this._numClients = 0;
this._interval = null;
this.presenter = {
text: '',
visible: false,
};
this.public = {
text: '',
visible: false,
};
this.lower = {
text: '',
visible: false,
};
// call general title reset
this._resetSelection();
this.numEvents = 0;
this._eventlist = null;
this.onAir = false;
// initialise socketIO server
this.messageStack = [];
this.MAX_MESSAGES = 100;
this._clientNames = {};
this.io = new Server(httpServer, {
cors: {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
},
});
// set recurrent emits
this._interval = setInterval(() => this.runCycle(), timerConfig?.refresh || 1000);
// listen to new connections
this._listenToConnections();
if (oscConfig != null) {
this._initOscClient(oscConfig);
}
if (httpConfig != null) {
this._initHTTPClient(httpConfig);
}
}
/**
* @description Shutdown process
*/
shutdown() {
clearInterval(this._interval);
this.info('SERVER', 'Shutting down ontime');
if (this.io != null) {
this.info('TX', '... Closing socket server');
this.io.close();
}
if (this.osc != null) {
this.info('TX', '... Closing OSC Client');
this.osc.shutdown();
}
if (this.http != null) {
this.info('TX', '... Closing HTTP Client');
this.http.shutdown();
}
}
/**
* Initialises OSC Integration object
* @param {object} oscConfig
* @private
*/
_initOscClient(oscConfig) {
this.osc = new OSCIntegration();
const r = this.osc.init(oscConfig);
r.success ? this.info('TX', r.message) : this.error('TX', r.message);
}
/**
* Initialises HTTP Integration object
* @param {object} httpConfig
* @private
*/
_initHTTPClient(httpConfig) {
this.info('TX', `Initialise HTTP Client on port`);
this.http = new HTTPIntegration();
this.http.init(httpConfig);
this.httpMessages = httpConfig.messages;
}
/**
* Sends time object over websockets
*/
broadcastTimer() {
// through websockets
this.io.emit('timer', this.getTimeObject());
}
/**
* Broadcasts complete object state
*/
broadcastState() {
this.broadcastTimer();
this.io.emit('playstate', this.state);
this.io.emit('selected', {
id: this.selectedEventId,
index: this.selectedEventIndex,
total: this.numEvents,
});
this.io.emit('selected-id', this.selectedEventId);
this.io.emit('next-id', this.nextEventId);
this.io.emit('numevents', this.numEvents);
this.io.emit('publicselected-id', this.selectedPublicEventId);
this.io.emit('publicnext-id', this.nextPublicEventId);
this.io.emit('titles', this.titles);
this.io.emit('publictitles', this.titlesPublic);
this.io.emit('onAir', this.onAir);
}
/**
* Broadcast given message
* @param {string} address - socket io address
* @param {any} payload - message body
*/
broadcastThis(address, payload) {
this.io.emit(address, payload);
}
/**
* @description Interface for triggering playback actions
* @param {string} action - state to be triggered
* @returns {boolean} Whether action was called
*/
trigger(action) {
// Todo: reply should come from status change
let reply = true;
switch (action) {
case 'start':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Start');
this.start();
break;
case 'pause':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Pause');
this.pause();
break;
case 'stop':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Stop');
this.stop();
break;
case 'roll':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Roll');
this.roll();
break;
case 'previous':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Previous');
this.previous();
break;
case 'next':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Play Mode Next');
this.next();
break;
case 'unload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Events unloaded');
this.unload();
break;
case 'reload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.info('PLAYBACK', 'Reloaded event');
this.reload();
break;
case 'onAir':
// Call action
this.info('PLAYBACK', 'Going On Air');
this.setonAir(true);
break;
case 'offAir':
// Call action and force update
this.info('PLAYBACK', 'Going Off Air');
this.setonAir(false);
break;
default:
// Error, disable flag
this.error('RX', `Unhandled action triggered ${action}`);
reply = false;
break;
}
// update state
this.runCycle();
return reply;
}
/**
* @description State machine checks what actions need to
* happen at every app cycle
*/
runCycle() {
const h = this.httpMessages?.messages;
let httpMessage = null;
switch (this.ontimeCycle) {
case 'idle':
break;
case 'armed':
// if we come from roll, see if we can start
if (this.state === 'roll') {
this.update();
}
break;
case 'onLoad':
// broadcast change
this.broadcastState();
// Todo: wrap in reusable function
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onLoad?.url !== '') {
httpMessage = h?.onLoad?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case 'onStart':
// broadcast current state
this.broadcastState();
// send OSC if there is something running
// _finish at is only set when an event is loaded
if (this._finishAt > 0) {
this.sendOsc(this.osc.implemented.play);
this.sendOsc(this.osc.implemented.eventNumber, this.selectedEventIndex || 0);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStart?.url !== '') {
httpMessage = h?.onStart?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
case 'onUpdate':
// call update
this.update();
// broadcast current state
this.broadcastTimer();
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
if (this.current != null && this.secondaryTimer == null) {
this.sendOsc(this.osc.implemented.time, this.timeTag);
this.sendOsc(this.osc.implemented.overtime, this.current > 0 ? 0 : 1);
this.sendOsc(this.osc.implemented.title, this.titles?.titleNow || '');
this.sendOsc(this.osc.implemented.presenter, this.titles?.presenterNow || '');
}
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onUpdate?.url !== '') {
httpMessage = h?.onUpdate?.url;
}
}
break;
case 'onPause':
// broadcast current state
this.broadcastState();
// send OSC
this.sendOsc(this.osc.implemented.pause);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onPause?.url !== '') {
httpMessage = h?.onPause?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case 'onStop':
// broadcast change
this.broadcastState();
// send OSC if something was actually stopped
if (this.prevCycle === this.cycleState.onUpdate) {
this.sendOsc(this.osc.implemented.stop);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStop?.url !== '') {
httpMessage = h?.onStop?.url;
}
}
// update lifecycle: idle
this.ontimeCycle = this.cycleState.idle;
break;
case 'onFinish':
// broadcast change
this.broadcastState();
// finished an event
this.sendOsc(this.osc.implemented.finished);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onFinish?.url !== '') {
httpMessage = h?.onFinish?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
default:
this.error('SERVER', `Unhandled cycle: ${this.ontimeCycle}`);
}
// send http message if any
if (httpMessage != null) {
const v = {
$timer: this.timeTag,
$title: this.titles.titleNow,
$presenter: this.titles.presenterNow,
$subtitle: this.titles.subtitleNow,
'$next-title': this.titles.titleNext,
'$next-presenter': this.titles.presenterNext,
'$next-subtitle': this.titles.subtitleNext,
};
const m = cleanURL(replacePlaceholder(httpMessage, v));
this.http.send(m);
}
// update
this.update();
// reset cycle
this.prevCycle = this.ontimeCycle;
}
update() {
// if there is nothing selected, update clock
const now = this._getCurrentTime();
// if we are not updating, send the timers
if (this.ontimeCycle !== this.cycleState.onUpdate) {
this.clock = now;
this.broadcastThis('timer', {
clock: now,
running: Timer.toSeconds(this.current),
secondary: Timer.toSeconds(this.secondaryTimer),
durationSeconds: Timer.toSeconds(this.duration),
expectedFinish: this._getExpectedFinish(),
startedAt: this._startedAt,
});
}
// Have we skipped onStart?
if (this.state === 'start' || this.state === 'roll') {
if (this.ontimeCycle === this.cycleState.armed) {
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
this.runCycle();
}
}
// update default functions
super.update();
if (this._finishedFlag) {
// update lifecycle: onFinish and call cycle
this.ontimeCycle = this.cycleState.onFinish;
this._finishedFlag = false;
this.runCycle();
}
// only implement roll here, rest implemented in super
if (this.state === 'roll') {
const u = {
selectedEventId: this.selectedEventId,
current: this.current,
// safeguard on midnight rollover
_finishAt: this._finishAt >= this._startedAt ? this._finishAt : this._finishAt + DAY_TO_MS,
clock: this.clock,
secondaryTimer: this.secondaryTimer,
_secondaryTarget: this._secondaryTarget,
};
const { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished } = updateRoll(u);
this.current = updatedTimer;
this.secondaryTimer = updatedSecondaryTimer;
if (isFinished) {
// update lifecycle: onFinish
this.ontimeCycle = this.cycleState.onFinish;
this.runCycle();
}
if (doRollLoad) {
this.rollLoad();
}
}
}
/**
* Set titles and broadcast change
* @param {string} action
* @param {any} payload
* @private
*/
_setTitles(action, payload) {
switch (action) {
/*******************************************/
// Presenter message
case 'set-timer-text':
this.presenter.text = payload;
this.broadcastThis('messages-timer', this.presenter);
break;
case 'set-timer-visible':
this.presenter.visible = payload;
this.broadcastThis('messages-timer', this.presenter);
break;
/*******************************************/
// Public message
case 'set-public-text':
this.public.text = payload;
this.broadcastThis('messages-public', this.public);
break;
case 'set-public-visible':
this.public.visible = payload;
this.broadcastThis('messages-public', this.public);
break;
/*******************************************/
// Lower third message
case 'set-lower-text':
this.lower.text = payload;
this.broadcastThis('messages-lower', this.lower);
break;
case 'set-lower-visible':
this.lower.visible = payload;
this.broadcastThis('messages-lower', this.lower);
break;
default:
break;
}
}
/**
* Handle socket io connections
* @private
*/
_listenToConnections() {
this.io.on('connection', (socket) => {
/*******************************/
/*** HANDLE NEW CONNECTION ***/
/*** --------------------- ***/
/*******************************/
// keep track of connections
this._numClients++;
this._clientNames[socket.id] = getRandomName();
const m = `${this._numClients} Clients with new connection: ${this._clientNames[socket.id]}`;
this.info('CLIENT', m);
// send state
socket.emit('timer', this.getTimeObject());
socket.emit('playstate', this.state);
socket.emit('selected-id', this.selectedEventId);
socket.emit('next-id', this.nextEventId);
socket.emit('publicselected-id', this.selectedPublicEventId);
socket.emit('publicnext-id', this.nextPublicEventId);
/********************************/
/*** HANDLE DISCONNECT USER ***/
/*** ---------------------- ***/
/********************************/
socket.on('disconnect', () => {
this._numClients--;
const m = `${this._numClients} Clients with disconnection: ${this._clientNames[socket.id]}`;
delete this._clientNames[socket.id];
this.info('CLIENT', m);
});
/***************************************/
/*** TIMER STATE GETTERS / SETTERS ***/
/*** ----------------------------- ***/
/***************************************/
/*******************************************/
// general playback state
socket.on('get-state', () => {
socket.emit('timer', this.getTimeObject());
socket.emit('playstate', this.state);
socket.emit('selected-id', this.selectedEventId);
socket.emit('next-id', this.nextEventId);
socket.emit('publicselected-id', this.selectedPublicEventId);
socket.emit('publicnext-id', this.this.nextPublicEventId);
});
/*******************************************/
// timer
socket.on('get-current', () => {
socket.emit('current', this.getCurrentInSeconds());
});
socket.on('get-timer', () => {
socket.emit('timer', this.getTimeObject());
});
socket.on('increment-timer', (data) => {
if (isNaN(parseInt(data))) return;
if (data < -5 || data > 5) return;
this.increment(data * 1000 * 60);
});
/*******************************************/
// playstate
socket.on('set-playstate', (data) => {
this.trigger(data);
});
socket.on('get-playstate', () => {
socket.emit('playstate', this.state);
});
socket.on('set-onAir', (data) => {
this.onAir = data;
this.broadcastThis('onAir', this.onAir);
});
socket.on('get-onAir', () => {
socket.emit('onAir', this.onAir);
});
/*******************************************/
// selection data
socket.on('get-selected', () => {
socket.emit('selected', {
id: this.selectedEventId,
index: this.selectedEventIndex,
total: this.numEvents,
});
});
socket.on('get-selected-id', () => {
socket.emit('selected-id', this.selectedEventId);
});
socket.on('get-numevents', () => {
socket.emit('numevents', this.numEvents);
});
socket.on('get-next-id', () => {
socket.emit('next-id', this.nextEventId);
});
socket.on('get-publicselected-id', () => {
socket.emit('publicselected-id', this.selectedPublicEventId);
});
socket.on('get-publicnext-id', () => {
socket.emit('publicnext-id', this.nextPublicEventId);
});
// title data
socket.on('get-titles', () => {
socket.emit('titles', this.titles);
});
// title data
socket.on('get-publictitles', () => {
socket.emit('publictitles', this.titlesPublic);
});
/***********************************/
/*** MESSAGE GETTERS / SETTERS ***/
/*** ------------------------- ***/
/***********************************/
/*******************************************/
// Messages
socket.on('get-messages', () => {
this.broadcastThis('messages-timer', this.presenter);
this.broadcastThis('messages-public', this.public);
this.broadcastThis('messages-lower', this.lower);
});
// Presenter message
socket.on('set-timer-text', (data) => {
this._setTitles('set-timer-text', data);
});
socket.on('set-timer-visible', (data) => {
this._setTitles('set-timer-visible', data);
});
socket.on('get-timer', () => {
this.broadcastThis('messages-timer', this.presenter);
});
/*******************************************/
// Public message
socket.on('set-public-text', (data) => {
this._setTitles('set-public-text', data);
});
socket.on('set-public-visible', (data) => {
this._setTitles('set-public-visible', data);
});
socket.on('get-public', () => {
socket.emit('messages-public', this.public);
});
/*******************************************/
// Lower third message
socket.on('set-lower-text', (data) => {
this._setTitles('set-lower-text', data);
});
socket.on('set-lower-visible', (data) => {
this._setTitles('set-lower-visible', data);
});
socket.on('get-lower', () => {
socket.emit('messages-lower', this.lower);
});
});
}
/**
* Deletes running event list from object
*/
clearEventList() {
// unload events
this.unload();
// set general
this._eventlist = [];
this.numEvents = 0;
// update lifecycle: onStop
this.ontimeCycle = this.cycleState.onStop;
// update clients
this.broadcastThis('numevents', this.numEvents);
}
/**
* Adds an event list to object
* @param {array} eventlist
*/
setupWithEventList(eventlist) {
if (!Array.isArray(eventlist) || eventlist.length < 1) return;
// filter only events
const events = eventlist.filter((e) => e.type === 'event');
const numEvents = events.length;
// set general
this._eventlist = events;
this.numEvents = numEvents;
// list may contain no events
if (numEvents < 1) return;
// load first event
this.loadEvent(0);
// update clients
this.broadcastState();
// run cycle
this.runCycle();
}
/**
* Updates event list in object
* @param {array} eventlist
*/
updateEventList(eventlist) {
// filter only events
const events = eventlist.filter((e) => e.type === 'event');
const numEvents = events.length;
// is this the first event
let first = this.numEvents === 0;
// set general
this._eventlist = events;
this.numEvents = numEvents;
// list may be empty
if (numEvents < 1) {
this.unload();
return;
}
// auto load if is the only event
if (first) {
this.loadEvent(0);
} else if (this.selectedEventId != null) {
// handle reload selected
// Look for event (order might have changed)
const eventIndex = this._eventlist.findIndex((e) => e.id === this.selectedEventId);
// Maybe is missing
if (eventIndex === -1) {
this._resetTimers();
this._resetSelection();
return;
}
// Reload data if running
const type = this._startedAt != null ? 'reload' : 'load';
this.loadEvent(eventIndex, type);
}
// update clients
this.broadcastState();
// run cycle
this.runCycle();
}
/**
* Updates a single id in the object list
* @param {string} id
* @param {object} entry - new event object
*/
updateSingleEvent(id, entry) {
// find object in events
const eventIndex = this._eventlist.findIndex((e) => e.id === id);
if (eventIndex === -1) return;
// update event in memory
const e = this._eventlist[eventIndex];
this._eventlist[eventIndex] = { ...e, ...entry };
try {
// check if entry is running
if (e.id === this.selectedEventId) {
// handle reload selected
// Reload data if running
let type = this.selectedEventId === id && this._startedAt != null ? 'reload' : 'load';
this.loadEvent(this.selectedEventIndex, type);
} else if (e.id === this.nextEventId) {
// roll needs to recalculate
if (this.state === 'roll') {
this.rollLoad();
}
}
// load titles
if ('title' in e || 'subtitle' in e || 'presenter' in e) {
// TODO: should be more selective on the need to load titles
this._loadTitlesNext();
this._loadTitlesNow();
}
} catch (error) {
this.error('SERVER', error);
}
// update clients
this.broadcastState();
// run cycle
this.runCycle();
}
/**
* Deleted an event from the list by its id
* @param {string} eventId
*/
deleteId(eventId) {
// find object in events
const eventIndex = this._eventlist.findIndex((e) => e.id === eventId);
if (eventIndex === -1) return;
// delete event and update count
this._eventlist.splice(eventIndex, 1);
this.numEvents = this._eventlist.length;
// reload data if necessary
if (eventId === this.selectedEventId) {
this.unload();
return;
}
// update selected event index
this.selectedEventIndex = this._eventlist.findIndex((e) => e.id === this.selectedEventId);
// reload titles if necessary
if (eventId === this.nextEventId || eventId === this.nextPublicEventId) {
this._loadTitlesNext();
} else if (eventId === this.selectedPublicEventId) {
this._loadTitlesNow();
}
// update clients
this.broadcastState();
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given Id
* @param {string} eventId - ID of event in eventlist
*/
loadEventById(eventId) {
const eventIndex = this._eventlist.findIndex((e) => e.id === eventId);
if (eventIndex === -1) return;
this.pause();
this.loadEvent(eventIndex, 'load');
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given index
* @param {number} eventIndex - Index of event in eventlist
*/
loadEventByIndex(eventIndex) {
if (eventIndex === -1 || eventIndex > this.numEvents) return;
this.pause();
this.loadEvent(eventIndex, 'load');
// run cycle
this.runCycle();
}
/**
* Loads a given event by index
* @param {object} eventIndex
* @param {string} [type='load'] - 'load' or 'reload', whether we are keeping running time
*/
loadEvent(eventIndex, type = 'load') {
const e = this._eventlist[eventIndex];
if (e == null) return;
const start = e.timeStart == null || e.timeStart === '' ? 0 : e.timeStart;
let end = e.timeEnd == null || e.timeEnd === '' ? 0 : e.timeEnd;
// in case the end is earlier than start, we assume is the day after
if (end < start) end += DAY_TO_MS;
// time stuff changes on whether we keep the running clock
if (type === 'load') {
this._resetTimers();
this.duration = end - start;
this.current = this.duration;
this.selectedEventIndex = eventIndex;
this.selectedEventId = e.id;
} else if (type === 'reload') {
const now = this._getCurrentTime();
const elapsed = this.getElapsed();
this.duration = end - start;
this.selectedEventIndex = eventIndex;
this._finishAt = now + (this.duration - elapsed);
}
// load current titles
this._loadTitlesNow();
// look for event after
this._loadTitlesNext();
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
}
_loadTitlesNow() {
const e = this._eventlist[this.selectedEventIndex];
if (e == null) return;
// private title is always current
// check if current is also public
if (e.isPublic) {
this._loadThisTitles(e, 'now');
} else {
this._loadThisTitles(e, 'now-private');
// assume there is no public event
this.titlesPublic.titleNow = null;
this.titlesPublic.subtitleNow = null;
this.titlesPublic.presenterNow = null;
this.selectedPublicEventId = null;
// if there is nothing before, return
if (this.selectedEventIndex === 0) return;
// iterate backwards to find it
for (let i = this.selectedEventIndex; i >= 0; i--) {
if (this._eventlist[i].type === 'event' && this._eventlist[i].isPublic) {
this._loadThisTitles(this._eventlist[i], 'now-public');
break;
}
}
}
}
_loadThisTitles(e, type) {
if (e == null) return;
switch (type) {
// now, load to both public and private
case 'now':
// public
this.titlesPublic.titleNow = e.title;
this.titlesPublic.subtitleNow = e.subtitle;
this.titlesPublic.presenterNow = e.presenter;
this.selectedPublicEventId = e.id;
// private
this.titles.titleNow = e.title;
this.titles.subtitleNow = e.subtitle;
this.titles.presenterNow = e.presenter;
this.titles.noteNow = e.note;
this.selectedEventId = e.id;
break;
case 'now-public':
this.titlesPublic.titleNow = e.title;
this.titlesPublic.subtitleNow = e.subtitle;
this.titlesPublic.presenterNow = e.presenter;
this.selectedPublicEventId = e.id;
break;
case 'now-private':
this.titles.titleNow = e.title;
this.titles.subtitleNow = e.subtitle;
this.titles.presenterNow = e.presenter;
this.titles.noteNow = e.note;
this.selectedEventId = e.id;
break;
// next, load to both public and private
case 'next':
// public
this.titlesPublic.titleNext = e.title;
this.titlesPublic.subtitleNext = e.subtitle;
this.titlesPublic.presenterNext = e.presenter;
this.nextPublicEventId = e.id;
// private
this.titles.titleNext = e.title;
this.titles.subtitleNext = e.subtitle;
this.titles.presenterNext = e.presenter;
this.titles.noteNext = e.note;
this.nextEventId = e.id;
break;
case 'next-public':
this.titlesPublic.titleNext = e.title;
this.titlesPublic.subtitleNext = e.subtitle;
this.titlesPublic.presenterNext = e.presenter;
this.nextPublicEventId = e.id;
break;
case 'next-private':
this.titles.titleNext = e.title;
this.titles.subtitleNext = e.subtitle;
this.titles.presenterNext = e.presenter;
this.titles.noteNext = e.note;
this.nextEventId = e.id;
break;
default:
break;
}
}
_loadTitlesNext() {
// maybe there is nothing to load
if (this.selectedEventIndex == null) return;
// assume there is no next event
this.titles.titleNext = null;
this.titles.subtitleNext = null;
this.titles.presenterNext = null;
this.titles.noteNext = null;
this.nextEventId = null;
this.titlesPublic.titleNext = null;
this.titlesPublic.subtitleNext = null;
this.titlesPublic.presenterNext = null;
this.nextPublicEventId = null;
if (this.selectedEventIndex < this.numEvents - 1) {
let nextPublic = false;
let nextPrivate = false;
for (let i = this.selectedEventIndex + 1; i < this.numEvents; i++) {
// check that is the right type
if (this._eventlist[i].type === 'event') {
// if we have not set private
if (!nextPrivate) {
this._loadThisTitles(this._eventlist[i], 'next-private');
nextPrivate = true;
}
// if event is public
if (this._eventlist[i].isPublic) {
this._loadThisTitles(this._eventlist[i], 'next-public');
nextPublic = true;
}
}
// Stop if both are set
if (nextPublic && nextPrivate) break;
}
}
}
_resetSelection() {
this.titles = {
titleNow: null,
subtitleNow: null,
presenterNow: null,
noteNow: null,
titleNext: null,
subtitleNext: null,
presenterNext: null,
noteNext: null,
};
this.titlesPublic = {
titleNow: null,
subtitleNow: null,
presenterNow: null,
titleNext: null,
subtitleNext: null,
presenterNext: null,
};
this.selectedEventIndex = null;
this.selectedEventId = null;
this.nextEventId = null;
this.selectedPublicEventId = null;
this.nextPublicEventId = null;
}
/**
* @description Set onAir property of timer
* @param {boolean} onAir - whether flag is active
*/
setonAir(onAir) {
this.onAir = onAir;
// broadcast change
this.broadcastThis('onAir', onAir);
}
start() {
// do we need to change
if (this.state === 'start') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.start();
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
}
pause() {
// do we need to change
if (this.state === 'pause') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.pause();
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onPause;
}
stop() {
// do we need to change
if (this.state === 'stop') return;
// call super
super.stop();
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onStop;
}
increment(amount) {
// call super
super.increment(amount);
// run cycle
this.runCycle();
}
rollLoad() {
const now = this._getCurrentTime();
let prevLoaded = this.selectedEventId;
// maybe roll has already been loaded
if (this.secondaryTimer === null) {
this._resetTimers(true);
this._resetSelection();
}
const { nowIndex, nowId, publicIndex, nextIndex, publicNextIndex, timers, timeToNext } =
getSelectionByRoll(this._eventlist, now);
// nothing to play, unload
if (nowIndex === null && nextIndex === null) {
this.unload();
this.warning('SERVER', 'Roll: no events found');
return;
}
// there is something running, load
if (nowIndex !== null) {
// clear secondary timers
this.secondaryTimer = null;
this._secondaryTarget = null;
// set timers
this._startedAt = timers._startedAt;
this._finishAt = timers._finishAt;
this.duration = timers.duration;
this.current = timers.current;
// set selection
this.selectedEventId = nowId;
this.selectedEventIndex = nowIndex;
}
// found something to run next
if (nextIndex != null) {
// Set running timers
if (nowIndex === null) {
// only warn the first time
if (this.secondaryTimer === null) {
this.info('SERVER', 'Roll: waiting for event start');
}
// reset running timer
// ??? should this not have been reset?
this.current = null;
// timer counts to next event
this.secondaryTimer = timeToNext;
this._secondaryTarget = this._eventlist[nextIndex].timeStart;
}
// TITLES: Load next private
this._loadThisTitles(this._eventlist[nextIndex], 'next-private');
}
// TITLES: Load next public
if (publicNextIndex !== null) {
this._loadThisTitles(this._eventlist[publicNextIndex], 'next-public');
}
// TITLES: Load now private
if (nowIndex !== null) {
this._loadThisTitles(this._eventlist[nowIndex], 'now-private');
}
// TITLES: Load now public
if (publicIndex !== null) {
this._loadThisTitles(this._eventlist[publicIndex], 'now-public');
}
if (prevLoaded !== this.selectedEventId) {
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
// ensure we go through onLoad cycle
this.runCycle();
}
}
roll() {
// do we need to change
if (this.state === 'roll') return;
if (this.numEvents === 0 || this.numEvents == null) return;
// set state
this.state = 'roll';
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
// load into event
this.rollLoad();
}
previous() {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the first event?
if (this.selectedEventIndex === 0) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
return;
}
// send OSC
this.sendOsc(this.osc.implemented.previous);
// change playstate
this.pause();
const gotoEvent = this.selectedEventIndex > 0 ? this.selectedEventIndex - 1 : 0;
if (gotoEvent === this.selectedEventIndex) return;
this.loadEvent(gotoEvent);
}
next() {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the last event?
if (this.selectedEventIndex === this.numEvents - 1) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
return;
}
// send OSC
this.sendOsc(this.osc.implemented.next);
// change playstate
this.pause();
const gotoEvent =
this.selectedEventIndex < this.numEvents - 1
? this.selectedEventIndex + 1
: this.numEvents - 1;
if (gotoEvent === this.selectedEventIndex) return;
this.loadEvent(gotoEvent);
}
unload() {
// reset timer
this._resetTimers(true);
// reset selected
this._resetSelection();
// broadcast state
this.broadcastState();
// reset playstate
this.stop();
}
reload() {
if (this.numEvents === 0 || this.numEvents == null) return;
// change playstate
this.pause();
// send OSC
this.sendOsc(this.osc.implemented.reload);
// reload data
this.loadEvent(this.selectedEventIndex);
}
/****************************************************************************/
/**
* Logger logic
* -------------
*
* This should be separate of event timer, left here for convenience
*
*/
/**
* Utility method, sends message and pushes into stack
* @param {string} level
* @param {string} origin
* @param {string} text
*/
_push(level, origin, text) {
const m = {
id: generateId(),
level,
origin,
text,
time: stringFromMillis(this._getCurrentTime()),
};
this.messageStack.unshift(m);
this.io.emit('logger', m);
if (process.env.NODE_ENV !== 'prod') {
console.log(`[${m.level}] \t ${m.origin} \t ${m.text}`);
}
if (this.messageStack.length > this.MAX_MESSAGES) {
this.messageStack.pop();
}
}
/**
* Sends a message with level LOG
* @param {string} origin
* @param {string} text
*/
info(origin, text) {
this._push('INFO', origin, text);
}
/**
* Sends a message with level WARN
* @param {string} origin
* @param {string} text
*/
warning(origin, text) {
this._push('WARN', origin, text);
}
/**
* Sends a message with level ERROR
* @param {string} origin
* @param {string} text
*/
error(origin, text) {
this._push('ERROR', origin, text);
}
/****************************************************************************/
/**
* Integrations
* -------------
*
* Code related to integrations
*
*/
/**
* Calls OSC send message and resolves reply to logger
* @param {string} message
* @param {any} [payload]
*/
async sendOsc(message, payload = undefined) {
// Todo: add disabled osc check
const reply = await this.osc.send(message, payload);
if (!reply.success) {
this.error('TX', reply.message);
}
}
/**
* Builds sync object
* @returns {{running: number, timer: (null|string|*), presenter: null, playback: string, clock: null, title: null}}
*/
poll() {
return {
clock: this.clock,
running: Timer.toSeconds(this.current),
timer: this.timeTag,
playback: this.state,
title: this.titles.titleNow,
presenter: this.titles.presenterNow,
};
}
} |
JavaScript | class progressRing extends LightningElement {
/**
* The percentage value of the progress ring. The value must be a number from 0 to 100.
* A value of 50 corresponds to a color fill of half the ring in a clockwise
* or counterclockwise direction, depending on the direction attribute.
* @type {number}
* @default 0
*/
@api value = 0;
/**
* Changes the appearance of the progress ring.
* Accepted variants include base, active-step, warning, expired, base-autocomplete.
*
* @type {string}
* @default 'base'
*/
@api variant = 'base';
/**
* Controls which way the color flows from the top of the ring, either clockwise or counterclockwise
* Valid values include fill and drain. The fill value corresponds to a color flow in the clockwise direction.
* The drain value indicates a color flow in the counterclockwise direction.
*
* @type {string}
* @default 'fill'
*/
@api direction = 'fill';
/**
* The size of the progress ring. Valid values include medium and large.
*
* @type {string}
* @default 'medium'
*/
@api size = 'medium';
get d() {
const fillPercent = this.value / 100;
const filldrain = this.direction === 'drain' ? 1 : 0;
const inverter = this.direction === 'drain' ? 1 : -1;
const islong = fillPercent > 0.5 ? 1 : 0;
const subCalc = 2 * Math.PI * fillPercent;
const arcx = Math.cos(subCalc);
const arcy = Math.sin(subCalc) * inverter;
return `M 1 0 A 1 1 0 ${islong} ${filldrain} ${arcx} ${arcy} L 0 0`;
}
get iconSvg() {
if (this.variant === 'warning') {
return 'M23.7 19.6L13.2 2.5c-.6-.9-1.8-.9-2.4 0L.3 19.6c-.7 1.1 0 2.6 1.1 2.6h21.2c1.1 0 1.8-1.5 1.1-2.6zM12 18.5c-.8 0-1.4-.6-1.4-1.4s.6-1.4 1.4-1.4 1.4.6 1.4 1.4-.6 1.4-1.4 1.4zm1.4-4.2c0 .3-.2.5-.5.5h-1.8c-.3 0-.5-.2-.5-.5v-6c0-.3.2-.5.5-.5h1.8c.3 0 .5.2.5.5v6z';
}
if (this.variant === 'expired') {
return 'M12 .9C5.9.9.9 5.9.9 12s5 11.1 11.1 11.1 11.1-5 11.1-11.1S18.1.9 12 .9zM3.7 12c0-4.6 3.7-8.3 8.3-8.3 1.8 0 3.5.5 4.8 1.5L5.2 16.8c-1-1.3-1.5-3-1.5-4.8zm8.3 8.3c-1.8 0-3.5-.5-4.8-1.5L18.8 7.2c1 1.3 1.5 3 1.5 4.8 0 4.6-3.7 8.3-8.3 8.3z';
}
if (this.isComplete) {
return 'M8.8 19.6L1.2 12c-.3-.3-.3-.8 0-1.1l1-1c.3-.3.8-.3 1 0L9 15.7c.1.2.5.2.6 0L20.9 4.4c.2-.3.7-.3 1 0l1 1c.3.3.3.7 0 1L9.8 19.6c-.2.3-.7.3-1 0z';
}
return undefined;
}
get computedAltText() {
if (this.variant === 'warning') {
return 'Warning';
}
if (this.variant === 'expired') {
return 'Expired';
}
if (this.isComplete) {
return 'Complete';
}
return undefined;
}
get computedOuterClass() {
return classSet('slds-progress-ring').add({
'slds-progress-ring_large': this.size === 'large',
'slds-progress-ring_warning': this.variant === 'warning',
'slds-progress-ring_expired': this.variant === 'expired',
'slds-progress-ring_active-step': this.variant === 'active-step',
'slds-progress-ring_complete': this.isComplete,
});
}
get computedIconTheme() {
return classSet('slds-icon_container').add({
'slds-icon-utility-warning': this.variant === 'warning',
'slds-icon-utility-error': this.variant === 'expired',
'slds-icon-utility-success': this.isComplete,
});
}
get isComplete() {
return (
this.variant === 'base-autocomplete' && Number(this.value) === 100
);
}
} |
JavaScript | class Shift {
/*
Retrieves a shift in the database by shiftID
and sets that shift as the current shift.
*/
async apply(shiftID){
let result = await db.query("select * from shifts where shiftID = ?",{conditions:[shiftID]});
if(result.length === 0)
return Promise.reject(new Error("❌ No shift with the id "+shiftID+" was found"));
this.shiftID = shiftID;
await this.build(result[0]);
return result[0];
}
/**
builds a structured shift object that holds more information
and assigns that object to the class.
@return {Object} structuredShiftObject
@param {Object} shiftData the raw sql return object
*/
async build(sqlResult){
this.rawData = sqlResult;
this.shiftData = {...sqlResult,
shiftDateEnd:new Date(Number(sqlResult.shiftDateEnd)),
shiftDateStart:new Date(Number(sqlResult.shiftDateStart)),
};
/* Gathers Posted and Covered Users Data. Data is pending Promise*/
if(sqlResult.postedBy !== null){
let postedBy = new User(undefined,'employee').lookup({by:'id',value:sqlResult.postedBy})
this.shiftData.postedBy = postedBy;
}
if(sqlResult.coveredBy !== null){
let coveredBy = new User(undefined,'employee').lookup({by:'id',value:sqlResult.coveredBy})
this.shiftData.coveredBy = coveredBy;
}
let posName = await db.query('select posName from positions where id = ?',{conditions:[sqlResult.positionID]});
this.shiftData.posName = posName[0].posName;
this.id = this.shiftData.shiftID;
}
/**
* Deletes the current shift present in the class instance
* Pass in the option migrate to migrate the shift data.
*
* Note: shiftData is set to undefined after
*
* @param {Object} options | Migrate should shift be migrated into legacyshifts after deletion.
*/
delete(options){
if(!this.shiftData) {
return new Error('Deletion aborted no shift selected');
}
db.query('delete from shifts where shiftID = ?',{conditions:[this.shiftData.shiftID]})
.catch(err => {
console.log("[Shift] Error shift deletion for ID "+this.shiftData.shiftID);
console.log(err);
return;
});
if(options && options.migrate){
let {shiftID,coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,shiftDateEnd,shiftDateStart} = this.rawData;
db.query('insert into legacyShifts (shiftID,coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,shiftDateEnd,shiftDateStart) values (?,?,?,?,?,?,?,?,?,?,?)',
{conditions:[
shiftID,coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,shiftDateEnd,shiftDateStart,
]})
.catch(err => {
console.log("[Shift] Error shift migrating");
console.log(err);
return;
});
}
this.shiftData = undefined;
this.rawData = undefined;
}
/**
*
* Creates a new shift that is inserted into the database
* and sets the shift data in the class instance
*
* @param {Int} shiftID
* @param {Int | null} coveredBy
* @param {Int} postedBy
* @param {Date} postedDate
* @param {Int} availability
* @param {Int} positionID
* @param {Int} groupID
* @param {Int} perm
* @param {String} message
* @param {Date} shiftDateEnd
* @param {Date} shiftDateStart
*/
async create({coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,shiftDateEnd,shiftDateStart}){
let end = shiftDateEnd.getTime();
let start = shiftDateStart.getTime();
await db.query('insert into shifts (coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,shiftDateEnd,shiftDateStart) values (?,?,?,?,?,?,?,?,?,?)',{conditions:[
coveredBy,postedBy,postedDate,availability,positionID,groupID,perm,message,end,start,
]})
.catch(err => {
console.log("[Shift] Error inserting new shift");
console.log(err);
return;
});
let dbResult = await db.query('select max(shiftID) from shifts');
let id = dbResult['0']['max(shiftID)'];
await this.apply(id);
return id;
}
/**
* Updates the current shift and database to a user assignment of a shift
*
* @param {String} user The bnid of the user that is being assigned the current shift
*/
async assignTo(user, options){
if(!this.shiftData) return new Error("Can't assign shift: shift doesn't exist");
//validate user exists and get ID
let userObj = await db.query('select * from users where empybnid = ?',{conditions:[user]});
if(userObj.length === 0){
console.log('user '+user+' was not found');
return;
}
//update
db.query('Update shifts set coveredBy = ?, availability = ? where shiftId = ?',{conditions:[userObj[0].id,0,this.shiftData.shiftID]});
this.shiftData.availability = 0;
this.shiftData.coveredBy = userObj[0];
if(!options) return;
if(options.notify){
}
}
} |
JavaScript | class AsyncIterator {
constructor (observable) {
this._observable = observable;
}
* iter () {
let isDone = false;
let pendingCallback;
let pendingValues = [];
// TO DO: Look for a more efficient queue implementation.
const callTheCallback = (callback, pendingValue) => {
if (pendingValue.value === doneSentinel) {
isDone = true;
}
callback(pendingValue.err, pendingValue.value);
};
const produce = pendingValue => {
if (pendingCallback) {
const cb = pendingCallback;
pendingCallback = null;
callTheCallback(cb, pendingValue);
} else {
pendingValues.push(pendingValue);
}
};
this._subscribeHandle = this._observable.subscribe(
value => produce({err: null, value: value}),
err => produce({err: err, value: null}),
() => produce({err: null, value: doneSentinel}));
const consumeViaCallback = () => {
return cb => {
let item = pendingValues.shift();
if (item === undefined) {
pendingCallback = cb;
} else {
callTheCallback(cb, item);
}
};
};
while (!isDone) { // eslint-disable-line no-unmodified-loop-condition
// isDone gets modified in callTheCallback, above.
yield consumeViaCallback();
}
}
makeIter () {
let result = this.iter();
result.nextValue = function * () {
let item = yield this._iter.next();
if (item.value === doneSentinel) {
throw new Error('Expected onNext notification, got onCompleted instead');
}
return item.value;
}.bind(this);
result.shouldComplete = function * () {
let item = yield this._iter.next();
if (item.value !== doneSentinel) {
throw new Error('Expected onCompleted notification, got onNext(' + item.value + ') instead');
}
}.bind(this);
result.shouldThrow = function * () {
let item;
try {
item = yield this._iter.next();
} catch (err) {
return err;
}
if (item.value === doneSentinel) {
throw new Error('Expected onError notification, got onCompleted instead');
} else {
throw new Error('Expected onError notification, got onNext(' + item.value + ') instead');
}
}.bind(this);
result.unsubscribe = function () {
if (this._subscribeHandle === undefined) {
throw new Error('toAsyncIterator: unsubscribing before first yield not allowed');
}
// Quietly ignore second unsubscribe attempt.
if (this._subscribeHandle) {
this._subscribeHandle.dispose();
this._subscribeHandle = false;
}
}.bind(this);
this._iter = result;
return result;
}
} |
JavaScript | class Block {
constructor(index, previousHash, timestamp, data, hash) {
this.index = index;
this.previousHash = previousHash.toString();
this.timestamp = timestamp;
this.data = data;
this.hash = hash.toString();
}
} |
JavaScript | class WidgetService extends EventEmitter {
/**
* Creates an instance of WidgetService.
*
* @param {string} consoleAppUrl the console app URL address
* @param {string} widgetId the widget ID
*/
constructor(consoleAppUrl, widgetId) {
super()
this.apiService = new ApiService(consoleAppUrl)
this.consoleAppUrl = consoleAppUrl
this.widgetId = widgetId
this.users = []
}
/**
* Initializes the service.
*
* @memberof WidgetService
*/
async init() {
return new Promise((resolve, reject) => {
this.apiService.getSettings().then((appSettingsJson) => {
this.appSettings = new ApplicationSettings(appSettingsJson)
try {
this.apiService.getWidgetById(this.widgetId).then((widgetObject) => {
this.widget = JSON.parse(widgetObject)
this.install().then((response) => {
const responseJson = JSON.parse(response)
if (responseJson.status === 'failure') {
reject(responseJson.result)
}
this.webSocketService = new WebSocketService(
this.appSettings.webSocketServiceUrl
)
this.webSocketService.addListener('register', (e) => {
this.onUserRegister(e)
})
this.webSocketService.addListener('listUsers', (e) => {
this.onListUsers(e)
})
this.webSocketService.addListener('callAccepted', (e) => {
this.onCallAccepted(e)
})
this.webSocketService.addListener('callRejected', () => {
this.onCallRejected()
})
this.webSocketService.addListener('error', (error) => {
this.emit('error', error)
})
this.webSocketService.addListener(
'communicationRecord',
(record) => {
this.onCommunicationRecord(record)
}
)
this.user = {
uuid: 'guest_' + String(Math.floor(Date.now() / 1000)),
roomId: this.widget.uuid,
}
this.webSocketService.registerGuest(
this.user.uuid,
this.widget.uuid
)
// attach videochat events
this.videochatProxy = videochat.proxy()
this.videochatProxy.addEventListener('close', () => {
this.onCloseVideoChat()
})
this.videochatProxy.addEventListener('remote_hangup', () => {
this.onCloseVideoChat()
})
resolve()
})
})
} catch (e) {
console.log(e)
}
})
})
}
/**
* Removes connection data in the videochat application.
*/
destroyVideoChatApp() {
try {
this.videochatProxy.destroy()
} catch (e) {
console.log('e', e)
}
}
/**
* Handles videochat session close.
*/
onCloseVideoChat() {
this.emit('videochatSessionClose')
}
/**
* Requests a call with an active admin.
*
* @memberof WidgetService
*/
requestCall() {
const adminUuid = this.admins[0]
this.webSocketService.requestCall(
this.user.uuid,
this.user.userId,
adminUuid,
this.widget.uuid
)
}
/**
* Cancels a call request.
*
* @memberof WidgetService
*/
cancelCall() {
const adminUuid = this.admins[0]
this.webSocketService.cancelCall(
this.sessionRecord.id,
this.user.userId,
adminUuid,
this.widget.uuid
)
}
/**
* Handles user register response.
*
* @param {string} response the response
* @memberof WidgetService
*/
onUserRegister(response) {
if (response === 'ok') {
this.webSocketService.listAdmins(this.user.uuid, this.widget.uuid)
}
}
/**
* Handles user list refresh response.
*
* @param {array<string>} a
* @memberof WidgetService
*/
onListUsers(a) {
this.admins = a
this.emit('listUsers', a)
if (a.length) {
const adminId = QhUtils.extractUserId(a[0])
this.getUser(adminId).then((user) => {
this.emit('admin', user)
})
}
}
/**
* Handles call accept notification.
*
* @param {string} uuid the UUID string
* @memberof WidgetService
*/
async onCallAccepted(uuid) {
this.emit('callAccepted', uuid)
}
/**
* Handles call reject notification.
*
* @memberof WidgetService
*/
onCallRejected() {
this.emit('callRejected')
// this.destroyVideoChatApp()
}
/**
* Handles communication record.
*
* @param {object} record the communication record
*/
onCommunicationRecord(record) {
this.sessionRecord = record
}
/**
* Sends contact form.
*
* @param {array<object>} fieldSet the field set
*/
sendContactForm(fieldSet) {
const url = `${this.consoleAppUrl}/dashboard/widget_extension_embed/${
this.widgetId
}/${encodeURIComponent(window.location.hostname.toLowerCase())}/${
this.widget.uuid
}`
return this.apiService.postAsXMLHttpRequest(fieldSet, url)
}
/**
* Sends start video chat form.
*
* @param {object} fieldSet
* @returns the response
*/
sendStartVideoChatForm(fieldSet) {
const url = `${this.consoleAppUrl}/dashboard/widget_active_operator/${
this.widgetId
}/${encodeURIComponent(window.location.hostname.toLowerCase())}/${
this.widget.uuid
}`
return this.apiService.postAsXMLHttpRequest(fieldSet, url)
}
/**
* Installs the widget.
*
* @returns true if installed correctly.
*/
async install() {
const url = `${this.consoleAppUrl}/dashboard/install/${
this.widgetId
}/${encodeURIComponent(window.location.hostname.toLowerCase())}/${
this.widget.uuid
}`
return this.apiService.postAsXMLHttpRequest({}, url)
}
/**
* Gets user by user ID.
*
* @param {*} userId
* @returns
*/
async getUser(userId) {
let userJson = await this.apiService.getUserById(userId)
return JSON.parse(userJson)
}
/**
* Sets communication session rate.
*
* @param {number} rate
* @returns
*/
async rateComSession(rate) {
let resultJson = await this.apiService.rateComSession(
this.sessionRecord.id,
rate
)
return JSON.parse(resultJson)
}
/**
* Sets local user ID.
*
* @param {number} userId
*/
setUserId(userId) {
this.user.userId = userId
}
/**
* Gets an active operator init form template.
*
* @returns the template string
*/
async getActiveOperatorInitForm() {
return await this.apiService.getAsXMLHttpRequest(
`${this.consoleAppUrl}/dashboard/active_operator_init_form`
)
}
/**
* Gets an inactive operator init form template.
*
* @returns the template string
*/
async getInactiveOperatorInitForm() {
return await this.apiService.getAsXMLHttpRequest(
`${this.consoleAppUrl}/dashboard/inactive_operator_init_form`
)
}
} |
JavaScript | class AddTodo extends React.Component {
/**
* @param {*} props
*/
constructor(props) {
super(props);
this.addTodo = this.addTodo.bind(this);
}
/**
* Call addTodo action.
* @param {Object} e event
* @param {Text} input
*/
addTodo(e, input) {
e.preventDefault();
if (!input.value.trim()) {
return;
}
this.props.actions.addTodo(input.value.trim());
input.value = "";
}
/**
* @return {JSX}
*/
render() {
let input;
return (
<div style={{
marginBottom: "10px",
marginTop: "10px",
}}>
<div className="input-group col-md-4">
<input ref={(node) => input = node}
className="form-control"
type="text"
placeholder="Input todo item..."
onKeyPress={(e)=>{
if (e.key === "Enter") {
this.addTodo(e, input);
}
}}/>
<span className="input-group-btn">
<button type="button"
className="btn btn-default"
onClick={(e)=> this.addTodo(e, input)}>
Ta Da!
</button>
</span>
</div>
</div>
);
}
} |
JavaScript | class FBSDKSendButton extends React.Component {
render() {
return (
<RCTFBSDKSendButton
{...this.props}
style={[styles.fbsdkSendButton, this.props.style]}
/>
);
}
} |
JavaScript | class AdvancedFilter {
/**
* Create a AdvancedFilter.
* @property {string} [key] The field/property in the event based on which
* you want to filter.
* @property {string} operatorType Polymorphic Discriminator
*/
constructor() {
}
/**
* Defines the metadata of AdvancedFilter
*
* @returns {object} metadata of AdvancedFilter
*
*/
mapper() {
return {
required: false,
serializedName: 'AdvancedFilter',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'operatorType',
clientName: 'operatorType'
},
uberParent: 'AdvancedFilter',
className: 'AdvancedFilter',
modelProperties: {
key: {
required: false,
serializedName: 'key',
type: {
name: 'String'
}
},
operatorType: {
required: true,
serializedName: 'operatorType',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Item {
constructor() {
this.id = 0;
}
} |
JavaScript | class SqlTypes {
/**
* @param {String} value Value to check.
* @returns {boolean} 'true' if given text is valid Java class name.
*/
validIdentifier(value) {
return !!(value && VALID_IDENTIFIER.test(value));
}
/**
* @param value {String} Value to check.
* @returns {boolean} 'true' if given text is one of H2 reserved keywords.
*/
isKeyword(value) {
return !!(value && _.includes(H2_SQL_KEYWORDS, value.toUpperCase()));
}
/**
* Find JDBC type descriptor for specified JDBC type and options.
*
* @param {Number} dbType Column db type.
* @return {String} Java type.
*/
findJdbcType(dbType) {
const jdbcType = _.find(JDBC_TYPES, (item) => item.dbType === dbType);
return jdbcType ? jdbcType : UNKNOWN_JDBC_TYPE;
}
} |
JavaScript | class Athlete extends React.Component {
constructor(props) {
super(props)
this.state = {
athletes: [],
athlete_sports: [],
athlete_teams: [],
sports: [],
teams: [],
sport_id_array : [],
team_id_array : [],
athlete_name: '',
athlete_dob: '',
athlete_age: '',
athlete_height: '',
athlete_body_weight: '',
msg: '',
id: 0
}
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.logChange = this.logChange.bind(this); // We capture the value and change state as user changes the value here.
this.handleEdit = this.handleEdit.bind(this); // Function where we submit data
}
openModal(athlete) {
this.setState({
athletes: [],
modalIsOpen: true,
athlete_sports: athlete.sports,
athlete_teams: athlete.teams,
athlete_name: athlete.athlete_name,
athlete_dob: athlete.athlete_dob,
athlete_age: athlete.athlete_age,
athlete_height: athlete.athlete_height,
athlete_body_weight: athlete.athlete_body_weight,
id: athlete.id
});
}
closeModal() {
this.setState({
modalIsOpen: false
});
this.props.history.push('/athletes');
}
logChange(e) {
this.setState({
[e.target.name]: e.target.value //setting value edited by the admin in state.
});
}
logChangeForMultiSelect(e) {
var options = e.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.setState({[e.target.name]: value});
}
componentDidMount() {
let self = this;
fetch(ConstantsClass.GET_ALL_ATHLETES, {
method: 'GET',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/x-www-form-urlencoded'
})
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
self.getAllTeams(self);
self.setState({athletes: data});
}).catch(err => {
this.props.history.push('/login');
console.log('caught it!',err);
})
}
getAllSelectedTeams(teamObj) {
var teamsId = [];
teamObj.map((item, key) => teamsId.push(item.id));
return teamsId;
}
getAllSelectedSports(sportObj) {
var sportsId = [];
sportObj.map((item, key) => sportsId.push(item.id));
return sportsId;
}
getAllTeams(context) {
fetch(ConstantsClass.GET_ALL_TEAMS, {
method: 'GET',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/x-www-form-urlencoded'
})
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
context.getAllSports(context);
context.setState({teams: data});
}).catch(err => {
context.history.push('/login');
console.log('caught it!',err);
})
}
getAllSports(context) {
fetch(ConstantsClass.GET_ALL_SPORTS, {
method: 'GET',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/x-www-form-urlencoded'
})
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
context.setState({sports: data});
}).catch(err => {
context.history.push('/login');
console.log('caught it!',err);
})
}
handleEdit(event) {
//Edit functionality
event.preventDefault();
var param = {
athlete_name: this.state.athlete_name,
athlete_dob: this.state.athlete_dob,
athlete_age: this.state.athlete_age,
athlete_height: this.state.athlete_height,
athlete_body_weight: this.state.athlete_body_weight
};
var self = this;
fetch(ConstantsClass.UPDATE_ATHLETE + this.state.id , {
method: 'POST',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/json'
}),
body: JSON.stringify(param)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
console.log(data);
self.closeModal();
if (data) {
// Code to add Sports And Teams For Athlete
var athleteSportsData = {
'athlete_id' : data.id,
'sport_id_array': self.state.sport_id_array
};
fetch(ConstantsClass.ADD_ATHLETE_SPORTS, {
method: 'POST',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/json'
}),
body: JSON.stringify(athleteSportsData)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
// For Team ids
var athleteTeamsData = {
'athlete_id' : data.id,
'team_id_array': self.state.team_id_array
};
fetch(ConstantsClass.ADD_ATHLETE_TEAMS, {
method: 'POST',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/json'
}),
body: JSON.stringify(athleteTeamsData)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
self.setState({
msg: "Data has been edited."
});
self.componentDidMount();
}).catch(err => {
self.props.history.push('/login');
console.log('caught it!',err);
})
//...
}).catch(err => {
self.props.history.push('/login');
console.log('caught it!',err);
})
//...
}
}).catch(function(err) {
console.log(err)
});
}
deleteAthlete(athlete){
var self = this;
var data = {
id: athlete.id
};
fetch(ConstantsClass.DELETE_ATHLETE + athlete.id , {
method: 'POST',
headers: new Headers({
'Authorization': window.sessionStorage.getItem('token'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
if (data.message === "success") {
self.setState({msg: "Athlete has been deleted."});
self.componentDidMount();
}
}).catch(function(err) {
console.log(err)
});
}
render() {
return (
<div>
<h3>Athletes</h3>
<div className="panel panel-default p50 uth-panel">
<table className="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>DOB</th>
<th>Height</th>
<th>Weight</th>
<th>Age</th>
<th>Associated Sports</th>
<th>Associated Teams</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.athletes.map((item, key) =>
<tr key={item.id}>
<td>{item.athlete_name} </td>
<td>{item.athlete_dob} </td>
<td>{item.athlete_height}cm </td>
<td>{item.athlete_body_weight}kg </td>
<td>{item.athlete_age} </td>
<td>{ item.sports.length > 0 ? item.sports.map((subItem, j) => <span key={subItem.id} className="badge badge-success">{subItem.sport_name}</span> ) : <span className="badge badge-warning">none</span>} </td>
<td>{ item.teams.length > 0 ? item.teams.map((subItem, j) => <span key={subItem.id} className="badge badge-success">{subItem.team_name}</span> ) : <span className="badge badge-warning">none</span>} </td>
<td><a className="linkStyle" onClick={() => this.openModal(item)} >Edit</a>|<a className="linkStyle" onClick={() => this.deleteAthlete(item)}>Delete</a></td>
</tr>
)}
</tbody>
</table>
{/* Modal to edit the data */}
<Modal
style={{'max-height': 'calc(100vh - 210px)', 'overflow-y': 'auto'}}
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
ariaHideApp={false}
contentLabel="Edit Athlete" >
<form onSubmit={this.handleEdit.bind(this)} method="POST" className="form-signin col-4">
<label className="modal-heading">Update Athlete</label><br/>
<label>Athlete Name</label>
<input onChange={this.logChange.bind(this)} name="athlete_name" type="text" value={this.state.athlete_name} id="inputName" className="form-control" placeholder="Athlete Name" validations={['required']} autoFocus />
<label htmlFor="inputDob">Athlete DOB</label>
<input onChange={this.logChange.bind(this)} name="athlete_dob" type="date" value={this.state.athlete_dob} id="inputDob" className="form-control" placeholder="Athlete Dob" validations={['required']} />
<label htmlFor="inputAge">Athlete Age</label>
<input onChange={this.logChange.bind(this)} name="athlete_age" type="number" value={this.state.athlete_age} min="0" max="100" id="inputAge" className="form-control" validations={['required']} />
<label htmlFor="inputHeight" >Athlete Height (CMs)</label>
<input onChange={this.logChange.bind(this)} name="athlete_height" type="number" value={this.state.athlete_height} step="any" min="0" max="350" id="inputHeight" className="form-control" validations={['required']} />
<label htmlFor="inputBodyWeight">Athlete Body Weight (KGs)</label>
<input onChange={this.logChange.bind(this)} name="athlete_body_weight" type="number" value={this.state.athlete_body_weight} step="any" min="0" max="400" id="inputBodyWeight" className="form-control" validations={['required']} />
<label htmlFor="inputSport" >Associated Sports</label><br/>
{ this.state.athlete_sports.length > 0 ? this.state.athlete_sports.map((subItem, j) => <span key={subItem.id} className="badge badge-success">{subItem.sport_name}</span> ) : <span className="badge badge-warning">none</span>}<br/>
<label htmlFor="inputTeam" >Associated Teams</label><br/>
{ this.state.athlete_teams.length > 0 ? this.state.athlete_teams.map((subItem, j) => <span key={subItem.id} className="badge badge-success">{subItem.team_name}</span> ) : <span className="badge badge-warning">none</span>}<br/>
<label htmlFor="inputSport" >All Sports</label>
<select multiple="multiple" className="custom-select" id="inputSport" onChange={this.logChangeForMultiSelect.bind(this)} name="sport_id_array">
{this.state.sports.map((item, key) =>
<option key={key} value={item.id}>{item.sport_name}</option>
)}
</select>
<small id="logoHelp" className="form-text text-muted">Update the associated Sports for this Athlete from above.</small>
<label htmlFor="inputTeam" >All Teams</label>
<select multiple="multiple" className="custom-select" id="inputTeam" onChange={this.logChangeForMultiSelect.bind(this)} name="team_id_array">
{this.state.teams.map((item, key) =>
<option key={key} value={item.id}>{item.team_name}</option>
)}
</select>
<small id="logoHelp" className="form-text text-muted">Update the associated Teams for this Athlete from above.</small>
<div className="submit-section">
<button className="btn btn-lg btn-primary btn-block" type="submit">Update</button>
</div>
</form>
</Modal>
</div>
</div>
);
}
} |
JavaScript | class Fibonacci {
constructor(sequence) {
this.value = -1;
this.sequence = sequence;
}
} |
JavaScript | class Fibonacci {
constructor(sequence) {
this.value = -1;
this.sequence = sequence;
}
} |
JavaScript | class Fibonacci {
constructor(sequence) {
this.value = -1;
this.sequence = sequence;
}
} |
JavaScript | class JobMaxRecurrence {
/**
* Create a JobMaxRecurrence.
* @member {string} [frequency] Gets or sets the frequency of recurrence
* (second, minute, hour, day, week, month). Possible values include:
* 'Minute', 'Hour', 'Day', 'Week', 'Month'
* @member {number} [interval] Gets or sets the interval between retries.
*/
constructor() {
}
/**
* Defines the metadata of JobMaxRecurrence
*
* @returns {object} metadata of JobMaxRecurrence
*
*/
mapper() {
return {
required: false,
serializedName: 'JobMaxRecurrence',
type: {
name: 'Composite',
className: 'JobMaxRecurrence',
modelProperties: {
frequency: {
required: false,
serializedName: 'frequency',
type: {
name: 'Enum',
allowedValues: [ 'Minute', 'Hour', 'Day', 'Week', 'Month' ]
}
},
interval: {
required: false,
serializedName: 'interval',
type: {
name: 'Number'
}
}
}
}
};
}
} |
JavaScript | class Cache {
constructor (capacity) {
this.capacity = capacity
this.size = 0
this.head = null
this.tail = null
this.map = new Map()
}
get (key) {
if (!this.map.has(key)) return null
// update the node to be the tail
const node = this.map.get(key)
this._setMostRecent(node)
return node.data.val
}
set (key, val) {
const node = new ListNode({ key, val })
if (!this.head) {
this.head = node
}
this.map.set(key, node)
this._setMostRecent(node)
this.size++
if (this.size > this.capacity) {
this._removeLeastRecent()
}
}
_removeLeastRecent () {
if (!this.head) return
// chop off the head
this.map.delete(this.head.data.key)
this.head = this.head.next
if (this.head) {
this.head.prev = null
}
this.size--
}
_setMostRecent (node) {
// set this node to be the tail of the internal list
const prev = node.prev
const next = node.next
if (prev) {
prev.next = next
}
if (this.head === node && this.head.next) {
this.head = this.head.next
if (this.head) {
this.head.prev = null
}
}
if (this.tail) {
this.tail.next = node
}
node.prev = this.tail
this.tail = node
node.next = null
}
} |
JavaScript | class InteractionTrack extends give.TrackObject {
/**
* typeList - get the key strings showing this type of data.
* This shall be the same as the `type` column for track entries in
* `trackDb` table so that GIVE is able to figure out the track is of
* this type.
* @static
* @property
*
* @returns {Array<string>} return all keys matching this type.
*/
static get typeList () {
return ['interaction']
}
/**
* _getWindowSpan - Get the number of windows for the track to span across
* @static
*
* @return {number} number of windows this track will span across
*/
static _getWindowSpan () {
return this.INTERACTION_WINDOW_SPAN
}
} |
JavaScript | class Descriptor {
constructor(name) {
this.name = name;
this.fields = {};
}
static parse(name, data) {
const descriptor = new Descriptor(name);
for (var fieldName in data) {
const fieldData = data[fieldName];
descriptor.fields[fieldName] = FieldDescriptor.parse(fieldName, fieldData);
}
return descriptor;
}
} |
JavaScript | class Reset extends Component {
constructor(props) {
super(props);
this.rest = omit(props, ['initialState', 'onReset']);
// begin edit
this.initialStateClone = clone(props.initialState);
this.onCancelEdit = this.onCancelEdit.bind(this);
}
onCancelEdit() {
let initialState = clone(this.initialStateClone);
this.props.onReset(initialState);
}
render() {
return <input type="button" onClick={this.onCancelEdit} {...this.rest} />;
}
} |
JavaScript | class Popover extends Component {
/**
* @param {Object} props
* @param {String} [props.position='bottom']
* @param {String} [props.title]
*/
constructor() {
super(...arguments);
this.popoverRef = useRef('popover');
this.orderedPositions = ['top', 'bottom', 'left', 'right'];
this.state = useState({
displayed: false,
});
this._onClickDocument = this._onClickDocument.bind(this);
this._onScrollDocument = this._onScrollDocument.bind(this);
this._onResizeWindow = this._onResizeWindow.bind(this);
this._onScrollDocument = _.throttle(this._onScrollDocument, 50);
this._onResizeWindow = _.debounce(this._onResizeWindow, 250);
/**
* Those events are only necessary if the popover is currently open,
* so we decided for performance reasons to avoid binding them while
* it is closed. This allows to have many popover instantiated while
* keeping the count of global handlers low.
*/
this._hasGlobalEventListeners = false;
}
mounted() {
this._compute();
}
patched() {
this._compute();
}
willUnmount() {
if (this._hasGlobalEventListeners) {
this._removeGlobalEventListeners();
}
}
//----------------------------------------------------------------------
// Private
//----------------------------------------------------------------------
/**
* @private
*/
_addGlobalEventListeners() {
/**
* Use capture for the following events to ensure no other part of
* the code can stop its propagation from reaching here.
*/
document.addEventListener('click', this._onClickDocument, {
capture: true,
});
document.addEventListener('scroll', this._onScrollDocument, {
capture: true,
});
window.addEventListener('resize', this._onResizeWindow);
this._hasGlobalEventListeners = true;
}
_close() {
this.state.displayed = false;
}
/**
* Computes the popover according to its props. This method will try to position the
* popover as requested (according to the `position` props). If the requested position
* does not fit the viewport, other positions will be tried in a clockwise order starting
* a the requested position (e.g. starting from left: top, right, bottom). If no position
* is found that fits the viewport, 'bottom' is used.
*
* @private
*/
_compute() {
if (!this._hasGlobalEventListeners && this.state.displayed) {
this._addGlobalEventListeners();
}
if (this._hasGlobalEventListeners && !this.state.displayed) {
this._removeGlobalEventListeners();
}
if (!this.state.displayed) {
return;
}
// copy the default ordered position to avoid updating them in place
const possiblePositions = [...this.orderedPositions];
const positionIndex = possiblePositions.indexOf(
this.props.position
);
const positioningData = this.constructor.computePositioningData(
this.popoverRef.el,
this.el
);
// check if the requested position fits the viewport; if not,
// try all other positions and find one that does
const position = possiblePositions
.slice(positionIndex)
.concat(possiblePositions.slice(0, positionIndex))
.map((pos) => positioningData[pos])
.find((pos) => {
this.popoverRef.el.style.top = `${pos.top}px`;
this.popoverRef.el.style.left = `${pos.left}px`;
const rect = this.popoverRef.el.getBoundingClientRect();
const html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
});
// remove all existing positioning classes
possiblePositions.forEach((pos) => {
this.popoverRef.el.classList.remove(`o_popover--${pos}`);
});
if (position) {
// apply the preferred found position that fits the viewport
this.popoverRef.el.classList.add(`o_popover--${position.name}`);
} else {
// use the given `position` props because no position fits
this.popoverRef.el.style.top = `${positioningData[this.props.position].top}px`;
this.popoverRef.el.style.left = `${positioningData[this.props.position].left}px`;
this.popoverRef.el.classList.add(`o_popover--${this.props.position}`);
}
}
/**
* @private
*/
_removeGlobalEventListeners() {
document.removeEventListener('click', this._onClickDocument, true);
document.removeEventListener('scroll', this._onScrollDocument, true);
window.removeEventListener('resize', this._onResizeWindow);
this._hasGlobalEventListeners = false;
}
//----------------------------------------------------------------------
// Handlers
//----------------------------------------------------------------------
/**
* Toggles the popover depending on its current state.
*
* @private
* @param {MouseEvent} ev
*/
_onClick(ev) {
this.state.displayed = !this.state.displayed;
}
/**
* A click outside the popover will dismiss the current popover.
*
* @private
* @param {MouseEvent} ev
*/
_onClickDocument(ev) {
// Handled by `_onClick`.
if (this.el.contains(ev.target)) {
return;
}
// Ignore click inside the popover.
if (this.popoverRef.el && this.popoverRef.el.contains(ev.target)) {
return;
}
this._close();
}
/**
* @private
* @param {Event} ev
*/
_onPopoverClose(ev) {
this._close();
}
/**
* Popover must recompute its position when children content changes.
*
* @private
* @param {Event} ev
*/
_onPopoverCompute(ev) {
this._compute();
}
/**
* A resize event will need to 'reposition' the popover close to its
* target.
*
* @private
* @param {Event} ev
*/
_onResizeWindow(ev) {
if (this.__owl__.status === 5 /* destroyed */) {
return;
}
this._compute();
}
/**
* A scroll event will need to 'reposition' the popover close to its
* target.
*
* @private
* @param {Event} ev
*/
_onScrollDocument(ev) {
if (this.__owl__.status === 5 /* destroyed */) {
return;
}
this._compute();
}
//----------------------------------------------------------------------
// Static
//----------------------------------------------------------------------
/**
* Compute the expected positioning coordinates for each possible
* positioning based on the target and popover sizes.
* In particular the popover must not overflow the viewport in any
* direction, it should actually stay at `margin` distance from the
* border to look good.
*
* @static
* @param {HTMLElement} popoverElement The popover element
* @param {HTMLElement} targetElement The target element, to which
* the popover will be visually 'bound'
* @param {integer} [margin=16] Minimal accepted margin from the border
* of the viewport.
* @returns {Object}
*/
static computePositioningData(popoverElement, targetElement, margin = 16) {
// set target position, possible position
const boundingRectangle = targetElement.getBoundingClientRect();
const targetTop = boundingRectangle.top;
const targetLeft = boundingRectangle.left;
const targetHeight = targetElement.offsetHeight;
const targetWidth = targetElement.offsetWidth;
const popoverHeight = popoverElement.offsetHeight;
const popoverWidth = popoverElement.offsetWidth;
const windowWidth = window.innerWidth || document.documentElement.clientWidth;
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
const leftOffsetForVertical = Math.max(
margin,
Math.min(
Math.round(targetLeft - (popoverWidth - targetWidth) / 2),
windowWidth - popoverWidth - margin,
),
);
const topOffsetForHorizontal = Math.max(
margin,
Math.min(
Math.round(targetTop - (popoverHeight - targetHeight) / 2),
windowHeight - popoverHeight - margin,
),
);
return {
top: {
name: 'top',
top: Math.round(targetTop - popoverHeight),
left: leftOffsetForVertical,
},
right: {
name: 'right',
top: topOffsetForHorizontal,
left: Math.round(targetLeft + targetWidth),
},
bottom: {
name: 'bottom',
top: Math.round(targetTop + targetHeight),
left: leftOffsetForVertical,
},
left: {
name: 'left',
top: topOffsetForHorizontal,
left: Math.round(targetLeft - popoverWidth),
},
};
}
} |
JavaScript | class Menu {
/**
* Receives elements to be manipulated within the class.
*
* @param {object} toggle - HTML element in object format
* @param {object} navbar - HTML element in object format
*/
constructor(toggle, navbar) {
this._toggle = toggle;
this._navbar = navbar;
this.openedMenu = false;
this.initialize();
}
/**
* Initializes with the class, with a listener event for the toggle element.
* <p>
* The "click" calls the {@link openOrClose} method which will decide whether the menu will be opened or not.
*/
initialize() {
this._toggle.removeAttribute('style');
this._toggle.addEventListener('click', ()=>{
this.openOrClose();
});
}
/**
* Apply CSS style to the element received by parameter.
*
* @param {object} style - Object with the CSS style that will be used by the method.
*/
applyStyleNavbar(style){
Object.keys(style).forEach(stl => {this._navbar.style[stl] = style[stl]});
}
/**
* Checks whether the menu, in mobile mode, is open or closed. If it is open, it calls the method to close,
* otherwise it calls the method to open.
*/
openOrClose() {
if(!this.openedMenu){
this.openMenu();
} else{
this.closeMenu();
}
}
/**
* This method creates a CSS-style object that, when {@link applyStyleNavbar} by the aplystryle method,
* will open the menu.
*/
openMenu() {
let top = this._navbar.getBoundingClientRect().top + 'px';
let style = {
maxHeight: 'calc(100vh - ' + top + ')',
overflow: 'visible'
}
this.applyStyleNavbar(style);
this.openedMenu = true;
}
/**
* This method creates a CSS-style object that, when {@link applyStyleNavbar} by the aplystryle method,
* will close the menu.
*/
closeMenu() {
let style = {
maxHeight: '0px',
overflow: 'hidden'
}
this.applyStyleNavbar(style);
this.openedMenu = false;
}
/**
* If the responsiveness changes and the maximum width is greater than 1024 pixels, this method will remove
* the toggle from the DOM for the view to enter desktop mode.
*/
removeToggle() {
this._navbar.removeAttribute('style');
this.openedMenu = true;
}
} |
JavaScript | class WelcomeSection extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="hero-container">
<section className="videoplayer">
<ReactPlayer
url="https://www.youtube.com/watch?v=8m9vzffbae4"
playing
loop
muted
width="100%"
height="80%"
/>
</section>
<h1>Find your most suitable car and loan.</h1>
<p>Get Started Here</p>
<div className="hero-btns">
<Button
className="btns"
buttonStyle="btn--outline"
buttonSize="btn--large"
link="/sign-up"
>
Get Started
</Button>
<Button
className="btns"
buttonStyle="btn--primary"
buttonSize="btn--large"
onClick={console.log("hey")}
link="/sign-in"
>
Sign In <i className="far fa-play-circle" />
</Button>
</div>
</div>
);
}
} |
JavaScript | class ItemModal extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: false,
name: " "
};
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({
modal: !this.state.modal
});
};
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value});
};
onSubmit = (e) => {
e.preventDefault();
const newItem = {
// id: uuid(), not needed again as we are fetching from the database
name: this.state.name
};
//add item via this action
this.props.addItem(newItem);
this.toggle();
}
render() {
return (
<div>
<Button color="danger" onClick={this.toggle}>Add item{this.props.buttonLabel}</Button>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>Shopping List</ModalHeader>
<ModalBody>
<Form onSubmit={this.onSubmit}>
<FormGroup row>
<Label for="exampleEmail" sm={2}>Name</Label>
<Col sm={10}>
<Input type="text" name="name" id="item" placeholder="Enter item name" onChange={this.onChange} />
</Col>
</FormGroup>
{/* <FormGroup row>
<Label for="examplePassword" sm={2}>Password</Label>
<Col sm={10}>
<Input type="password" name="password" id="examplePassword" placeholder="password placeholder" />
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleSelect" sm={2}>Select</Label>
<Col sm={10}>
<Input type="select" name="select" id="exampleSelect" />
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleSelectMulti" sm={2}>Select Multiple</Label>
<Col sm={10}>
<Input type="select" name="selectMulti" id="exampleSelectMulti" multiple />
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleText" sm={2}>Text Area</Label>
<Col sm={10}>
<Input type="textarea" name="text" id="exampleText" />
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleFile" sm={2}>File</Label>
<Col sm={10}>
<Input type="file" name="file" id="exampleFile" />
<FormText color="muted">
This is some placeholder block-level help text for the above input.
It's a bit lighter and easily wraps to a new line.
</FormText>
</Col>
</FormGroup>
<FormGroup tag="fieldset" row>
<legend className="col-form-label col-sm-2">Radio Buttons</legend>
<Col sm={10}>
<FormGroup check>
<Label check>
<Input type="radio" name="radio2" />{' '}
Option one is this and that—be sure to include why it's great
</Label>
</FormGroup>
<FormGroup check>
<Label check>
<Input type="radio" name="radio2" />{' '}
Option two can be something else and selecting it will deselect option one
</Label>
</FormGroup>
<FormGroup check disabled>
<Label check>
<Input type="radio" name="radio2" disabled />{' '}
Option three is disabled
</Label>
</FormGroup>
</Col>
</FormGroup>
<FormGroup row>
<Label for="checkbox2" sm={2}>Checkbox</Label>
<Col sm={{ size: 10 }}>
<FormGroup check>
<Label check>
<Input type="checkbox" id="checkbox2" />{' '}
Check me out
</Label>
</FormGroup>
</Col>
</FormGroup> */}
<FormGroup check row>
<Col sm={{ size: 10, offset: 2 }}>
<Button>Submit Item</Button>
</Col>
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
<Button color="secondary" onClick={this.toggle}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
);
}
} |
JavaScript | class Cars extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
catalogue: [],
currentIndex: 0,
category_third_lv_id: 1,
loading: true,
error: null
};
}
fetchBiddings = () => {
axios.get("http://desmond.business:8080/fyp/getBiddings")
.then(res => {
// Transform the raw data by extracting the nested posts
const tmpCatalogue = []
const updateCatalogue = this.state.catalogue
const posts = res.data.results;
posts.forEach((elm) => {
if (elm.category_third_lv_id == this.state.category_third_lv_id) {
updateCatalogue.push(
<Col key={elm.id} className="col-md-4">
<Card style={{ width: '20rem' }}>
<CardImg top src={require("assets/img/mac_apple.jpg")} alt="..." />
<CardBody>
<CardTitle>{elm.title}</CardTitle>
<CardText>{elm.create_timestamp}</CardText>
<Link to={`/CarsforSale/${elm.id}`}>
<Button color="primary">
${elm.selling_price}
</Button>
</Link>
</CardBody>
</Card>
</Col>
)
}
})
console.log(this.state.catalogue);
//console.log(posts);
// Update state to trigger a re-render.
// Clear any errors, and turn off the loading indiciator.
this.setState({
posts,
catalogue: updateCatalogue,
currentIndex: this.state.currentIndex + 10,
loading: false,
error: null
});
})
.catch(err => {
// Something went wrong. Save the error in state and re-render.
this.setState({
loading: false,
error: err
});
});
}
componentDidMount() {
// Remove the 'www.' to cause a CORS error (and see the error state)
this.fetchBiddings()
}
showMore = () => {
this.fetchBiddings()
console.log(this.state.catalogue);
console.log(this.state.currentIndex);
}
renderLoading() {
return <div>Loading...</div>;
}
renderError() {
return (
<div>
Uh oh: {this.state.error.message}
</div>
);
}
renderPosts() {
if (this.state.error) {
return this.renderError();
}
console.log(this.state.posts[0]);
return (
<h6>
Success getting Bidding Records
</h6>
);
}
render() {
const catalogue = this.state.catalogue
if (this.state.loading) {
return (
<div className="section">
<Container className="text-center">
<Card className="text-center">
<Row>
<Col>
<div className="title">
<h1 className="bd-title">{this.props.title}</h1>
</div>
</Col>
</Row>
<CardBody>
<div>
<Spinner animation="border" variant="primary" />
</div>
<Row>
<Col>
<Button
className="btn-round mr-1"
color="primary"
type="button"
onClick={this.fetchBiddings}
>
Show More
</Button>
</Col>
</Row>
</CardBody>
</Card>
</Container>
<Route exact path="/carsForSale/:id" render={(props) => {
const id = props.match.params.id;
return <Item id={id}{...props} />
}} />
</div>
)
} else {
return (
<div className="section">
<Container className="text-center">
<Card className="text-center">
<Row>
<Col>
<div className="title">
<h1 className="bd-title">{this.props.title}</h1>
</div>
</Col>
</Row>
<CardBody>
<Row>
{catalogue}
</Row>
<Row>
<Col>
<Button
className="btn-round mr-1"
color="primary"
type="button"
onClick={this.fetchBiddings}
>
Show More
</Button>
</Col>
</Row>
</CardBody>
</Card>
</Container>
<Route exact path="/carsForSale/:id" render={(props) => {
const id = props.match.params.id;
return <Item id={id}{...props} />
}} />
</div>
);
}
}
} |
JavaScript | class Util {
/**
* Create an emty file.
* @param {String} path - The path to the file to create.
*/
_createEmptyFile(path) {
fs.createWriteStream(path).end();
}
/** Create the temporary directory. */
createTemp() {
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
if (fs.existsSync(tempDir)) this._resetTemp();
this._createEmptyFile(path.join(tempDir, statusFile));
this._createEmptyFile(path.join(tempDir, updatedFile));
}
/**
* Execute a command from within the root folder.
* @param {String} cmd - The command to execute.
* @returns {Promise} - The output of the command.
*/
executeCommand(cmd) {
return new Promise((resolve, reject) => {
childProcess.exec(cmd, {
cwd: __dirname
}, (err, stdout) => {
if (err) return reject(err);
return resolve(stdout.split("\n").join(""));
});
});
}
/**
* Export a collection to a JSON file.
* @param {String} collection - The collection to export.
* @returns {Promise} - The output of the mongoexport command.
*/
exportCollection(collection) {
const jsonFile = path.join(tempDir, `${collection}s.json`);
logger.info(`Exporting collection: '${collection}s', to: '${jsonFile}'`);
return this.executeCommand(`mongoexport --db ${dbName} --collection ${collection}s --out "${jsonFile}"`);
}
/**
* Import a json file to a collection.
* @param {String} collection - The collection to import.
* @param {String} jsonFile - The json file to import..
* @returns {Promise} - The output of the mongoimport command.
*/
importCollection(collection, jsonFile) {
if (!path.isAbsolute(jsonFile)) jsonFile = path.join(process.cwd(), jsonFile);
if (!fs.existsSync(jsonFile)) throw new Error(`Error: no such file found for '${jsonFile}'`);
logger.info(`Importing collection: '${collection}', from: '${jsonFile}'`);
return this.executeCommand(`mongoimport --db ${dbName} --collection ${collection} --file "${jsonFile}" --upsert`);
}
/**
* Error logger function.
* @param {String} errorMessage - The error message you want to display.
* @returns {Error} - A new error with the given error message.
*/
onError(errorMessage) {
logger.error(errorMessage);
return new Error(errorMessage);
}
/** Reset the default log file. */
resetLog() {
const logFile = path.join(tempDir, `${name}.log`);
if (fs.existsSync(logFile)) fs.unlinkSync(logFile);
}
/**
* Removes all the files in the temporary directory.
* @param {String} [tmpPath=popcorn-api/tmp] - The path to remove all the files within (Default is set in the `config/constants.js`).
*/
_resetTemp(tmpPath = tempDir) {
const files = fs.readdirSync(tmpPath);
files.forEach(file => {
const stats = fs.statSync(path.join(tmpPath, file));
if (stats.isDirectory()) {
this.resetTemp(file);
} else if (stats.isFile()) {
fs.unlinkSync(path.join(tmpPath, file));
}
});
}
/**
* Search for a key in an array of object.
* @param {String} key - The key to search for.
* @param {String} value - The value of the key to search for.
* @return {Object} - The object with the correct key-value pair.
*/
search(key, value) {
return element => element[key] === value;
}
/**
* Updates the `lastUpdated.json` file.
* @param {String} [updated=Date.now()] - The epoch time when the API last started scraping.
*/
setLastUpdated(updated = (Math.floor(new Date().getTime() / 1000))) {
fs.writeFile(path.join(tempDir, updatedFile), JSON.stringify({
updated
}), () => {});
}
/**
* Updates the `status.json` file.
* @param {String} [status=Idle] - The status which will be set to in the `status.json` file.
*/
setStatus(status = "Idle") {
fs.writeFile(path.join(tempDir, statusFile), JSON.stringify({
status
}), () => {});
}
} |
JavaScript | class Widget extends okanjo._EventEmitter {
constructor(element, options) {
super();
// Verify element was given (we can't load unless we have one)
if (!element || element === null || element.nodeType === undefined) {
okanjo.report('Invalid or missing element on widget construction', { widget: this, element, options });
throw new Error('Okanjo: Invalid element - make sure to pass a valid DOM element when constructing Okanjo Widgets.');
}
// Verify configuration is OK
if (options && typeof options !== "object") {
// Warn and fix it
okanjo.report('Invalid widget options. Expected object, got: ' + typeof options, { widget: this, element, options });
options = {};
} else {
options = options || {};
}
// Store basics
this.name = 'Widget';
this.element = element;
this.instanceId = okanjo.util.shortid();
// Clone initial config, breaking the top-level reference
this.config = Object.assign({}, options);
}
/**
* Base widget initialization procedures
*/
init() {
// process config attributes
this._applyConfiguration();
this._setCompatibilityOptions();
// ensure placement key
if (!this._ensurePlacementKey()) return;
// Tell the widget to load
this.load();
}
/**
* This is for extended widgets, so they may modify the configuration before loading
*/
_setCompatibilityOptions() {
// By default, this does nothing. Must be overridden to be useful
}
//noinspection JSMethodCanBeStatic
/**
* Widget configuration definitions
* @return {{}}
*/
getSettings() {
// Override this
return {};
}
/**
* Main widget load function.
*/
load() {
// Override this in the widget implementation
}
/**
* Applies data attribute settings and defaults to the widget configuration
* @private
*/
_applyConfiguration() {
// this.config was set to the options provided in the constructor
// so layer data attributes on top
const data = this.getDataAttributes();
const settings = this.getSettings();
Object
.keys(data)
.forEach((key) => {
let normalizedKey = key.replace(DATA_REPLACE_PATTERN, '_');
let val = data[key];
// Attempt to convert the value if there's a setting for it
if (settings[normalizedKey]) val = settings[normalizedKey].value(val, false);
if (!okanjo.util.isEmpty(val)) {
this.config[normalizedKey] = val;
}
})
;
// Apply defaults from the widget settings
Object.keys(settings).forEach((key) => {
if (this.config[key] === undefined && settings[key]._default !== undefined) {
this.config[key] = settings[key].value(undefined, false);
}
});
}
//noinspection JSUnusedGlobalSymbols
/**
* Gets a copy of the configuration, suitable for transmission
* @return {{}}
*/
getConfig() {
const settings = this.getSettings();
const out = {};
Object.keys(this.config).forEach((origKey) => {
let val = this.config[origKey];
let key = origKey;
let group = null;
// Check if this is a known property
if (settings[key]) {
val = settings[key].value(val);
group = settings[key].getGroup();
}
// Init the target/group if not already setup
let target = out;
if (group) {
target[group] = target[group] || {};
target = target[group];
}
// Set the value on the target if set
if (val === null) {
target[key] = ''; // format null values as empty strings for transmission
} else if (val !== undefined) {
target[key] = val;
}
});
return out;
}
/**
* Before loading, ensure that a placement key is present or abort
* @return {boolean}
* @private
*/
_ensurePlacementKey() {
// Check if set on widget or globally
if (this.config.key) {
return true;
} else if (okanjo.key) {
// Copy key from global scope,
this.config.key = okanjo.key;
return true;
}
// No key set, can't load.
okanjo.report('No key provided on widget', { widget: this });
this.showError('Error: Missing placement key.');
return false;
}
/**
* Displays an error in the widget element
* @param message
*/
showError(message) {
this.setMarkup(okanjo.ui.engine.render(
'okanjo.error',
this,
{ message }
));
}
/**
* Sets the markup of the widget's element
* @param markup
*/
setMarkup(markup) {
this.element.innerHTML = markup;
}
//noinspection JSUnusedGlobalSymbols
/**
* Gets the current page URL, sans query string and fragment.
* @returns {string} - URL
*/
static getCurrentPageUrl() {
return window.location.href.replace(/([?#].*)$/, '');
}
/**
* Instead of using HTML5 dataset, just rip through attributes and return data attributes
* @returns {*}
*/
getDataAttributes() {
const data = {};
Array
.from(this.element.attributes)
.forEach((attr) => {
const match = DATA_ATTRIBUTE_PATTERN.exec(attr.name);
if (match) {
data[match[1]] = attr.value;
}
});
return data;
}
} |
JavaScript | class PieChart extends Chart {
/**
* Creates an instance of the PieChart class
* @param {string} data - JSON string containing the data columns.
*/
constructor(data) {
super(data)
// Set charts types as Pie
this._outputJson.data.type = 'pie'
}
} |
JavaScript | class Names {
/**
* Capitalizes the words of the name and joins them together.
*
* @param {Name} name - The name to capitalize.
* @returns {String} The capitalized name.
*/
static capitalized (name) {
return name.words
.map((word) => Words.capitalized(word))
.join('')
}
/**
* Converts the words of the given name to lower case and joins them using the given separator.
*
* @param {Name} name - The name to convert.
* @param {String} separator - The separator.
* @returns {String} The converted name.
*/
static lowerJoined (name, separator) {
return name.words
.map((word) => word.toLowerCase())
.join(separator)
}
/**
* Renders the name of the given concept according to its type.
*
* @param {Concept} concept - The concept.
* @returns {String} The rendered name.
*/
static render (concept) {
if (concept == null) {
return ''
}
const name = concept.name
if (concept instanceof concepts.Service) {
return Names.capitalized(name)
}
if (concept instanceof concepts.Method) {
return Names.lowerJoined(name, '')
}
if (concept instanceof concepts.Locator) {
return Names.lowerJoined(name, '')
}
if (concept instanceof concepts.Type) {
if (concept instanceof concepts.ListType) {
return Names.render(concept.element) + '[]'
}
return Names.capitalized(name)
}
return Names.lowerJoined(name, '_')
}
} |
JavaScript | class DeferredPromise {
constructor() {
this._promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.then = this._promise.then.bind(this._promise);
this.catch = this._promise.catch.bind(this._promise);
this[Symbol.toStringTag] = 'Promise';
}
} |
JavaScript | class RootIndex extends React.Component {
render() {
const siteTitle = get(this, 'props.data.site.siteMetadata.title')
return (
<ChakraProvider>
<Layout>
<Helmet title={siteTitle} />
<Hero />
<About />
<Emails />
{/* updates and upcoming events buttons*/}
<Box m={10} mx={20}>
<Text fontSize="3xl" fontWeight="bold"> Learn more </Text>
<Text>We meet biweekly on Wednesdays at 10:30am via <a href="http://tinyurl.com/acsrecurring"><strong>Zoom.</strong></a> Join our mailing list, <a href="https://www.remind.com/join/4hfc2hb"><strong>Remind</strong></a>, or <a href="https://www.facebook.com/groups/475915516547617"><strong>Facebook</strong></a> group to stay up to date on the latest events. Additionally, check out the information from past meetings on our website.</Text>
<br />
<Center>
<HStack spacing="25px">
<Link to="/blog/upcoming-events"><Button bg="blue.100" className="primary-btn" fontWeight="light" _hover={{ bg: "red.400"}}>Upcoming Events →</Button></Link>
<Link to="/updates"><Button border="2px" borderColor="gray.200" bg="white" className="primary-btn" fontWeight="light" _hover={{ bg: "white" }}>Past Meetings → </Button></Link>
</HStack>
</Center>
</Box>
{/** Officers section */}
<Box m={10} mx={20}>
<Text fontSize="3xl" fontWeight="bold"> Officers</Text>
<Flex display="flex" flexDirection="row" flexWrap="wrap" justifyContent="center">
<Person name="Emily Lu" role="President" bio="Emily is a junior at Foothill and is also the founder of the ACS club at FHS." src="" />
<Person name="Beatricia Lam" role="Treasurer" bio="Beatricia is a junior at Foothill and has been a member of ACS for 2 years." src="" />
<Person name="Ellen Huang" role="Secretary" bio="Ellen is a junior at Foothill and has taken part in ACS for 2 years." src="" />
<Person name="Saurabi Sakthivel" role="Event Coordinator" bio="Saurabi is a sophomore at Foothill and has taken part in FHS ACS for 2 years." src="" />
</Flex>
</Box>
</Layout>
</ChakraProvider>
)
}
} |
JavaScript | class YEnc {
static reserved = [NULL_CHAR, LF_CHAR, CR_CHAR, EQ_CHAR]
static encode(bytes /*: Uint8Array|Buffer */) /*: Uint8Array */ {
const yEncodedTypedArray = new Uint8Array(YEnc.encoder(bytes))
return yEncodedTypedArray
}
static decode(yEncodedTypedArray) /*: Uint8Array */ {
const byteArray = new Uint8Array(YEnc.decoder(yEncodedTypedArray))
return byteArray
}
static *encoder(bytes) {
for (const byte of bytes) {
const offsetByte = (byte + BASE_OFFSET) % UINT8_BOUNDARY
if (YEnc.reserved.includes(offsetByte)) {
yield EQ_CHAR
yield (offsetByte + ESCAPE_OFFSET) % UINT8_BOUNDARY
} else {
yield offsetByte
}
}
}
static *decoder(bytes) {
let escape = false
for (const offsetByte of bytes) {
if (escape) {
// previous byte started the escape sequence
escape = false
yield positiveModulo(offsetByte - ESCAPE_OFFSET - BASE_OFFSET, UINT8_BOUNDARY)
continue
}
if (offsetByte === EQ_CHAR) {
// this byte is starting an escape sequence
escape = true
continue
}
// typically encoded byte
yield positiveModulo(offsetByte - BASE_OFFSET, UINT8_BOUNDARY)
}
}
} |
JavaScript | class MSALAuthCode extends MsalBrowser {
/**
* Sets up an MSAL object based on the given parameters.
* MSAL with Auth Code allows sending a previously obtained `authenticationRecord` through the optional parameters,
* which is set to be the active account.
* @param options - Parameters necessary and otherwise used to create the MSAL object.
*/
constructor(options) {
super(options);
this.loginHint = options.loginHint;
this.msalConfig.cache = {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true, // Set to true to improve the experience on IE11 and Edge.
};
this.msalConfig.system = {
loggerOptions: {
loggerCallback: defaultLoggerCallback(this.logger, "Browser"),
},
};
// Preparing the MSAL application.
this.app = new msalBrowser.PublicClientApplication(this.msalConfig);
if (this.account) {
this.app.setActiveAccount(publicToMsal(this.account));
}
}
/**
* Loads the account based on the result of the authentication.
* If no result was received, tries to load the account from the cache.
* @param result - Result object received from MSAL.
*/
async handleBrowserResult(result) {
try {
if (result && result.account) {
this.logger.info(`MSAL Browser V2 authentication successful.`);
this.app.setActiveAccount(result.account);
return msalToPublic(this.clientId, result.account);
}
// If by this point we happen to have an active account, we should stop trying to parse this.
const activeAccount = await this.app.getActiveAccount();
if (activeAccount) {
return msalToPublic(this.clientId, activeAccount);
}
// If we don't have an active account, we try to activate it from all the already loaded accounts.
const accounts = this.app.getAllAccounts();
if (accounts.length > 1) {
// If there's more than one account in memory, we force the user to authenticate again.
// At this point we can't identify which account should this credential work with,
// since at this point the user won't have provided enough information.
// We log a message in case that helps.
this.logger.info(`More than one account was found authenticated for this Client ID and Tenant ID.
However, no "authenticationRecord" has been provided for this credential,
therefore we're unable to pick between these accounts.
A new login attempt will be requested, to ensure the correct account is picked.
To work with multiple accounts for the same Client ID and Tenant ID, please provide an "authenticationRecord" when initializing "InteractiveBrowserCredential".`);
// To safely trigger a new login, we're also ensuring the local cache is cleared up for this MSAL object.
// However, we want to avoid kicking the user out of their authentication on the Azure side.
// We do this by calling to logout while specifying a `onRedirectNavigate` that returns false.
await this.app.logout({
onRedirectNavigate: () => false,
});
return;
}
// If there's only one account for this MSAL object, we can safely activate it.
if (accounts.length === 1) {
const account = accounts[0];
this.app.setActiveAccount(account);
return msalToPublic(this.clientId, account);
}
this.logger.info(`No accounts were found through MSAL.`);
}
catch (e) {
this.logger.info(`Failed to acquire token through MSAL. ${e.message}`);
}
return;
}
/**
* Uses MSAL to handle the redirect.
*/
async handleRedirect() {
return this.handleBrowserResult((await this.app.handleRedirectPromise(redirectHash)) || undefined);
}
/**
* Uses MSAL to trigger a redirect or a popup login.
*/
async login(scopes = []) {
const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
const loginRequest = {
scopes: arrayScopes,
loginHint: this.loginHint,
};
switch (this.loginStyle) {
case "redirect": {
await this.app.loginRedirect(loginRequest);
return;
}
case "popup":
return this.handleBrowserResult(await this.app.loginPopup(loginRequest));
}
}
/**
* Uses MSAL to retrieve the active account.
*/
async getActiveAccount() {
const account = this.app.getActiveAccount();
if (!account) {
return;
}
return msalToPublic(this.clientId, account);
}
/**
* Attempts to retrieve a token from cache.
*/
async getTokenSilent(scopes, options) {
const account = await this.getActiveAccount();
if (!account) {
throw new AuthenticationRequiredError({
scopes,
getTokenOptions: options,
message: "Silent authentication failed. We couldn't retrieve an active account from the cache.",
});
}
const parameters = {
authority: (options === null || options === void 0 ? void 0 : options.authority) || this.msalConfig.auth.authority,
correlationId: options === null || options === void 0 ? void 0 : options.correlationId,
claims: options === null || options === void 0 ? void 0 : options.claims,
account: publicToMsal(account),
forceRefresh: false,
scopes,
};
try {
this.logger.info("Attempting to acquire token silently");
const response = await this.app.acquireTokenSilent(parameters);
return this.handleResult(scopes, this.clientId, response);
}
catch (err) {
throw this.handleError(scopes, err, options);
}
}
/**
* Attempts to retrieve the token in the browser.
*/
async doGetToken(scopes, options) {
const account = await this.getActiveAccount();
if (!account) {
throw new AuthenticationRequiredError({
scopes,
getTokenOptions: options,
message: "Silent authentication failed. We couldn't retrieve an active account from the cache.",
});
}
const parameters = {
authority: (options === null || options === void 0 ? void 0 : options.authority) || this.msalConfig.auth.authority,
correlationId: options === null || options === void 0 ? void 0 : options.correlationId,
claims: options === null || options === void 0 ? void 0 : options.claims,
account: publicToMsal(account),
loginHint: this.loginHint,
scopes,
};
switch (this.loginStyle) {
case "redirect":
// This will go out of the page.
// Once the InteractiveBrowserCredential is initialized again,
// we'll load the MSAL account in the constructor.
await this.app.acquireTokenRedirect(parameters);
return { token: "", expiresOnTimestamp: 0 };
case "popup":
return this.handleResult(scopes, this.clientId, await this.app.acquireTokenPopup(parameters));
}
}
} |
JavaScript | class CustomHeader extends LitElement {
constructor() {
super();
}
static get properties() {
return {
headerLogo: {type: Object},
headerNav: {type: Array}
};
}
render() {
return html`
<style>
:host {
display: block;
position: relative;
z-index: 1;
padding-left: 20px;
padding-right: 20px;
background-color: rgb(239,223,65);
-webkit-box-shadow: 0 0px 10px 0 rgba(0,0,0,0.47);
-moz-box-shadow: 0 0px 10px 0 rgba(0,0,0,0.47);
box-shadow: 0 0px 10px 0 rgba(0,0,0,0.47);
}
.CustomHeader {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
text-align: left;
}
logo-component {height: 75px;}
.Title {display: none;}
@media screen and (min-width: 768px) {
logo-component {height: 150px;}
.Title {display: block;}
}
</style>
<header class="CustomHeader">
<logo-component
logourl=${JSON.parse(this.headerLogo).logourl}
imageurl=${JSON.parse(this.headerLogo).imageurl}
imagealt=${JSON.parse(this.headerLogo).imagealt}
imagetitle=${JSON.parse(this.headerLogo).imagetitle}
></logo-component>
<div class="Title"><slot></slot></div>
<installer-component></installer-component>
</header>
`
}
} |
JavaScript | class AmpStoryAccess extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @const @private {!../../../src/service/action-impl.ActionService} */
this.actions_ = Services.actionServiceForDoc(this.element);
/** @private {?Element} */
this.scrollableEl_ = null;
/** @private @const {!./amp-story-store-service.AmpStoryStoreService} */
this.storeService_ = Services.storyStoreService(this.win);
}
/** @override */
buildCallback() {
const drawerEl = renderAsElement(this.win.document, TEMPLATE);
const contentEl = dev().assertElement(
drawerEl.querySelector('.i-amphtml-story-access-content'));
copyChildren(this.element, contentEl);
removeChildren(this.element);
this.element.appendChild(drawerEl);
// Allow <amp-access> actions in STAMP (defaults to no actions allowed).
this.actions_.addToWhitelist('SCRIPT.login');
// TODO(gmajoulet): allow wildcard actions to enable login namespaces.
// this.actions_.addToWhitelist('SCRIPT.login.*');
this.initializeListeners_();
}
/** @override */
isLayoutSupported(layout) {
return layout == Layout.NODISPLAY;
}
/** @override */
prerenderAllowed() {
return false;
}
/**
* @private
*/
initializeListeners_() {
this.storeService_.subscribe(StateProperty.ACCESS_STATE, isAccess => {
this.onAccessStateChange_(isAccess);
});
this.scrollableEl_ =
this.element.querySelector('.i-amphtml-story-access-overflow');
this.scrollableEl_.addEventListener(
'scroll', throttle(this.win, () => this.onScroll_(), 100));
}
/**
* Reacts to access state updates, and shows/hides the UI accordingly.
* @param {boolean} isAccess
* @private
*/
onAccessStateChange_(isAccess) {
this.mutateElement(() => {
this.element.classList.toggle('i-amphtml-story-access-visible', isAccess);
});
}
/**
* Toggles the fullbleed UI on scroll.
* @private
*/
onScroll_() {
let isFullBleed;
// Toggles the fullbleed UI as soon as the scrollable container, which has a
// 88px margin top, reaches the top of the screen.
const measurer =
() => isFullBleed = this.scrollableEl_./*OK*/scrollTop > 88;
const mutator = () => {
this.element
.classList.toggle('i-amphtml-story-access-fullbleed', isFullBleed);
};
this.element.getResources()
.measureMutateElement(this.element, measurer, mutator);
}
} |
JavaScript | class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
searchText: "",
};
this.afterSubmission = this.afterSubmission.bind(this);
}
handleRoute = (route) => () => {
this.props.history.push({ pathname: route });
};
handleSearchInput = (event) => {
this.setState({
searchText: event.target.value,
});
};
handleSearchSubmit = () => {
if (document.getElementById("searchBar").value) {
this.props.history.replace({
pathname:
"/results/" +
encodeURIComponent(document.getElementById("searchBar").value),
state: {
searchText: document.getElementById("searchBar").value,
},
});
} else {
alert("Please enter text in search bar!");
}
};
handleKeyPress = (e) => {
if (e.key === "Enter") {
this.handleSearchSubmit();
}
};
afterSubmission(event) {
event.preventDefault();
}
render() {
return (
<div className="custom-navbar">
<Navbar id="navbar" bg="black" variant="dark" expand="lg">
<Navbar.Brand className="active" href="/">
Movie Dashboard
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav id="nav" className="mr-auto" bg="black" expand="md">
<NavLink
to="/movie/popular/1"
href="/movie/popular/1"
activeClassName="current"
>
Popular Movies
</NavLink>
<NavLink
to="/tv/popular/1"
href="/tv/popular/1"
activeStyle={{ color: "red" }}
>
Popular TV Shows
</NavLink>
<NavLink
to="/movie/top_rated/1"
href="/movie/top_rated/1"
activeStyle={{ color: "red" }}
>
Top Rated Movies
</NavLink>
<NavLink
to="/tv/top_rated/1"
href="/tv/top_rated/1"
activeStyle={{ color: "red" }}
>
Top Rated TV Shows
</NavLink>
<NavLink to="/About" href="/About" activeStyle={{ color: "red" }}>
About
</NavLink>
</Nav>
<Form id="search-form" inline onSubmit={this.afterSubmission}>
<FormGroup>
<Form.Label className="hidden" htmlFor="searchBar">
Search
</Form.Label>
<FormControl
onKeyDown={this.handleKeyPress}
type="text"
placeholder="Search"
required
className="mr-sm-1"
id="searchBar"
/>
</FormGroup>
<Button variant="outline-light" onClick={this.handleSearchSubmit}>
Search
</Button>
</Form>
</Navbar.Collapse>
</Navbar>
<Switch>
{/* Popular movies */}
<Redirect exact from="/" to="/movie/popular/1" />
<Redirect exact path="/movie/popular/" to="/movie/popular/1" />
<Route exact path="/movie/popular/:page" component={PopMovies} />
{/* Popular tv shows */}
<Redirect exact path="/tv/popular/" to="/tv/popular/1" />
<Route exact path="/tv/popular/:page" component={PopTVShows} />
{/* Top rated movies */}
<Redirect exact path="/movie/top_rated/" to="/movie/top_rated/1" />
<Route
exact
path="/movie/top_rated/:page"
component={TopRatedMovies}
/>
{/* About */}
<Route exact path="/About" component={About} />
{/* Top rated tv shows */}
<Redirect exact path="/tv/top_rated/" to="/tv/top_rated/1" />
<Route exact path="/tv/top_rated/:page" component={TopRatedTVShows} />
{/* Display information about movie/tv show/short/person */}
<Route
exact
path="/info/:imdbID/:mediaType/:tmdbID?"
component={Info}
/>
{/* Search results page */}
<Redirect exact path="/results/:title/" to="/results/:title/1" />
<Route exact path="/results/:title/:page" component={Results} />
{/* 404 not found page when invalid url input */}
<Route component={NotFound} />
</Switch>
</div>
);
}
} |
JavaScript | class PuppyApp {
// Constructor: takes in a parent element and list of puppies
// Add puppy: pushes new data into list of puppies and re-renders the app
// Render;
render() {
// Empty parent element
// Create and render a new form
// Append puppy list element to parent (in a wrapper div)
}
} |
JavaScript | class TickStopEvent extends event_1.event {
constructor() {
super("tick_stop", default_action);
}
static setDefaultAction(action) {
default_action = action;
}
} |
JavaScript | class Budget {
/**
* Construct the budget
* @param {number} parts The maximum number of parts
* @param {number} radius The machine radius
*/
constructor(parts, radius) {
this.parts = parts;
this.radius = radius;
}
} |
JavaScript | class Target extends Struct {
constructor(type, target) {
super();
this.type = types.INET4;
this.target = '0.0.0.0';
this.inet4 = '0.0.0.0';
this.inet6 = '::';
this.from(type, target);
}
from(type, target) {
if (typeof type === 'string')
return this.fromString(type);
if (type != null)
this.type = type;
if (target != null)
this.target = target;
return this;
}
static from(type, target) {
return new this().from(type, target);
}
toString() {
if (this.isGlue()) {
if (this.inet4 === '0.0.0.0' && this.inet6 === '::')
throw new Error('Bad glue address.');
const ips = [];
if (this.inet4 !== '0.0.0.0')
ips.push(this.inet4);
if (this.inet6 !== '::')
ips.push(this.inet6);
return `${this.target}@${ips.join(',')}`;
}
return this.target;
}
fromString(str) {
assert(typeof str === 'string');
assert(str.length <= 255);
str = str.toLowerCase();
const parts = str.split('@');
if (parts.length > 1) {
const name = util.fqdn(parts[0]);
assert(isName(name));
const ips = parts[1].split(',');
assert(ips.length <= 2);
this.type = types.GLUE;
this.target = name;
for (const ip of ips) {
const [type, addr] = parseIP(ip);
switch (type) {
case types.ONION:
throw new Error('Bad glue address.');
case types.INET4:
if (addr === '0.0.0.0')
throw new Error('Bad glue address.');
this.inet4 = addr;
break;
case types.INET6:
if (addr === '::')
throw new Error('Bad glue address.');
this.inet6 = addr;
break;
}
}
return this;
}
if (IP.isIPv4String(str) || IP.isIPv6String(str)) {
const [type, target] = parseIP(str);
this.type = type;
this.target = target;
return this;
}
if (onion.isLegacyString(str)) {
this.type = types.ONION;
this.target = onion.normalizeLegacy(str);
return this;
}
if (onion.isNGString(str)) {
this.type = types.ONIONNG;
this.target = onion.normalizeNG(str, sha3.digest);
return this;
}
const name = util.fqdn(str);
assert(isName(name));
this.type = types.NAME;
this.target = name;
return this;
}
getJSON() {
return this.toString();
}
fromJSON(json) {
return this.fromString(json);
}
isNull() {
return this.type === types.INET4 && this.target === '0.0.0.0';
}
toPointer(name) {
assert(typeof name === 'string');
assert(util.isFQDN(name));
assert(this.isINET());
const ip = IP.toBuffer(this.target);
const data = ipPack(ip);
const hash = base32.encodeHex(data);
const labels = util.split(name);
const tld = util.label(name, labels, -1);
return `_${hash}.${tld}.`;
}
fromPointer(name) {
assert(typeof name === 'string');
assert(name.length > 0 && name[0] === '_');
const data = base32.decodeHex(name.substring(1));
assert(data.length > 0 && data.length <= 17);
const ip = ipUnpack(data);
if (IP.isIPv4(ip)) {
this.type = types.INET4;
this.target = IP.toString(ip);
} else {
this.type = types.INET6;
this.target = IP.toString(ip);
}
return this;
}
static fromPointer(name) {
return new this().fromPointer(name);
}
static isPointer(name, type) {
if (type != null
&& type !== wire.types.ANY
&& type !== wire.types.A
&& type !== wire.types.AAAA) {
return false;
}
if (name.length < 2 || name.length > 29)
return false;
if (name[0] !== '_')
return false;
return base32.testHex(name.substring(1));
}
matches(type) {
switch (type) {
case wire.types.ANY:
return true;
case wire.types.A:
return this.isINET4();
case wire.types.AAAA:
return this.isINET6();
default:
return false;
}
}
isINET4() {
return this.type === types.INET4;
}
isINET6() {
return this.type === types.INET6;
}
isOnion() {
return this.type === types.ONION;
}
isOnionNG() {
return this.type === types.ONIONNG;
}
isINET() {
return this.type <= types.INET6;
}
isName() {
return this.type === types.NAME || this.type === types.GLUE;
}
isGlue() {
return this.type === types.GLUE;
}
isTor() {
return this.isOnion() || this.isOnionNG();
}
toDNS() {
return this.target;
}
compress() {}
getSize(c) {
if (this.type === types.GLUE) {
let size = 1;
size += sizeTarget(types.NAME, this.target, c);
size += sizeTarget(types.INET4, this.inet4, c);
size += sizeTarget(types.INET6, this.inet6, c);
return size;
}
return 1 + sizeTarget(this.type, this.target, c);
}
write(bw, c) {
bw.writeU8(this.type);
if (this.type === types.GLUE) {
if (this.inet4 === '0.0.0.0' && this.inet6 === '::')
throw new Error('Bad glue address.');
writeTarget(types.NAME, this.target, bw, c);
writeTarget(types.INET4, this.inet4, bw, c);
writeTarget(types.INET6, this.inet6, bw, c);
} else {
writeTarget(this.type, this.target, bw, c);
}
return this;
}
read(br) {
this.type = br.readU8();
if (this.type === types.GLUE) {
this.target = readTarget(types.NAME, br);
this.inet4 = readTarget(types.INET4, br);
this.inet6 = readTarget(types.INET6, br);
if (this.inet4 === '0.0.0.0' && this.inet6 === '::')
throw new Error('Bad glue address.');
} else {
this.target = readTarget(this.type, br);
}
return this;
}
format() {
return `<Target: ${this.toString()}>`;
}
} |
JavaScript | class Service extends Struct {
constructor() {
super();
this.service = 'tcpmux.';
this.protocol = 'icmp.';
this.priority = 0;
this.weight = 0;
this.target = new Target();
this.port = 0;
}
compress() {}
getSize() {
let size = 0;
size += sizeName(this.service);
size += sizeName(this.protocol);
size += 1;
size += 1;
size += this.target.getSize();
size += 2;
return size;
}
write(bw, c) {
writeNameBW(bw, this.service, c.labels);
writeNameBW(bw, this.protocol, c.labels);
bw.writeU8(this.priority);
bw.writeU8(this.weight);
this.target.write(bw, c);
bw.writeU16BE(this.port);
return this;
}
read(br) {
this.service = readNameBR(br);
if (util.countLabels(this.service) !== 1)
throw new Error('Invalid label.');
this.protocol = readNameBR(br);
if (util.countLabels(this.protocol) !== 1)
throw new Error('Invalid label.');
this.priority = br.readU8();
this.weight = br.readU8();
this.target.read(br);
this.port = br.readU16BE();
return this;
}
getJSON() {
return {
service: util.trimFQDN(this.service),
protocol: util.trimFQDN(this.protocol),
priority: this.priority,
weight: this.weight,
target: this.target.toJSON(),
port: this.port
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
if (json.service != null) {
assert(isSingle(json.service));
this.service = util.fqdn(json.service);
}
if (json.protocol != null) {
assert(isSingle(json.protocol));
this.protocol = util.fqdn(json.protocol);
}
if (json.priority != null) {
assert((json.priority & 0xff) === json.priority);
this.priority = json.priority;
}
if (json.weight != null) {
assert((json.weight & 0xff) === json.weight);
this.weight = json.weight;
}
if (json.target != null)
this.target.fromJSON(json.target);
if (json.port != null) {
assert((json.port & 0xffff) === json.port);
this.port = json.port;
}
return this;
}
} |
JavaScript | class Location extends Struct {
constructor() {
super();
this.version = 0;
this.size = 0;
this.horizPre = 0;
this.vertPre = 0;
this.latitude = 0;
this.longitude = 0;
this.altitude = 0;
}
compress() {}
getSize() {
return 16;
}
write(bw) {
bw.writeU8(this.version);
bw.writeU8(this.size);
bw.writeU8(this.horizPre);
bw.writeU8(this.vertPre);
bw.writeU32BE(this.latitude);
bw.writeU32BE(this.longitude);
bw.writeU32BE(this.altitude);
return this;
}
read(br) {
this.version = br.readU8();
this.size = br.readU8();
this.horizPre = br.readU8();
this.vertPre = br.readU8();
this.latitude = br.readU32BE();
this.longitude = br.readU32BE();
this.altitude = br.readU32BE();
return this;
}
getJSON() {
return {
version: this.version,
size: this.size,
horizPre: this.horizPre,
vertPre: this.vertPre,
latitude: this.latitude,
longitude: this.longitude,
altitude: this.altitude
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
if (json.version != null) {
assert((json.version & 0xff) === json.version);
this.version = json.version;
}
if (json.size != null) {
assert((json.size & 0xff) === json.size);
this.size = json.size;
}
if (json.horizPre != null) {
assert((json.horizPre & 0xff) === json.horizPre);
this.horizPre = json.horizPre;
}
if (json.vertPre != null) {
assert((json.vertPre & 0xff) === json.vertPre);
this.vertPre = json.vertPre;
}
if (json.latitude != null) {
assert((json.latitude >>> 0) === json.latitude);
this.latitude = json.latitude;
}
if (json.longitude != null) {
assert((json.longitude >>> 0) === json.longitude);
this.longitude = json.longitude;
}
if (json.altitude != null) {
assert((json.altitude >>> 0) === json.altitude);
this.altitude = json.altitude;
}
return this;
}
} |
JavaScript | class Magnet extends Struct {
constructor(nid, nin) {
super();
this.nid = nid || 'bt.';
this.nin = nin || '';
}
compress() {}
getSize() {
let size = 0;
size += sizeName(this.nid);
size += 1 + (this.nin.length >>> 1);
return size;
}
write(bw, c) {
writeNameBW(bw, this.nid, c.labels);
bw.writeU8(this.nin.length >>> 1);
bw.writeString(this.nin, 'hex');
return this;
}
read(br) {
this.nid = readNameBR(br);
if (util.countLabels(this.nid) !== 1)
throw new Error('Invalid label.');
const size = br.readU8();
assert(size <= 64);
this.nin = br.readString(size, 'hex');
return this;
}
toString() {
const nid = util.trimFQDN(this.nid);
return `magnet:?xt=urn:${nid.toLowerCase()}:${this.nin}`;
}
fromString(str) {
assert(typeof str === 'string');
assert(str.length <= 1024);
assert(str.length >= 7);
str = str.toLowerCase();
assert(str.substring(0, 7) === 'magnet:');
const index = str.indexOf('xt=urn:');
assert(index !== -1);
assert(index !== 0);
assert(str[index - 1] === '?' || str[index - 1] === '&');
str = str.substring(index + 7);
const parts = str.split(/[:&]/);
assert(parts.length >= 2);
const [nid, nin] = parts;
assert(nid.length <= 255);
assert(nin.length <= 255);
assert(isSingle(nid));
this.nid = util.fqdn(nid);
this.nin = nin;
return this;
}
getJSON() {
return this.toString();
}
fromJSON(json) {
return this.fromString(json);
}
} |
JavaScript | class DS extends Struct {
constructor() {
super();
this.keyTag = 0;
this.algorithm = 0;
this.digestType = 0;
this.digest = DUMMY;
}
compress() {}
getSize() {
return 4 + 1 + this.digest.length;
}
write(bw) {
bw.writeU16BE(this.keyTag);
bw.writeU8(this.algorithm);
bw.writeU8(this.digestType);
bw.writeU8(this.digest.length);
bw.writeBytes(this.digest);
return this;
}
read(br) {
this.keyTag = br.readU16BE();
this.algorithm = br.readU8();
this.digestType = br.readU8();
const size = br.readU8();
assert(size <= 64);
this.digest = br.readBytes(size);
return this;
}
getJSON() {
return {
keyTag: this.keyTag,
algorithm: this.algorithm,
digestType: this.digestType,
digest: this.digest.toString('hex')
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
assert((json.keyTag & 0xffff) === json.keyTag);
assert((json.algorithm & 0xff) === json.algorithm);
assert((json.digestType & 0xff) === json.digestType);
assert(typeof json.digest === 'string');
assert((json.digest.length >>> 1) <= 255);
this.keyTag = json.keyTag;
this.algorithm = json.algorithm;
this.digestType = json.digestType;
this.digest = util.parseHex(json.digest);
return this;
}
} |
JavaScript | class TLS extends Struct {
constructor() {
super();
this.protocol = 'icmp.';
this.port = 0;
this.usage = 0;
this.selector = 0;
this.matchingType = 0;
this.certificate = DUMMY;
}
compress() {}
getSize() {
return sizeName(this.protocol) + 6 + this.certificate.length;
}
write(bw, c) {
writeNameBW(bw, this.protocol, c.labels);
bw.writeU16BE(this.port);
bw.writeU8(this.usage);
bw.writeU8(this.selector);
bw.writeU8(this.matchingType);
bw.writeU8(this.certificate.length);
bw.writeBytes(this.certificate);
return this;
}
read(br) {
this.protocol = readNameBR(br);
if (util.countLabels(this.protocol) !== 1)
throw new Error('Invalid label.');
this.port = br.readU16BE();
this.usage = br.readU8();
this.selector = br.readU8();
this.matchingType = br.readU8();
this.certificate = br.readBytes(br.readU8());
return this;
}
getJSON() {
const protocol = util.trimFQDN(this.protocol);
return {
protocol: protocol.toLowerCase(),
port: this.port,
usage: this.usage,
selector: this.selector,
matchingType: this.matchingType,
certificate: this.certificate.toString('hex')
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
assert(typeof json.protocol === 'string');
assert(json.protocol.length <= 255);
assert((json.port & 0xffff) === json.port);
assert((json.usage & 0xff) === json.usage);
assert((json.selector & 0xff) === json.selector);
assert((json.matchingType & 0xff) === json.matchingType);
assert(typeof json.certificate === 'string');
assert((json.certificate.length >>> 1) <= 255);
assert(isSingle(json.protocol));
this.protocol = util.fqdn(json.protocol);
this.port = json.port;
this.usage = json.usage;
this.selector = json.selector;
this.matchingType = json.matchingType;
this.certificate = util.parseHex(json.certificate);
return this;
}
} |
JavaScript | class SMIME extends Struct {
constructor() {
super();
this.hash = DUMMY;
this.usage = 0;
this.selector = 0;
this.matchingType = 0;
this.certificate = DUMMY;
}
compress() {}
getSize() {
return 28 + 4 + this.certificate.length;
}
write(bw) {
bw.writeBytes(this.hash);
bw.writeU8(this.usage);
bw.writeU8(this.selector);
bw.writeU8(this.matchingType);
bw.writeU8(this.certificate.length);
bw.writeBytes(this.certificate);
return this;
}
read(br) {
this.hash = br.readBytes(28);
this.usage = br.readU8();
this.selector = br.readU8();
this.matchingType = br.readU8();
this.certificate = br.readBytes(br.readU8());
return this;
}
getJSON() {
return {
hash: this.hash.toString('hex'),
usage: this.usage,
selector: this.selector,
matchingType: this.matchingType,
certificate: this.certificate.toString('hex')
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
assert(typeof json.hash === 'string');
assert(json.hash.length === 56);
assert((json.usage & 0xff) === json.usage);
assert((json.selector & 0xff) === json.selector);
assert((json.matchingType & 0xff) === json.matchingType);
assert(typeof json.fingerprint === 'string');
assert((json.fingerprint.length >>> 1) <= 255);
this.hash = util.parseHex(json.hash);
this.port = json.port;
this.usage = json.usage;
this.selector = json.selector;
this.matchingType = json.matchingType;
this.certificate = util.parseHex(json.certificate);
return this;
}
} |
JavaScript | class SSH extends Struct {
constructor() {
super();
this.algorithm = 0;
this.keyType = 0;
this.fingerprint = DUMMY;
}
compress() {}
getSize() {
return 2 + 1 + this.fingerprint.length;
}
write(bw) {
bw.writeU8(this.algorithm);
bw.writeU8(this.keyType);
bw.writeU8(this.fingerprint.length);
bw.writeBytes(this.fingerprint);
return this;
}
read(br) {
this.algorithm = br.readU8();
this.keyType = br.readU8();
const size = br.readU8();
assert(size <= 64);
this.fingerprint = br.readBytes(size);
return this;
}
getJSON() {
return {
algorithm: this.algorithm,
keyType: this.keyType,
fingerprint: this.fingerprint.toString('hex')
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
assert((json.algorithm & 0xff) === json.algorithm);
assert((json.keyType & 0xff) === json.keyType);
assert(typeof json.fingerprint === 'string');
assert((json.fingerprint >>> 1) <= 255);
this.algorithm = json.algorithm;
this.keyType = json.keyType;
this.fingerprint = util.parseHex(json.fingerprint);
return this;
}
} |
JavaScript | class PGP extends Struct {
constructor() {
super();
this.hash = DUMMY;
this.publicKey = DUMMY;
}
compress() {}
getSize() {
return 28 + 2 + this.publicKey.length;
}
write(bw) {
bw.writeBytes(this.hash);
bw.writeU16BE(this.publicKey.length);
bw.writeBytes(this.publicKey);
return this;
}
read(br) {
this.hash = br.readBytes(28);
const size = br.readU16BE();
assert(size <= 512);
this.publicKey = br.readBytes(size);
return this;
}
getJSON() {
return {
hash: this.hash.toString('hex'),
publicKey: this.publicKey.toString('hex')
};
}
fromJSON(json) {
assert(typeof json === 'object');
assert(typeof json.hash === 'string');
assert((json.hash.length >>> 1) === 28);
this.hash = util.parseHex(json.hash);
this.publicKey = util.parseHex(json.publicKey);
return this;
}
} |
JavaScript | class Addr extends Struct {
constructor(currency, address) {
super();
this.currency = currency || 'bitcoin.';
this.address = address || '';
}
compress() {}
getSize() {
if (util.equal(this.currency, 'handshake.')) {
const {hash} = bech32.decode(this.address);
return 1 + 2 + hash.length;
}
if (util.equal(this.currency, 'bitcoin.') && bech32.test(this.address)) {
const {hash} = bech32.decode(this.address);
return 1 + 2 + hash.length;
}
if (util.equal(this.currency, 'ethereum.'))
return 1 + 20;
return 1 + sizeName(this.currency) + 1 + this.address.length;
}
write(bw, c) {
if (util.equal(this.currency, 'handshake.')) {
const {hrp, version, hash} = bech32.decode(this.address);
assert(hash.length >= 1);
assert(hash.length <= 128);
const test = hrp === 'ts' ? 0x80 : 0x00;
const size = hash.length - 1;
const field = test | size;
bw.writeU8(1);
bw.writeU8(field);
bw.writeU8(version);
bw.writeBytes(hash);
return this;
}
if (util.equal(this.currency, 'bitcoin.') && bech32.test(this.address)) {
const {hrp, version, hash} = bech32.decode(this.address);
assert(hash.length >= 1);
assert(hash.length <= 128);
const test = hrp === 'tb' ? 0x80 : 0x00;
const size = hash.length - 1;
const field = test | size;
bw.writeU8(2);
bw.writeU8(field);
bw.writeU8(version);
bw.writeBytes(hash);
return this;
}
if (util.equal(this.currency, 'ethereum.')) {
bw.writeU8(3);
bw.writeString(this.address.substring(2), 'hex');
return this;
}
bw.writeU8(0);
writeNameBW(bw, this.currency, c.labels);
bw.writeU8(this.address.length);
bw.writeString(this.address, 'ascii');
return this;
}
read(br) {
const type = br.readU8();
if (type === 1) {
const field = br.readU8();
const test = (field & 0x80) !== 0;
const size = (field & 0x7f) + 1;
const hrp = test ? 'ts' : 'hs';
const version = br.readU8();
const hash = br.readBytes(size);
this.currency = 'handshake.';
this.address = bech32.encode(hrp, version, hash);
return this;
}
if (type === 2) {
const field = br.readU8();
const test = (field & 0x80) !== 0;
const size = (field & 0x7f) + 1;
const hrp = test ? 'tb' : 'bc';
const version = br.readU8();
const hash = br.readBytes(size);
this.currency = 'bitcoin.';
this.address = bech32.encode(hrp, version, hash);
return this;
}
if (type === 3) {
this.currency = 'ethereum.';
this.address = '0x' + br.readString(20, 'hex');
return this;
}
this.currency = readNameBR(br);
this.address = readAscii(br, br.readU8());
return this;
}
toAddress(Address, network) {
assert(util.equal(this.currency, 'handshake.'));
return Address.fromString(this.address, network);
}
fromAddress(addr, network) {
assert(addr && typeof addr === 'object');
this.currency = 'handshake.';
this.address = addr.toString(network);
return this;
}
static fromAddress(addr, network) {
return new this().fromAddress(addr, network);
}
toString() {
const currency = util.trimFQDN(this.currency);
return `${currency.toLowerCase()}:${this.address}`;
}
fromString(str) {
assert(typeof str === 'string');
assert(str.length <= 512);
const parts = str.split(':');
assert(parts.length === 2);
const [currency, address] = parts;
assert(currency.length <= 255);
assert(address.length <= 255);
assert(isSingle(currency));
this.currency = util.fqdn(currency);
this.address = address;
return this;
}
static fromString(str) {
return new this().fromString(str);
}
getJSON() {
return this.toString();
}
fromJSON(json) {
return this.fromString(json);
}
} |
JavaScript | class Extra extends Struct {
constructor() {
super();
this.type = 0;
this.data = DUMMY;
}
compress() {}
getSize() {
return 3 + this.data.length;
}
write(bw) {
bw.writeU8(this.type);
bw.writeU16BE(this.data.length);
bw.writeBytes(this.data);
return this;
}
read(br) {
this.type = br.readU8();
this.data = br.readBytes(br.readU16BE());
return this;
}
getJSON() {
return {
type: this.type,
data: this.data.toString('hex')
};
}
fromJSON(json) {
assert(json && typeof json === 'object');
assert((json.type & 0xff) === json.type);
assert(typeof json.data === 'string');
assert((json.data >>> 1) <= 255);
this.type = json.type;
this.data = util.parseHex(json.data);
return this;
}
} |
JavaScript | class Requestable {
/**
* Initialize the http internals.
* @param {Requestable.auth} [auth] - the credentials to authenticate to Xnat. If auth is
* not provided request will be made unauthenticated
* @param {string} [apiBase] - the base Xnat URL
*/
constructor(jsXnat) {
this.jsXnat = jsXnat;
// this.__apiBase = cleanseUrl(apiBase);
// this.__auth = {
// token: auth.token,
// username: auth.username,
// password: auth.password,
// };
// if (auth.token) {
// this.__authorizationHeader = 'token ' + auth.token;
// } else if (auth.username && auth.password) {
// this.__authorizationHeader =
// 'Basic ' + Base64.encode(auth.username + ':' + auth.password);
// }
}
/**
* Compute the URL to use to make a request.
* @private
* @param {string} path - either a URL relative to the API base or an absolute URL
* @return {string} - the URL to use
*/
__getURL(path) {
let url = path;
if (path.indexOf('//') === -1) {
url = this.jsXnat.basePath + path;
}
const newCacheBuster = 'timestamp=' + new Date().getTime();
return url.replace(/(timestamp=\d+)/, newCacheBuster);
}
/**
* Compute the headers required for an API request.
* @private
* @return {Object} - the headers to use in the request
*/
async __getRequestHeaders(requiredAuthMethod) {
const headers = {};
headers.Authorization = await this.jsXnat.getAuthorizationHeader(
requiredAuthMethod
);
return headers;
}
/**
* Sets the default options for API requests
* @protected
* @param {Object} [requestOptions={}] - the current options for the request
* @return {Object} - the options to pass to the request
*/
_getOptionsWithDefaults(requestOptions = {}) {
if (!(requestOptions.visibility || requestOptions.affiliation)) {
requestOptions.type = requestOptions.type || 'all';
}
requestOptions.sort = requestOptions.sort || 'updated';
requestOptions.per_page = requestOptions.per_page || '100'; // eslint-disable-line
return requestOptions;
}
/**
* A function that receives the result of the API request.
* @callback Requestable.callback
* @param {Requestable.Error} error - the error returned by the API or `null`
* @param {(Object|true)} result - the data returned by the API or `true` if the API returns `204 No Content`
* @param {Object} request - the raw {@linkcode https://github.com/mzabriskie/axios#response-schema Response}
*/
/**
* Make a request.
* @param {string} method - the method for the request (GET, PUT, POST, DELETE)
* @param {string} path - the path for the request
* @param {*} [bodyParams] - the data to send to the server. For HTTP methods that don't have a body the data
* will be sent as query parameters
* @param {Requestable.callback} [cb] - the callback for the request
* @param {boolean} [raw=false] - if the request should be sent as raw. If this is a falsy value then the
* request will be made as JSON
* @return {Promise} - the Promise for the http request
*/
async _request(
method,
path,
bodyParams,
cb,
contentType = CONTENT_TYPES.json,
requiredAuthMethod = undefined
) {
let url = this.__getURL(path);
const headers = await this.__getRequestHeaders(requiredAuthMethod);
let queryParams = {};
let shouldUseDataAsQueryString = false;
let body = undefined;
if (bodyParams) {
shouldUseDataAsQueryString =
typeof bodyParams === 'object' && methodHasNoBody(method);
if (shouldUseDataAsQueryString) {
queryParams = bodyParams;
bodyParams = undefined;
}
}
if (contentType === CONTENT_TYPES.json) {
headers['Content-Type'] = contentType;
body = JSON.stringify(bodyParams);
} else if (
contentType === CONTENT_TYPES.binary ||
contentType === CONTENT_TYPES.xml ||
contentType === CONTENT_TYPES.plain
) {
headers['Content-Type'] = contentType;
body = bodyParams;
} else if (contentType === CONTENT_TYPES.form) {
headers['Content-Type'] = contentType;
if (bodyParams instanceof URLSearchParams) {
body = bodyParams;
} else {
const urlParams = new URLSearchParams();
Object.keys(bodyParams).forEach((key) => {
urlParams.append(key, bodyParams[key]);
});
body = urlParams;
}
} else if (contentType === CONTENT_TYPES.multipart) {
// Content-Type for multipart form type will be automtically popuplated by note-fetch (along with the boundary parameter)
if (bodyParams instanceof FormData) {
body = bodyParams;
} else {
const formData = new FormData();
Object.keys(bodyParams).forEach((key) => {
formData.append(key, bodyParams[key]);
});
body = formData;
}
} else {
throw new IllegalArgumentsError(
`Content Type is not valid: ${contentType}`
);
}
const config = {
method: method,
headers: headers,
body,
// body: typeof data === 'object' ? JSON.stringify(data) : data,
};
if (Object.keys(queryParams).length > 0) {
url = `${url}?${queryString.stringify(queryParams)}`;
}
log(`${config.method} to ${url}`);
let responseData;
try {
const response = await fetch(url, config);
responseData = await getResponseData(response);
if (!response.ok) {
throwErrorBasedOnStatus(path, responseData, response);
}
if (cb) cb(null, responseData, response);
} catch (err) {
callbackErrorOrThrow(cb, path, err);
}
return responseData;
}
/**
* Make a request to an endpoint the returns 204 when true and 404 when false
* @param {string} path - the path to request
* @param {Object} data - any query parameters for the request
* @param {Requestable.callback} cb - the callback that will receive `true` or `false`
* @param {method} [method=GET] - HTTP Method to use
* @return {Promise} - the promise for the http request
*/
_request204or404(path, data, cb, method = 'GET') {
return this._request(method, path, data).then(
function success(response) {
if (cb) {
cb(null, true, response);
}
return true;
},
function failure(response) {
if (response.response.status === 404) {
if (cb) {
cb(null, false, response);
}
return false;
}
if (cb) {
cb(response);
}
throw response;
}
);
}
} |
JavaScript | class HeaderView {
/**
* Controls all stuff for header view.
*
*/
constructor() {
this.api_key = 1;
this.api_base_URL = `https://www.thesportsdb.com/api/v1/json/${this.api_key}/`;
this.api_URLs = {
allSportsList: `${this.api_base_URL}all_sports.php`,
allLeagueList: `${this.api_base_URL}all_leagues.php`,
/**
*
* @param {string} leagueName
* @return {URL}
*/
allTeamsInALeague: function (leagueName) {
return `${this.api_base_URL}search_all_teams.php?l=${leagueName
.split(" ")
.join("%20")}`;
},
/**
*
* @param {number} teamId
* @return {URL}
*/
searchByTeamId: function (teamId) {
return `${this.api_base_URL}lookupteam.php?id=${teamId}`;
},
/**
*
* @param {number} leagueId
* @return {URL}
*/
searchByLeagueId: function (leagueId) {
return `${this.api_base_URL}lookupleague.php?id=${leagueId}`;
},
};
}
/**
* Manipulate all essential DOM elements for Header preview and insert it on a parent element.
*
* @param {HTMLDivElement} parent_el - The parent HTML element where manipulated DOM will be inserted.
* @returns {object} - The reference of all manipulated DOM elements.
*/
async manipulateDOM(parent_el) {
try {
parent_el.innerHTML = `
<section id="headerSection" class="header-section">
<div class="banner-container">
<h1>Soccer Mania ⚽</h1>
</div>
<div class="row">
<div class="soccer-items-heading-container">
<h2 id="soccerItemsHeading">all soccer leagues</h2>
</div>
<div
id="soccerItemsContainer"
class="soccer-items-container"
></div>
</div>
</section>
`;
const header_section_el = document.getElementById("headerSection");
const soccer_items_heading_el =
document.getElementById("soccerItemsHeading");
const soccer_items_container_el = document.getElementById(
"soccerItemsContainer"
);
throw {
header_section_el,
soccer_items_heading_el,
soccer_items_container_el,
};
} catch (err) {
return err;
}
}
/**
* Fetch all excepted leagues details and return it.
*
* @param {string[]} excepted_leagues
* @return {object[]}
*/
async getAllLeagues(excepted_leagues) {
try {
const respnose_for_short_leagues = await fetch(
this.api_URLs.allLeagueList
);
const data_for_short_leagues =
await respnose_for_short_leagues.json();
const soccer_short_leagues = [];
const leagues_details = [];
for (let i = 0; i < data_for_short_leagues.leagues.length; i++) {
if (
excepted_leagues.includes(
data_for_short_leagues.leagues[i].strLeague
)
) {
soccer_short_leagues.push(
await data_for_short_leagues.leagues[i]
);
}
}
for (let i = 0; i < soccer_short_leagues.length; i++) {
try {
const response_for_league_details = await fetch(
this.api_URLs.searchByLeagueId.call(
this,
soccer_short_leagues[i].idLeague
)
);
const data_for_league_details =
await response_for_league_details.json();
leagues_details.push(
...(await data_for_league_details.leagues)
);
} catch (err) {
return err;
}
}
throw leagues_details;
} catch (err) {
return err;
}
}
/**
* Return a list of all teams in a league
*
* @param {URL} api_URL
* @return {}
*/
async allTeamsInALeague(api_URL) {
try {
const response = await fetch(api_URL);
const data = await response.json();
throw data;
} catch (err) {
return err;
}
}
/**
* Render all soccer league items into soccer items container.
*
* @param {HTMLCollection} DOMObj
* @param {ImageData} leagueImage
* @param {string} leagueName
* @param {string} leagueType
* @param {number} leagueIndex
* @returns {object}
*/
async renderAllLeagues(
DOMObj,
leagueImage,
leagueName,
leagueType,
leagueIndex
) {
try {
DOMObj.soccer_items_container_el.innerHTML += `
<div class="soccer-item"">
<div class="soccer-item-image">
<img src="${leagueImage}" alt="${leagueName}" />
</div>
<div class="soccer-item-text">
<h3>name: ${leagueName}</h3>
<h4>type: ${leagueType}</h4>
</div>
<div class="soccer-item-button">
<button id="btnExploreLeague" class="btn-explore" data-item="${leagueIndex}">explore</button>
</div>
</div>
`;
DOMObj.btn_explore_league = [
...document.querySelectorAll("#btnExploreLeague"),
];
throw DOMObj;
} catch (err) {
return err;
}
}
} |
JavaScript | class ScrollerStream extends stream.Readable {
/**
* Create a ScrollerStream.
* @param {object} options - Stream options.
* @param {ElasticsearchClient} options.esClient - Elasticsearch client. More info: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
* @param {string} options.index - Index to be scrolled.
* @param {string} options.type - Type of documents to be scrolled.
* @param {number} options.size - Response size of each scroll iteration.
*/
constructor(options) {
super(options);
this.esClient = options.esClient;
this.index = options.index;
this.type = options.type;
this.size = options.size;
this.scrollId = null;
this.scrolledDocsLength = 0;
}
_read() {
if (this.scrollId) {
this.esClient.scroll({
scrollId: this.scrollId,
scroll: '30s'
}).then(response => {
console.log(`[ScrollerStream] ${this.scrolledDocsLength} docs has been read`);
if (this.scrolledDocsLength < response.hits.total) {
this._readData(response);
//this.resume();
} else {
this.push(null);
}
});
} else {
console.log(`[ScrollerStream] Starting scroller...`);
this.esClient.search({
index: this.index,
type: this.type,
scroll: '30s',
size: this.size
//search_type: 'scan'
}).then((response) => {
console.log(`[ScrollerStream] Total of ${response.hits.total} docs will be read`);
console.log(`[ScrollerStream] ${this.scrolledDocsLength} docs has been read`);
if (this.scrolledDocsLength < response.hits.total) {
this.scrollId = response._scroll_id;
this._readData(response);
//this.resume();
} else {
this.push(null);
}
});
}
//this.pause();
}
_readData(response) {
const docs = response.hits.hits.map(hit => hit._source);
this.scrolledDocsLength += docs.length;
this.push(JSON.stringify(docs));
}
} |
JavaScript | class JourneyMan {
/**
* Static getter for the Plugin class. This provides `Plugin` to plugins without having to
* require the actual file itself. Plugin authors are advised to use this property since the
* path to the class might change at any time. `JourneyMan` *is* the stable API.
*
* @returns {Plugin}
* @constructor
*/
static get Plugin () {
return require( './Plugins/Plugin' );
}
/**
* Static getter for the Command class. This provides `Command` to plugins without having to
* require the actual file itself. Plugin authors are advised to use this property since the
* path to the class might change at any time. `JourneyMan` *is* the stable API.
*
* @returns {Command}
* @constructor
*/
static get Command () {
return require( './Console/Command' );
}
/**
* Creates a new instance of JourneyMan.
*
* @param {String} configFilePath Path to the configuration file.
*/
constructor ( configFilePath = process.cwd() ) {
/**
* Holds Config instance for the application. Journeyman will generally first try to load
* a file called `.journeyman`. If it is available, a new Config will be created with no
* sub-key (`.journeyman` files are expected to only contain Journeyman configuration).
* In case there is none, Journeyman will try to find and load a `package.json` file in
* the current directory.
*
* @type {Config}
*/
this.config = fs.existsSync( path.join( configFilePath, '.journeyman' ) )
? new Config( path.join( configFilePath, '.journeyman', configSchema ) )
: new Config( path.join( configFilePath, 'package.json' ), 'journeyman', configSchema );
this.plugins = [];
}
/**
* Runs the application. This is kind of the *"main"* function in Journeyman, kicking off the
* entire process chain. In order, the input is detected, plugins are loaded and the correct
* command is routed.<br>
* The output produced by any command than ran will be returned as the result; if anything
* throws, it will bubble up to this point. Catching these exceptions is up to the final
* implementation: Either a programmatic consumer or the CLI app `journ`.
*
* @param {Object} proc Process object. While in node, `process` is a global, we want
* JourneyMan to stay as portable as possible. Therefore, process
* is a freely shimable dependency here.
* @param {String} proc.argv Command line arguments
* @param {function} proc.cwd Current working directory
* @param {WritableStream} proc.stdout Standard output
* @param {WritableStream} proc.stderr Standard error output
* @returns {Promise<*>} Resulting output from the command
*/
async run ( proc ) {
/**
* Holds the command line input.
*
* @type {Input}
*/
this.input = new Input( proc.argv.slice( 2 ) );
// Wait for the npm module to initialize
await loadNpm();
// Prepare the plugin loader
this._loader = new Loader( npm );
// Load all plugins
this.plugins = await this._loader.discover(
this._loader.paths.concat( this.config.paths.plugins )
);
const plugin = this._resolvePlugin();
// noinspection UnnecessaryLocalVariableJS
const result = await plugin.$run( this.input.command, {
input: this.input,
output: new ConsoleOutput( proc.stdout, proc.stderr),
plugins: this.plugins
} );
return result;
}
/**
* Resolves the requested plugin by looking for the given name in the plugin list.
*
* @returns {Plugin}
* @private
*
* @throws {UnknownPluginError} If the plugin name can't be resolved.
*/
_resolvePlugin () {
const PluginType = this.plugins.find( plugin => plugin.name === this.input.plugin );
if ( PluginType ) {
return new PluginType( this );
}
throw new UnknownPluginError( this, this.input.plugin );
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
navigator.geolocation.getCurrentPosition(location => {
this.props.requestLocation(location.coords);
this.mapInstance = {};
});
}
componentDidMount() {
// Load places after mount
this.props.getPlaces();
}
componentDidCatch(error, info) {
alert(`Sorry we got error: ${error}`);
}
render() {
var mapsData = {
googleMapURL:
"https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyCUDVUPaIm0AA6yj7kQnU-JW7lQ7mhKFuc",
loadingElement: <div style={{ height: "100%" }} />,
containerElement: <div style={{ height: "100%" }} />
};
return (
<div className="app flex-dir-column">
{/* navbar */}
<div
className="nav-bar title-bar"
data-responsive-toggle="places-menu"
data-hide-for="medium"
>
<button
className="menu-icon"
type="button"
onClick={this.props.toggleMenu}
/>
</div>
<div className="main-container grid-x flex-dir-row">
<div
className={
"cell medium-4 large-2 " + (!this.props.showMenu && "hide")
}
>
{/* sidebar */}
<Sidebar
{...mapsData}
filteredPlaces={this.props.filteredPlaces}
filterPlaces={this.props.filterPlaces}
onMarkerClick={this.props.onMarkerClick}
onPlacesChanged={this.props.onPlacesChanged}
bounds={this.props.bounds}
/>
</div>
<div
className={"cell " + (this.props.showMenu && "medium-8 large-10")}
>
{/* map */}
<Map {...mapsData} />
</div>
</div>
</div>
);
}
} |
JavaScript | class Switch {
constructor(initial_value = false) {
bs.assert_type(initial_value, bs.TYPE_BOOLEAN);
this.__SWITCH_STATE__ = initial_value;
this.fun_event_off = null;
this.fun_event_on = null;
}
assign_event_on(fun_event) {
bs.assert_type(fun_event, bs.TYPE_FUNCTION);
this.fun_event_on = fun_event;
}
assign_event_off(fun_event) {
bs.assert_type(fun_event, bs.TYPE_FUNCTION);
this.fun_event_off = fun_event;
}
turn_on() {
bs.assert(this.is_off(), "Attempting to turn on, but was already on!");
this.__SWITCH_STATE__ = true;
if (bs.is_null_or_undefined(this.fun_event_on) === false) this.fun_event_on();
}
turn_off() {
bs.assert(this.is_on(), "Attempting to turn off, but was already off!");
this.__SWITCH_STATE__ = false;
if (bs.is_null_or_undefined(this.fun_event_off) === false) this.fun_event_off();
}
is_on() {
return this.__SWITCH_STATE__;
}
is_off() {
return !this.is_on();
}
} |
JavaScript | class TimedSwitch extends Switch {
constructor(initial_value = false, secs = 60) {
super(initial_value);
this.__LAST_SWITCH__ = Date.now() / 1000;
this.__VALIDITY__ = secs;
}
__is_valid__() {
let now = Date.now() / 1000;
return now - this.__LAST_SWITCH__ <= this.__VALIDITY__;
}
is_on() {
if (this.__is_valid__()) {
return super.is_on();
} else {
return false;
}
}
is_off() {
return !this.is_on();
}
} |
JavaScript | class CustomAppController extends mvc.Controller {
constructor(model = null, view = null) {
super(model, view);
// Keep a version of the initial model so it can reset to it when needed
this.initial_model = new mvc.Model(model.data_dict);
this.reset();
}
/**
* Resets the controller, including its model, to its initial state
*/
reset() {
this.model = new mvc.Model(this.initial_model.data_dict);
this.canvas_click_listener = new Switch(false);
this.ajax_lock = new TimedSwitch(false);
this.start_button_enter_key_listener = new Switch(true);
this.modal_button_enter_key_listener = new Switch(true);
this.modal_button_esc_key_listener = new Switch(true);
this.running_session = new Switch(false);
this.predictive_mode = new Switch(false);
this.only_predictive = new Switch(false);
this.wait_time_before_resizing = 1000;
this.resize_timeout = null;
// Add some extra properties to the model and provide initial values
this.model.add("margin_x", 0.008);
this.model.add("margin_y", 0.2);
this.model.add("scaling_value", null);
this.model.add("current_score", 0);
this.model.add("session_score", 0);
this.model.add("max_session_score", 0);
this.model.add("beginning_time", null);
this.model.add("iteration_click_time_y_estimation", []);
this.model.add("iteration_click_time_x_prediction", []);
this.model.add("error", Number.POSITIVE_INFINITY);
this.model.add("smallest_error", Number.POSITIVE_INFINITY);
this.model.add("update_session", false);
this.model.add("x_prediction", []);
}
/**
* Start the controller.
*
* Bootstraps eventual things to do in the beginning.
*/
start() {
this.handle_start_application();
}
// noinspection JSMethodCanBeStatic
/**
* Terminates the controller.
*
* Can handle things to to in the end.
*/
end() {
console.warn("Nothing to do");
}
/**
* Sets the events to be tracked by the controller.
*/
set_events() {
// Connects the ajax Error event to a reporting function
$(document).ajaxError($.proxy(this.handle_ajax_error, this));
// Start the session
this.view.get(EL.button_start).on_click($.proxy(this.handle_start_button_click, this));
// Move the line cursor following the cursor position
this.view.get(EL.canvas_plot).get_jq_element().mousemove($.proxy(this.handle_canvas_mouse_move, this));
// This may be needed for updating the cursor position at the end of the iteration
$(document).mousemove($.proxy(this.handle_document_mouse_move, this));
// User click to provide feedback
this.view.get(EL.canvas_plot).get_jq_element().click($.proxy(this.handle_canvas_click, this));
// Triggers a resize for the canvas and its plot
window.onresize = $.proxy(this.handle_window_resize, this);
// Triggers events for pressing keys
window.addEventListener('keydown', $.proxy(this.handle_keydown, this));
// Triggers events for when the session completes
window.addEventListener('session_complete_event', $.proxy(this.handle_session_complete, this));
}
/*===================================*
Category: Event handlers
/*===================================*/
/**
* Handles possible ajax errors.
*
* Please, refer to https://api.jquery.com/ajaxError/ for more information.
*
* @param {Event} event - event object
* @param {jquery.jqXHR} jqXHR - https://api.jquery.com/Types/#jqXHR
* @param {Object} ajax_settings
* @param {Error} thrown_error
*/
handle_ajax_error(event, jqXHR, ajax_settings, thrown_error) {
this.view.get(EL.text_view_logs).show();
this.view.get(EL.modal_dialogue).alert("An error occurred. Please, inform the study conductor.");
console.error("Ajax Error:", thrown_error);
// noinspection JSUnresolvedVariable
console.error("Response error:", jqXHR.responseText);
// noinspection JSUnresolvedFunction
console.error("Full response:", jqXHR.getAllResponseHeaders());
throw new bs.RuntimeError("Something went wrong with server's AJAX response.");
}
/**
* Handles server's answer to a new function sample request.
*
* This method updates the model using the received response.
* Then it updates the view, showing some interacting elements or others
* according to the received settings.
*
* Important settings (boolean):
* - ("settings")["only_predictive"] - Enables the a study which is only predictive (no y estimation);
* - ("settings")["show_max"] - Shows the maximum of the function or not
* - ("settings")["session_score_as_max"] - Show the best score so far instead of cumulative and current score.
*
* @param {Object} response - An object obtained from parsing server's JSON response.
*/
handle_api_sample_success_response(response) {
// Update the model from the response
let response_dict = new bs.Dictionary(response);
this.model.update_full_data(response_dict);
this.model.update("current_score", 0);
this.model.update("session_score", 0);
this.model.update("max_session_score", 0);
// Set this variable to let functions know how to behave
if (this.model.get("settings")["only_predictive"] === true && this.only_predictive.is_off()) {
this.only_predictive.turn_on();
}
// Log the received data
console.log("Received the following data:");
for (let key of this.model.keys()) {
console.log(`'${key}' - type: ${bs.type(this.model.get(key))}`);
}
let model_settings = this.model.get("settings");
for (let key of Object.keys(model_settings)) {
console.log(`settings: '${key}' - type: ${bs.type(model_settings[key])}`);
}
// Show canvas
this.view.get(EL.div_canvas_container).show();
// Show canvas related elements for y feedback
if (this.only_predictive.is_off()) {
this.view.get(EL.div_cursor_line_left).show();
this.view.get(EL.div_cursor_line_right).show();
}
// Disable cursor view on canvas
this.view.get(EL.canvas_plot).disable_cursor();
// Set the beginning time
this.model.update("beginning_time", Date.now());
// Show max arrow conditionally on settings
if (this.model.get("settings")["show_max"] === true) {
this.view.get(EL.div_max_indicator_container).show();
} else {
this.view.get(EL.div_max_indicator_container).hide();
}
// Update and display text elements related to y feedback
if (this.only_predictive.is_off()) {
// When showing max score don't show current score
if (this.model.get("settings")["session_score_as_max"] === true) {
this.view.get(EL.text_session_score).set_rich_text(this.get_max_session_score_rich_text());
}
else {
this.view.get(EL.text_session_score).set_rich_text(this.get_cumulative_session_score_rich_text());
this.view.get(EL.text_current_score).set_rich_text(this.get_current_score_rich_text());
this.view.get(EL.text_current_score).show();
}
this.view.get(EL.text_question).set_text(MESSAGES.in_session_select_height);
this.view.get(EL.text_session_score).show();
}
// Update and display text elements related to x prediction
else if (this.predictive_mode.is_off()){
this.switch_to_predictive_mode();
}
// Update other text elements
this.view.get(EL.text_iteration_number).set_text(this.get_iteration_number_text());
this.view.get(EL.text_session_number).set_text(this.get_session_number_text());
this.view.get(EL.text_user_id).set_text(this.get_user_id_text());
this.view.get(EL.button_start).set_text("Restart");
// Display text elements
this.show_explore_or_exploit_text();
this.view.get(EL.text_iteration_number).show();
this.view.get(EL.text_session_number).show();
this.view.get(EL.text_user_id).show();
// Hide start button
this.view.get(EL.button_start).hide();
// Hide title element
this.view.get(EL.text_title).hide();
// Update all about the canvas
// These functions need to be run after all show() and hide(), otherwise the behaviour will be incorrect
this.initialise_plot_with_best_box();
this.update_canvas_all();
this.move_horizontal_line_cursors_on_canvas();
// Update model for properties to be computed (only max score)
// This is updated here because requires the canvas to already be open.
this.model.update("smallest_error", this.get_smallest_error_compute_from_data());
this.model.update("max_session_score", this.get_current_max_score_compute_from_smallest_error());
if (this.model.get("settings")["session_score_as_max"] === true) {
this.view.get(EL.text_session_score).set_rich_text(this.get_max_session_score_rich_text());
}
// Enable click events on the canvas
this.canvas_click_listener.turn_on();
}
/**
* Handles server's answer to an iteration regression_update.
*
* This method updates the model and the view after a response from the
* server, which has updated the posterior using the last received data.
*
* Important settings (boolean):
* - ("settings")["predictive_mode"] - Enables the predictive mode to get a user prediction using the new posterior
*
* It may trigger a session complete when reaching the last iteration of the session. This
* does not happen in predictive mode, to allow the user to first provide a prediction.
*
* @param {Object} response - An object obtained from parsing server's JSON response.
*/
handle_api_update_gp_success_response(response) {
// Update the full model using the new data from the server
let response_dict = new bs.Dictionary(response);
this.model.update_full_data(response_dict);
// Update model for properties to be computed
this.model.update("error", this.get_last_error_compute_from_data());
this.model.update("smallest_error", this.get_smallest_error_compute_from_data());
this.model.update("current_score", this.get_current_score_compute_from_error());
this.model.update("session_score", this.model.get("session_score") + this.model.get("current_score"));
this.model.update("max_session_score", this.get_current_max_score_compute_from_smallest_error());
// Update text elements
if (this.only_predictive.is_off()) {
// Showing only the max score
if (this.model.get("settings")["session_score_as_max"] === true) {
this.view.get(EL.text_session_score).set_rich_text(this.get_max_session_score_rich_text());
}
// Showing cumulative score and max score
else {
this.view.get(EL.text_session_score).set_rich_text(this.get_cumulative_session_score_rich_text());
this.view.get(EL.text_current_score).set_rich_text(this.get_current_score_rich_text());
}
this.view.get(EL.text_question).set_text(MESSAGES.in_session_select_height);
}
else {
this.view.get(EL.text_question).set_text(MESSAGES.in_session_select_x_prediction);
}
// Enable predictive mode if settings ask so
// if (this.model.get("settings")["predictive_mode"] === true) {
// this.canvas_click_listener.turn_on();
// this.switch_to_predictive_mode();
// this.update_canvas_all();
// }
// // Check if the session is finished and eventually trigger its corresponding session complete event
// else
if (this.model.get("iteration") >= this.model.get("settings")["max_iterations"]) {
this.handle_session_complete();
} else {
// Update iteration number if session is not complete
this.view.get(EL.text_iteration_number).set_text(this.get_iteration_number_text());
this.update_canvas_all();
// Enable click events on the canvas
console.log("Session keeps running...",
"iteration:", this.model.get("iteration"),
"max_iteration:", this.model.get("settings")["max_iterations"]);
this.canvas_click_listener.turn_on();
}
}
/**
* Handles a click on the canvas.
*
* @param {MouseEvent} event - The mouse click event
* @param {Number} event.pageX - The X coordinate of the mouse pointer relative to the whole document.
* @param {Number} event.pageY - The Y coordinate of the mouse pointer relative to the whole document.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
*/
handle_canvas_click(event) {
let click_time = Date.now();
// Check if the event should be considered or dismissed
if (this.canvas_click_listener.is_off()) {
console.log("Canvas clicked but click listener is disabled.");
return;
} else {
// Disable the listener to avoid multiple clicks!
this.canvas_click_listener.turn_off();
}
// Call the appropriate function
if (this.predictive_mode.is_on()) {
console.log("Calling for x prediction feed");
this.send_user_click_for_x_prediction(event, click_time);
} else {
console.log("Calling for y position feed");
this.send_user_click_for_y_position(event, click_time);
}
}
/**
* Handles a mouse movement on the canvas.
*
* @param {MouseEvent} event - The mouse movement event
* @param {Number} event.pageX - The X coordinate of the mouse pointer relative to the whole document.
* @param {Number} event.pageY - The Y coordinate of the mouse pointer relative to the whole document.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
*/
handle_canvas_mouse_move(event) {
if (bs.is_null_or_undefined(event)) {
console.warn("Received null event, likely no mousemove has been done");
return;
}
// Update cursor line position to cursor position
let cursor_line_left = this.view.get(EL.div_cursor_line_left).get_jq_element();
let cursor_line_right = this.view.get(EL.div_cursor_line_right).get_jq_element();
let cursor_line_top = this.view.get(EL.div_cursor_line_top).get_jq_element();
let cursor_line_bottom = this.view.get(EL.div_cursor_line_bottom).get_jq_element();
// Update the top of each cursor
let new_top = event.pageY - (cursor_line_left.height() / 2);
let new_left = event.pageX - (cursor_line_top.width() / 2);
bs.assert(new_top > 0, "Cursor top lower than 0");
bs.assert(new_top !== undefined, "Cursor top is undefined");
bs.assert(Number.isNaN(new_top) === false, "Cursor top is NaN");
cursor_line_left.css('top', new_top);
cursor_line_right.css('top', new_top);
cursor_line_top.css('left', new_left);
cursor_line_bottom.css('left', new_left);
}
/**
* Handles a mouse movement on whole document.
*
* The mouse coordinates are stored in a property of the controller 'this.mouse_pos'
* so that can be retrieved when needed.
*
* @param {MouseEvent} event - The mouse movement event
* @param {Number} event.pageX - The X coordinate of the mouse pointer relative to the whole document.
* @param {Number} event.pageY - The Y coordinate of the mouse pointer relative to the whole document.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
*/
handle_document_mouse_move(event) {
this.mouse_pos = event;
}
/**
* Handles a keydown event.
*
* Currently it handles 'Enter' and 'Escape' keys only.
*
* @param {KeyboardEvent} event - The keydown event
* @param {String} event.key- Returns a DOMString representing the key value of the key represented by the event.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
*/
handle_keydown(event) {
// Enter key
if (event.key === 'Enter') {
if (this.view.get(EL.modal_dialogue).is_in_focus && this.modal_button_enter_key_listener.is_on()) {
console.log("Received 'Enter' keydown, using with modal");
this.view.get(EL.modal_dialogue).click_ok();
} else if (this.start_button_enter_key_listener.is_on()) {
console.log("Received 'Enter' keydown, using with start button");
this.view.get(EL.button_start).get_jq_element().click();
} else {
console.log(`Received '${event.key}' keydown, not handling`);
}
}
// Escape key
else if (event.key === 'Escape') {
if (this.view.get(EL.modal_dialogue).is_in_focus && this.modal_button_esc_key_listener.is_on()) {
this.view.get(EL.modal_dialogue).click_cancel();
} else {
console.log(`Received '${event.key}' keydown, not handling due to switch off.`)
}
} else {
// console.log(`Received '${event.key}' (which:${event.which}) keydown, not handled.`);
}
}
/**
* Handles the completion of a session.
*
* If the completed session is the last, it also closes the study, otherwise moves to
* the following session.
*
* TODO: consider whether to split it in two different functions.
* TODO: check if some parts of the code can be deduplicated.
*/
handle_session_complete() {
console.log("Session complete!");
this.view.get(EL.canvas_plot).enable_cursor();
const is_study_complete = (bs.is_null_or_undefined(this.model.get("settings")["max_sessions"]) === false &&
this.model.get("session") >= this.model.get("settings")["max_sessions"] - 1);
if (is_study_complete === false) {
// Session complete message
let message;
if (this.only_predictive.is_off()) {
message = (
`${this.get_session_number_text()} completed!\n` +
(
(this.model.get("settings")["session_score_as_max"] === true) ?
`Session max score: ${this.model.get("max_session_score")}\n` :
`Session score: ${this.model.get("session_score")}\n`
) +
"Press <Enter> (or click OK) to proceed to next session."
)
}
else {
message = (
`${this.get_session_number_text()} completed!\n` +
"Press <Enter> (or click OK) to proceed to next session."
)
}
this.view.get(EL.modal_dialogue).alert(
message,
$.proxy(function () {
// This allows resampling without user action
this.model.update("update_session", true);
// This is necessary because the last success function may be the caller of this function
if (this.ajax_lock.is_on()) this.ajax_lock.turn_off();
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.send_ajax_gp_sample_request();
console.log("Moving line cursor to last know position");
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.handle_canvas_mouse_move(this.mouse_pos);
}, this)
);
} else {
// Session complete message
let message;
if (this.only_predictive.is_off()) {
message = (
`Final session completed!\n` +
(
(this.model.get("settings")["session_score_as_max"] === true) ?
`Session max score: ${this.model.get("max_session_score")}\n` :
`Session score: ${this.model.get("session_score")}\n`
) +
MESSAGES.session_complete_text
)
}
else {
message = (
`Final session completed!\n` +
MESSAGES.session_complete_text
)
}
// Check and eventually close enabled modes
if (this.only_predictive.is_on()) {
this.only_predictive.turn_off();
}
if (this.predictive_mode.is_on()) {
this.predictive_mode.turn_off();
}
this.view.get(EL.modal_dialogue).alert(
message,
$.proxy(function () {
// Hide study related elements
this.view.get(EL.text_session_score).hide();
this.view.get(EL.text_current_score).hide();
this.view.get(EL.text_iteration_number).hide();
this.view.get(EL.text_session_number).hide();
this.view.get(EL.text_user_id).hide();
this.view.get(EL.div_canvas_container).hide();
this.view.get(EL.div_max_indicator_container).hide();
this.view.get(EL.div_cursor_line_left).hide();
this.view.get(EL.div_cursor_line_right).hide();
this.view.get(EL.div_cursor_line_top).hide();
this.view.get(EL.div_cursor_line_bottom).hide();
// Show interface elements
this.view.get(EL.text_title).show();
this.view.get(EL.button_start).show();
this.view.get(EL.text_question).set_text(MESSAGES.session_complete_text);
this.start_button_enter_key_listener.turn_on();
this.running_session.turn_off();
this.model.update("update_session", false);
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.reset();
}, this)
);
}
}
/**
* Handles the application start by displaying the initial UI elements.
*/
handle_start_application() {
// Show interface elements
this.view.get(EL.text_title).show();
this.view.get(EL.button_start).show();
this.view.get(EL.text_question).show();
}
/**
* Handles clicking on the start button.
*
* A modal dialogue appears prompting to input the name of the study to run.
*/
handle_start_button_click() {
if (this.canvas_click_listener.is_on()) {
this.canvas_click_listener.turn_off();
}
this.start_button_enter_key_listener.turn_off();
this.view.get(EL.modal_dialogue).prompt(
"Please, insert the current study code. Keep" +
" the default value if undecided.\n" +
"If you clicked by mistake, press Cancel.",
"default",
$.proxy(function (input) {
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.send_ajax_gp_sample_request(input);
console.log("Moving line cursor to last know position");
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.handle_canvas_mouse_move(this.mouse_pos);
}, this),
$.proxy(function () {
this.start_button_enter_key_listener.turn_on();
}, this)
);
}
/**
* Handles a browser window resize.
*
* If a session is running, it updates the canvas and its elements size, and redraws the plot.
*/
handle_window_resize() {
if (this.running_session.is_on()) {
clearTimeout(this.resize_timeout);
this.resize_timeout = setTimeout(
$.proxy(this.update_canvas_all(), this),
this.wait_time_before_resizing);
} else {
console.log("Window resize: nothing to regression_update because no session is running.");
}
}
/*===================================*
Category: Helper functions
/*===================================*/
/**
* Returns custom HTML text for displaying the session cumulative score.
*
* It retrieves the value from the model.
*
* @returns {string} - HTML rich text
*/
// noinspection JSMethodCanBeStatic
get_cumulative_session_score_rich_text() {
return `Session score:
<span class="session_score_value">
${this.model.get('session_score')}
</span>
points.`
}
/**
* Returns custom HTML text for displaying the current score.
*
* It retrieves the value from the model.
* The 'current' score is determined by the error of the previous iteration.
*
* @returns {string} - HTML rich text
*/
get_current_score_rich_text() {
return `Current score:
<span class="current_score_value">
${this.model.get('current_score')}
</span>
points.`;
}
/**
* Returns the current score computed from the current error.
*
* The score is inversely proportioned to the error and normalised as a percentage
* between the height of the max and that of the min.
* In this way the score for the min is 0 and that of the max is 100.
*
* TODO: check if this method can be merged with 'get_current_max_score_compute_from_smallest_error()' or simplified.
*
* @returns {number}
*/
get_current_score_compute_from_error() {
let y = this.model.get("y");
let scaling_value = this.model.get("scaling_value");
let error = this.model.get("error");
let min_y = np.list_min(y);
let max_y = np.list_max(y);
let farthest_distance = Math.abs(max_y - min_y) * scaling_value;
let scaled_error = error / farthest_distance * 100;
let score = Math.round(100 - scaled_error);
bs.assert(
Number.isNaN(score) === false,
"Error value is Nan. Involved variables:\n" +
`y: ${y}, ` +
`scaling_value: ${scaling_value}, ` +
`min_y: ${min_y}, ` +
`max_y: ${max_y}, ` +
`farthest_distance: ${farthest_distance}, ` +
`scaled_error: ${scaled_error}, ` +
`score: ${score}.`
);
return score;
}
/**
* Returns the current score computed from the current error.
*
* The score is inversely proportioned to the error and normalised as a percentage
* between the height of the max and that of the min.
* In this way the score for the min is 0 and that of the max is 100.
*
* TODO: check if this method can be merged with 'get_current_score_compute_from_error()' or simplified.
*
* @returns {number}
*/
get_current_max_score_compute_from_smallest_error() {
let y = this.model.get("y");
let scaling_value = this.model.get("scaling_value");
let error = this.model.get("smallest_error");
let min_y = np.list_min(y);
let max_y = np.list_max(y);
let farthest_distance = Math.abs(max_y - min_y) * scaling_value;
let scaled_error = error / farthest_distance * 100;
let score = Math.round(100 - scaled_error);
bs.assert(
Number.isNaN(score) === false,
"Error value is Nan. Involved variables:\n" +
`scaling_value: ${scaling_value}, ` +
`min_y: ${min_y}, ` +
`max_y: ${max_y}, ` +
`farthest_distance: ${farthest_distance}, ` +
`scaled_error: ${scaled_error}, ` +
`score: ${score},` +
`y: ${y}.`
);
return score;
}
/**
* Returns text for displaying the current iteration number.
*
* @returns {string}
*/
get_iteration_number_text() {
return `Iteration ${this.get_text_value_of_max_value(
this.model.get("iteration") + 1,
this.model.get("settings")["max_iterations"]
)}`;
}
/**
* Returns the error of the previous iteration using latest model data.
*
* The error is the difference between the height of the maximum and that of the
* point, computed using the visual space. This allows that the same visual
* distance produces the same error.
*
* TODO: check if this method can be merged with 'get_smallest_error_compute_from_data()' or simplified.
*
* @returns {number}
*/
get_last_error_compute_from_data() {
let y_max = np.list_max(this.model.get("y"));
bs.assert(Number.isNaN(y_max) === false);
let y_data_actual = this.model.get("y_data_actual");
if (bs.len(y_data_actual) === 0) return Number.POSITIVE_INFINITY;
let y_user_last = y_data_actual[bs.len(y_data_actual) - 1];
bs.assert(Number.isNaN(y_user_last) === false);
let scaling_value = this.model.get("scaling_value");
bs.assert(Number.isNaN(scaling_value) === false);
let scaled_y_max = y_max * scaling_value;
let scaled_y_user_last = y_user_last * scaling_value;
let error = scaled_y_max - scaled_y_user_last;
bs.assert(
Number.isNaN(error) === false,
"Error value is Nan. Involved variables:\n" +
`y_max: ${y_max}, ` +
`y_user_last: ${y_user_last}, ` +
`scaling_value: ${scaling_value}, ` +
`scaled_y_max: ${scaled_y_max}, ` +
`scaled_y_user_last: ${scaled_y_user_last}, ` +
`error: ${error}.`
);
return error;
}
/**
* Returns custom HTML text for displaying the session maximum score.
*
* It retrieves the value from the model.
*
* @returns {string} - HTML rich text
*/
get_max_session_score_rich_text() {
return `Session Max score:
<span class="session_score_value">
${this.model.get('max_session_score')}
</span>
points.`
}
/**
* Returns text for displaying the current iteration number.
*
* @returns {string}
*/
get_session_number_text() {
return `Session ${this.get_text_value_of_max_value(
this.model.get("session") + 1,
this.model.get("settings")["max_sessions"]
)}`;
}
/**
* Returns the smallest error using latest model data.
*
* The error is the difference between the height of the maximum and that of the
* point, computed using the visual space. This allows that the same visual
* distance produces the same error.
*
* This considers also the current point value!
*
* TODO: check if this method can be merged with 'get_last_error_compute_from_data()' or simplified.
*
* @returns {number}
*/
get_smallest_error_compute_from_data() {
let new_point_index = this.model.get("new_point_index");
let y = this.model.get("y");
let y_max = np.list_max(y);
bs.assert(Number.isNaN(y_max) === false);
let y_user_max = np.list_max(this.model.get("y_data_actual").concat(y[new_point_index]));
bs.assert(Number.isNaN(y_user_max) === false);
let scaling_value = this.model.get("scaling_value");
bs.assert(Number.isNaN(scaling_value) === false);
let scaled_y_max = y_max * scaling_value;
let scaled_y_user_max = y_user_max * scaling_value;
let error = scaled_y_max - scaled_y_user_max;
bs.assert(
Number.isNaN(error) === false,
"Error value is Nan. Involved variables:\n" +
`y_max: ${y_max}, ` +
`y_user_max: ${y_user_max}, ` +
`scaling_value: ${scaling_value}, ` +
`scaled_y_max: ${scaled_y_max}, ` +
`scaled_y_user_max: ${scaled_y_user_max}, ` +
`error: ${error}.`
);
return error;
}
// noinspection JSMethodCanBeStatic
/**
* Returns a text in the form "'value' of 'max_value'".
*
* This method is used by other functions to display text in this form.
*
* @param {number} value - the value or quantity of something
* @param {number|null} [max_value=null] - the maximum value or quantity of something
* @returns {string} in the form "'value' of 'max_value'".
*/
get_text_value_of_max_value(value, max_value = null) {
let value_str = `${value}`;
if (bs.is_null_or_undefined(max_value) === false) {
value_str += ` of ${max_value}`;
}
return value_str;
}
/**
* Returns text for displaying the user ID.
*
* Retrieves the value from the model.
*
* @returns {string}
*/
get_user_id_text() {
return `User ID: ${this.model.get("settings")["user_id"]}`;
}
/**
* Initialises the plotting utility computing the best box given the plot size and the data.
*
* The 'best box' is a concept pertaining the plotting library, which is used
* to draw the plot appropriately in the given canvas size.
*
* @param {boolean} [reinitialise=false] - Closes the current canvas before initialising it again.
*/
initialise_plot_with_best_box(reinitialise = false) {
let x = this.model.get("x");
let y = this.model.get("y");
let mean = this.model.get("mean");
let std = this.model.get("std");
let margin_x = this.model.get("margin_x");
let margin_y = this.model.get("margin_y");
if (reinitialise === true) plt.close();
// Initialises the canvas dictionary and generates the first rectangle
plt.open_canvas(
this.view.get(EL.canvas_plot).get_dom_element(),
null,
plt.get_best_box_lists([x], [y, mean, std], margin_x, margin_y)
);
}
/**
* Moves the horizontal line cursor on the canvas.
*
* This method is used at the beginning of the study and actually
* moves the cursors only if they are out of the canvas.
*/
move_horizontal_line_cursors_on_canvas() {
let canvas_jq = this.view.get(EL.canvas_plot).get_jq_element();
let cursor_line_left_jq = this.view.get(EL.div_cursor_line_left).get_jq_element();
let cursor_line_right_jq = this.view.get(EL.div_cursor_line_right).get_jq_element();
// Make the cursor line be on the canvas
if (cursor_line_left_jq.offset().top > canvas_jq.offset().top + canvas_jq.height()) {
console.log("Found line cursors out of canvas..");
console.log("canvas-top:", canvas_jq.offset().top, "canvas_jq.height():", canvas_jq.height(),
"cursor_line_left_jq.offset().top:", cursor_line_left_jq.offset().top);
cursor_line_left_jq.css('top', canvas_jq.offset().top + canvas_jq.height() - cursor_line_left_jq.height());
cursor_line_right_jq.css('top', canvas_jq.offset().top + canvas_jq.height() - cursor_line_left_jq.height());
}
}
/**
* Sends an ajax post request.
*
* It disables ajax calling until the success function is finished.
*
* @param {string} url - url string of the api
* @param {Object} ajax_data - a data dictionary
* @param {function} success_function - function to be called on success
*
* @override super.send_ajax_and_run
*
*/
send_ajax_and_run(url, ajax_data, success_function) {
if (this.ajax_lock.is_on() === true) {
console.warn("Send ajax and run: not calling api because already waiting a previous response.");
return;
} else {
// Other processes cannot use ajax
this.ajax_lock.turn_on();
}
let inner_success_function = function (response) {
if (this.ajax_lock.is_on()) {
this.ajax_lock.turn_off();
} else {
console.warn("Found lock unexpectedly off.");
}
success_function(response);
};
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: {'ajax_data': JSON.stringify(ajax_data)},
success: $.proxy(inner_success_function, this),
global: true
});
}
/**
* Shows or hides the exploration text.
*
* It checks whether to show the text based on settings and
* on which session we are on. It also displays a modal
* to ler the user to exploit from some point on.
*/
show_explore_or_exploit_text() {
// If exploration session is defined, check if it's appropriate to show it
if (bs.is_null_or_undefined(this.model.get("settings")["exploration_sessions"]) === false) {
if (this.model.get("session") < this.model.get("settings")["exploration_sessions"]) {
/**
* @type interface_elements.Text
*/
this.view.get(EL.text_explore).set_text("Practice Sessions");
this.view.get(EL.text_explore).show();
} else {
if (this.model.get("session") === this.model.get("settings")["exploration_sessions"]) {
this.view.get(EL.modal_dialogue).alert(
MESSAGES.practice_complete_text,
$.proxy(function () {
console.log("Moving line cursor to last know position");
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.handle_canvas_mouse_move(this.mouse_pos);
}, this)
);
}
this.view.get(EL.text_explore).hide();
}
} else {
console.log("No key for exploration sessions..")
}
}
/**
* When using the predictive mode, it returns to a normal state.
*
* It disables variables related to predictive mode and hides its related elements.
* At the same time it also shows the elements of the normal mode (i.e. y estimation).
*/
switch_out_of_predictive_mode() {
this.predictive_mode.turn_off();
this.view.get(EL.div_cursor_line_top).hide();
this.view.get(EL.div_cursor_line_left).show();
this.view.get(EL.div_cursor_line_right).show();
this.view.get(EL.text_question).fadeOut(50,
$.proxy(function () {
this.view.get(EL.text_question).set_text(MESSAGES.in_session_select_height);
}, this)
);
this.view.get(EL.text_question).fadeIn(50);
this.update_canvas_all();
}
/**
* When in normal mode, it enables the predictive mode.
*
* It enables variables related to predictive mode and shows its related elements.
* At the same time it also hides the elements of the normal mode (i.e. y estimation).
*
*/
switch_to_predictive_mode() {
this.predictive_mode.turn_on();
this.view.get(EL.div_cursor_line_top).show();
this.view.get(EL.div_cursor_line_left).hide();
this.view.get(EL.div_cursor_line_right).hide();
this.view.get(EL.text_question).fadeOut(50,
$.proxy(function () {
this.view.get(EL.text_question).set_text(MESSAGES.in_session_select_x_prediction);
}, this)
);
this.view.get(EL.text_question).fadeIn(50);
this.update_canvas_all();
}
/**
* Wrapper to regression_update the plot, the canvas and its related elements in a single call.
*/
update_canvas_all() {
this.update_canvas_size();
this.update_canvas_elements();
this.update_canvas_plot();
}
/**
* Redraws the plot and updates the scaling value in the model.
*
* It expects the canvas to have been already initialised.
*/
update_canvas_plot() {
console.log("update_canvas_plot");
let x = this.model.get("x");
let new_point_x = this.model.get("new_point_x");
let y = this.model.get("y");
let mean = this.model.get("mean");
let std = this.model.get("std");
let std_low = std.slice(0, std.length / 2);
let std_high = std.slice(std.length / 2, std.length);
let x_data = this.model.get("x_data");
let y_data = this.model.get("y_data");
// Initialise or clear the canvas
if (plt.is_canvas_open() === false) {
console.warn("Found canvas uninitialised!");
this.initialise_plot_with_best_box();
} else {
plt.clear();
}
let is_ucb_to_display = this.model.get("settings")["display_uncertainty"];
if (is_ucb_to_display !== false) {
plt.fill(x, std_low, std_high, null, "#d8ecff");
}
plt.plot(x, mean, "dashed", "blue");
// Look-ahead visualisations
if (bs.is_not_null_or_undefined(this.model.get("settings")["show_lookahead"]) &&
this.model.get("settings")["show_lookahead"] === true) {
let look_ahead_upper_confidence = this.model.get("look_ahead_upper_confidence");
let look_ahead_lower_confidence = this.model.get("look_ahead_lower_confidence");
let look_ahead_query_index = this.model.get("look_ahead_query_index");
let upboosted_points = this.model.get("upboosted_points");
let downboosted_points = this.model.get("downboosted_points");
console.log("upboosted_points:", upboosted_points);
console.log("downboosted_points:", downboosted_points);
let y_max = np.list_max(y) + 0.8;
let y_min = np.list_min(y) - 0.8;
// Makes a list of size n of elements of value val
let f_list = function(n, val) {
let new_array = [];
for (let i = 0; i < n; i ++){ new_array.push(val) }
return new_array;
};
let mean_lookahead = this.model.get("look_ahead_gp_mean");
plt.plot(x, look_ahead_upper_confidence, "dashed", "green");
plt.plot(x, look_ahead_lower_confidence, "dashed", "green");
plt.plot(x, mean_lookahead, null, "green");
plt.scatter(upboosted_points, f_list(bs.len(upboosted_points), y_max), null, "#58D68D");
plt.scatter(downboosted_points, f_list(bs.len(downboosted_points), y_min), null, "#FF5733");
if (look_ahead_query_index !== -1) {
plt.vline(x[look_ahead_query_index], null, "#0d7814");
}
}
plt.plot(x, y, null, "black");
if (this.predictive_mode.is_off()) {
plt.vline(new_point_x, null, "orange");
}
if (this.model.get("settings")["session_score_as_max"] === true)
{
// Make a copy to avoid errors
let y_data_actual = [...this.model.get("y_data_actual")];
let new_point_index = this.model.get("new_point_index");
y_data_actual.push(y[new_point_index]);
// It's always true but we keep it for possible future modifications
if (bs.len(y_data_actual) > 0) {
let max_y_data_actual_index = np.list_argmax(y_data_actual);
// Make a copy to avoid errors
let x_data_plus_new = [...this.model.get("x_data")];
x_data_plus_new.push(x[new_point_index]);
let max_y_data_actual = y_data_actual[max_y_data_actual_index];
let x_where_max_y_data_actual = x_data_plus_new[max_y_data_actual_index];
plt.scatter([x_where_max_y_data_actual], [max_y_data_actual], 10, "red");
}
}
plt.scatter(x_data, y_data, null, "orange");
plt.show();
// Get a scaling value
let scaling_value = plt.get_canvas_dict().get_current_vertical_scaling_value_to_visual_space();
this.model.update("scaling_value", scaling_value);
}
/**
* Updates size and position of canvas elements to match size nd position updates.
*/
update_canvas_elements() {
console.log("update_canvas_elements");
if (plt.is_canvas_open() === false) {
console.warn("Canvas found uninitialised.");
this.initialise_plot_with_best_box();
}
let margin_around_point = 5; // px
let canvas_jq = this.view.get(EL.canvas_plot).get_jq_element();
let div_canvas_container = this.view.get(EL.div_canvas_container).get_jq_element();
let cursor_line_left_jq = this.view.get(EL.div_cursor_line_left).get_jq_element();
let cursor_line_right_jq = this.view.get(EL.div_cursor_line_right).get_jq_element();
let cursor_line_top_jq = this.view.get(EL.div_cursor_line_top).get_jq_element();
let cursor_line_bottom_jq = this.view.get(EL.div_cursor_line_bottom).get_jq_element();
let max_indicator_jq = this.view.get(EL.div_max_indicator_container).get_jq_element();
let limit_square = plt.get_canvas_dict().limit_square;
let usable_width = canvas_jq.width(); // TODO: may not work if proportional is enabled, check plt.cx for details
let left_canvas_offset = this.view.get(EL.canvas_plot).get_jq_element().offset()["left"];
let top_canvas_offset = this.view.get(EL.canvas_plot).get_jq_element().offset()["top"];
console.log("Left canvas offset:", left_canvas_offset);
bs.assert_type(left_canvas_offset, bs.TYPE_NUMBER);
if (left_canvas_offset === 0) console.warn("Canvas left offset found to be 0!");
console.log("Left canvas offset:", left_canvas_offset);
// Set the container to have the same size as the canvas
div_canvas_container.height(canvas_jq.height());
div_canvas_container.width(canvas_jq.width());
// Get the visual position of the chosen point by document coordinates
let relative_new_x = plt.cx(
usable_width,
[this.model.get("new_point_x")],
limit_square.x_min(),
limit_square.x_max())[0];
bs.assert_type(relative_new_x, bs.TYPE_NUMBER);
// Set the initial position and sizes for the line cursors
// Horizontal
cursor_line_left_jq.css('left', left_canvas_offset);
// cursor_line_right_jq.css('left', left_canvas_offset);
cursor_line_left_jq.css('width', relative_new_x - margin_around_point);
cursor_line_right_jq.css('left', relative_new_x + margin_around_point + cursor_line_left_jq.offset().left);
cursor_line_right_jq.css('width', canvas_jq.width() - (relative_new_x + margin_around_point));
// Vertical
cursor_line_top_jq.css('top', top_canvas_offset);
cursor_line_top_jq.css('height', canvas_jq.height());
// Compute the function maximum and move the max indicator
let fun_argmax = np.list_argmax(this.model.get("y"));
bs.assert_type(fun_argmax, bs.TYPE_NUMBER);
let x_max = this.model.get("x")[fun_argmax];
bs.assert_type(x_max, bs.TYPE_NUMBER);
let relative_x_max = plt.cx(usable_width, [x_max], limit_square.x_min(), limit_square.x_max())[0];
bs.assert_type(relative_x_max, bs.TYPE_NUMBER);
max_indicator_jq.css("margin-left", relative_x_max - ((max_indicator_jq.width() / 2)));
}
/**
* Updates the canvas size according to viewport size and rounds its position.
*
* Position rounding is useful for better precision in detecting mouse positioning
* when the user provides a feedback.
*
* TODO: consider splitting size regression_update from position rounding
*/
update_canvas_size() {
console.log("Adapting canvas size..");
let canvas_plot = this.view.get(EL.canvas_plot);
let left_canvas_offset = canvas_plot.get_dom_element().offsetLeft;
let window_width = document.documentElement.clientWidth;
let canvas_position;
if (canvas_plot.get_dom_element().height !== 400) {
console.warn(`Found plot to be ${canvas_plot.get_dom_element().height}px high when 400px was expected!`);
// TODO: why is it required to set it up here? If removed it glitches the canvas!
canvas_plot.get_dom_element().height = 400;
}
// Adapts the width of the canvas to that of the window
canvas_plot.get_dom_element().width = window_width - (2 * left_canvas_offset);
// TODO: can we do something similar in CSS? Is this hackish?
// TODO: if we keep it, it's a good idea to move it to a CSS_override.js script
// Override the jquery height/width using the dom element height/width
// canvas_plot.get_jq_element().css('height', canvas_plot.get_dom_element().height);
// canvas_plot.get_jq_element().css('width', canvas_plot.get_dom_element().width);
// Position canvas to have round position numbers.
// This is important to obtain appropriate conversion values.
canvas_position = canvas_plot.get_jq_element().offset();
console.log(`\tCanvas position before rounding - Top: ${canvas_position.top}px, Left: ${canvas_position.left}px`);
// noinspection JSSuspiciousNameCombination
canvas_plot.get_jq_element().offset({
top: Math.round(canvas_position.top),
left: Math.round(canvas_position.left)
});
canvas_position = canvas_plot.get_jq_element().offset();
console.log(`\tCanvas position after rounding - Top: ${canvas_position.top}px, Left: ${canvas_position.left}px`);
// Center the max indicator by moving its left margin
console.log("Adapting canvas size.. Completed!");
}
/*===================================*
Category: Request senders
/*===================================*/
/**
* Sends a request to the server for a new GP function sample.
*
* @param {string|null} input_dialogue_value - the name of the study to run. It needs to be a non-empty string.
*/
send_ajax_gp_sample_request(input_dialogue_value = null) {
let study_settings_name;
let keep_current_study = this.model.get("update_session");
if (keep_current_study === true) {
// When advancing from the previous session, keep the same settings-name without any dialogue
study_settings_name = this.model.get("settings")["settings_name"];
} else {
study_settings_name = input_dialogue_value;
if (bs.is_null_or_undefined(study_settings_name) || study_settings_name === "") {
// The user pressed cancel, do not start the session
console.log("Input dialog value was null or undefined or an empty string.");
if (study_settings_name === "") {
this.view.get(EL.text_question).set_text(
"An empty string is not a valid study name. " + MESSAGES.press_start_message
);
}
this.start_button_enter_key_listener.turn_on();
return;
} else {
// Start a new session
this.running_session.turn_on();
console.log("Session turned on!");
}
}
// Ajax data to send to the server
let ajax_data = {
"settings_name": study_settings_name,
"update_session": this.model.get("update_session")
};
// If we are in a multi-session study, it provides some additional arguments
let update_sampling = (this.model.get("session", false) !== undefined && keep_current_study === true);
// Extra arguments needed to avoid the server assigning new session and user values
if (update_sampling) {
ajax_data["session"] = this.model.get("session");
ajax_data["user_id"] = this.model.get("settings")["user_id"];
}
this.send_ajax_and_run(
"api_initialise_gp_and_sample",
ajax_data,
$.proxy(this.handle_api_sample_success_response, this));
}
/**
* Sends the user feedback with the model to the server. The server should then regression_update its posterior.
*
* @param {MouseEvent} event - The mouse click event
* @param {Number} event.pageX - The X coordinate of the mouse pointer relative to the whole document.
* @param {Number} event.pageY - The Y coordinate of the mouse pointer relative to the whole document.
* @param {Number} click_time - The exact time the canvas has been clicked.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
*/
send_user_click_for_x_prediction(event, click_time) {
// Get the current mouse position relatively to the canvas.
const [mouse_x, mouse_y] = this.view.get(EL.canvas_plot).get_mouse_relative_position(
event.pageX,
event.pageY,
true
);
// Get a the mouse coordinates in the plot reference system, we only care about the x
let mouse_as_plot_coordinates = plt.get_values_from_pixels_to_coordinates(new plt.Point([mouse_x, mouse_y]));
// Add the y-value selected by the user to the data
this.model.update_by_push("x_prediction", mouse_as_plot_coordinates.x);
// Add the click time to the model
this.model.update_by_push("iteration_click_time_x_prediction", click_time);
// If only-predictive, use actual point as user feedback
if (this.only_predictive.is_on()) {
// Add the currently queried x point to the model
let new_point_index = this.model.get("new_point_index");
this.model.update_by_push("x_data", this.model.get("x")[new_point_index]);
// Add the correct y value (i.e. y = f(x))
this.model.update_by_push("y_data_actual", this.model.get("y")[new_point_index]);
// Add the correct y value (i.e. y = f(x)) as if it was selected by the user
this.model.update_by_push("y_data", this.model.get("y")[new_point_index]);
// Add the user error on maximisation
this.model.update("error", this.get_last_error_compute_from_data());
}
let data = this.model.data_dict;
// Don't keep the mode if not necessary
if (this.only_predictive.is_off()) {
this.switch_out_of_predictive_mode();
this.send_ajax_and_run(
"api_update_gp",
JSON.parse(JSON.stringify(data)),
$.proxy(this.handle_api_update_gp_success_response, this)
);
// this.update_canvas_all();
// // Check if the session is finished and eventually trigger its corresponding event
// if (this.model.get("iteration") >= this.model.get("settings")["max_iterations"]) {
// this.handle_session_complete();
// }
// else {
// this.canvas_click_listener.turn_on();
// console.log("Updated iteration:", this.get_iteration_number_text());
// this.view.get(EL.text_iteration_number).set_text(this.get_iteration_number_text());
// }
}
else {
this.send_ajax_and_run(
"api_update_gp",
JSON.parse(JSON.stringify(data)),
$.proxy(this.handle_api_update_gp_success_response, this)
);
}
}
/**
* Sends the user feedback with the model to the server. The server should then regression_update its posterior.
*
* @param {MouseEvent} event - The mouse click event
* @param {Number} event.pageX - The X coordinate of the mouse pointer relative to the whole document.
* @param {Number} event.pageY - The Y coordinate of the mouse pointer relative to the whole document.
* @param {Number} click_time - The exact time the canvas has been clicked.
* See more on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
*/
send_user_click_for_y_position(event, click_time) {
// Get the current mouse position relatively to the canvas.
const [mouse_x, mouse_y] = this.view.get(EL.canvas_plot).get_mouse_relative_position(
event.pageX,
event.pageY,
true
);
// Get a the mouse coordinates in the plot reference system, we only care about the y
let mouse_as_plot_coordinates = plt.get_values_from_pixels_to_coordinates(new plt.Point([mouse_x, mouse_y]));
// Add the click time to the model
this.model.update_by_push("iteration_click_time_y_estimation", click_time);
// Add the currently queried x point to the model
let new_point_index = this.model.get("new_point_index");
this.model.update_by_push("x_data", this.model.get("x")[new_point_index]);
// Add the correct y value (i.e. y = f(x))
this.model.update_by_push("y_data_actual", this.model.get("y")[new_point_index]);
// Add the y-value selected by the user to the data
this.model.update_by_push("y_data", mouse_as_plot_coordinates.y);
// Add the user error on maximisation
this.model.update("error", this.get_last_error_compute_from_data());
console.log("scaling_value at click time before canvas regression_update:", this.model.get("scaling_value"));
// Redraw the canvas for user feedback
this.update_canvas_plot();
let data = this.model.data_dict;
console.log("scaling_value at click time after canvas regression_update:", this.model.get("scaling_value"));
// Enable predictive mode if settings ask so
if (this.model.get("settings")["predictive_mode"] === true) {
this.canvas_click_listener.turn_on();
this.switch_to_predictive_mode();
this.update_canvas_all();
}
else {
this.send_ajax_and_run(
"api_update_gp",
JSON.parse(JSON.stringify(data)),
$.proxy(this.handle_api_update_gp_success_response, this)
);
}
}
} |
JavaScript | class NewsPublisherSearchByNameData {
/**
* Constructs a new <code>NewsPublisherSearchByNameData</code>.
* The data member contains the request's primary data.
* @alias module:model/NewsPublisherSearchByNameData
* @param searchValue {String} Restricts the search to publishers, which match the search value. The comparison for a match is case sensitive.
* @param matchType {module:model/NewsPublisherSearchByNameData.MatchTypeEnum} The match type that is applied to the search.
*/
constructor(searchValue, matchType) {
NewsPublisherSearchByNameData.initialize(this, searchValue, matchType);
}
/**
* 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, searchValue, matchType) {
obj['searchValue'] = searchValue;
obj['matchType'] = matchType;
}
/**
* Constructs a <code>NewsPublisherSearchByNameData</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/NewsPublisherSearchByNameData} obj Optional instance to populate.
* @return {module:model/NewsPublisherSearchByNameData} The populated <code>NewsPublisherSearchByNameData</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new NewsPublisherSearchByNameData();
if (data.hasOwnProperty('searchValue')) {
obj['searchValue'] = ApiClient.convertToType(data['searchValue'], 'String');
}
if (data.hasOwnProperty('matchType')) {
obj['matchType'] = ApiClient.convertToType(data['matchType'], 'String');
}
if (data.hasOwnProperty('filter')) {
obj['filter'] = NewsPublisherSearchByNameDataFilter.constructFromObject(data['filter']);
}
}
return obj;
}
} |
JavaScript | class Modal extends Component {
initialize (options) {
this.options = {};
this.options.klass = options.klass || false;
this.content = options.content;
this.el.removeAttribute('content');
this.el.classList.add('uniformModal');
this.listenTo(document, 'keyup', this.keyup);
this.listenTo(this.el, 'click', this.checkCloseButton);
}
keyup (e) {
if(e.which != 27) return;
this.close();
}
render () {
var that = this;
this.highest_z_index = 0;
this.overlay = createElement('div', {class: 'uniformModal-overlay'});
this.blur = createElement('div', {class: 'uniformModal-blur'});
this.original_scroll = window.scrollY;
this.blur.style.top = 0 - this.original_scroll + "px";
if (document.body.querySelectorAll('.uniformModal').length > 0) {
this.highest_z_index = Math.max(Array.prototype.map.call(document.body.querySelectorAll('.uniformModal'), function(el){
return parseInt(css(el, 'zIndex'));
}));
this.el.style.zIndex = this.highest_z_index + 2;
}
let next_element = document.body.children[0]
while(next_element){
const element = next_element;
next_element = element.nextElementSibling;
if(!element.matches('[blurrable="false"]')) {
this.blur.appendChild(element)
}
}
document.body.classList.add('uniformModal-active');
document.body.appendChild(this.blur);
document.body.appendChild(this.el);
this.el.style.top = window.scrollY;
this.listenTo(this.overlay, 'click', this.close);
const container = createElement('div', {
class: 'uniformModal-container',
children: this.content
});
const closeButton = createElement('div', {
class: 'uniformModal-close-container',
children: {
class: 'uniformModal-close'
}
});
this.el.append(this.overlay);
this.el.append(container);
this.el.append(closeButton);
if (this.options.klass) container.classList.add(this.options.klass);
if (this.content.innerHTML) trigger(this.content, 'rendered');
this.trigger('rendered');
return this;
}
checkCloseButton (e) {
if(e.target.classList.contains('uniformModal-close')){
this.close();
}
}
close () {
document.querySelectorAll('uniformModal-active').forEach(el => el.classList.remove('uniformModal-active'));
var elements = this.blur.children;
var elementCount = elements.length
for(var i=0; i < elementCount; i++){
document.body.appendChild(elements[0]);
}
if(this.blur.parentNode) this.blur.parentNode.removeChild(this.blur);
window.scrollTo(0, this.original_scroll);
this.trigger('closed');
this.remove();
}
remove () {
Component.prototype.remove.apply(this, arguments);
if(this.overlay && this.overlay.parentNode) this.overlay.parentNode.removeChild(this.overlay);
delete this.overlay;
}
} |
JavaScript | class Office {
/**
* Create office(admin)
* @param {Values} req - request values into keys
* @param {Object} res - request object
* @returns {array} - returns all key value pairs as object in array
*/
static async create(req, res) {
if (!req.body.type && !req.body.name) {
return res.status(400).send({
status: 400,
error: "Inputs fields can't be left empty",
});
}
if (!req.body.type) {
return res.status(400).send({
status: 400,
error: 'Type field is empty',
});
}
if (!req.body.name) {
return res.status(400).send({
status: 400,
error: 'Name field is empty',
});
}
if (!userAuthHelper.isName(req.body.name, req.body.type)) {
return res.status(400).send({
status: 400,
error: 'Alphabets only',
});
}
// if (!userAuthHelper.isHigher(req.body.name, req.body.type)) {
// return res.status(400).send({
// "status": 400,
// "error": "Alphabets only"
// })
// };
const check = 'SELECT * FROM office WHERE name=$1';
const { name } = req.body;
const result = await db.query(check, [name]);
if (result.rowCount !== 0) {
return res.status(400).send({
status: 400,
error: 'Office already exist',
});
}
const createQuery = `INSERT INTO
office(id, name, type, created_date)
VALUES($1, $2, $3, $4)
returning *`;
const values = [
uuidv4(),
req.body.name,
req.body.type,
moment(new Date()),
];
try {
// const result = await db.query(query);
// if (result.row !== 0) {
// return res.status(400).json({
// status: 400,
// error: 'An office with this name already exist',
// });
// }
const { rows } = await db.query(createQuery, values);
return res.status(201).send({
status: 201,
data: [{
message: 'office created',
order: rows[0],
}],
});
} catch (error) {
return res.status(500).send({
status: 400,
data: 'There was an error, please try again.',
});
}
}
/**
* get all political offices(users)
* @param {uuid} id
* @param {Object} res - request object
* @returns {array} - returns all key value pairs as object in array
*/
static async getAllOffices(req, res) {
const findAllQuery = 'SELECT * FROM office';
try {
const { rows, rowCount } = await db.query(findAllQuery);
// return rows;
return res.status(200).json({
status: 200,
data: rows,
rowCount,
});
} catch (error) {
return res.status(400).send({
status: 400,
error: 'Bad Request',
});
}
}
/**
* User fetch specific office
* @param {uuid} id
* @param {Object} res - request object
* @returns {array} - returns specific party
*/
static async getOneOffice(req, res) {
const text = 'SELECT * FROM office WHERE id = $1';
try {
const { rows } = await db.query(text, [req.params.id]);
if (!rows[0]) {
return res.status(404).send({
status: 404,
error: 'Office not found',
});
}
if (!userAuthHelper.isUUID(req.params)) {
return res.status(400).send({
status: 400,
error: 'The user ID used is invalid',
});
}
return res.status(200).send({
status: 200,
data: rows[0],
});
} catch (error) {
return res.status(400).send({
status: 400,
error: 'Bad request. Check and try again',
});
}
}
/**
*
* @param {*} request
* @param {*} response
* @return promise;
*/
static async officeResult(req, res) {
const { officeid } = req.params;
if (!userAuthHelper.isUUID(officeid)) {
return res.status(400).send({
status: 400,
error: 'The user ID used is invalid',
});
}
const text = 'SELECT * FROM office WHERE id = $1';
const { rows } = await db.query(text, [officeid]);
if (!rows[0]) {
return res.status(404).send({
status: 404,
error: 'Office not found',
});
}
const text2 = 'SELECT *, COUNT(candidate) FROM votes WHERE office = $1 GROUP BY id, created_on, created_by, officename, office, candidatename, username, candidate';
const row = await db.query(text2, [officeid]);
console.log(row, '>>>>>>><<<<<<<<');
const pollResult = [];
for (let i = 0; i < row.rows.length; i += 1) {
const singleResult = {
office: officeid,
candidate: row.rows[0].candidate,
username: row.rows[0].username,
candidatename: row.rows[0].candidatename,
officename: row.rows[0].officename,
result: Number(row.rows[i].count),
};
pollResult.push(singleResult);
}
const response = {
status: 200,
data: pollResult,
};
// console.log(response);
return res.status(200).send(response);
}
// eslint-disable-next-line class-methods-use-this
catch(error, res) {
return res.status(500).send({
status: 500,
error,
});
}
static async delete(req, res) {
const deleteQuery = 'DELETE FROM office WHERE id=$1 returning *';
try {
const { rows } = await db.query(deleteQuery, [req.params.id]);
if (!rows[0]) {
return res.status(404).send({
error: 404,
message: 'office not found',
});
}
return res.status(410).send({
data: 'deleted',
});
} catch (error) {
// console.log(error);
return res.status(400).send({
error: 'Oops, something wrong happened. Check and try again',
});
}
}
} |
JavaScript | class WidgetsScout extends Component {
constructor(props) {
super(props);
this.state = {
images: [scountimage1, scountimage2, scountimage3, scountimage4, scountimage5, scountimage6],
imgCur: 0,
}
}
// for image change when click
onClickScout(e){
this.setState({imgCur: e});
}
render() {
return (
<section className="features-area saas-features ptb-100 pb-0">
<div className="features-inner-area">
<div className="section-title">
<h2>Elevate your content with these sensational widgets</h2>
<div className="bar"></div>
<p>Weather, news, traffic, video & more</p>
</div>
<div className="container">
<div className="row h-100 justify-content-center align-items-center">
<div className="col-lg-6 col-md-12">
<div className="features-image">
<img src={this.state.images[this.state.imgCur]} alt="image" />
</div>
</div>
<div className="col-lg-6 col-md-12">
<div className="scout-item" onClick={e => this.onClickScout(0)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/enca.png')} alt="scout" />
</div>
<div className="scout-item" onClick={e => this.onClickScout(1)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/Foreign exchange.png')} alt="scout" />
</div>
<div className="scout-item" onClick={e => this.onClickScout(2)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/News 24.png')} alt="scout" />
</div>
<div className="scout-item" onClick={e => this.onClickScout(3)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/Socail account.psd.png')} alt="scout" />
</div>
<div className="scout-item" onClick={e => this.onClickScout(4)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/Traffic.png')} alt="scout" />
</div>
<div className="scout-item" onClick={e => this.onClickScout(5)} style={{"cursor": "pointer"}}>
<img src={require('../../images/widgets/scouticons/Weather.png')} alt="scout" />
</div>
</div>
</div>
</div>
</div>
</section>
);
}
} |
JavaScript | class Stack extends State {
/**
* Create a {@link Stack} instance.
* @param {Array} [list=[]] Genesis state for the {@link Stack} instance.
* @return {Stack} Instance of the {@link Stack}.
*/
constructor (list = []) {
super(list);
this.limit = MAX_MEMORY_ALLOC;
this.frame = Buffer.alloc(MAX_FRAME_SIZE);
this.config = list || [];
// Patch for new Collection inheritance
this.settings = Object.assign({
verbosity: 2
}, list);
this['@type'] = this.config['@type'];
this['@entity'].frames = {};
this['@entity'].states = {};
this['@states'] = {};
this['@data'] = [];
if (list instanceof Array) {
for (let i in list) {
this.push(list[i]);
}
}
this['@entity']['@type'] = this['@type'];
this['@entity']['@data'] = this['@data'];
this['@id'] = this.id;
return this;
}
get size () {
return this['@data'].length;
}
/**
* Push data onto the stack. Changes the {@link Stack#frame} and
* {@link Stack#id}.
* @param {Mixed} data Treated as a {@link State}.
* @return {Number} Resulting size of the stack.
*/
push (data) {
let state = new State(data);
this['@entity'].states[this.id] = this['@data'];
this['@entity'].states[state.id] = state['@data'];
this['@entity'].frames[this.id] = this['@data'];
this['@entity'].frames[state.id] = state['@data'];
// write the frame
// NOTE: no garbage collection
this.frame = Buffer.from(state.id);
// push frame onto stack
this['@data'].push(this.frame);
this['@type'] = 'Stack';
this['@size'] = this['@data'].length * MAX_FRAME_SIZE;
this.commit();
return this['@data'].length;
}
dedupe () {
return new Stack([...new Set(this.asArray())]);
}
pop () {
let element = this['@data'].pop();
return element;
}
asArray () {
return Array.from(this['@data']);
}
asMerkleTree () {
return new MerkleTree(this.asArray(), this.sha256, {
isBitcoinTree: true
});
}
snapshot () {
return this.id || { '@id': `${this.sha256(this.state['@data'])}` };
}
commit () {
let stack = this;
let changes = super.commit();
if (changes.length) {
let data = Object.assign({}, {
parent: stack.tip,
changes: changes
});
stack.state['@data'] = data;
stack.history.push(stack.state.id);
}
// TODO: return Transaction
return changes;
}
} |
JavaScript | class Callable {
/**
* #### Alternative constructors
*
* When registering ({@link Bot#register}) a {@link Handler} or constructing
* a {@link Requirement}, you can also make use of alternative constructor
* signatures:
* ```
* // (object)
* new Callable({
* name: 'testCallable',
* callable: (done, processor) => {},
* options: { verbose: true }
* });
* ```
* ```
* // (name, callable, requires)
* new Callable('testCallable', (done, processor) => {}, []);
* ```
* ```
* // (namedFunction, requires)
* new Callable(function testCallable(done, processor) {});
* ```
*
* #### **1**. `(object)` - Object constructor
* #### **2**. `(callable, [requires])` - Named function constructor
* #### **3**. `(name, callable, [requires])` - Function constructor
*
* @param {object|Function|string} object Object, Callable
* function with name, or
* Callable's name
* @param {string} object.name Callable's name
* @param {Callable~callable} object.callable Callable function
* @param {Requirement[]} [object.requires] Requirements
* @param {Requirement[]|Function} callable Array of Requirements
* or Callable
* @param {Requirement[]} [requires] Array of Requirements
*
*/
constructor(object = {}, callable, requires) {
if (typeof object === 'string' && callable instanceof Function) {
// new Callable('testCallable', (data) => {})
object = { name: object, callable, requires };
} else if (object instanceof Function && object.name) {
// new Callable(function testCallable, (data) => {})
object = { name: object.name, callable: object, requires: callable };
}
// Check if essential parameters are unusable and throw Error
this.setName(object.name);
if (!object.callable || !(object.callable instanceof Function)) {
throw new Error(this.constructor.name +
' needs to have a valid callable!');
}
// Use all passed properties, no matter if valid or not
Object.assign(this, object);
// Correct wrong values
this.name = camelCase(object.name);
this.setCallable(object.callable);
if (!this.requires) this.requires = [];
else if (!(this.requires instanceof Array)) this.requires = [this.requires];
// flattens the requires tree to this.requirements
this.prepareRequirements();
}
/**
* Flattens the Callback's requires tree to this.requirements
*
* @param {Callable} [object] Object that might have `requires` node
*/
prepareRequirements(object) {
if (!object) this.requirements = [];
const requires = object ? object.requires : this.requires;
if (requires) {
for (let i = 0; i < requires.length; i++) {
const requirement = requires[i];
// if may be required multiple times or
// has not been added to the requirements until then
if ((requirement.options && requirement.options.multiple)
|| !this.requirements.includes(requirement)) {
// recursively get requirements of requirements
this.prepareRequirements(requirement);
this.requirements.push(requirement);
}
}
}
}
/** @private */
setCallable(callable) {
if (callable instanceof Function) {
this.callable = callable;
} else {
throw new TypeError('Callable must be a function!');
}
}
setName(name) {
if (!name) {
throw new Error(`${this.constructor.name} needs to have a name!`);
} else if (typeof name !== 'string') {
throw new Error(`${this.constructor.name}'s name needs to be a string!`);
}
this.name = name;
}
} |
JavaScript | class Token {
constructor(id, user, validUntil) {
this.id = id;
this.user = user;
this.validUntil = validUntil;
}
} |
JavaScript | class History extends AbstractService {
constructor (container, serviceName = 'History') {
super(container, serviceName)
debug(`☕️ ${serviceName} awake`)
/**
* Keep track of the status in historic order.
*
* @readOnly
* @type {Array}
*/
this.history = []
}
/**
* Add a new set of url and namespace.
*
* @param {String} url
* @param {String} transitionName
* @param {String} context (ajax, history)
* @param {Object} data (optional data)
*
* @return {Object}
*/
add (url, transitionName, context, data = {}) {
const state = { url, transitionName, context, data }
this.history.push(state)
return state
}
/**
* Return information about the current status.
*
* @return {Object}
*/
currentStatus () {
return this.history[this.history.length - 1]
}
/**
* Return information about the previous status.
*
* @return {Object}
*/
prevStatus () {
const history = this.history
if (history.length < 2) { return null }
return history[history.length - 2]
}
} |
JavaScript | class QR {
/**
* Create a new instance of QR.
* @param typeNumber 0 to 40, 0 means autodetect
* @param errorCorrectLevel 'L','M','Q','H'
*/
constructor(typeNumber = 6, errorCorrectLevel = errorCorrectLevel_1.ErrorCorrectLevel.L) {
if (!numberHelper_1.NumberHelper.isInteger(typeNumber) || typeNumber < 0 || typeNumber > 40) {
throw Error("The typeNumber parameter should be a number >= 0 and <= 40");
}
this._typeNumber = typeNumber;
this._errorCorrectLevel = errorCorrectLevel;
this._qrData = [];
this._moduleCount = 0;
this._modules = [];
mathHelper_1.MathHelper.initialize();
}
/**
* Add text data to the QR Code.
* @param qrData The data to add.
*/
addText(qrData) {
this._qrData.push(new qrByte8_1.QRByte8(qrData));
}
/**
* Add number to the QR Code.
* @param qrData The data to add.
*/
addNumber(qrData) {
this._qrData.push(new qrNumber_1.QRNumber(qrData));
}
/**
* Add alpha numeric to the QR Code.
* @param qrData The data to add.
*/
addAlphaNumeric(qrData) {
this._qrData.push(new qrAlphaNumeric_1.QRAlphaNumeric(qrData));
}
/**
* Generate the display buffer.
* @param cellSize The size of the cell to generate.
* @param margin The size of the margins to generate.
* @returns Boolean buffer of pixels
*/
generate() {
this.autoDetectTypeNumber();
this.makeImpl(false, this.getBestMaskPattern());
const pixels = [];
for (let y = 0; y < this._moduleCount; y++) {
for (let x = 0; x < this._moduleCount; x++) {
pixels[x] = pixels[x] || [];
pixels[x][y] = this.isDark(y, x);
}
}
return pixels;
}
/* @internal */
isDark(row, col) {
if (this._modules[row][col] !== null) {
return this._modules[row][col];
}
return false;
}
/* @internal */
getBestMaskPattern() {
let minLostPoint = 0;
let pattern = 0;
for (let i = 0; i < 8; i++) {
this.makeImpl(true, i);
const lostPoint = this.getLostPoint();
if (i === 0 || minLostPoint > lostPoint) {
minLostPoint = lostPoint;
pattern = i;
}
}
return pattern;
}
/* @internal */
makeImpl(test, maskPattern) {
this._moduleCount = this._typeNumber * 4 + 17;
this._modules = [];
for (let i = 0; i < this._moduleCount; i++) {
this._modules.push([]);
for (let j = 0; j < this._moduleCount; j++) {
this._modules[i].push(null);
}
}
this.setupPositionProbePattern(0, 0);
this.setupPositionProbePattern(this._moduleCount - 7, 0);
this.setupPositionProbePattern(0, this._moduleCount - 7);
this.setupPositionAdjustPattern();
this.setupTimingPattern();
this.setupTypeInfo(test, maskPattern);
if (this._typeNumber >= 7) {
this.setupTypeNumber(test);
}
const data = this.createData();
this.mapData(data, maskPattern);
}
/* @internal */
mapData(data, maskPattern) {
let inc = -1;
let row = this._moduleCount - 1;
let bitIndex = 7;
let byteIndex = 0;
const maskFunc = qrHelper_1.QRHelper.getMaskMethod(maskPattern);
for (let col = this._moduleCount - 1; col > 0; col -= 2) {
if (col === 6) {
col -= 1;
}
let flag = true;
while (flag) {
for (let c = 0; c < 2; c++) {
if (this._modules[row][col - c] === null) {
let dark = false;
if (byteIndex < data.length) {
dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
}
const mask = maskFunc(row, col - c);
if (mask) {
dark = !dark;
}
this._modules[row][col - c] = dark;
bitIndex -= 1;
if (bitIndex === -1) {
byteIndex++;
bitIndex = 7;
}
}
}
row += inc;
if (row < 0 || this._moduleCount <= row) {
row -= inc;
inc = -inc;
flag = false;
}
}
}
}
/* @internal */
setupPositionAdjustPattern() {
const pos = qrHelper_1.QRHelper.getPatternPosition(this._typeNumber);
for (let i = 0; i < pos.length; i++) {
for (let j = 0; j < pos.length; j++) {
const row = pos[i];
const col = pos[j];
if (this._modules[row][col] !== null) {
continue;
}
for (let r = -2; r <= 2; r++) {
for (let c = -2; c <= 2; c++) {
if (r === -2 || r === 2 || c === -2 || c === 2
|| (r === 0 && c === 0)) {
this._modules[row + r][col + c] = true;
}
else {
this._modules[row + r][col + c] = false;
}
}
}
}
}
}
/* @internal */
setupPositionProbePattern(row, col) {
for (let r = -1; r <= 7; r++) {
for (let c = -1; c <= 7; c++) {
if (row + r <= -1 || this._moduleCount <= row + r
|| col + c <= -1 || this._moduleCount <= col + c) {
continue;
}
if ((0 <= r && r <= 6 && (c === 0 || c === 6))
|| (0 <= c && c <= 6 && (r === 0 || r === 6))
|| (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
this._modules[row + r][col + c] = true;
}
else {
this._modules[row + r][col + c] = false;
}
}
}
}
/* @internal */
setupTimingPattern() {
for (let r = 8; r < this._moduleCount - 8; r++) {
if (this._modules[r][6] !== null) {
continue;
}
this._modules[r][6] = r % 2 === 0;
}
for (let c = 8; c < this._moduleCount - 8; c++) {
if (this._modules[6][c] !== null) {
continue;
}
this._modules[6][c] = c % 2 === 0;
}
}
/* @internal */
setupTypeNumber(test) {
const bits = qrHelper_1.QRHelper.getBCHTypeNumber(this._typeNumber);
for (let i = 0; i < 18; i++) {
this._modules[~~(i / 3)][i % 3 + this._moduleCount - 8 - 3] =
!test && ((bits >> i) & 1) === 1;
}
for (let i = 0; i < 18; i++) {
this._modules[i % 3 + this._moduleCount - 8 - 3][~~(i / 3)] =
!test && ((bits >> i) & 1) === 1;
}
}
/* @internal */
setupTypeInfo(test, maskPattern) {
const data = (this._errorCorrectLevel << 3) | maskPattern;
const bits = qrHelper_1.QRHelper.getBCHTypeInfo(data);
// vertical
for (let i = 0; i < 15; i++) {
const mod = !test && ((bits >> i) & 1) === 1;
if (i < 6) {
this._modules[i][8] = mod;
}
else if (i < 8) {
this._modules[i + 1][8] = mod;
}
else {
this._modules[this._moduleCount - 15 + i][8] = mod;
}
}
// horizontal
for (let i = 0; i < 15; i++) {
const mod = !test && ((bits >> i) & 1) === 1;
if (i < 8) {
this._modules[8][this._moduleCount - i - 1] = mod;
}
else if (i < 9) {
this._modules[8][15 - i - 1 + 1] = mod;
}
else {
this._modules[8][15 - i - 1] = mod;
}
}
// fixed
this._modules[this._moduleCount - 8][8] = !test;
}
/* @internal */
getLostPoint() {
const moduleCount = this._moduleCount;
let lostPoint = 0;
// LEVEL1
for (let row = 0; row < moduleCount; row++) {
for (let col = 0; col < moduleCount; col++) {
let sameCount = 0;
const dark = this.isDark(row, col);
for (let r = -1; r <= 1; r++) {
if (row + r < 0 || moduleCount <= row + r) {
continue;
}
for (let c = -1; c <= 1; c++) {
if (col + c < 0 || moduleCount <= col + c) {
continue;
}
if (r === 0 && c === 0) {
continue;
}
if (dark === this.isDark(row + r, col + c)) {
sameCount++;
}
}
}
if (sameCount > 5) {
lostPoint += (3 + sameCount - 5);
}
}
}
// LEVEL2
for (let row = 0; row < moduleCount - 1; row++) {
for (let col = 0; col < moduleCount - 1; col++) {
let count = 0;
if (this.isDark(row, col)) {
count++;
}
if (this.isDark(row + 1, col)) {
count++;
}
if (this.isDark(row, col + 1)) {
count++;
}
if (this.isDark(row + 1, col + 1)) {
count++;
}
if (count === 0 || count === 4) {
lostPoint += 3;
}
}
}
// LEVEL3
for (let row = 0; row < moduleCount; row++) {
for (let col = 0; col < moduleCount - 6; col++) {
if (this.isDark(row, col)
&& !this.isDark(row, col + 1)
&& this.isDark(row, col + 2)
&& this.isDark(row, col + 3)
&& this.isDark(row, col + 4)
&& !this.isDark(row, col + 5)
&& this.isDark(row, col + 6)) {
lostPoint += 40;
}
}
}
for (let col = 0; col < moduleCount; col++) {
for (let row = 0; row < moduleCount - 6; row++) {
if (this.isDark(row, col)
&& !this.isDark(row + 1, col)
&& this.isDark(row + 2, col)
&& this.isDark(row + 3, col)
&& this.isDark(row + 4, col)
&& !this.isDark(row + 5, col)
&& this.isDark(row + 6, col)) {
lostPoint += 40;
}
}
}
// LEVEL4
let darkCount = 0;
for (let col = 0; col < moduleCount; col++) {
for (let row = 0; row < moduleCount; row++) {
if (this.isDark(row, col)) {
darkCount++;
}
}
}
const ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
lostPoint += ratio * 10;
return lostPoint;
}
/* @internal */
createData() {
const rsBlocks = rsBlock_1.RSBlock.getRSBlocks(this._typeNumber, this._errorCorrectLevel);
const buffer = new bitBuffer_1.BitBuffer();
for (let i = 0; i < this._qrData.length; i++) {
const data = this._qrData[i];
buffer.put(data.getMode(), 4);
buffer.put(data.getLength(), data.getLengthInBits(this._typeNumber));
data.write(buffer);
}
// calc max data count
let totalDataCount = 0;
for (let i = 0; i < rsBlocks.length; i++) {
totalDataCount += rsBlocks[i].getDataCount();
}
if (buffer.getLengthInBits() > totalDataCount * 8) {
throw new Error(`There is not enough space in the QR code to store the data, ${buffer.getLengthInBits()} > ${totalDataCount * 8}, try increasing the typeNumber from ${this._typeNumber}`);
}
// end
if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
buffer.put(0, 4);
}
// padding
while (buffer.getLengthInBits() % 8 !== 0) {
buffer.putBit(false);
}
// padding
let flag = true;
while (flag) {
if (buffer.getLengthInBits() >= totalDataCount * 8) {
break;
}
buffer.put(QR.PAD0, 8);
if (buffer.getLengthInBits() >= totalDataCount * 8) {
flag = false;
}
else {
buffer.put(QR.PAD1, 8);
}
}
return this.createBytes(buffer, rsBlocks);
}
/* @internal */
createBytes(buffer, rsBlocks) {
let offset = 0;
let maxDcCount = 0;
let maxEcCount = 0;
const dcdata = [];
const ecdata = [];
for (let r = 0; r < rsBlocks.length; r++) {
dcdata.push([]);
ecdata.push([]);
}
function createNumArray(len) {
const a = [];
for (let i = 0; i < len; i++) {
a.push(0);
}
return a;
}
// tslint:disable:no-console
for (let r = 0; r < rsBlocks.length; r++) {
const dcCount = rsBlocks[r].getDataCount();
const ecCount = rsBlocks[r].getTotalCount() - dcCount;
maxDcCount = Math.max(maxDcCount, dcCount);
maxEcCount = Math.max(maxEcCount, ecCount);
dcdata[r] = createNumArray(dcCount);
for (let i = 0; i < dcdata[r].length; i++) {
dcdata[r][i] = 0xFF & buffer.getBuffer()[i + offset];
}
offset += dcCount;
const rsPoly = qrHelper_1.QRHelper.getErrorCorrectPolynomial(ecCount);
const rawPoly = new polynomial_1.Polynomial(dcdata[r], rsPoly.getLength() - 1);
const modPoly = rawPoly.mod(rsPoly);
ecdata[r] = createNumArray(rsPoly.getLength() - 1);
for (let i = 0; i < ecdata[r].length; i++) {
const modIndex = i + modPoly.getLength() - ecdata[r].length;
ecdata[r][i] = (modIndex >= 0) ? modPoly.getAt(modIndex) : 0;
}
}
let totalCodeCount = 0;
for (let i = 0; i < rsBlocks.length; i++) {
totalCodeCount += rsBlocks[i].getTotalCount();
}
const data = createNumArray(totalCodeCount);
let index = 0;
for (let i = 0; i < maxDcCount; i++) {
for (let r = 0; r < rsBlocks.length; r++) {
if (i < dcdata[r].length) {
data[index] = dcdata[r][i];
index++;
}
}
}
for (let i = 0; i < maxEcCount; i++) {
for (let r = 0; r < rsBlocks.length; r++) {
if (i < ecdata[r].length) {
data[index] = ecdata[r][i];
index++;
}
}
}
return data;
}
/* @internal */
autoDetectTypeNumber() {
if (this._typeNumber === 0) {
for (let typeNumber = 1; typeNumber <= 40; typeNumber++) {
const rsBlocks = rsBlock_1.RSBlock.getRSBlocks(typeNumber, this._errorCorrectLevel);
const buffer = new bitBuffer_1.BitBuffer();
for (let i = 0; i < this._qrData.length; i++) {
const data = this._qrData[i];
buffer.put(data.getMode(), 4);
buffer.put(data.getLength(), data.getLengthInBits(typeNumber));
data.write(buffer);
}
let totalDataCount = 0;
for (let i = 0; i < rsBlocks.length; i++) {
totalDataCount += rsBlocks[i].getDataCount();
}
if (buffer.getLengthInBits() <= totalDataCount * 8) {
this._typeNumber = typeNumber;
break;
}
if (typeNumber === 40) {
throw new Error(`There is not enough space in the QR code to store the data, ${buffer.getLengthInBits()} > ${totalDataCount * 8}, typeNumber can not be > 40`);
}
}
}
}
} |
JavaScript | class FacetsRenderer extends Component {
static propTypes = {
isFolder: PropTypes.bool.isRequired,
onFacetSelected: PropTypes.func,
record: PropTypes.object,
values: PropTypes.array.isRequired
}
static defaultProps = {
isFolder: false
}
state = {
inputVisible: false
}
onFacetSelected = (val, facet) => {
const { onFacetSelected, record } = this.props
onFacetSelected && onFacetSelected(val, record, facet)
}
handleInputConfirm = inputValues => {
if (!inputValues[0]) return this.setState({ inputVisible: false })
const currentFacets = this.getFacetsForCurrentFolder()
let newFacets = currentFacets
if (currentFacets.indexOf(inputValues[0]) === -1) newFacets = [...currentFacets, inputValues[0]]
if (inputValues.length > 0 && !isEqual(newFacets, currentFacets)) {
this.onFacetSelected(newFacets)
}
this.setState({ inputVisible: false })
}
handleClose = removedFacet => {
this.onFacetSelected(null, removedFacet)
}
showInput = () => this.setState({ inputVisible: true })
getFacetsForCurrentFolder = () => {
const { isFolder, facets, record } = this.props
if (!isFolder || !facets) return []
const facetsFiltered = Object.values(facets).map(
globs => globs.filter(glob => Contribution.folderMatchesGlob(record, glob)).length > 0
)
return Object.keys(facets).filter((_, i) => facetsFiltered[i])
}
renderExistingFacets = currentFacets => {
const { facets, record } = this.props
return currentFacets.map((tag, i) => {
const isMatchingThisFolder =
facets && facets[tag].filter(glob => Contribution.folderMatchesGlobExactly(record, glob)).length > 0
return (
<Tag key={i} closable={isMatchingThisFolder} onClose={() => this.handleClose(tag)}>
{tag}
</Tag>
)
})
}
render() {
const { isFolder, values } = this.props
const { inputVisible } = this.state
const currentFacets = this.getFacetsForCurrentFolder()
return (
<div className="facetsRenderer">
{values.length > 0
? values.map((val, i) => (
<Tag
key={i}
closable={isFolder}
onClose={() => this.handleClose(val)}
className={val.isDifferent ? 'facets--isEdited' : ''}
>
{val.value}
</Tag>
))
: currentFacets.length === 0 && <div />}
{isFolder && this.renderExistingFacets(currentFacets)}
{isFolder &&
(!inputVisible ? (
<Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
<Icon type="plus" />
</Tag>
) : (
<Select
mode="multiple"
maxTagCount={1}
style={{ width: '50%' }}
onChange={this.handleInputConfirm}
//onBlur={this.handleInputConfirm}
>
{Contribution.nonCoreFacets
.filter(el => !currentFacets.includes(el))
.map(facet => (
<Select.Option key={facet}>{facet}</Select.Option>
))}
</Select>
))}
</div>
)
}
} |
JavaScript | class FCLLayout extends DataType {
static isValid(value) {
return !!FCLLayouts[value];
}
} |
JavaScript | class ExpanderButton extends React.PureComponent {
static contextType = ThemeContext
handleClicked = (event) => {
var nextState = !this.props.expanded
this.props.onClick(nextState)
event.stopPropagation()
};
render () {
let theme = this.context
const style = this.props.expanded ? expandedStyle : collapsedStyle
return (
<button className={style(theme)} onClick={this.handleClicked} />
)
}
} |
JavaScript | class App extends React.Component {
constructor(props){
super(props);
}
render() {
return(
<div className='App'>
<div id="default">
<h3>Welcome to VGTracker!</h3>
<HomeButtons />
</div>
</div>
);
}
} |
JavaScript | class Intern extends Employee {
constructor(name, id, email, school){
super(name, id, email);
this.school= school;
}
// getting object function to retrieve school
getSchool(){
return this.school;
}
// getting object function to update role to intern
getRole(){
return "Intern";
}
} |
JavaScript | class LimeFunctionProperty extends LimeFunction {
// Constructor
constructor(lime, mode) {
// Super from function class
super(lime, { name: 'property', mode });
// Binary operation
this.operations.b = [
'tf(_.)',
'tf(.+)',
'tf(./)',
'tf(.^)',
'tf(.%)',
'tf(.*)',
'tf(.-)',
'eb(expr,str)',
];
// Algorithms
this.algorithms.set('b(expr,str)', (step) => {
step.bs(step.left[step.right.value]);
});
}
} |
JavaScript | class SearchRestaurantsTab extends Component {
/**
* Used to clear search resault
*
* @returns Void
*/
componentWillMount() {
this.props.clearSearchResult();
this.props.searchText('');
}
/**
* Used to clear search resault
*
* @returns Void
*/
componentDidMount() {
this.props.clearSearchResult();
this.props.searchText('');
}
/**
* Used to render the search tab component.
*
* @returns {ReactElement} search tab component
*/
render() {
return (
<View style={Styles.firstTab} >
<Image
style={Styles.searchBarStyle}
source={{ uri: getCDNRoute('background') + this.props.background }}
>
<SearchBar />
</Image>
<View style={Styles.bodyContainer} >
<TouchableOpacity onPress={() => Actions.offersScreen()}>
<QuickSearchLinks
title='احدث الحملات و العروض'
number={this.props.offersCount}
icon={offers}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Actions.nearbyRestaurantsMapScreen()}>
<QuickSearchLinks
title='ما هي المطاعم القريبة مني'
number={this.props.nearByLocationsCount}
icon={location}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Actions.featuredScreen()}>
<QuickSearchLinks
title='مطاعم مميزة '
icon={featured}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Actions.searchByServicesScreen()}>
<QuickSearchLinks
title='اريد مطعما يناسبني '
icon={services}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Actions.onlineOrderScreen()}>
<Image
style={Styles.mainIconStyle}
source={order}
resizeMode='contain'
/>
</TouchableOpacity>
</View>
<View style={Styles.advertisement} >
<View style={Styles.lineDivider} />
<Text> منطقة اعلانات تجارية</Text>
</View>
</View >
);
}
} |
JavaScript | class EventObjectSpnEmitter extends SharedEmitter {
/**
* @param {EventObject} modelObject
*/
constructor(modelObject) {
super(modelObject);
this.type = 'SPN';
}
/**
* @param {EventObjectEmitterView} emitterView
*/
emit(emitterView) {
if (this.modelObject.ok) {
this.emitObject(emitterView);
}
}
/**
* @return {EventObjectSpn}
*/
createObject() {
return new EventObjectSpn(this);
}
} |
JavaScript | class TalksList extends LitElement {
constructor() {
super();
}
static get properties() {
return {
title: {type: String},
talks: {type: Array},
};
}
render() {
return html`
<style>
:host {
display: block;
padding: 10px;
background-color: #323230;
}
.Title {
text-align: center;
margin-top: 0;
margin-bottom: 0;
color: #FFF;
}
.TalksList {
display: flex;
flex-direction: row;
flex-wrap: wrap;
list-style-type: none;
padding-left: 0;
margin-bottom: 0;
margin-top: 0;
}
.TalksList-item {
margin: 10px;
width: calc(100% - 20px);
flex-basis: calc(100% - 20px);
}
@media screen and (min-width: 480px) {
.TalksList-item {
width: calc(33% - 20px);
flex-basis: calc(33% - 20px);
}
}
@media screen and (min-width: 768px) {
.TalksList-item {
width: calc(25% - 20px);
flex-basis: calc(25% - 20px);
}
}
talk-card {
height: 100%;
background-color: #f00;
}
</style>
<h2 class="Title">${this.title}</h2>
<ul class="TalksList">
${repeat((this.talks), i => html`
<li class="TalksList-item">
<talk-card id="${i.id}" userId="${i.userId}" title="${i.title}" body="${i.body}"></talk-card>
</li>
`)}
</ul>
`
}
} |
JavaScript | class Parser {
constructor() {
this.funs = new Map();
this.services = [];
const grammar = readFileSync(resolve(__dirname, "./mushcode.pegjs"), {
encoding: "utf-8",
});
this.peg = peg.generate(grammar);
}
/**
* Create a new function to add to the global list.
* @param {string} name The name of the function to be added.
* @param {function} fun The function to be run when the mushcode
* parser maakes a match.
*/
function(name, fun) {
this.funs.set(name, fun);
}
/**
* Parse a muschode string into an AST.
* @param {string} string The string to parse
*/
parse(string) {
return this.peg.parse(string);
}
/**
* Add a new service to the game. Services can be thought of as
* commands the client can send directly to the game.
* @param {function} service The service to handle the command from
* the client.
*/
service(service) {
service.hooks = new Map();
service.hooks.set("before", []);
service.hooks.set("after", []);
this.services.push(service);
return this;
}
/**
* Attach a hooks to a service.
* @param {string} when 'before' or 'after ' the service has run
* @param {string} name The name of the servicce to attach too.
* @param {...any} hooks The list of hooks to assign to a service
*/
hooks(name, when, ...hooks) {
srv = this.services.find((service) => service.name === name);
// if the service exists and the 'when' is either before or after.
if (srv && srv.hooks.has(when)) {
// For each hook, push it into the proper stack.
hooks.forEach((hook) => srv.hooks.get(when).push(hook));
}
}
/**
* Process an action from the client.
* @param {Object} ctx The context object
*/
async process(ctx) {
for (const service of this.services) {
if (service.name === ctx.command.toLowerCase()) {
for (const bhook of service.hooks.get("before")) {
ctx = await bhook(ctx);
}
ctx = await service.exec(ctx);
for (const ahook of service.hooks.get("after")) {
ctx = await ahook(ctx);
}
return ctx;
}
}
}
/**
* Evaluate a parsed mushcode AST.
* @param {Object} en The database object of the enactor
* @param {Object} expr The parsed expression to be evaluated.
* @param {Object} scope The context for the run of the expression.
*/
async evaluate(en, expr, scope) {
// If the expression is a word, return it's value in scope, else
// just the value of the expression.
if (expr.type === "word") {
// if it's not an imbededded version of a scope variable, return it.
if (scope[expr.value]) {
return scope[expr.value];
} else {
let res = expr.value;
for (let k in scope) {
res = expr.value.replace(k, scope[k]);
}
return res;
}
} else if (expr.type === "function") {
// If the expression is a function, search for it to see if it
// exists first.
const name = expr.operator.value;
if (this.funs.has(name)) {
return await this.funs.get(name)(en, expr.args, scope);
} else {
throw new Error("Unknown Function");
}
} else if (expr.type === "list") {
// A list happens when two or more expressions are placed
// next to each other. They are each evaluated and their
// output is concatinated together.
let output = "";
for (const expression of expr.args) {
output += await this.evaluate(en, expression, scope);
}
return output;
} else {
throw new Error("Unknown expression");
}
}
/**
* Strip MUSH ansi subsitution shorthand from a string.
* @param {string} string - The text to strip the substitution
* characters from.
*/
stripSubs(string) {
return string
.replace(/%[cCxX]./g, "")
.replace(/(/g, " ")
.replace(/)/g, " ")
.replace(/[/g, " ")
.replace(/]/g, " ");
}
async run(en, string, scope) {
string = string
.replace(/%\(/g, "(")
.replace(/%\)/g, ")")
.replace(/%\[/g, "[")
.replace(/%\]/g, "]")
.replace(/%,/g, ",");
try {
return await this.evaluate(en, this.parse(string), scope);
} catch (error) {
return await this.string(en, string, scope);
}
}
async string(en, text, scope) {
let parens = -1;
let brackets = -1;
let match = false;
let workStr = "";
let output = "";
let start = -1;
let end = -1;
// Loop through the text looking for brackets.
for (let i = 0; i < text.length; i++) {
if (text[i] === "[") {
brackets = brackets > 0 ? brackets + 1 : 1;
start = start > 0 ? start : i;
match = true;
} else if (text[i] === "]") {
brackets = brackets - 1;
} else if (text[i] === "(") {
parens = parens > 0 ? parens + 1 : 1;
} else if (text[i] === ")") {
parens = parens - 1;
}
// Check to see if brackets are evenly matched.
// If so process that portion of the string and
// replace it.
if (match && brackets !== 0 && parens !== 0) {
workStr += text[i];
} else if (match && brackets === 0 && parens === 0) {
// If the brackets are zeroed out, replace the portion of
// the string with evaluated code.
workStr += text[i];
end = i;
// If end is actually set (We made it past the first characracter),
// then try to parse `workStr`. If it won't parse (not an expression)
// then run it through string again just to make sure. If /that/ fails
// error.
if (end) {
let results = await this.run(en, workStr, scope).catch(async () => {
output += await this.string(en, workStr, scope).catch(console.log);
});
// Add the results to the rest of the processed string.
output += results;
}
// Reset the count variables.
parens = -1;
brackets = -1;
match = false;
start = -1;
end = -1;
workStr = "";
} else {
// If stray paren or bracket slips through, add it to `workStr`
// else add it right to the output. There's no code there.
if (text[i].match(/[\[\]\(\)]/)) {
workStr += text[i];
} else {
output += text[i];
}
}
}
// Return the evaluated text
return output ? output : workStr;
}
} |
JavaScript | class SimState {
constructor() {
this.index = -1;
this.line = 0;
this.charPos = -1;
}
reset() {
this.index = -1;
this.line = 0;
this.charPos = -1;
this.dfaState = undefined;
}
} |
JavaScript | class ActiveLearner {
constructor(opts) {
opts = opts || {};
if (opts instanceof qm.fs.FIn || typeof opts == "string") {
this.load(opts);
} else {
// SETTINGS
let settings = this._getDefaultSettings();
override(settings, opts.settings || {});
this._settings = settings;
// STATE
this._X = opts.X || null;
this._y = opts.y || new Map();
this._SVC = new exports.SVC(this._settings.SVC);
}
}
/**
* Returns default settings
*/
_getDefaultSettings() {
return {
learner: {
disableAsserts: false
},
SVC: {
algorithm: "LIBSVM",
c: 1.0,
j: 1.0
}
};
}
/**
* Asserts if the object is a la matrix
*/
_assertMatrix(X) {
if (this._settings.learner.disableAsserts) { return; }
assert(X instanceof la.Matrix || X instanceof la.SparseMatrix, "X should be a dense or a sparse matrix (qm.la object)");
}
/**
* Asserts if a label and the index are valid, given number of examples `cols`
*/
_assertLabel(cols, idx, label) {
if (this._settings.learner.disableAsserts) { return; }
if (cols == undefined) { throw new Error("Columns not defined"); }
if (!isFinite(idx) || (idx >= cols) || (idx < 0)) { throw new Error("Label index out of range"); }
if ((label != -1) && (label != 1)) { throw new Error("Label should be either -1 or 1"); }
}
/**
* Asserts if a Map with labels is valid
*/
_assertLabelSet(cols, y) {
if (this._settings.learner.disableAsserts) { return; }
assert(y instanceof Map, "y should be a map from data instance indices to +1 or -1");
// assert y indices and values
for (let pair of y.entries()) {
this._assertLabel(cols, pair[0], pair[1]);
}
}
/**
* Transforms an Array of labels to a Map from indices to labels
*/
_getLabelMapFromArr(_y) {
assert(_y instanceof Array);
let y = new Map();
for (let i = 0; i < _y.length; i++) {
let lab = _y[i];
if (this._settings.learner.disableAsserts) {
assert(lab === -1 || lab === 1 || lab === 0, "Label must be ither -1, 0 or 1");
}
if (lab !== 0) {
y.set(i, lab);
}
}
return y;
}
/**
* Returns an array of indices of labelled examples
*/
_getLabIdxArr(y) {
return Array.from(y.keys());
}
/**
* Returns an array of label values corresponding to the labelled examples
*/
_getLabArr(y) {
return Array.from(y.values());
}
/**
* Returns an array of indices of unlabelled examples
*/
_getUnlabIdxArr(cols, y) {
let unlabIdxArr = [];
for (let idx = 0; idx < cols; idx++) {
if (!y.has(idx)) {
unlabIdxArr.push(idx);
}
}
return unlabIdxArr;
}
/**
* Retrains the SVC model
* @param {(module:la.Matrix | module:la.SparseMatrix)} X - data matrix (column examples)
* @param {Map} y - a Map from indices to 1 or -1
* @param {module:analytics.SVC} SVC - a SVC model
*/
_retrain(X, y, SVC) {
// asert y indices and values
this._assertMatrix(X);
let cols = X.cols;
this._assertLabelSet(cols, y);
if (y.size == 0) { throw new Error("No labelled information in y"); }
// get all labelled examples and fit SVM
let labIdxArr = this._getLabIdxArr(y);
let trainIdx = new la.IntVector(labIdxArr);
let Xsub = X.getColSubmatrix(trainIdx);
let yArr = this._getLabArr(y);
let yVec = new la.Vector(yArr);
SVC.fit(Xsub, yVec);
}
/**
* Retrains the SVC model
*/
retrain() {
this._retrain(this._X, this._y, this._SVC);
}
/**
* Return an array of indices where the model has the highest uncertainty (1 element by default)
* @param {(module:la.Matrix | module:la.SparseMatrix)} X - data matrix (column examples)
* @param {Map} y - a Map from indices to 1 or -1
* @param {module:analytics.SVC} SVC - a SVC model
* @param {number} [num=1] - the length of the array that is returned (top `num` indices where uncertainty is maximal)
* @returns {Array<number>} - array of indices of unlabelled examples
*/
_getQueryIdx(X, y, SVC, num) {
num = (isFinite(num) && num > 0 && Number.isInteger(num)) ? num : 1;
// use the classifier on unlabelled examples and return
// get unlabelled indices
let unlabIdxArr = this._getUnlabIdxArr(X.cols, y);
if (unlabIdxArr.length == 0) { return []; } // exhausted
let unlabIdxVec = new la.IntVector(unlabIdxArr);
let Xsub = X.getColSubmatrix(unlabIdxVec);
if (SVC.weights.length == 0) {
this._retrain(X, y, SVC);
}
// get examples with largest uncertainty
let uncertaintyArr = SVC.decisionFunction(Xsub).toArray().map((x) =>Math.abs(x));
let u = new la.Vector(uncertaintyArr);
let su = u.sortPerm(); // sorted in ascending order
num = Math.min(num, u.length);
// take `num` unlabelled indices where we are most uncertain
let subVec = unlabIdxVec.subVec(su.perm.trunc(num));
return subVec.toArray();
}
/**
* Returns an array of 0 or more example indices sorted by uncertainty (first element is the closest to the hyperplane)
* @param {number} [num=1] - maximal length of the array
* @returns {Array<number>} array of unlabelled example indices
*/
getQueryIdx(num) {
return this._getQueryIdx(this._X, this._y, this._SVC, num)
}
/**
* Sets the label
* @param {number} idx - instance index
* @param {number} label - should be either 1 or -1
*/
setLabel(idx, label) {
let cols = this._X.cols;
this._assertLabel(cols, idx, label);
this._y.set(idx, label);
}
/**
* Sets the data matrix (column examples)
* @param {(module:la.Matrix | module:la.SparseMatrix)} X - data matrix (column examples)
*/
setX(X) {
this._assertMatrix(X);
this._X = X
}
/**
* Sets the labels
* @param {(Array<number> | module.la.Vector | module.la.IntVector | Map)} _y - array (like) object that encodes labels
* (-1, 0 or 1) or a Map from indices to 1 or -1
*/
sety(_y) {
let y = _y;
this._assertMatrix(this._X);
let cols = this._X.cols;
if (_y instanceof Array) { y = this._getLabelMapFromArr(_y); }
if (_y.toArray != undefined) { y = this._getLabelMapFromArr(_y.toArray()); }
this._assertLabelSet(cols, y);
this._y = y;
}
/**
* Returns the SVC model
* @returns {module:analytics.SVC} SVC model
*/
getSVC() { return this._SVC; }
/**
* Returns the data matrix (column examples)
* @returns {(module:la.Matrix | module:la.SparseMatrix)} data matrix (column examples)
*/
getX() { return this._X; }
/**
* Returns the Map from example indices to labels (-1 or 1)
* @returns {Map} label map
*/
gety() { return this._y; }
/**
* Loads instance matrix, labels and the model from the input stream
* @param {(string | module:fs.FIn)} input - a file name or an input stream
*/
load(input) {
if (input instanceof qm.fs.FIn) {
this._settings = input.readJson();
let matrixType = input.readJson().matrixType;
if (matrixType == "null") {
this._X = null;
} else if (matrixType == "full") {
this._X = new la.Matrix();
this._X.load(input);
} else if (matrixType == "sparse") {
this._X = new la.SparseMatrix();
this._X.load(input);
} else {
throw new Error("Cannot load matrix, the type is not supported");
}
let y = input.readJson();
this._y = new Map(y);
this._SVC = new exports.SVC(input);
return input;
} else {
let fin = qm.fs.openRead(input);
this.load(fin).close();
}
}
/**
* Saves the instance matrix, labels and the model to the input stream
* @param {(string | module:fs.FOut)} output - a file name or an output stream
*/
save(output) {
let X = this._X;
let y = this._y;
let SVC = this._SVC;
if (output instanceof qm.fs.FOut) {
output.writeJson(this._settings);
if (X == undefined) {
output.writeJson({ matrixType: "null" });
} else if (X instanceof la.Matrix) {
output.writeJson({ matrixType: "full" });
X.save(output);
} else if (X instanceof la.SparseMatrix) {
output.writeJson({ matrixType: "sparse" });
X.save(output);
} else {
throw new Error("Cannot save matrix, the type is not supported.");
}
output.writeJson(Array.from(this._y));
SVC.save(output);
return output;
} else {
let fout = qm.fs.openWrite(output);
this.save(fout).close();
}
}
} |
JavaScript | class LogicalIDs {
constructor() {
/**
* The rename table (old to new)
*/
this.renames = {};
/**
* All assigned names (new to old, may be identical)
*
* This is used to ensure that:
*
* - No 2 resources end up with the same final logical ID, unless they were the same to begin with.
* - All renames have been used at the end of renaming.
*/
this.reverse = {};
}
/**
* Rename a logical ID from an old ID to a new ID
*/
addRename(oldId, newId) {
if (oldId in this.renames) {
throw new Error(`A rename has already been registered for '${oldId}'`);
}
this.renames[oldId] = newId;
}
/**
* Return the renamed version of an ID or the original ID.
*/
applyRename(oldId) {
let newId = oldId;
if (oldId in this.renames) {
newId = this.renames[oldId];
}
// If this newId has already been used, it must have been with the same oldId
if (newId in this.reverse && this.reverse[newId] !== oldId) {
// tslint:disable-next-line:max-line-length
throw new Error(`Two objects have been assigned the same Logical ID: '${this.reverse[newId]}' and '${oldId}' are now both named '${newId}'.`);
}
this.reverse[newId] = oldId;
validateLogicalId(newId);
return newId;
}
/**
* Throw an error if not all renames have been used
*
* This is to assure that users didn't make typoes when registering renames.
*/
assertAllRenamesApplied() {
const keys = new Set();
Object.keys(this.renames).forEach(keys.add.bind(keys));
Object.keys(this.reverse).map((newId) => {
keys.delete(this.reverse[newId]);
});
if (keys.size !== 0) {
const unusedRenames = Array.from(keys.values());
throw new Error(`The following Logical IDs were attempted to be renamed, but not found: ${unusedRenames.join(", ")}`);
}
}
} |
JavaScript | class XMLFeature extends FeatureFormat {
constructor() {
super();
/**
* @type {XMLSerializer}
* @private
*/
this.xmlSerializer_ = new XMLSerializer();
}
/**
* @inheritDoc
*/
getType() {
return FormatType.XML;
}
/**
* Read a single feature.
*
* @param {Document|Node|Object|string} source Source.
* @param {import("./Feature.js").ReadOptions=} opt_options Read options.
* @return {import("../Feature.js").default} Feature.
* @api
*/
readFeature(source, opt_options) {
if (isDocument(source)) {
return this.readFeatureFromDocument(/** @type {Document} */ (source), opt_options);
} else if (isNode(source)) {
return this.readFeatureFromNode(/** @type {Node} */ (source), opt_options);
} else if (typeof source === 'string') {
const doc = parse(source);
return this.readFeatureFromDocument(doc, opt_options);
} else {
return null;
}
}
/**
* @param {Document} doc Document.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @return {import("../Feature.js").default} Feature.
*/
readFeatureFromDocument(doc, opt_options) {
const features = this.readFeaturesFromDocument(doc, opt_options);
if (features.length > 0) {
return features[0];
} else {
return null;
}
}
/**
* @param {Node} node Node.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @return {import("../Feature.js").default} Feature.
*/
readFeatureFromNode(node, opt_options) {
return null; // not implemented
}
/**
* Read all features from a feature collection.
*
* @param {Document|Node|Object|string} source Source.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @return {Array<import("../Feature.js").default>} Features.
* @api
*/
readFeatures(source, opt_options) {
if (isDocument(source)) {
return this.readFeaturesFromDocument(
/** @type {Document} */ (source), opt_options);
} else if (isNode(source)) {
return this.readFeaturesFromNode(/** @type {Node} */ (source), opt_options);
} else if (typeof source === 'string') {
const doc = parse(source);
return this.readFeaturesFromDocument(doc, opt_options);
} else {
return [];
}
}
/**
* @param {Document} doc Document.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @protected
* @return {Array<import("../Feature.js").default>} Features.
*/
readFeaturesFromDocument(doc, opt_options) {
/** @type {Array<import("../Feature.js").default>} */
const features = [];
for (let n = doc.firstChild; n; n = n.nextSibling) {
if (n.nodeType == Node.ELEMENT_NODE) {
extend(features, this.readFeaturesFromNode(n, opt_options));
}
}
return features;
}
/**
* @abstract
* @param {Node} node Node.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @protected
* @return {Array<import("../Feature.js").default>} Features.
*/
readFeaturesFromNode(node, opt_options) {}
/**
* @inheritDoc
*/
readGeometry(source, opt_options) {
if (isDocument(source)) {
return this.readGeometryFromDocument(
/** @type {Document} */ (source), opt_options);
} else if (isNode(source)) {
return this.readGeometryFromNode(/** @type {Node} */ (source), opt_options);
} else if (typeof source === 'string') {
const doc = parse(source);
return this.readGeometryFromDocument(doc, opt_options);
} else {
return null;
}
}
/**
* @param {Document} doc Document.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @protected
* @return {import("../geom/Geometry.js").default} Geometry.
*/
readGeometryFromDocument(doc, opt_options) {
return null; // not implemented
}
/**
* @param {Node} node Node.
* @param {import("./Feature.js").ReadOptions=} opt_options Options.
* @protected
* @return {import("../geom/Geometry.js").default} Geometry.
*/
readGeometryFromNode(node, opt_options) {
return null; // not implemented
}
/**
* Read the projection from the source.
*
* @param {Document|Node|Object|string} source Source.
* @return {import("../proj/Projection.js").default} Projection.
* @api
*/
readProjection(source) {
if (isDocument(source)) {
return this.readProjectionFromDocument(/** @type {Document} */ (source));
} else if (isNode(source)) {
return this.readProjectionFromNode(/** @type {Node} */ (source));
} else if (typeof source === 'string') {
const doc = parse(source);
return this.readProjectionFromDocument(doc);
} else {
return null;
}
}
/**
* @param {Document} doc Document.
* @protected
* @return {import("../proj/Projection.js").default} Projection.
*/
readProjectionFromDocument(doc) {
return this.dataProjection;
}
/**
* @param {Node} node Node.
* @protected
* @return {import("../proj/Projection.js").default} Projection.
*/
readProjectionFromNode(node) {
return this.dataProjection;
}
/**
* @inheritDoc
*/
writeFeature(feature, opt_options) {
const node = this.writeFeatureNode(feature, opt_options);
return this.xmlSerializer_.serializeToString(node);
}
/**
* @param {import("../Feature.js").default} feature Feature.
* @param {import("./Feature.js").WriteOptions=} opt_options Options.
* @protected
* @return {Node} Node.
*/
writeFeatureNode(feature, opt_options) {
return null; // not implemented
}
/**
* Encode an array of features as string.
*
* @param {Array<import("../Feature.js").default>} features Features.
* @param {import("./Feature.js").WriteOptions=} opt_options Write options.
* @return {string} Result.
* @api
*/
writeFeatures(features, opt_options) {
const node = this.writeFeaturesNode(features, opt_options);
return this.xmlSerializer_.serializeToString(node);
}
/**
* @param {Array<import("../Feature.js").default>} features Features.
* @param {import("./Feature.js").WriteOptions=} opt_options Options.
* @return {Node} Node.
*/
writeFeaturesNode(features, opt_options) {
return null; // not implemented
}
/**
* @inheritDoc
*/
writeGeometry(geometry, opt_options) {
const node = this.writeGeometryNode(geometry, opt_options);
return this.xmlSerializer_.serializeToString(node);
}
/**
* @param {import("../geom/Geometry.js").default} geometry Geometry.
* @param {import("./Feature.js").WriteOptions=} opt_options Options.
* @return {Node} Node.
*/
writeGeometryNode(geometry, opt_options) {
return null; // not implemented
}
} |
JavaScript | class BaseIterator {
/**
* Instances of BaseIterator must not be created. This class is only for
* inheritance.
*/
constructor() {
if (new.target === BaseIterator)
throw new Error("Can't instantiate abstract type.");
}
/**
* Returns the iterator to the initial state.
* @throws {Error} Will throw an error if not overriden.
*/
reset() {
throw new Error("Not implemented.");
}
/**
* Changes the reference of current item of iterator to the next position.
* @throws {Error} Will throw an error if not overriden.
*/
moveNext() {
throw new Error("Not implemented.");
}
/**
* Checks completion of the data iteration.
* @returns {Boolean} Returns true if iteration is complete,
* otherwise false.
* @throws {Error} Will throw an error if not overriden.
*/
checkCompletion() {
throw new Error("Not implemented.");
}
/**
* Gets the current value of the iterator.
* @returns {*} Returns current item of the iterator.
* @throws {Error} Will throw an error if not overriden.
*/
getCurrent() {
throw new Error("Not implemented.");
}
} |
JavaScript | class RGLTile {
constructor(origin) {
this.origin = origin;
this._id = RGLTile._idcntr++;
this.precalc = "";
this.coords = [0, 0];
assert.ok(origin.length == 8, Errors.EBADBUF);
this.origin = Buffer.from(origin);
this.precalc = (RGLTile.mappings_s.get(origin[6]) ?? (t => t))((RGLTile.mappings_b.get(origin[5]) ?? (t => t))((RGLTile.mappings_c.get(origin[4]) ?? (t => t))(RGLTile.decoder.write(origin.slice(0, 4)).replace(RGLTile.trim, ''))));
this.reserved = origin[7];
} //ctor
get serialize() {
//debug(`RGLTile.serialize`);
return Buffer.from(this.origin);
} //serialize
/**
* Parse data into a Convertable.
*
* @param {Readonly<Buffer>} chunk
*/
static parse(chunk, parent) {
//debug(`RGLTile.parse`);
let ret;
if (chunk instanceof RGLTile) {
ret = new RGLTile(chunk.origin);
ret.coords = Array.from(chunk.coords);
}
else
ret = new RGLTile(chunk);
ret.parent = parent;
return ret;
} //parse
toString() {
return this.precalc;
} //toString
[Symbol.toPrimitive](hint) {
if (hint === "string")
return this.toString();
else
return this;
}
} //RGLTile
|
JavaScript | class RGLMap {
constructor(reserved = Buffer.alloc(3, 0), size = Buffer.alloc(2, 0), tiles = [], trailing = Buffer.allocUnsafe(0), _fromFile = "", trans = [0, 0]) {
this.reserved = reserved;
this.size = size;
this.tiles = tiles;
this.trailing = trailing;
this._fromFile = _fromFile;
this.trans = trans;
this._id = RGLMap._idcntr++;
this._fromFile = path.resolve(path.normalize(_fromFile));
} //ctor
get serialize() {
debug(`RGLMap.serialize`);
let ret = Buffer.concat([this.reserved, RGLMap.RGL, this.size]);
this._sortTiles();
for (const tile of this.tiles)
ret = Buffer.concat([ret, tile.serialize]);
return Buffer.concat([ret, RGLMap.MAGIC, this.trailing]);
} //serialize
/**
* Store Convertable into a writable 'file'.
*
* @param file - Target file
*/
async serializeFile(file = this._fromFile) {
debug(`RGLMap.serializeFile: ${file}`);
let data;
await fs.outputFile(file, data = this.serialize, {
mode: 0o751,
encoding: "binary",
flag: "w"
});
return data;
} //serializeFile
/**
* Parse data into a Convertable.
*
* @param {Readonly<Buffer>} chunk
*/
static parse(data) {
debug(`RGLMap.parse`);
assert.ok(Buffer.isBuffer(data), Errors.ENOBUF);
assert.ok(Buffer.isEncoding("binary"), Errors.ENOBIN);
assert.ok(data.length >= 9, Errors.EBADBUF);
const map = new RGLMap(data.slice(0, 3), data.slice(7, 9));
let idx = 9, cntr = 0;
while (idx < data.length && !data.slice(idx, idx + 5).equals(RGLMap.MAGIC)) {
let tile;
map.tiles.push(tile = RGLTile.parse(data.slice(idx, idx += 8)));
tile.parent = map;
tile.coords = [cntr % map.size[0], Math.floor(cntr / map.size[0])];
}
if (idx != data.length) {
debug_v(`RGLMap.parse: has trailing`);
map.trailing = data.slice(idx + 5);
}
return map;
} //parse
/**
* Read Buffer from 'file'.
*
* @param file - Target file
*/
static async parseFile(file) {
debug(`RGLMap.parseFile: ${file}`);
return new Promise(async (res, rej) => {
debug_v(`RGLMap.parseFile: ACCESS`);
fs.access(file, fs.constants.F_OK | fs.constants.R_OK, err => {
if (err) {
debug_e(`RGLMap.parseFile: ${file} -> EACCESS`);
rej(err);
}
else {
debug_v(`RGLMap.parseFile: RSTREAM`);
const str = fs.createReadStream(file, {
flags: "r",
encoding: "binary",
mode: fs.constants.S_IRUSR | fs.constants.S_IXGRP,
emitClose: true
})
.once("readable", async () => {
debug_v(`RGLMap.parseFile: ${file} -> Readable`);
let data = '';
str.setEncoding("binary");
for await (let chunk of str)
data += chunk;
str.once("close", () => {
const map = RGLMap.parse(Buffer.from(data, "binary"));
map._fromFile = file;
res(map);
});
});
}
});
});
} //parseFile
_sortTiles(tiles = this.tiles) {
tiles.sort((a, b) => util.crdToIdx(a.coords, this.size[0]) - util.crdToIdx(b.coords, this.size[0]));
} //_sortTiles
/**
* Check validity of tile's coords.
*/
checkValidity() {
return true;
} //checkValidity
toString() {
return this.tiles.map((tile) => tile.toString()).join('');
} //toString
[Symbol.toPrimitive](hint) {
if (hint === "string")
return this.toString();
else
return this;
}
} //RGLMap
|
JavaScript | class RGLGround {
constructor(maplist = new Map(), foreground = null, viewport = [0, 0]) {
this.maplist = maplist;
this.foreground = foreground;
this.viewport = viewport;
} //ctor
/**
* Sets the foreground or retrieves.
*/
focus(fg) {
if (!!fg) {
if (typeof fg === "string")
this.foreground = this.maplist.get(fg);
else
this.foreground = fg;
}
return this.foreground;
} //focus
/**
* Add or retrieve a map.
*/
map(name, mp) {
if (!!mp)
this.maplist.set(name, mp);
else if (!!name)
assert.fail(Errors.EBADPARAM);
return this.maplist.entries();
} //map
} //RGLGround
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.