language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class SceneMenu extends Phaser.Scene {
constructor() {
super("SceneMenu");
}
preload() {
//CHAT POSTITIONS BEFORE - AFTER
var chtOffset = 1000;
chatTween = [
game.config.width - 625, game.config.height - 200, //icono
game.config.width - 300, game.config.height - 380, //base
game.config.width - 300, game.config.height - 380, //frame
game.config.width - 315, game.config.height - 110, //write msg
game.config.width - 55, game.config.height - 110, //send
game.config.width - 625, game.config.height - 400, //global
];
chatPos = [
game.config.width - 100, chatTween[1], //icono
chatTween[2] + chtOffset, chatTween[3], //base
chatTween[4] + chtOffset, chatTween[5], //frame
chatTween[6] + chtOffset, chatTween[7], //write msg
chatTween[8] + chtOffset, chatTween[9], //send
game.config.width - 100, chatTween[11] //global
];
//LOGIN POSTITIONS BEFORE - AFTER
var loginOffset = 4000
loginTween = [
660, 70, //login option
320, 80, //box
540, 80, //login dfault profile picture
110, 110, //login bttn
540, 80, //login profilepic
340, 110, //regiter button
110, 115, //field name
365, 115, //field password
540, 115, //login confirm
340, 110, //logout button
540, 90 //UserImg
];
loginPos = [
70, 70, //login option,
loginTween[2] - loginOffset, loginTween[3], //box
loginTween[4] - loginOffset, loginTween[5], //login dfault profile picture
loginTween[6] - loginOffset, loginTween[7], //login btn
loginTween[8] - loginOffset, loginTween[9], //login profilepic
loginTween[10] - loginOffset, loginTween[11], //register boton
loginTween[12] - loginOffset, loginTween[13], //field name
loginTween[14] - loginOffset, loginTween[15], //field pass
loginTween[16] - loginOffset, loginTween[17], //login confirm
loginTween[18] - loginOffset, loginTween[19], //logout button
loginTween[20] - loginOffset, loginTween[21]//UserImg
];
//REGISTER POSTITIONS BEFORE - AFTER
var registerOffset = chtOffset;
regisTween = [
game.config.width / 4, 310, //regisbox
game.config.width / 4 + 170, 400, //btn nfirm
game.config.width / 4 + 240, 340, //dech
game.config.width / 4 + 100, 340, //izq
110, 200, //cerrar
572, 286//userImg
];
regisPos = [
regisTween[0] - registerOffset, regisTween[1], //regisbox
regisTween[2] - registerOffset, regisTween[3], //boton regustrarse
regisTween[4] - registerOffset, regisTween[5], //dch
regisTween[6] - registerOffset, regisTween[7], //izq
regisTween[8] - registerOffset, regisTween[9], //cerrar
regisTween[10] - registerOffset, regisTween[11],//userImg
];
}
create() {
key_pause = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ESC, false);
soundtrack.pistas[1].stop();
soundtrack.pistas[3].stop();
//FONDOS
this.bckMenu = this.add.image(game.config.width / 2, game.config.height / 2, 'bckMenu').setScale(0.3);
var that = this;
this.spaceYlogo = this.add.image(300, game.config.height - 300, 'spaceYlogo').setScale(0.2);
this.tweens.add({
targets: this.spaceYlogo,
duration: 1500,
y: this.spaceYlogo.y - 25,
ease: 'linear',
yoyo: true,
repeat: -1,
});
this.earthLogo = this.add.image(game.config.width * 7 / 8, game.config.height * 1 / 4, 'earthLogo').setScale(0.2);
this.tweens.add({
targets: this.earthLogo,
duration: 2000,
y: this.earthLogo.y - 25,
ease: 'linear',
yoyo: true,
repeat: -1,
});
//ASIGNACION DE METODO
this.playButton = this.add.text((game.config.width / 8) * 3, -1000, 'Play', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.goCreateJoinLobby())
.on('pointerover', () => this.enterIconHoverState(this.playButton, this))
.on('pointerout', () => this.enterIconRestState(this.playButton));
this.playButton.setOrigin(0.5);
this.easeMe(this.playButton, this, 1);
this.tutorialButton = this.add.text((game.config.width / 2) * 4, -1000, 'Tutorial', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.enterTutorial())
.on('pointerover', () => this.enterIconHoverState(this.tutorialButton, this))
.on('pointerout', () => this.enterIconRestState(this.tutorialButton));
this.tutorialButton.setOrigin(0.5);
this.easeMe(this.tutorialButton, this, 2);
this.optionsButton = this.add.text(-1000, (game.config.height / 8) * 5, 'Options', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.enterOptions())
.on('pointerover', () => this.enterIconHoverState(this.optionsButton, this))
.on('pointerout', () => this.enterIconRestState(this.optionsButton));
this.optionsButton.setOrigin(0.5);
this.easeMe(this.optionsButton, this, 3);
this.contactButton = this.add.text(game.config.width + 1000, (game.config.height / 8) * 6, 'Contact', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.enterContact())
.on('pointerover', () => this.enterIconHoverState(this.contactButton, this))
.on('pointerout', () => this.enterIconRestState(this.contactButton));
this.contactButton.setOrigin(0.5);
this.easeMe(this.contactButton, this, 4);
//BOTONES HOST/JOIN/BACK
//****************
//Botones crear/unirse a partida
this.boxGameId = this.add.image((game.config.width / 2) * 4, -1000, "Login_Field").setScale(0.1, 0.18).setDepth(0).setVisible(true);
this.writeGameID = this.add.dom((game.config.width / 2) * 4, -1000).createFromCache('formLobby').setVisible(true).setDepth(0);
this.lobbyCode = this.add.text(game.config.width / 2, (game.config.height / 8) * 3.5, 'CODIGINHO', { fill: '#FEB600', fontFamily: 'menuFont', fontSize: '60px' })
.setVisible(false);
this.lobbyCode.setOrigin(0.5);
//HOST
this.hostButton = this.add.text((game.config.width / 8) * 3, -1000, 'Host', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.goHost())
.on('pointerover', () => this.enterIconHoverState(this.hostButton, this))
.on('pointerout', () => this.enterIconRestState(this.hostButton));
this.hostButton.setOrigin(0.5);
//JOIN
this.joinButton = this.add.text((game.config.width / 2) * 4, -1000, 'Join', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.goJoin())
.on('pointerover', () => this.enterIconHoverState(this.joinButton, this))
.on('pointerout', () => this.enterIconRestState(this.joinButton));
this.joinButton.setOrigin(0.5);
//BACK
this.backButton = this.add.text(-1000, (game.config.height / 8) * 5, 'Back', { fill: '#FEDEBE', fontFamily: 'menuFont', fontSize: '60px' })
.setInteractive()
.on('pointerdown', () => this.goBackToMenu())
.on('pointerover', () => this.enterIconHoverState(this.backButton, this))
.on('pointerout', () => this.enterIconRestState(this.backButton));
this.backButton.setOrigin(0.5);
//OPCION TIERRA
this.earthOption = this.add.image(game.config.width * 7 / 8, game.config.height * 1 / 4, 'earthLogo').setScale(0.2)
.setInteractive()
.on('pointerdown', () => this.selectEarth())
.on('pointerover', () => { if (election != "Mars") this.Highlight(this.earthOption, true); })
.on('pointerout', () => { if (election != "Mars") this.Highlight(this.earthOption, false); })
.setVisible(false);
this.earthOption.setOrigin(0.5);
//OPCION MARTE
this.marsOption = this.add.image(300, game.config.height - 300, 'spaceYlogo').setScale(0.2)
.setInteractive()
.on('pointerdown', () => this.selectMars())
.on('pointerover', () => { if (election != "Earth") this.Highlight(this.marsOption, true); })
.on('pointerout', () => { if (election != "Earth") this.Highlight(this.marsOption, false); })
.setVisible(false);
this.marsOption.setOrigin(0.5);
//TEXTO AVISO LOG NEEDED
this.loginNeededWarning = this.add.text(game.config.width / 2, game.config.height * 2 / 8, 'You need to be logged in', { fill: '#FF0000', fontFamily: 'menuFont', fontSize: '40px' })
.setVisible(false);
this.loginNeededWarning.setOrigin(0.5);
//TEXTO AVISO PLANET NEEDED
this.planetElectionNeededWarning = this.add.text(game.config.width / 2, game.config.height * 2 / 8, 'You need to choose a planet', { fill: '#FF0000', fontFamily: 'menuFont', fontSize: '40px' })
.setVisible(false);
this.planetElectionNeededWarning.setOrigin(0.5);
//TEXTO AVISO HOST INEXISTENTE
this.wrongCodeWarning = this.add.text(game.config.width / 2, game.config.height * 2 / 8, 'Wrong code: Lobby not found', { fill: '#FF0000', fontFamily: 'menuFont', fontSize: '40px' })
.setVisible(false);
this.wrongCodeWarning.setOrigin(0.5);
//TEXTO AVISO YA ERES HOST; NO PUEDES HACER JOIN
this.alreadyHostWarning = this.add.text(game.config.width / 2, game.config.height * 2 / 8, 'You are already hosting', { fill: '#FF0000', fontFamily: 'menuFont', fontSize: '40px' })
.setVisible(false);
this.alreadyHostWarning.setOrigin(0.5);
//*****************
var graphics = this.make.graphics();
graphics.fillRect(game.config.width / 6 * 4 + 10, game.config.height / 5 + 1, game.config.width / 6 * 4 + 300, game.config.height / 5 * 3 + 5);
var mask = new Phaser.Display.Masks.GeometryMask(this, graphics);
//LOBBY
this.lobbyContent = ["Connected Users: "];
loadLobby(this);
this.lobbyText = this.add.text(game.config.width / 6 * 4 + 10, game.config.height / 5 + 10, this.lobbyContent,
{ fontSize: "25px", fontFamily: 'menuFont', color: 'white', wordWrap: { width: 450 } }).setOrigin(0);
this.lobbyText.setMask(mask).setVisible(false).setDepth(1000);
this.numPlayers = updateUsers(this);
this.numPlayersTxt = this.add.text(game.config.width * 3.25 / 4, (game.config.height / 8) * 6.8, "REGISTERED USERS: " + this.numPlayers, { fill: '#FFFFFF', fontFamily: 'menuFont', fontSize: '40px' });
this.numPlayersTxt.setOrigin(0.5).setVisible(false).setDepth(1000);
this.serverOnlineTxt = this.add.text(game.config.width * 3.25 / 4, (game.config.height / 8) * 7.2, "SERVER ¿?", { fill: '#FFFFFF', fontFamily: 'menuFont', fontSize: '40px' });
this.serverOnlineTxt.setOrigin(0.5).setVisible(false).setDepth(1000);
isServerOnline(this);
//global icon
this.globalbutton = this.add.image(chatPos[10], chatPos[11], 'ChatBox_GlobalIcon') //CAMBIAR POR ChatBox_NewMsgIcon cuando haya nuevo mensaje
.setScale(0.6);
this.globalbutton.setInteractive()
.on('pointerdown', () => this.MovinBoxes(this, 0))
.on('pointerover', () => this.enterIconHoverState(this.globalbutton, this))
.on('pointerout', () => this.enterIconRestState(this.globalbutton))
this.globalbutton.setOrigin(0.5);
//CHATBOX
//Chatbox icon
this.chatbutton = this.add.image(chatPos[0], chatPos[1], 'ChatBox_ChatIcon') //CAMBIAR POR ChatBox_NewMsgIcon cuando haya nuevo mensaje
.setScale(0.6);
this.chatbutton.setInteractive()
.on('pointerdown', () => this.MovinBoxes(this, 1))
.on('pointerover', () => this.enterIconHoverState(this.chatbutton, this))
.on('pointerout', () => this.enterIconRestState(this.chatbutton))
this.chatbutton.setOrigin(0.5);
//chatbox base
this.chatBase = this.add.image(chatPos[2], chatPos[3], 'ChatBox_Base')
.setScale(0.8);
this.chatBase.setOrigin(0.5);
//chatbox write msg
this.chatWritter = this.add.image(chatPos[6], chatPos[7], 'ChatBox_MsgBox')
.setScale(0.37);
this.chatWritter.setOrigin(0.5);
//chatbox send
this.sendButton = this.add.image(chatPos[8], chatPos[9], 'ChatBox_SendBtn')
.setScale(0.4);
this.sendButton.setInteractive()
.on('pointerdown', () => RestCreateMsg(this, userName))
.on('pointerover', () => this.enterIconHoverState(this.sendButton, this))
.on('pointerout', () => this.enterIconRestState(this.sendButton))
this.sendButton.setOrigin(0.5);
this.chatboxStuff = [this.chatbutton, this.chatBase, this.chatFrame, this.chatWritter, this.sendButton, this.globalbutton];
var key_enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER, false);
key_enter.on('down', () => RestCreateMsg(this, userName));
//Chatbox code
this.chatContent = [];
loadMsgs(this);
this.chatText = this.add.text(game.config.width / 6 * 4 + 10, game.config.height / 5 + 10, this.chatContent, { fontSize: "25px", fontFamily: 'menuFont', color: 'white', wordWrap: { width: 450 } }).setOrigin(0);
this.chatText.setMask(mask).setVisible(false);
var zone = this.add.zone(game.config.width / 6 * 4 + 10, game.config.height / 5 + 1, 320, game.config.height / 5 * 3 + 5).setOrigin(0).setInteractive();
var that = this;
zone.on('pointermove', function (pointer) {
if (pointer.isDown) {
that.chatText.y += (pointer.velocity.y / 10);
that.chatText.y = Phaser.Math.Clamp(that.chatText.y, (game.config.height / 5 + 10) - (25 * lineasChat), game.config.height / 5 + 10);
}
});
this.writeTextChat = this.add.dom(1280, 785).createFromCache('formChat').setVisible(false);
//REGISTER
//register box
this.registerBox = this.add.image(regisPos[0], regisPos[1], 'Register_Form')
.setScale(0.4);
this.registerBox.setOrigin(0.5);
//Register button
this.registerBtn = this.add.image(regisPos[2], regisPos[3], 'Confirm_Btn')
.setScale(0.34);
this.registerBtn.setInteractive()
.on('pointerdown', () => this.goCreateUser())
.on('pointerover', () => this.enterIconHoverState(this.registerBtn, this))
.on('pointerout', () => this.enterIconRestState(this.registerBtn))
this.registerBtn.setOrigin(0.5);
//RegisterImg
this.regUserImgNum = 1;
this.userImg = this.add.image(regisPos[10], regisPos[11], 'userImages', this.regUserImgNum).setScale(0.16).setOrigin(0.5);
//Register next img
this.nextImg = this.add.image(regisPos[4], regisPos[5], 'Register_Arrow')
.setScale(0.4);
this.nextImg.setInteractive()
.on('pointerdown', () => this.RegNextImg(1))
.on('pointerover', () => this.enterIconHoverState(this.nextImg, this))
.on('pointerout', () => this.enterIconRestState(this.nextImg))
this.nextImg.setOrigin(0.5);
//Register prev img
this.prevImg = this.add.image(regisPos[6], regisPos[7], 'Register_Arrow')
.setScale(-0.4, 0.4);
this.prevImg.setInteractive()
.on('pointerdown', () => this.RegNextImg(-1))
.on('pointerover', () => this.enterIconHoverState(this.prevImg, this))
.on('pointerout', () => this.enterIconRestState(this.prevImg))
this.prevImg.setOrigin(0.5);
//register close
this.registerClose = this.add.image(regisPos[8], regisPos[9], 'Register_Close')
.setScale(0.17);
this.registerClose.setInteractive()
.on('pointerdown', () => this.MovinBoxes(this, 3))
.on('pointerover', () => this.enterIconHoverState(this.registerClose, this))
.on('pointerout', () => this.enterIconRestState(this.registerClose))
this.registerStuff = [this.registerBox, this.registerBtn, this.nextImg, this.prevImg, this.registerClose, this.userImg];
//LOGIN
//login option
//box
//login dfault profile picture
//login btn
//login profilepic
//registro iniciar
//Login box
this.loginBox = this.add.image(loginPos[2], loginPos[3], 'Login_Box')
.setScale(0.14);
this.loginBox.setOrigin(0.5);
//icono para abrir login
this.loginOption = this.add.image(loginPos[0], loginPos[1], 'Login_Option')
.setScale(0.7);
this.loginOption.setOrigin(0.5);
this.loginOption.setInteractive()
.on('pointerdown', () => this.MovinBoxes(this, 2))
.on('pointerover', () => this.enterIconHoverState(this.loginOption))
.on('pointerout', () => this.enterIconRestState(this.loginOption))
//login default picture
this.loginDfPic = this.add.image(loginPos[4], loginPos[5], 'Login_Default')
.setScale(0.15);
//login button to log in
this.loginBtn = this.add.image(loginPos[6], loginPos[7], 'Login_Btn')
.setScale(0.35);
this.loginBtn.setInteractive()
.on('pointerdown', () => this.ShowLoginFields(this, true))
.on('pointerover', () => this.enterIconHoverState(this.loginBtn, this))
.on('pointerout', () => this.enterIconRestState(this.loginBtn));
//login picture
this.loginProfilepic = this.add.image(loginPos[8], loginPos[9], 'Login_Profile')
.setScale(0.15);
//login botn regitrarse
this.loginRegister = this.add.image(loginPos[10], loginPos[11], 'Register_Btn')
.setScale(0.35);
this.loginRegister.setInteractive()
.on('pointerdown', () => this.MovinBoxes(this, 3))
.on('pointerover', () => this.enterIconHoverState(this.loginRegister))
.on('pointerout', () => this.enterIconRestState(this.loginRegister));
//login field name base
this.loginNameField = this.add.image(loginPos[12], loginPos[13], 'Login_Field')
.setScale(0.12).setVisible(false);
//login field pass base
this.loginPassField = this.add.image(loginPos[14], loginPos[15], 'Login_Field')
.setScale(0.12).setVisible(false);
//Login send button
this.loginConfirm = this.add.image(loginPos[20], loginPos[21], 'Confirm_Btn')
.setScale(0.3)
.setInteractive()
.on('pointerdown', () => this.goLogInText())
.on('pointerover', () => this.enterIconHoverState(this.loginConfirm, this))
.on('pointerout', () => this.enterIconRestState(this.loginConfirm))
.setVisible(false);
//Log out button
this.logOutBtn = this.add.image(loginPos[23], loginPos[24], 'Logout_Btn')
.setScale(0.35);
this.logOutBtn.setInteractive()
.on('pointerdown', () => this.goLogOut())
.on('pointerover', () => this.enterIconHoverState(this.logOutBtn, this))
.on('pointerout', () => this.enterIconRestState(this.logOutBtn))
this.logOutBtn.setOrigin(0.5);
this.logOutBtn.setActive(false);
this.logOutBtn.setVisible(false);
//UserImage
this.userImage = this.add.image(loginPos[27], loginPos[28], 'userImages', 0).setScale(0.1);
this.loginStuff = [this.loginOption, this.loginBox, this.loginDfPic, this.loginBtn, this.loginProfilepic, this.loginRegister, this.loginNameField,
this.loginPassField, this.loginConfirm, this.logOutBtn, this.userImage];
//Campos Login
this.accountText = this.add.text(20, 52, 'Please enter in your account', { fill: 'white', fontFamily: 'menuFont', fontSize: '35px' });
this.accountText.setOrigin(0, 0.5).setVisible(false);
this.accountLogin = this.add.dom(260, 113).createFromCache('nameform').setVisible(false);
this.accountLogin.addListener('click');
//Campos Registro
this.regLogin = this.add.dom(275, 330).createFromCache('formReg').setVisible(false);
//SelectMarsImg
this.regUserImgNum = 1;
this.regLogin = this.add.dom(275, 330).createFromCache('formReg').setVisible(false);
//Timer
this.event = this.time.addEvent({ delay: 300, callback: this.UpdateServer, callbackScope: this, loop: true });
if (userName != "Anon") {
GetUserImg(this, userName)
this.userImage.setPosition(-400, loginPos[28]);
this.accountText.setColor("white");
this.accountText.setText('Welcome, ' + userName + " !");
this.logOutBtn.setPosition(-400, loginPos[24]);
this.logOutBtn.setVisible(true);
this.logOutBtn.setActive(true);
}
game.input.keyboard.enabled = false
var that = this;
this.writeTextChat.getChildByName("Chat")
.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
RestCreateMsg(that, userName);
}
});
// Desconexión de usuario si refresca la página
window.onbeforeunload = function(){
if (userName != "Anon") {
setUserOnline(that, userName, false);
}
}
}
Highlight(obj, b, selectPlanet) {
if (selectPlanet == "Mars") {
obj.alpha = 1;
obj.tint = Phaser.Display.Color.GetColor(255, 255, 255);
this.earthOption.alpha = 0.4;
}
else if (selectPlanet == "Earth") {
obj.alpha = 1;
obj.tint = Phaser.Display.Color.GetColor(255, 255, 255);
this.marsOption.alpha = 0.4;
}
else
b ? obj.tint = Phaser.Display.Color.GetColor(139, 139, 139) : obj.tint = Phaser.Display.Color.GetColor(255, 255, 255);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//Llamada desde el start
goCreateJoinLobby() {
this.playButton.setActive(false);
this.tutorialButton.setActive(false);
this.optionsButton.setActive(false);
this.contactButton.setActive(false);
this.easeMeOut(this.playButton, this, 1);
this.easeMeOut(this.tutorialButton, this, 2);
this.easeMeOut(this.optionsButton, this, 3);
this.easeMeOut(this.contactButton, this, 4);
this.easeSelectionLogo(this.earthOption, this, 1);
this.easeSelectionLogo(this.marsOption, this, 2);
this.earthOption.setVisible(true);
this.marsOption.setVisible(true);
this.earthLogo.setVisible(false);
this.spaceYlogo.setVisible(false);
this.hostButton.setInteractive = false;
this.boxGameId.setVisible(true);
this.writeGameID.setVisible(true);
this.hostButton.setActive(true);
this.joinButton.setActive(true);
this.backButton.setActive(true);
this.easeMe(this.hostButton, this, 1);
this.easeMe(this.joinButton, this, 2);
this.easeMe(this.boxGameId, this, 5);
this.easeMe(this.writeGameID, this, 6);
this.easeMe(this.backButton, this, 3);
}
//Llamada desde el Back
goBackToMenu() {
//Si vuelvo al menú y había creado una conexión, la cierro
if (connection != undefined) {
connection.close();
}
//Borro el id del lobby al que iba a ir para tener buen control de los datos
if (gameLobbyID != undefined) {
gameLobbyID = undefined;
}
this.playButton.setActive(true);
this.tutorialButton.setActive(true);
this.optionsButton.setActive(true);
this.contactButton.setActive(true);
this.easeMe(this.playButton, this, 1);
this.easeMe(this.tutorialButton, this, 2);
this.easeMe(this.optionsButton, this, 3);
this.easeMe(this.contactButton, this, 4);
this.easeOutSelectionLogo(this.earthOption, this, 1);
this.easeOutSelectionLogo(this.marsOption, this, 2);
this.Highlight(this.earthOption, false);
this.Highlight(this.marsOption, false);
this.earthOption.alpha = 1;
this.marsOption.alpha = 1;
this.lobbyCode.setVisible(false);
this.boxGameId.setVisible(false);
this.writeGameID.setVisible(false);
this.hostButton.setActive(false);
this.joinButton.setActive(false);
this.backButton.setActive(false);
this.easeMeOut(this.hostButton, this, 1);
this.easeMeOut(this.joinButton, this, 2);
this.easeMeOut(this.boxGameId, this, 5);
this.easeMeOut(this.writeGameID, this, 6);
this.easeMeOut(this.backButton, this, 3);
}
selectEarth() {
election = "Earth";
this.Highlight(this.earthOption, true, "Earth");
}
selectMars() {
election = "Mars";
this.Highlight(this.marsOption, true, "Mars");
}
//Llamada desde el Host
goHost() {
var texto = this.lobbyCode;
var boton = this.hostButton;
if (userName != "Anon" && connection == undefined && election != undefined) {
connection = new WebSocket("wss://" + urlServer + "/lobbies");
connection.onopen = function () {
var data = {
action: "Create"
}
connection.send(JSON.stringify(data));
}
var that = this;
connection.onmessage = function (msg) {
var data = JSON.parse(msg.data);
switch (data["type"]) {
case "connected":
gameLobbyID = data["lobbyID"];
texto.text = data["lobbyID"];
boton.setInteractive = false;
texto.setVisible(true);
break;
case "startGame":
if (data["gamemode"] == "Mars")
that.startGame('SceneMars');
else
that.startGame('SceneEarth');
break;
case "playerJoined":
var data = {
action: "startGame",
gamemode: election,
}
connection.send(JSON.stringify(data));
break;
case "otherClientDisconnected":
break;
}
}
connection.onclose = function () {
connection = undefined;
texto = "";
}
}
else {
if (userName == "Anon") {
//Aviso de que se tiene que registrar
this.tweenFadeIn(this.loginNeededWarning, this);
this.tweenFadeOut(this.loginNeededWarning, this);
}
else if (election == undefined) {
//Aviso de que tiene que elegir un planeta
this.tweenFadeIn(this.planetElectionNeededWarning, this);
this.tweenFadeOut(this.planetElectionNeededWarning, this);
}
}
}
//Llamada desde el Join
goJoin() {
var code = this.writeGameID;
if (userName != "Anon" && connection == undefined) {
connection = new WebSocket("wss://" + urlServer + "/lobbies");
connection.onopen = function () {
var data = {
action: "Join",
lobbyID: code.getChildByName("lobbyID").value,
}
gameLobbyID = code.getChildByName("lobbyID").value;
connection.send(JSON.stringify(data));
}
var that = this;
connection.onmessage = function (msg) {
var data = JSON.parse(msg.data);
switch (data["type"]) {
case "connected":
break;
case "error":
console.error("Error en la conexión: " + data["cause"]);
//Aviso de que no existe un lobby con esa ID
that.tweenFadeIn(that.wrongCodeWarning, that);
that.tweenFadeOut(that.wrongCodeWarning, that);
connection.close();
break;
case "startGame":
election = data["gamemode"];
if (data["gamemode"] == "Mars")
that.startGame('SceneMars');
else
that.startGame('SceneEarth'); 333
break;
}
}
connection.onclose = function () {
connection = undefined;
}
} else if (userName == "Anon") {
this.tweenFadeIn(this.loginNeededWarning, this);
this.tweenFadeOut(this.loginNeededWarning, this);
} else if (connection != undefined) {
this.tweenFadeIn(this.alreadyHostWarning, this);
this.tweenFadeOut(this.alreadyHostWarning, this);
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
RegNextImg(dir) {
this.regUserImgNum += dir;
if (this.regUserImgNum === 5)
this.regUserImgNum = 1;
if (this.regUserImgNum === 0)
this.regUserImgNum = 4;
this.userImg.setFrame(this.regUserImgNum);
}
UpdateServer() {
if (chatBoxOut) {
loadLobby(this);
loadMsgs(this);
}
}
goLogInText() {
this.accountText.setColor("white");
this.accountText.setText('Logging in...');
var inputName = this.accountLogin.getChildByName('user');
var inputPassword = this.accountLogin.getChildByName('password');
// ¿Está conectado?
if (isUserOnline(this, inputName.value)) {
this.accountText.setColor("red");
this.accountText.setText('User already logged in');
}
else
// Han metido algo?
if (inputName.value !== '' && inputPassword.value !== '') {
CheckUserPasswordCorrect(this, inputName.value, inputPassword.value);
}
else {
this.accountText.setColor("red");
this.accountText.setText('User or password incomplete');
}
}
goLogOut() {
this.accountText.setText('Logging out...');
setUserOnline(this, userName, false);
}
goCreateUser() {
this.accountText.setColor("white");
this.accountText.setText('Registering...');
var user = this.regLogin.getChildByName("user").value;
var email = this.regLogin.getChildByName("email").value;
var pass = this.regLogin.getChildByName("pass").value;
var passConfirm = this.regLogin.getChildByName("passConfirm").value;
if (user !== "" && email !== "" && pass !== "" && passConfirm !== "") {
if (pass === passConfirm) {
RestCreateUser(this, user, pass, this.regUserImgNum);
}
else {
this.accountText.setColor("red");
this.accountText.setText('Password doesnt match');
}
}
else {
this.accountText.setColor("red");
this.accountText.setText('Please fill all fields');
}
}
//INTERACTIVIDAD
enterIconHoverState(boton, scene) {
sfx.sounds[1].play();
boton.x = boton.x + movTxt;
boton.y = boton.y + movTxt;
}
enterIconRestState(boton) {
boton.x = boton.x - movTxt;
boton.y = boton.y - movTxt;
}
//click
startGame(nextScene) {
connection.close();
sfx.sounds[0].play();
clientGamemode = nextScene;
if (election == "Mars")
this.Rocketeing(this.marsOption, this, this.marsOption.x, 900, 2, nextScene);
else
this.Rocketeing(this.earthOption, this, this.earthOption.x, 900, 2, nextScene);
}
enterTutorial() {
soundtrack.pistas[0].stop();
sfx.sounds[0].play();
this.tweens.add({
targets: [this.playButton, this.optionsButton, this.tutorialButton, this.contactButton],
//delay: 100,
alpha: 0,
duration: 2000,
ease: 'Expo.easeOut',
onComplete: this.scene.start('SceneTutorial')
});
//fin transicion
isTutorial = true;
}
enterOptions() {
sfx.sounds[0].play();
this.scene.start('SceneOptions');
}
enterContact() {
sfx.sounds[0].play();
this.scene.start('SceneContact');
}
enterAPIREST() {
sfx.sounds[0].play();
this.scene.start('SceneREST');
}
enterButtonHoverState(boton) {
sfx.sounds[1].play();
boton.setStyle({ fill: '#FE6E00' });
boton.x = boton.x + movTxt;
boton.y = boton.y + movTxt;
}
enterButtonRestState(boton) {
boton.setStyle({ fill: '#FEDEBE' });
boton.x = boton.x - movTxt;
boton.y = boton.y - movTxt;
}
//USALO COMO ES DEBIDO PEPE :D
Rocketeing(object, scene, xPos, yPos, shake, nextScene) {
var dir = 1;
var loopTime = 10;
var motion; //landing - launching
if (yPos < 0) { //si está lanzandose
motion = 'Expo.easeOut';
}
else { //si aterriza
motion = 'Expo.easeIn'
}
scene.tweens.add({
targets: object,
props: {
x: {
value:
function () {
return xPos + (dir *= -1) * shake;
},
ease: 'Linear',
duration: loopTime, //cuanto mas bajo más potente
yoyo: true, //ida y vuelta
repeat: -1, // que se repita en bucle este ease en x
},
y: {
value: function () {
return object.y -= yPos;
},
ease: motion,
duration: yPos //que el ease en y dure 3s
},
},
duration: 100, //que todo el tween dure
});
this.contactButton.setVisible(false);
this.optionsButton.setVisible(false);
this.tutorialButton.setVisible(false);
isTutorial = false;
var that = this;
var timedEvent = this.time.addEvent({
delay: yPos + 500, callback: function () {
isTutorial = false;
this.scene.start(nextScene);
}, callbackScope: this
});
//VAR CONNECTION POR AQUÍ
}
//Show login fields
ShowLoginFields(scene, show) {
scene.loginRegister.setActive(false);
scene.loginRegister.setVisible(false);
scene.loginBtn.setActive(false);
scene.loginBtn.setVisible(false);
//campos y textos
scene.loginNameField.setActive(false);
scene.loginNameField.setVisible(false);
scene.loginPassField.setVisible(false);
scene.loginPassField.setActive(false);
scene.loginConfirm.setVisible(false);
scene.loginConfirm.setActive(false);
scene.accountLogin.setVisible(false);
scene.accountLogin.setActive(false);
if (userName === "Anon") {
//mostramos oscultamos register y log in buttons
scene.loginRegister.setActive(!show);
scene.loginRegister.setVisible(!show);
scene.loginBtn.setActive(!show);
scene.loginBtn.setVisible(!show);
//campos y textos
scene.loginNameField.setActive(show);
scene.loginNameField.setVisible(show);
scene.loginPassField.setVisible(show);
scene.loginPassField.setActive(show);
scene.loginConfirm.setVisible(show);
scene.loginConfirm.setActive(show);
scene.accountLogin.setVisible(show);
scene.accountLogin.setActive(show);
scene.logOutBtn.setVisible(false);
scene.logOutBtn.setActive(false);
}
sfx.sounds[0].play();
loginOut = !loginOut;
}
CheckLoggedIn(scene) {
if (userName !== 'Anon') {
scene.loginRegister.setActive(false);
scene.loginRegister.setVisible(false);
scene.loginBtn.setActive(false);
scene.loginBtn.setVisible(false);
scene.loginNameField.setActive(false);
scene.loginNameField.setVisible(false);
scene.loginPassField.setVisible(false);
scene.loginPassField.setActive(false);
scene.loginConfirm.setVisible(false);
scene.loginConfirm.setActive(false);
scene.logOutBtn.setVisible(true);
scene.logOutBtn.setActive(true);
}
}
CloseChat(scene) {
var nX = 0; var nY = 1;
scene.chatWritter.setVisible(false);
scene.sendButton.setVisible(false);
scene.chatText.setVisible(false);
scene.writeTextChat.setVisible(false);
scene.lobbyText.setVisible(false);
scene.numPlayersTxt.setVisible(false);
scene.serverOnlineTxt.setVisible(false);
for (let i = 0; i < scene.chatboxStuff.length; i++) {
scene.tweens.add({
targets: scene.chatboxStuff[i],
x: chatPos[nX],
y: chatPos[nY],
duration: 100,
ease: 'Bounce.easeIn',
});
nX += 2; nY += 2;
}
chatBoxOut = false;
chatBoxActive = false;
lobbyActive = false;
}
OpenChat(scene) {
var nX = 0; var nY = 1;
for (let i = 0; i < scene.chatboxStuff.length; i++) {
scene.tweens.add({
targets: scene.chatboxStuff[i],
x: chatTween[nX],
y: chatTween[nY],
duration: 100,
ease: 'Bounce.easeOut',
});
nX += 2; nY += 2;
}
chatBoxOut = true;
}
ChatManager(scene, id) {
if (!chatBoxActive && chatBoxOut && !lobbyActive) {
this.CloseChat(scene);
}
if (chatBoxActive && !chatBoxOut && !lobbyActive) //abrimos chat
{
scene.chatWritter.setVisible(true);
scene.sendButton.setVisible(true);
scene.chatText.setVisible(true);
scene.writeTextChat.setVisible(true);
scene.lobbyText.setVisible(false);
scene.numPlayersTxt.setVisible(false);
scene.serverOnlineTxt.setVisible(false);
this.OpenChat(scene);
}
if (!chatBoxActive && !chatBoxOut && lobbyActive) //abrimos lobby
{
scene.chatWritter.setVisible(false);
scene.sendButton.setVisible(false);
scene.chatText.setVisible(false);
scene.writeTextChat.setVisible(false);
scene.lobbyText.setVisible(true);
scene.numPlayersTxt.setVisible(true);
scene.serverOnlineTxt.setVisible(true);
this.OpenChat(scene);
}
if (chatBoxActive && chatBoxOut && lobbyActive) {
if (id == 0) {
scene.chatWritter.setVisible(false);
scene.sendButton.setVisible(false);
scene.chatText.setVisible(false);
scene.writeTextChat.setVisible(false);
scene.lobbyText.setVisible(true);
scene.numPlayersTxt.setVisible(true);
scene.serverOnlineTxt.setVisible(true);
chatBoxActive = false;
}
else {
scene.chatWritter.setVisible(true);
scene.sendButton.setVisible(true);
scene.chatText.setVisible(true);
scene.writeTextChat.setVisible(true);
scene.lobbyText.setVisible(false);
scene.numPlayersTxt.setVisible(false);
scene.serverOnlineTxt.setVisible(false);
lobbyActive = false;
}
}
}
//sacar el chat
MovinBoxes(scene, id) {
sfx.sounds[1].play();
var nX = 0; var nY = 1;
switch (id) {
case 0: // Abrir cerrar lobby
lobbyActive = !lobbyActive;
this.ChatManager(scene, id);
break;
case 1: //abrir cerrar chatbox chatbox
chatBoxActive = !chatBoxActive;
this.ChatManager(scene, id);
break;
case 2: //login loginBox,loginOption;
if (loginOut) //guardar log in
{
for (let i = 0; i < scene.loginStuff.length; i++) {
scene.tweens.add({
targets: scene.loginStuff[i],
x: loginPos[nX],
y: loginPos[nY],
duration: 100,
ease: 'Bounce.easeOut',
});
nX += 2; nY += 2;
}
loginOut = true;
this.ShowLoginFields(scene, loginOut);
this.accountText.setVisible(false);
this.accountLogin.setVisible(false);
this.accountLogin.setVisible(false);
this.accountLogin.setActive(false);
}
else if (!loginOut) //sacar log in
{
this.accountText.setVisible(true);
for (let i = 0; i < scene.loginStuff.length; i++) {
scene.tweens.add({
targets: scene.loginStuff[i],
x: loginTween[nX],
y: loginTween[nY],
duration: 100,
ease: 'Bounce.easeOut',
});
nX += 2; nY += 2;
}
loginOut = false;
this.ShowLoginFields(scene, loginOut);
}
break;
case 3: //register registerBox, registerBtn, nextImg, prevImg;
if (registerOut) //guardar register
{
this.regLogin.setVisible(false);
this.accountText.setColor("white");
this.accountText.setText('Please enter in your account');
for (let i = 0; i < scene.registerStuff.length; i++) {
scene.tweens.add({
targets: scene.registerStuff[i],
x: regisPos[nX],
y: regisPos[nY],
duration: 100,
ease: 'Expo.easeOut',
});
nX += 2; nY += 2;
}
registerOut = false
}
else if (!registerOut) //sacar register
{
this.regLogin.setVisible(true);
for (let i = 0; i < scene.registerStuff.length; i++) {
scene.tweens.add({
targets: scene.registerStuff[i],
x: regisTween[nX],
y: regisTween[nY],
duration: 100,
ease: 'Expo.easeOut',
});
nX += 2; nY += 2;
}
registerOut = true
}
break;
}
}
//LOGIN
//EASINGS
easeMe(boton, scene, nOp) {
var endX;
var endY;
switch (nOp) {
case 1: endX = game.config.width / 2; endY = (game.config.height / 8) * 3; break;
//Altura boton Play
case 1: endX = game.config.width / 2; endY = (game.config.height / 8) * 3; break;
//Altura boton Tutorial
case 2: endX = game.config.width / 2; endY = (game.config.height / 8) * 4; break;
//Altura boton Options
case 3: endX = game.config.width / 2; endY = (game.config.height / 8) * 5; break;
//Altura boton contacts
case 4: endX = game.config.width / 2; endY = (game.config.height / 8) * 6; break;
//this.boxgameId >> sprite blanco caja
case 5: endX = game.config.width / 2; endY = (game.config.height / 16) * 9; break;
//this.writeGameID >> texto de caja codigo join
case 6: endX = game.config.width / 2; endY = (game.config.height / 50) * 29; break;
default: break;
}
scene.tweens.add({
targets: boton,
x: endX,
y: endY,
delay: nOp * 100,
duration: 500,
ease: 'Circ.easeOut',
repeat: 0,
yoyo: false,
});
}
//EASINGS INVERTIDOS
easeMeOut(boton, scene, nOp) {
var endX;
var endY;
switch (nOp) {
//Altura boton Play
case 1: endX = (game.config.width / 8) * 3; endY = -1000; break;
//Altura boton Tutorial
case 2: endX = (game.config.width / 2) * 4; endY = -1000; break;
//Altura boton Options
case 3: endX = -1000; endY = (game.config.height / 8) * 5; break;
//Altura boton contacts
case 4: endX = game.config.width + 1000; endY = (game.config.height / 8) * 6; break;
//this.boxgameId
case 5: endX = (game.config.width / 2) * 4; endY = -1000; break;
//this.writeGameID
case 6: endX = (game.config.width / 2) * 4; endY = -1000; break;
default: break;
}
scene.tweens.add({
targets: boton,
x: endX,
y: endY,
delay: nOp * 100,
duration: 500,
ease: 'Circ.easeOut',
repeat: 0,
yoyo: false,
});
}
easeSelectionLogo(logo, scene, nOp) {
var endX;
var endY;
var scale;
switch (nOp) {
//Altura logo tierra
case 1: endX = game.config.width * 5 / 8; endY = game.config.height * 3 / 8; scale = 0.1; break;
//Altura logo marte
case 2: endX = game.config.width * 3 / 8; endY = game.config.height * 3 / 8; scale = 0.04; break;
default: break;
}
scene.tweens.add({
targets: logo,
x: endX,
y: endY,
scaleX: scale,
scaleY: scale,
delay: 0,
duration: 500,
ease: 'Circ.easeOut',
repeat: 0,
yoyo: false,
});
}
easeOutSelectionLogo(logo, scene, nOp) {
var endX;
var endY;
var scale = 0.2;
var that = this;
switch (nOp) {
//Altura logo tierra
case 1: endX = game.config.width * 7 / 8; endY = game.config.height * 1 / 4; break;
//Altura logo marte
case 2: endX = 300; endY = game.config.height - 300; break;
default: break;
}
scene.tweens.add({
targets: logo,
x: endX,
y: endY,
scaleX: 0.2,
scaleY: 0.2,
delay: 0,
duration: 500,
ease: 'Circ.easeOut',
repeat: 0,
yoyo: false,
onComplete: function () {
logo.setVisible(false);
that.earthLogo.setVisible(true);
that.spaceYlogo.setVisible(true);
}
});
}
//Fade del texto
tweenFadeIn(texto, escena) {
var that = this;
escena.tweens.add({
targets: texto,
alpha: 0,
duration: 12000,
ease: 'Cubic.easeOut',
repeat: 0,
yoyo: false,
onStart: function () { texto.setVisible(true); texto.alpha = 1; },
onComplete: function () { texto.setVisible(false); },
});
}
tweenFadeOut(texto, escena) {
var that = this;
escena.tweens.add({
targets: texto,
alpha: 0,
duration: 10000,
ease: 'Cubic.easeOut',
repeat: 0,
yoyo: false,
onComplete: function () { texto.setVisible(false); texto.alpha = 1; },
});
}
} |
JavaScript | class OdinssonBot {
/**
* @param {Object} config for running bot.
* @param {array} commands to match and execute against messages.
* @param {Logger} logger used to log.
*/
constructor(config, commands, logger, database) {
// Initialize bot for interacting with Discord
this.bot = new Discord.Client();
// Config for bot behaviour and connecting to Discord
this.config = config;
// Top level commands that can be executed via discord messages
this.commands = commands;
// Logging provider to log with
this.logger = logger;
// Database for remembering data
this.database = database;
// Instantiating jobs
this.worldBackupJob = new ValheimWorldBackupJob(this.logger);
// Instantiating helpers
this.embedHelper = new ValheimServerStatusEmbedHelper(this.config, this.logger);
}
/**
* Prepares Odinsson for the journey ahead.
* (Starts scheduled jobs and signal handling).
*/
prepare() {
this.logger.log('Odinsson is rallying warriors of the 10th world!')
// Start job to backup valheim world at scheduled times
if (this.config.schedules.backups.length > 0) {
this.worldBackupJob.start(this.config.schedules.backups);
}
// On process termination, update discord with a server offline message
process.on('SIGTERM', async () => {
this.logger.log('Odinsson is off to the mead hall!');
try {
await this.embedHelper.sendOfflineStatus(this.bot.guilds.cache);
this.logger.log('Odinsson is face down in mead!');
} catch (error) {
this.logger.log('Odinsson\'s mead has soured!');
this.logger.log(error, 'error');
}
this.bot.destroy();
this.logger.log('Odinsson is sleeping in the mead hall!');
// make sure to always exit the process!
process.exit(0);
});
}
/**
* Takes in an array of commands and add it to the bots top level commands.
*
* @param {Command[]} commands to be executed on messages received.
*/
load(commands) {
this.commands.push.apply(this.commands, commands);
}
/**
* Listens for and responds to messages in discord.
*/
listen() {
this.logger.log('Odinsson is lifting the sails!');
// Wait for bot to be ready to process messages
this.bot.once('ready', () => {
this.logger.log('Odinsson is sailing the seas of Valhalla!');
this.embedHelper.sendOnlineStatus(this.bot.guilds.cache);
});
// listen for messages
this.bot.on('message', (message) => {
// Bots are unworthy of Odinsson (and can result in infinite bot message loops)
if (message.author.bot) {
return;
}
// Attempt to interpret and respond to messages that mention Odinsson
if (message.mentions.users.has(this.config.secrets.client_id)) {
let foundMatch = false;
let content = message.content.replace(`<@!${this.config.secrets.client_id}>`, '').trim();
this.commands.every((command) => {
let args;
if (args = command.match(content)) {
this.logger.log(`Matched ${command.name}: "${content}"`);
command.respond(message, args);
foundMatch = true;
return false; // Found match, stop iterating
}
return true; // Match not yet found, keep iterating
});
if (!foundMatch) {
this.logger.log(`Failed to match: "${content}"`);
}
}
});
this.bot.login(this.config.secrets.token);
}
} |
JavaScript | class Jogador {
constructor(Leitor, Sensor) {
this._leitor = Leitor;
this._sensor = Sensor;
this._deciding;
this.status = 'INICIADO!';
this.isActive = 1;
this.tempoExec = 0;
}
start(interval) {
console.log('\nJogador iniciado!\n');
robot.moveMouseSmooth(this._leitor._dinoEyeOffset.X, this._leitor._dinoEyeOffset.Y);
robot.mouseClick('left');
robot.keyTap('up');
this._deciding = setInterval(this.decide.bind(this), interval);
}
decide() {
let t0 = performance.now();
if (this._sensor.distancia < 85) robot.keyTap('up');
this.isActive = 0;
let gameOverAreaCapture = this._leitor.capturePixels('GAME_OVER');
let X = 0;
while (X < gameOverAreaCapture.width) {
let Y = 0;
while (Y < gameOverAreaCapture.height) {
if(gameOverAreaCapture.colorAt(X, Y) != GAME_COLOR) this.isActive = 1;
Y++;
}
X++;
}
if(!this.isActive){
this.status = 'GAME OVER!';
this._sensor.stop();
this.stop();
return;
}
this.status = 'ATIVO!';
this.tempoExec = (performance.now() - t0).toFixed(1);
}
stop(){
clearInterval(this._deciding);
this._deciding = false;
}
} |
JavaScript | class PropertyViewModel{
// this is an observable array of the todo of our todo editor
// it is marked as observable because also adding and removing elements
// from the todo list should be tracked by the view and/or computed values.
@observable propertys = new Map();
// User gundb id, each user has its own database
@observable userId = 'gordon';
// when the viewmodel is constructed, attempt to load the todos.
constructor(){
this.gun = Gun([
'http://127.0.0.1:8080/gun',
]);
this.load();
}
@action
selectUser( user ) {
console.log( 'user ', user);
this.userId = user;
this.propertys.clear();
this.load();
}
//
// wouldn't tracka when key === null, which means once. pull(null)
@action
listen( key ) {
const that = this;
this.gun.get(this.userId).get( key ).on( (property, key) => {
if ( property === null ) {
console.log('listen() property === null')
that.propertys.delete( key );
} else {
console.log('listen() property !== null')
that.propertys.set( key, property ) ;
}
});
}
// this is an action, using the "@action" decorator tells MobX we are going to change
// some observable inside this function. With this function we are going to add a new
// todo into the tods list.
@action
add(){
var newProperty = new Property()
const ref = this.gun.get(this.userId).set( newProperty.serialize() );
// Get new Key of newProperty
const key = ref._.soul;
this.propertys.set( key, newProperty )
// listen for update for every new items
this.listen( key );
}
@action
clear() {
this.gun.put(null)
}
// remove and deletes the given todo
@action
remove( key ) {
this.gun.get(this.userId).get(key).put(null);
// Delete menally, because when put(null) with key, listen woudn't tracker
this.propertys.delete( key );
};
@action
load() {
var that = this;
this.gun.get(this.userId).map().val( (property, key) => {
if ( property !== null ) {
// assign property to be monitored, update
that.listen( key );
that.propertys.set( key, property );
console.log( 'load() loads Property', property)
} else {
console.log( 'error shoudn\'t have null property in loadGunDb')
}
})
}
@action
update( key, property ) {
this.gun.get(this.userId).path( key ).put( { ...property } , (ack) => {
if (ack.err) {
console.log('update() ack.err', ack.err)
} else {
console.log('update() ack.ok')
}
});
return;
}
// save todos, if possible
// don't know if we still need it!
@action
save(){
const that = this;
this.propertys.forEach( (property, key) => {
that.gun.get(that.userId).get(key).pull( property );
})
}
} |
JavaScript | class Visualization {
constructor(el, width, height, margins, data) {
this.el = document.querySelector(el);
this.width = width;
this.height = height;
this.margins = margins;
this.data = data;
[this.g, this.svg, this.trueWidth, this.trueHeight] = this.initVis(
this.el,
width,
height,
margins
);
this.draw = this.draw.bind(this);
}
initVis(el, width, height, margins) {
// Calculate total size of figure
const trueWidth = width + margins.left + margins.right;
const trueHeight = height + margins.top + margins.bottom + CREDIT_HEIGHT;
// Add SVG element
const svg = d3
.select(el)
.append("svg")
.attr("viewBox", `0 0 ${trueWidth} ${trueHeight}`)
.attr("width", trueWidth);
// .attr("height", trueHeight);
// Add g element (this is like our "canvas")
const g = svg
.append("g")
.attr("transform", `translate(${margins.left}, ${margins.top})`);
return [g, svg, trueWidth, trueHeight];
}
draw() {
this.svg
.append("text")
.text(`${this.author} / ${ORG_NAME}`)
.attr(
"transform",
`translate(${this.trueWidth - this.margins.right - 4}, ${
this.trueHeight - 4
})`
)
.attr("text-anchor", "end")
.attr("alignment-baseline", "baseline")
.attr("class", "credit-text");
}
} |
JavaScript | class FileWithChangedTimesByFDSync extends AsyncObject {
constructor (fd, atime, mtime) {
super(fd, atime, mtime)
}
syncCall () {
return (fd, atime, mtime) => {
fs.futimesSync(fd, atime, mtime)
return fd
}
}
} |
JavaScript | class Gateway extends events.EventEmitter {
/**
* @param {{
* gateway_host: string,
* force_protocol: string,
* force_http: boolean
* force_websocket_protocol: boolean,
* gateway_subdomain: string,
* logger: Console,
* log_errors_to_console:boolean,
* }} param0
*/
constructor({
gateway_host = null,
force_protocol = null,
force_http = true,
force_websocket_protocol = true,
gateway_subdomain = 'gateway-proxy',
socket_ports = [22],
logger = null,
log_errors_to_console = true,
} = {}) {
super()
this.gateway_host = gateway_host
this.force_protocol = force_protocol
this.force_http = force_http
this.force_websocket_protocol = force_websocket_protocol
this.gateway_subdomain = gateway_subdomain
this.socket_ports = socket_ports
/**@type {GatewayEventListenRegister} */
this.on
/**@type {GatewayEventListenRegister} */
this.once
/**@type {GatewayEventEmitter} */
this.emit
if (logger) {
this.on('log', (level, ...args) => {
logger[level.toLowerCase()](...args)
})
}
this.on('error', (err) => {
if (logger && logger.error) logger.error(err)
if (log_errors_to_console) console.error(err)
})
}
/**
* Create a proxy request for the info.
* @param {Error} err
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {GatewayRequestInfo} info
*/
_handle_proxy_request_error(err, req, res, next, info) {
const originalCode = err.code || '[unknown]'
const status = map_dns_status_to_http_code(originalCode)
if (status == 500)
this.emit(
'log',
'ERROR',
`Backend service error while executing request (${status}): ` +
err.message
)
if (info.is_websocket_request) return res.sendStatus(status)
err.code = status
err.statusCode = status
err.originalCode = originalCode
next(err)
}
/**
* Create a proxy request for the info.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {GatewayRequestInfo} info
* @param {(res:http.IncomingMessage)=>{}} handle_response
* @returns {http.ClientRequest}
*/
create_proxy_request(
req,
res,
next,
info,
handle_response = null,
headers = null,
override_headers = false
) {
/**
* @type {http.RequestOptions}
*/
const options = {
method: info.target_method,
protocol: info.backend_url.protocol,
hostname: info.backend_url.hostname,
port: info.backend_url.port,
path: info.backend_url.pathname + info.backend_url.search,
}
options.headers = {
...(override_headers ? {} : req.headers),
...(headers || {}),
}
// reset the host if self redirect
if ((options.headers.host || '').endsWith(info.backend_url.host))
options.headers.host = null
let proxy_request = null
switch (info.backend_url.protocol) {
case 'wss:':
case 'https:':
{
proxy_request = https.request(options, handle_response)
}
break
default:
{
proxy_request = http.request(options, handle_response)
}
break
}
proxy_request.on('error', (err) => {
this.emit('error', err)
this._handle_proxy_request_error(err, req, res, next, info)
})
return proxy_request
}
/**
* A middleware function to execute the auth.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {GatewayRequestInfo} info
*/
send_proxy_request(req, res, next, info) {
const proxy_request = this.create_proxy_request(
req,
res,
next,
info,
(proxy_rsp) => {
res.writeHead(proxy_rsp.statusCode, proxy_rsp.headers)
proxy_rsp.pipe(res, {
end: true,
})
}
)
req.pipe(proxy_request, {
end: true,
})
}
/**
* A middleware function to execute the auth.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {GatewayRequestInfo} info
*/
create_websocket_proxy(req, res, next, info) {
try {
const client_socket = req.socket
client_socket.setTimeout(0)
client_socket.setNoDelay(true)
client_socket.setKeepAlive(true, 0)
const ws_request = this.create_proxy_request(req, res, next, info)
const create_websocket_socket_header = (...args) => {
let lines = []
for (let v of args) {
if (Array.isArray(v)) {
lines = lines.concat(v)
}
if (typeof v == 'object') {
for (let key of Object.keys(v)) {
let ov = v[key]
if (Array.isArray(ov))
ov.forEach((v) => {
lines.push(key + ': ' + value[i])
})
else lines.push(key + ': ' + ov)
}
} else lines.push(v)
}
return lines.join('\r\n') + '\r\n\r\n'
}
ws_request.on('response', (proxy_rsp) => {
if (proxy_rsp.upgrade == true) {
res.writeHead(proxy_rsp.statusCode, proxy_rsp.headers)
proxy_rsp.pipe(res)
} else {
this.emit(
'log',
'WARN',
`Websocket proxy @ ${info.backend_url} denied the websocket.`
)
res.send('denied')
}
})
ws_request.on('upgrade', (proxy_rsp, proxy_socket, proxy_head) => {
proxy_socket.on('error', (err) => {
this.emit('error', err)
this.emit('log', 'ERROR', 'Proxy socket error')
})
if (proxy_head && proxy_head.length) proxy_socket.unshift(proxy_head)
proxy_socket.on('close', () => {
client_socket.end()
})
client_socket.on('close', () => {
proxy_socket.end()
})
// keep the proxy socket active.
proxy_socket.setKeepAlive(true, 0)
proxy_socket.setNoDelay(true, 0)
proxy_socket.setTimeout(0)
client_socket.write(
create_websocket_socket_header(
'HTTP/1.1 101 Switching Protocols',
proxy_rsp.headers
)
)
proxy_socket.pipe(client_socket).pipe(proxy_socket)
})
req.pipe(ws_request)
} catch (err) {
this.emit('error', err)
this.emit('log', 'ERROR', 'Proxy websocket setup with error')
}
}
/**
* A middleware function to execute the auth.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {GatewayRequestInfo} info
*/
create_socket_tunnel(req, res, next, info) {
const client_socket = req.socket
const proxy_socket = new net.Socket({
allowHalfOpen: true,
readable: true,
writable: true,
})
const handle_error = (err) => {
try {
proxy_socket.end()
client_socket.end()
} catch {}
this.emit('error', err)
this._handle_proxy_request_error(err, req, res, next, info)
}
proxy_socket.on('connect', () => {
// piping
proxy_socket.pipe(client_socket).pipe(proxy_socket)
proxy_socket.on('close', () => {
client_socket.end()
})
client_socket.on('close', () => {
proxy_socket.end()
})
})
proxy_socket.connect({
port: info.backend_url.port,
host: info.backend_url.host,
})
proxy_socket.on('error', handle_error)
client_socket.on('error', handle_error)
}
/**
* Call to auto detect gateway host.
* @param {Request} req
*/
get_gateway_host(req) {
if (this.gateway_host != null) return this.gateway_host
// auto-detect
const host = req.get('host')
const subdomain_prefix = `.${this.gateway_subdomain}.`
const last_index = host.lastIndexOf(subdomain_prefix)
if (last_index == -1) {
// assume not a direct gateway call.
return host
} else {
return host.substr(last_index + subdomain_prefix.length)
}
}
/**
* @param {Request} req
* @param {GatewayRequestInfo} info
* @returns {string} The host redirect
*/
get_gateway_host_redirect(req, info) {
const redirect_host = this.get_gateway_host(req)
return (
info.backend_url.protocol +
'//' +
encode_hostname(info.target_id) +
'.' +
this.gateway_subdomain +
'.' +
redirect_host +
info.backend_url.pathname +
info.backend_url.search
)
}
/**
* @param {GatewayBackendParser | (gateway:Gateway, req: Request)=>string} parser
* @returns {GatewayBackendParser}
*/
_validate_parser(parser) {
assert(parser != null, 'Parser must not be null')
if (!(parser instanceof GatewayBackendParser)) {
assert(
typeof parser == 'function',
'the parser must be a function or of type GatewayRequestParser'
)
parser = new GatewayBackendParser({
parse_url_from_route: parser,
})
}
return parser
}
/**
* Parse the basic request parameters.
* @param {GatewayBackendParser} parser
* @param {GatewayRequestInfo} info
* @param {Request} req
*/
_parse_request_core_info(parser, info, req) {
const req_host = req.get('host')
info.gateway_domain_postfix =
this.gateway_subdomain + '.' + this.get_gateway_host(req)
info.is_gateway_host = req_host.endsWith(info.gateway_domain_postfix)
info.is_websocket_request =
req.headers['sec-websocket-protocol'] != null ||
req.headers.upgrade == 'websocket'
if (info.is_gateway_host) {
info.target_id = decode_hostname(
req_host.substr(
0,
req_host.length - info.gateway_domain_postfix.length - 1
)
)
info.backend_url = parser.parse_url_from_id(this, req, info.target_id)
}
}
/**
* Parse the basic request parameters.
* @param {GatewayBackendParser} parser
* @param {GatewayRequestInfo} info
* @param {Request} req
*/
_parse_request_intercept_info(parser, info, req) {
// try intercept if not ignored by filter.
info.is_gateway_intercept = true
if (info.is_gateway_host != true) {
// case a gateway request. No id.
info.backend_url = parser.parse_url_from_route(this, req)
}
if (info.backend_url == null) {
info.is_gateway_intercept = false
} else {
info.backend_url =
info.backend_url instanceof URL
? info.backend_url
: new URL(info.backend_url)
info.target_id = info.target_id || info.backend_url.host
assert(
info.backend_url != null,
'Target url not defined or target url not resolved'
)
info.target_method = parser.parse_method(this, req)
info.backend_url.protocol = parser.parse_protocol(this, req)
if (info.is_websocket_request) {
info.backend_url.pathname = info.backend_url.pathname.replace(
/\/[.]websocket$/,
''
)
}
}
}
/**
* @param {GatewayBackendParser | (gateway:Gateway, req: Request)=>string} parser
* @param {GatewayRequestFilter} request_filter
*/
middleware(parser, request_filter = null) {
parser = this._validate_parser(parser)
/**
* A middleware function to execute the auth.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
const run_middleware = async (req, res, next) => {
let is_next_override = false
let next_override_result = null
const next_with_override = (...args) => {
is_next_override = true
next_override_result = next(...args)
return next_override_result
}
try {
const info = new GatewayRequestInfo()
this._parse_request_core_info(parser, info, req)
// checking the filter.
const is_allowed =
request_filter != null
? request_filter(info, req, res, next_with_override) === false
? false
: true
: true
if (!is_allowed || is_next_override) {
if (!is_next_override) return next()
else return next_override_result
}
// complete the information after the filter.
this._parse_request_intercept_info(parser, info, req)
// skip if not a gateway request.
if (!info.is_gateway_intercept) return next()
// websocket/socket request do not require their own domain.
if (info.is_websocket_request) {
this.emit(
'log',
'INFO',
`Starting websocket proxy ${req.originalUrl} -> ${info.backend_url}`
)
this.create_websocket_proxy(req, res, next, info)
return
}
// any other web request should be redirected.
if (!info.is_gateway_host) {
const redirect_path = this.get_gateway_host_redirect(req, info)
this.emit('log', 'INFO', 'Redirect: ' + redirect_path)
res.redirect(redirect_path)
return
}
this.send_proxy_request(req, res, next, info)
} catch (err) {
this.emit('error', err)
this.emit(
'log',
'ERROR',
'Error while processing proxy request: ' + (err.message || 'No text')
)
res.sendStatus(500)
return
}
}
return run_middleware
}
} |
JavaScript | class ClusterIdCardHandler {
constructor (node) {
this.node = node;
this.idCard = null;
this.ip = node.ip;
this.refreshDelay = node.heartbeatDelay;
this.refreshWorker = null;
this.nodeId = null;
this.nodeIdKey = null;
// Flag to prevent updating the id card if it has been disposed.
// Prevents race condition if a topology update occurs at the same time as
// the id card is been disposed because the node is evicting itself from the
// cluster
this.disposed = false;
}
/**
* Generates and reserves a unique ID for this node instance.
* Makes sure that the ID is not already taken by another node instance.
*
* @return {void}
*/
async createIdCard () {
let reserved;
do {
this.nodeId = generateRandomName('knode');
this.nodeIdKey = `${REDIS_PREFIX}${this.nodeId}`;
this.idCard = new IdCard({
birthdate: Date.now(),
id: this.nodeId,
ip: this.ip,
topology: [],
});
reserved = await this._save({ creation: true });
} while (!reserved);
this.refreshWorker = this._constructWorker(`${__dirname}/workers/IDCardRenewer.js`);
this.refreshWorker.unref();
this.refreshWorker.on('message', async message => {
if (message.error) {
await this.node.evictSelf(message.error);
}
});
// Transfer informations to the worker
this.refreshWorker.postMessage({
action: 'start', // start the worker
kuzzle: {
config: global.kuzzle.config,
id: global.kuzzle.id,
},
nodeIdKey: this.nodeIdKey,
// Used to configure a redis the same way as the Cache Engine does
redis: {
config: global.kuzzle.config.services.internalCache,
name: 'internal_adapter',
},
refreshDelay: this.refreshDelay,
});
}
// Used to Mock the creation of a worker for the tests
_constructWorker(path) {
return new Worker(path);
}
async dispose () {
this.disposed = true;
if (this.refreshWorker) {
this.refreshWorker.postMessage({action: 'dispose'});
}
}
/**
* Retrieves the ID cards from other nodes
* @return {Array.<IdCard>}
*/
async getRemoteIdCards () {
const result = [];
let keys = await global.kuzzle.ask(
'core:cache:internal:searchKeys',
`${REDIS_PREFIX}*`);
keys = keys.filter(nodeIdKey => nodeIdKey !== this.nodeIdKey);
if (keys.length === 0) {
return result;
}
const values = await global.kuzzle.ask('core:cache:internal:mget', keys);
for (let i = 0; i < keys.length; i++) {
// filter keys that might have expired between the key search and their
// values retrieval
if (values[i] !== null) {
result.push(IdCard.unserialize(values[i]));
}
}
return result;
}
/**
* Adds a remote node IdCard to the node known topology
*/
async addNode (id) {
if (this.disposed || this.idCard.topology.has(id)) {
return;
}
this.idCard.topology.add(id);
await this._save();
}
/**
* Removes a remote node IdCard from the node known topology
*/
async removeNode (id) {
if (!this.disposed && this.idCard.topology.delete(id)) {
await this._save();
}
}
/**
* Saves the local node IdCard into Redis
*/
_save ({ creation } = { creation: false }) {
return global.kuzzle.ask(
'core:cache:internal:store',
this.nodeIdKey,
this.idCard.serialize(),
{ onlyIfNew: creation, ttl: this.refreshDelay * 3 });
}
} |
JavaScript | class Select2StockMarketTemplate {
/**
* Define how will be render the item result.
*
* @param {{loading: boolean, text: string, title: string}} stockMarket An stock market object with text property.
*
* @return {*}
*/
templateResult(stockMarket) {
if (stockMarket.loading) {
return stockMarket.text;
}
let markup = "<div class='select2-result-stock-market clearfix'>" +
stockMarket.title +
"</div>";
return markup;
}
/**
* Define how will be render the item selected.
*
* @param {{text: string, title: string}} stockMarket An stock market object with text property.
*
* @return {string}
*/
templateSelection(stockMarket) {
if (!stockMarket.title) {
return stockMarket.text;
}
return stockMarket.title;
}
} |
JavaScript | class SMSForm extends Component {
constructor(props) {
super(props);
this.state = {
message: {
to: '',
body: `Who Wants To Win 5 Bucks?!: ${this.props.contestant} needs your help! Join the Chat: https://who-wants-to-win-bucks-chat.herokuapp.com/`
},
submitting: false,
error: false
};
}
onHandleChange = (event) => {
const name = event.target.getAttribute('name');
this.setState({
message: { ...this.state.message, [name]: event.target.value }
});
}
onSubmit =(event) => {
event.preventDefault();
this.setState({ submitting: true });
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.message)
})
.then(res => res.json())
.then(data => {
if (data.success) {
this.props.textSent()
window.open('https://who-wants-to-win-bucks-chat.herokuapp.com/')
} else {
alert('Invalid Number. Try Again!')
this.setState({
error: true,
submitting: false
});
}
});
}
render() {
return (
// renders red line around SMSFrom div if invalid number has been entered
<div id="popup">
<form
id="myPopup" onSubmit={this.onSubmit} className={this.state.error ? 'error sms-form' : 'sms-form'}>
<div>
<label htmlFor="to">Who Would You Like To Call!?:</label>
<input
type="tel"
name="to"
id="to"
value={this.state.message.to}
onChange={this.onHandleChange}
/>
</div>
<button type="submit" disabled={this.state.submitting}>Send Message</button>
</form>
</div>
);
}
} |
JavaScript | class Anchor {
/**
*
* @param {number} x
* @param {number} y
*/
constructor(x, y) {
this.x = x;
this.y = y;
}
/**
* @param {Anchor} other
* @returns {boolean}
*/
equal(other) {
return this.isAt(other.x, other.y);
}
/**
* @param {number} x
* @param {number} y
* @returns {boolean}
*/
isAt(x, y) {
return Pair.equal(this.x, this.y, x, y);
}
/**
* Creates a translated copy of this Anchor
* according to a vector
*
* @param {number} dx
* @param {number} dy
* @returns {Anchor}
*/
translated(dx, dy) {
return this.copy().translate(dx, dy);
}
/**
* Translates this anchor given to a vector
*
* @param {number} dx
* @param {number} dy
*/
translate(dx, dy) {
this.x += dx;
this.y += dy;
return this;
}
/**
* Answers whether this Anchor is near to another given a tolerance
*
* @param {Anchor} other
* @param {number} tolerance the max distance within its radius is considered to be "close"
* @returns {boolean}
*/
closeTo(other, tolerance) {
return between(this.x, other.x-tolerance, other.x + tolerance) && between(this.y, other.y-tolerance, other.y + tolerance)
}
/**
* @returns {Anchor}
*/
copy() {
return new Anchor(this.x, this.y);
}
/**
* Calculates the difference between this anchor and another
*
* @param {Anchor} other
* @returns {import('./pair').Pair}
*/
diff(other) {
return Pair.diff(this.x, this.y, other.x, other.y)
}
/**
* Converts this anchor into a point
*
* @returns {import('./pair').Pair}
*/
asPair() {
return [this.x, this.y];
}
/**
* Converts this anchor into a vector
*
* @returns {import('./vector').Vector}
*/
asVector() {
return vector(this.x, this.y);
}
/**
* @returns {import('./vector').Vector}
*/
export() {
return this.asVector();
}
/**
* @param {number} maxX
* @param {number} maxY
* @returns {Anchor}
*/
static atRandom(maxX, maxY) {
return new Anchor(Math.random() * maxX, Math.random() * maxY);
}
/**
*
* @param {import('./vector').Vector} vector
* @returns {Anchor}
*/
static import(vector) {
return anchor(vector.x, vector.y);
}
} |
JavaScript | class UploadResourceForm
{
constructor()
{
this.prevBtn = $('#prev_btn');
this.nextBtn = $('#next_btn');
this.slideCounter = 1;
this.currentSlide = $('#slide_'+this.slideCounter);
this.error = $('#showError');
this.pageType = $('#resourceUploadForm').attr('data-type');
// Input Fields
this.resourceTitle = $('#resource_title');
this.resourceAttachment = $('#resource_attachment_field');
this.resourceAttachmentDropzone = $('#resource-attachment-upload');
this.resourceDescription = $('#resource_description');
this.tagsDropdown = $('.tagsDropdown');
this.termsConditionBox = $('#termsConditionsCheck');
// Listening to the events
this.events();
// Checking First and Last Slide
this.firstAndLastSlide();
// Appending active class
this.changeCurrentClass();
}
// Events Binding
events()
{
this.prevBtn.on('click',this.previousSlide.bind(this));
this.nextBtn.on('click',this.nextSlide.bind(this));
}
// Methods Section
previousSlide()
{
this.decrementSlideCounter();
this.showSlide(this.slideCounter);
this.changeCurrentClass();
}
nextSlide()
{
this.incrementSlideCounter();
this.showSlide(this.slideCounter);
this.changeCurrentClass();
}
showSlide(slide)
{
$("#slide_"+slide).show();
$("#slide_"+slide).siblings().hide();
}
changeCurrentClass()
{
$('#slide-'+this.slideCounter+'-trigger').addClass('current');
$('#slide-'+this.slideCounter+'-trigger').siblings().removeClass('current');
}
incrementSlideCounter()
{
if(!this.validateResourceFields())
return false;
if(this.pageType == 'createResourceForm')
{
this.saveState(this.slideCounter);
}
this.slideCounter++;
this.firstAndLastSlide();
}
decrementSlideCounter()
{
this.slideCounter--;
this.firstAndLastSlide();
}
firstAndLastSlide()
{
if(this.slideCounter == 1)
{
this.prevBtn.hide();
this.nextBtn.show();
}
else if(this.slideCounter == 4)
{
this.nextBtn.hide();
this.prevBtn.show();
}
else
{
this.prevBtn.show();
this.nextBtn.show();
}
}
validateResourceFields()
{
this.error.hide();
if(this.resourceTitle.val() == '' || this.resourceTitle.val() == ' ')
{
this.resourceTitle.focus();
this.error.html('Resource Title is required *');
this.error.show();
return false;
}
if(this.pageType == 'createResourceForm')
{
if(this.resourceAttachment.val() == '' || this.resourceAttachment.val() == ' ')
{
this.resourceAttachmentDropzone.focus();
this.error.html('Resource Attachment is required *');
this.error.show();
return false;
}
}
if(this.resourceDescription.val() == '' || this.resourceDescription.val() == ' ')
{
this.resourceDescription.focus();
this.error.html('Resource Description is required *');
this.error.show();
return false;
}
if($.isEmptyObject(this.tagsDropdown.val()) && this.slideCounter == 2)
{
this.error.html('Please choose atleast one tag *');
this.error.show();
return false;
}
return true;
}
saveState(counter)
{
var form = $("#resourceUploadForm");
var route = form.attr('action');
var formdata = new FormData(form[0]);
formdata.append('resource_upload','ajax_wizard');
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: 'POST',
url: route,
data: formdata,
contentType: false,
processData: false,
success: function (data){
console.log(data);
if(data.resource)
{
$('#wizard_resource_id').val(data.resource.id);
}
else
{
console.log('something went wrong');
}
}
});
}
} |
JavaScript | class TrackingDatabase {
constructor(database, onStartQuery, onEndQuery) {
this.database = database;
this.onStartQuery = onStartQuery;
this.onEndQuery = onEndQuery;
}
query(options, contextVars, filteredContextVarValues) {
// Notify of query
this.onStartQuery();
return new Promise((resolve, reject) => {
this.database
.query(options, contextVars, filteredContextVarValues)
.then((rows) => {
resolve(rows);
})
.catch((reason) => {
reject(reason);
})
.finally(() => {
this.onEndQuery();
});
});
}
addChangeListener(changeListener) {
// Do nothing as printing should not update dynamically
}
removeChangeListener(changeListener) {
// Do nothing as printing should not update dynamically
}
transaction() {
return this.database.transaction();
}
refresh() {
// Do nothing as printing should not update dynamically
}
} |
JavaScript | class TrackingDataSource extends mwater_expressions_1.DataSource {
constructor(dataSource, onStartQuery, onEndQuery) {
super();
this.dataSource = dataSource;
this.onStartQuery = onStartQuery;
this.onEndQuery = onEndQuery;
}
performQuery(query, cb) {
if (!cb) {
return new Promise((resolve, reject) => {
this.performQuery(query, (error, rows) => {
if (error) {
reject(error);
}
else {
resolve(error);
}
});
});
}
this.onStartQuery();
this.dataSource.performQuery(query, (error, rows) => {
this.onEndQuery();
cb(error, rows);
});
return;
}
/** Get the url to download an image (by id from an image or imagelist column)
Height, if specified, is minimum height needed. May return larger image
Can be used to upload by posting to this url
*/
getImageUrl(imageId, height) {
return this.dataSource.getImageUrl(imageId, height);
}
// Clears the cache if possible with this data source
clearCache() {
this.dataSource.clearCache();
}
// Get the cache expiry time in ms from epoch. No cached items before this time will be used. 0 for no cache limit.
// Useful for knowing when cache has been cleared, as it will be set to time of clearing.
getCacheExpiry() {
return this.dataSource.getCacheExpiry();
}
} |
JavaScript | class Card extends DecoratorView {
constructor(options) {
if (!options) {
options = {};
}
if (!options.name) {
options.name = "card";
}
if (!options.style) {
options.style = "card";
} else {
options.style = `card ${options.style}`;
}
super(options);
if (options && options.body) {
this._body = options.body;
} else {
this._body = "";
}
}
/**
* body property - the body of the card
* @property body
*/
/**
* style property - the style
* @property style
*/
set style(style) {
this._style = style;
}
get style() {
return this._style;
}
/**
* template - sets content of the dialog, handled internally
* @private
*/
_template() {
return this._body;
}
/**
* The body content of the card (supports HTML)
* @property body
*/
set body(body) {
this._body = body;
}
get body() {
return this._body;
}
/**
* render - render the card
*/
render() {
if (this.el) {
const el = document.querySelector(this.el);
if (el) {
el.innerHTML = this._template();
}
this.delegateEvents();
}
return this;
}
/**
* remove
*/
remove() {
this.removeTemplate(this.el, true);
return super.remove();
}
} |
JavaScript | class Footer extends DecoratorView {
constructor(options) {
super(options);
if (options && options.body) {
this._body = options.body;
} else {
this._body = "";
}
}
/**
* The body content of the card (supports HTML)
* @property body
*/
set body(body) {
this._body = body;
}
get body() {
return this._body;
}
/**
* template - sets content of the footer, handled internally
* @private
*/
_template() {
return this._body;
}
/**
* render - render the footer
*/
render() {
if (this.el) {
const el = document.querySelector(this.el);
if (el) {
el.innerHTML = this._template();
}
this.delegateEvents();
this.syncAllBoundElements();
}
return this;
}
remove() {
this.removeTemplate(this.el, true);
return super.remove();
}
} |
JavaScript | class Header extends DecoratorView {
constructor(options) {
super(options);
if (options && options.title) {
this._title = options.title;
} else {
this._title = "";
}
if (options && options.subTitle) {
this._subTitle = options.subTitle;
} else {
this._subTitle = "";
}
}
/**
* @property {string} title A title property
*/
set title(title) {
this._title = title;
}
get title() {
return this._title;
}
/**
* @property {string} subTitle A subTitle property
*/
set subTitle(subTitle) {
this._subTitle = subTitle;
}
get subTitle() {
return this._subTitle;
}
/**
* render - render the header
*/
render() {
if (this.el) {
const el = document.querySelector(this.el);
if (el) {
el.innerHTML = `${this.template}${this.title ? "<h1>" + this.title + "</h1>" : ""}${this.subTitle ? "<h2>" + this.subTitle + "</h2>" : ""}`;
}
this.delegateEvents();
this.syncAllBoundElements();
}
return this;
}
/**
* Remove the Header
* @returns {object} Returns the view context ('this')
*/
remove() {
this.removeTemplate(this.el, true);
return super.remove();
}
} |
JavaScript | class Manager extends Mediator {
constructor(options) {
super(options);
}
/**
* Manages a component (colleague)
* @param {View} component A component or view to manage
*/
manageComponent(component) {
return this.observeColleagueAndTrigger(component, component.name, component.name);
}
/**
* Unmanages a component (colleague)
* @param {View} component A component or view to manage
*/
unmanageComponent(component) {
return this.dismissColleagueTrigger(component, component.name, component.name);
}
} |
JavaScript | class Renderer
{
/**
* Initialize this renderer from canvas.
* @param {Canvas} canvas Canvas instance.
*/
_init(canvas)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
*
* @param {PintarJS.Color} color Color to clear screen to.
* @param {PintarJS.Rect} rect Optional rectangle to clear.
*/
clear(color, rect)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Draw text.
* @param {PintarJS.TextSprite} textSprite Text sprite to draw.
*/
drawText(textSprite)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Draw a sprite.
* @param {PintarJS.Sprite} sprite Sprite to draw.
*/
drawSprite(sprite)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Draw a rectangle.
* @param {PintarJS.ColoredRectangle} coloredRectangle Colored rectangle to draw.
*/
drawRectangle(coloredRectangle)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Draw a single color.
* @param {PintarJS.Point} position Pixel position.
* @param {PintarJS.Color} color Pixel color.
*/
drawPixel(position, color)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Draw a line.
* @param {PintarJS.Point} pointA Line starting point.
* @param {PintarJS.Point} pointB Line ending point.
* @param {PintarJS.Color} color Line color.
*/
drawLine(pointA, pointB, color)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Set the currently active viewport.
* @param {PintarJS.Viewport} viewport Viewport to set.
*/
setViewport(viewport)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Create and return a render target.
* @param {PintarJS.Point} size Texture size.
*/
createRenderTarget(size)
{
throw new PintarConsole.Error("Not Implemented.");
}
/**
* Start a rendering frame.
*/
startFrame()
{
}
/**
* End a rendering frame.
*/
endFrame()
{
}
} |
JavaScript | class MyRecipesScraper extends BaseScraper {
constructor(url) {
super(url, "myrecipes.com/recipe");
}
scrape($) {
this.defaultSetImage($);
const { ingredients, instructions, time } = this.recipe;
this.recipe.name = this.textTrim($("h1.headline"));
$(".ingredients-item").each((i, el) => {
const ingredient = this.textTrim($(el)).replace(/\s\s+/g, " ");
ingredients.push(ingredient);
});
$($(".instructions-section-item").find("p")).each((i, el) => {
instructions.push($(el).text());
});
let metaBody = $(".recipe-meta-item-body");
time.active = this.textTrim(metaBody.first());
time.total = this.textTrim($(metaBody.get(1)));
this.recipe.servings = this.textTrim(metaBody.last());
}
} |
JavaScript | class App extends React.Component {
/**
* Initial state.
*
* @type {Object}
*/
state = {
error: null,
info: null,
}
/**
* Catch the `error` and `info`.
*
* @param {Error} error
* @param {Object} info
*/
componentDidCatch(error, info) {
this.setState({ error, info })
}
/**
* Render the example app.
*
* @return {Element}
*/
render() {
return (
<HashRouter>
<div>
<Nav>
<Title>Slate Examples</Title>
<LinkList>
<Link href="https://github.com/ianstormtaylor/slate">GitHub</Link>
<Link href="https://docs.slatejs.org/">Docs</Link>
</LinkList>
</Nav>
<TabList>
{EXAMPLES.map(([name, Component, path]) => (
<Route key={path} exact path={path}>
{({ match }) => (
<Tab to={path} active={match && match.isExact}>
{name}
</Tab>
)}
</Route>
))}
</TabList>
{this.state.error ? (
<Warning>
<p>
An error was thrown by one of the example's React components!
</p>
<pre>
<code>
{this.state.error.stack}
{'\n'}
{this.state.info.componentStack}
</code>
</pre>
</Warning>
) : (
<Example>
<Switch>
{EXAMPLES.map(([name, Component, path]) => (
<Route key={path} path={path} component={Component} />
))}
<Redirect from="/" to="/rich-text" />
</Switch>
</Example>
)}
</div>
</HashRouter>
)
}
} |
JavaScript | class Animation{
constructor(scene, idAnimation, duration){
this.scene = scene;
this.id = idAnimation;
this.duration = duration;
}
} |
JavaScript | class agent{
constructor(){
this.procInfo = $.NSProcessInfo.processInfo;
this.procName = $.NSProcessInfo.processName;
this.hostInfo = $.NSHost.currentHost;
this.cu = ObjC.deepUnwrap(this.procInfo.userName);
this.pid = this.procInfo.processIdentifier;
this.host = ObjC.deepUnwrap(this.hostInfo.names)[0];
}
} |
JavaScript | class GridActionButtonComponent extends Component {
static get selector() { return 'app-action-button' }
static get template() { return template }
static get props() { return ['row', 'col'] }
/**
* The text shown on the action button.
* @type {string}
*/
text = ''
/**
* The CSS color of the action button.
* @type {string}
*/
color = 'white'
/**
* If true, the action button will be hidden.
* @type {boolean}
*/
hidden = false
/**
* Called when the component is instantiated. Updates the text, color, and hide status.
* @return {Promise<void>}
*/
async vue_on_create() {
this.update_text()
this.update_color()
this.update_hidden()
}
/**
* Called when the row value changes. Updates the text, color, and hide status.
*/
watch_row() {
this.update_text()
this.update_color()
this.update_hidden()
}
/**
* Called when the column value changes. Updates the text, color, and hide status.
*/
watch_col() {
this.update_text()
this.update_color()
this.update_hidden()
}
/**
* Determine the text to show on the button based on the column definition.
*/
update_text() {
if ( typeof this.col.button_text === 'function' ) {
this.text = this.col.button_text(this.row, this.col)
} else {
this.text = this.col.button_text || ''
}
}
/**
* Determine the color to show on the button based on the column definition.
*/
update_color() {
if ( typeof this.col.button_color === 'function' ) {
this.color = this.col.button_color(this.row, this.col)
} else {
this.color = this.col.button_color || 'white'
}
}
/**
* Determine whether the button should be shown or not, based on the column definition.
*/
update_hidden() {
if ( !('button_hidden' in this.col) ) {
this.hidden = false;
} else if ( typeof this.col.button_hidden === 'function' ) {
this.hidden = this.col.button_hidden(this.row, this.col)
} else {
this.hidden = this.col.button_hidden
}
}
/**
* Called when the button is clicked. Emits a click event and updates the text, color, and hide status.
* @param {MouseEvent} $event
*/
on_click($event) {
this.$emit('click', [this.row, this.col])
this.update_text()
this.update_color()
this.update_hidden()
}
} |
JavaScript | class QuillEditor extends React.Component {
constructor (props) {
super(props)
this.state = { editorHtml: '', theme: 'snow' }
this.handleChange = this.handleChange.bind(this)
}
handleChange (html) {
this.setState({ editorHtml: html });
}
handleThemeChange (newTheme) {
if (newTheme === "core") newTheme = null;
this.setState({ theme: newTheme })
}
render () {
return (
<div>
<ReactQuill
theme={this.state.theme}
onChange={this.handleChange}
value={this.state.editorHtml}
modules={QuillEditor.modules}
formats={QuillEditor.formats}
bounds={'.app'}
placeholder={this.props.placeholder}
/>
<div className="themeSwitcher">
<label>Theme </label>
<select onChange={(e) =>
this.handleThemeChange(e.target.value)}>
<option value="snow">Snow</option>
<option value="bubble">Bubble</option>
<option value="core">Core</option>
</select>
</div>
</div>
)
}
} |
JavaScript | class Menu extends GuiElement {
/** @type {number} */
width;
/** @type {number} */
height;
/** @type {{text: string, func: () => void | undefined}[]} */
items;
/** @type {number} index of currently selected item */
index;
/** @type {string | CanvasPattern | CanvasGradient} */
itemFillStyle;
/** @type {string | CanvasPattern | CanvasGradient} */
selectedFillStyle;
/**
* @type {string | CanvasPattern | CanvasGradient} when you're holding down
* the select button
*/
downFillStyle;
/** @type {string | CanvasPattern | CanvasGradient} */
itemStrokeStyle;
/** @type {number} */
itemStrokeWidth;
/** @type {number} */
itemBorderRadius;
/** @type {string} */
textStyle;
/** @type {CanvasTextAlign} */
textAlign;
/** @type {string | CanvasPattern | CanvasGradient} */
textFillStyle;
/** @type {number} in pixels */
itemHeight;
/** @type {number} items are centered in overall width */
itemWidth;
/** @type {number in pixels */
itemMargin;
/**
* @type {number}
* number of game steps between when a button is first pressed and when it
* starts repeating
*/
keyDelay;
/** @type {number} number of game steps between key repeats */
keyRate;
/** @type {number} counter used for key repeat measurements */
keyCounter;
/** @type {boolean} */
keyRepeated;
/** @type boolean primary button being held */
down;
/**
* @param {Vector} pos top-left position
* @param {number} width total width of this menu
* @param {number} height total height of this menu
* @param {{text: string, func: () => void | undefined}[]} items
*/
constructor(
pos = new Vector(0, 0),
width = getCanvasWidth(),
height = getCanvasHeight(),
items = []
) {
super(pos);
this.width = width;
this.height = height;
this.items = items;
this.itemFillStyle = "#101010";
this.selectedFillStyle = "#fa5b11";
this.downFillStyle = "#303030";
this.itemStrokeStyle = "black";
this.itemStrokeWidth = 4;
this.itemBorderRadius = 0;
this.itemHeight = 70;
this.itemWidth = this.width;
this.textStyle = "bold 50px anonymous";
this.textAlign = "center";
this.textFillStyle = "white";
this.itemMargin = 10;
this.index = 0;
this.keyDelay = 40;
this.keyRate = 8;
this.keyCounter = 0;
this.keyRepeated = false;
this.down = false;
this.lerpVal = 0;
// values for clamping the position of menu correctly
this.topPos = undefined;
this.bottomPos = undefined;
this.currentPos = undefined;
}
/**
* we need this because items isn't initialized in the constructor
* @param {{ text: string; func: () => void; }[]} items
*/
setItems(items) {
this.items = items;
this.updateTopAndBottomPos();
}
calcMiddle() {
return this.pos.y + this.height / 2;
}
calcTopOffset() {
return -this.index * (this.itemMargin + this.itemHeight);
}
calcBottomOffset() {
return (
(this.items.length - this.index) * (this.itemMargin + this.itemHeight) -
this.itemMargin
);
}
calcListHeight() {
return (
this.items.length * (this.itemMargin + this.itemHeight) - this.itemMargin
);
}
/**
* calculate where the top should be given the bottom
* @param {number} bottom
*/
calcTopFromBottom(bottom) {
return bottom - this.calcBottomOffset() + this.calcTopOffset();
}
updateTopAndBottomPos() {
const middle = this.calcMiddle();
const { height } = getScreenDimensions();
this.topPos = middle + this.calcTopOffset();
this.bottomPos = middle + this.calcBottomOffset();
if (this.calcListHeight() < height) {
this.offsetPos = height / 2 - this.calcListHeight() / 2;
return;
}
// adjust so that selected element is always centered
this.offsetPos = this.topPos;
let overTop = false;
let overBottom = false;
if (this.topPos > 0) {
// clamp to top
overTop = true;
}
if (this.bottomPos < height) {
// clamp to bottom
overBottom = true;
}
if (overTop && overBottom) {
// too small to clamp
this.offsetPos = this.calcMiddle();
} else if (overTop) {
this.offsetPos = 0;
} else if (overBottom) {
this.offsetPos = this.calcTopFromBottom(height);
}
}
/**
* Called each step, reads buttons to move up/down or execute
* @override
*/
action() {
this.lerpVal *= 0.9;
if (buttons.back.status.isReleased) {
// Fixes a bug where the button being released was seen by multiple menus
// at once. You should press it multiple times to close multiple menus
buttons.back.status.isReleased = false;
this.onBack();
}
this.down = buttons.select.status.isDown || buttons.altSelect.status.isDown;
if (buttons.select.status.isPressed || buttons.altSelect.status.isPressed)
playSound("menu-select");
if (
buttons.select.status.isReleased ||
buttons.altSelect.status.isReleased
) {
if (this.items[this.index] && this.items[this.index].func !== undefined)
this.items[this.index].func();
}
const navDir = buttons.move.vec.add(buttons.shoot.vec);
// key repeat logic
if (Math.abs(navDir.y) < 0.25) {
// not being pressed, reset counter
this.keyCounter = 0;
this.keyRepeated = false;
} else if (!this.down && this.keyCounter <= 0) {
// move up/down based on direction of move directional
this.keyCounter = this.keyRepeated ? this.keyRate : this.keyDelay;
if (navDir.y < -0.25) {
this.move(-1);
this.keyRepeated = true;
} else if (navDir.y > 0.25) {
this.move(1);
this.keyRepeated = true;
}
}
this.keyCounter--;
}
/**
* moves up or down
* @param {number} num number of items to move (positive or negative)
*/
move(num) {
playSound("menu-nav");
this.index += num;
this.index = clamp(this.index, 0, this.items.length - 1);
const prevPos = this.offsetPos;
this.updateTopAndBottomPos();
const currPos = this.offsetPos;
this.lerpVal += prevPos - currPos;
}
/**
* draws this menu
* @override
*/
draw() {
const x = this.pos.x + this.itemMargin;
let y = this.offsetPos;
// adjust y if the selected element is off the screen
for (let i = 0; i < this.items.length; ++i) {
let downOffset = 0;
let style = this.itemFillStyle;
if (i === this.index) {
style = this.selectedFillStyle;
if (this.down) {
style = this.downFillStyle;
downOffset += 3;
}
}
roundedRect(
new Vector(
x + (this.width - this.itemWidth) / 2,
y + downOffset + this.lerpVal
),
this.itemWidth,
this.itemHeight,
style,
this.itemStrokeStyle,
this.itemStrokeWidth,
this.itemBorderRadius
);
this.drawText(x, y + this.lerpVal + downOffset, this.items[i].text);
y += this.itemHeight + this.itemMargin;
}
}
/**
* draws text at the right location
* because canvas doesn't draw tabs. This is a dumb hack to draw the
* second tabular item right-aligned
* @param {number} x
* @param {number} y
* @param {string} text
*/
drawText(x, y, text) {
const tabs = text.split("\t");
let textOffset = 0;
switch (this.textAlign) {
case "left":
textOffset = -0.5 * this.itemWidth;
break;
case "right":
textOffset = 0.5 * this.itemWidth;
break;
}
centeredText(
tabs[0],
new Vector(
x + this.width / 2 + this.itemMargin + textOffset,
y + this.itemHeight / 2
),
this.textStyle,
this.textAlign,
"middle",
this.textFillStyle,
undefined,
undefined
);
if (tabs[1] !== undefined) {
centeredText(
tabs[1],
new Vector(
x + this.width / 2 - this.itemMargin + this.itemWidth / 2,
y + this.itemHeight / 2
),
this.textStyle,
"right",
"middle",
this.textFillStyle
);
}
}
/**
* By default pressing 'back' closes the menu, but can be overriden
*/
onBack() {
playSound("menu-back");
this.active = false;
}
} |
JavaScript | class FullscreenIphoneButton extends Button {
constructor(player, options) {
super(player, options);
this.controlText('Fullscreen')
}
buildCSSClass() {
/* Each button will have the classes:
`vjs-fullscreen-iphone-button
So you could have a generic icon for "skip back" and a more
specific one for "skip back 30 seconds"
*/
return "vjs-fullscreen-iphone-control vjs-control vjs-button";
}
handleClick() {
//if openNewPage is true, open a new page
//else show at current page with the window size, but loation bar cann't be remove.
if (this.options_.openNewPage) {
if (this.options_.closeMe) {
window.close();
} else if (typeof(this.options_.redirectTo) !== 'undefined' && this.options_.redirectTo !== ''){
// console.log(this.options_.redirectTo);
this.player_.pause();
top.open(this.options_.redirectTo, '', 'resizable=no, toolbar=no, scrollbars=no, menubar=no, status=no, directories=no, location=no');
}
} else {
if (this.player_.hasClass('vjs-fullscreen-iphone-video')) {
//scale down
this.player_.removeClass('vjs-fullscreen-iphone-on');
this.player_.removeClass('vjs-fullscreen-iphone-video');
} else {
this.player_.addClass('vjs-fullscreen-iphone-on');
this.player_.addClass('vjs-fullscreen-iphone-video');
}
}
}
} |
JavaScript | class GamesPage extends ListPage {
constructor() {
let pageName = 'game';
let columns = [
{data: null,
render: function (data) {
return '<a href="/registration/game/' + data.id + '"><i class="fa fa-edit"></i> ' + data.date + '</a>';
}
},
{data: 'eventDesc'},
{data: 'totalPlayers'},
{data: 'gameStatus'}
];
super(pageName, columns);
}
} |
JavaScript | class VRSplashScreen{
constructor(gl, texture, stereo) {
const splashVS = `
uniform mat4 projectionMat;
uniform mat4 modelViewMat;
uniform vec4 texCoordScaleOffset;
attribute vec3 position;
attribute vec2 texCoord;
varying vec2 vTexCoord;
void main() {
vTexCoord = (texCoord * texCoordScaleOffset.xy) + texCoordScaleOffset.zw;
gl_Position = projectionMat * modelViewMat * vec4( position, 1.0 );
}
`;
const splashFS = `
precision mediump float;
uniform sampler2D diffuse;
varying vec2 vTexCoord;
void main() {
gl_FragColor = texture2D(diffuse, vTexCoord);
}
`;
this.gl = gl;
this.modelViewMat = mat4.create();
this.texture = texture;
this.stereo = stereo;
this.program = new WGLUProgram(gl);
this.program.attachShaderSource(splashVS, gl.VERTEX_SHADER);
this.program.attachShaderSource(splashFS, gl.FRAGMENT_SHADER);
this.program.bindAttribLocation({
position: 0,
texCoord: 1
});
this.program.link();
let splashVerts = [];
let size = 0.4;
// X Y Z U V
splashVerts.push(-size, -size, 0.0, 0.0, 1.0);
splashVerts.push( size, -size, 0.0, 1.0, 1.0);
splashVerts.push( size, size, 0.0, 1.0, 0.0);
splashVerts.push(-size, -size, 0.0, 0.0, 1.0);
splashVerts.push( size, size, 0.0, 1.0, 0.0);
splashVerts.push(-size, size, 0.0, 0.0, 0.0);
this.vertBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(splashVerts), gl.STATIC_DRAW);
}
render(projectionMat, eye) {
var gl = this.gl;
var program = this.program;
program.use();
// We're going to just completely ignore the view matrix in this case,
// because we want to render directly in front of the users face no matter
// where they are looking.
mat4.identity(this.modelViewMat);
mat4.translate(this.modelViewMat, this.modelViewMat, [0, 0, -1]);
gl.uniformMatrix4fv(program.uniform.projectionMat, false, projectionMat);
gl.uniformMatrix4fv(program.uniform.modelViewMat, false, this.modelViewMat);
if (this.stereo) {
if (eye == "left") {
gl.uniform4f(program.uniform.texCoordScaleOffset, 0.5, 1.0, 0.0, 0.0);
} else if (eye == "right") {
gl.uniform4f(program.uniform.texCoordScaleOffset, 0.5, 1.0, 0.5, 0.0)
}
} else {
gl.uniform4f(program.uniform.texCoordScaleOffset, 1.0, 1.0, 0.0, 0.0);
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer);
gl.enableVertexAttribArray(program.attrib.position);
gl.enableVertexAttribArray(program.attrib.texCoord);
gl.vertexAttribPointer(program.attrib.position, 3, gl.FLOAT, false, 20, 0);
gl.vertexAttribPointer(program.attrib.texCoord, 2, gl.FLOAT, false, 20, 12);
gl.activeTexture(gl.TEXTURE0);
gl.uniform1i(this.program.uniform.diffuse, 0);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
} |
JavaScript | class Character {
constructor() {
this.size = 30;
this.padding = 0;
this.translateX = 0;
this.translateY = 0;
this.currentCell = null;
this.canMove = true;
this.completed = () => null;
this.node = document.createElement('div');
this.node.className = "character";
document.addEventListener("keydown", this.move.bind(this));
}
setSizing(cellSize) {
if (cellSize < this.size) {
this.size = cellSize * 0.8;
}
this.padding = (cellSize - this.size) / 2;
this.setStyle();
}
setStyle() {
this.node.setAttribute("style",
`margin:${this.padding}px;`
+ `transform:translate(${this.translateX}px, ${this.translateY}px);`
+ `height:${this.size}px;width:${this.size}px;`
);
}
/**
*
* @param {Cell} cell
*/
moveToCell(cell) {
this.setSizing(cell.node.offsetWidth);
this.translateX = cell.node.offsetLeft;
this.translateY = cell.node.offsetTop;
this.setStyle();
this.currentCell = cell;
this.canMove = false;
let movementDelay = 100;
if (cell.exit) {
// TODO: Perhaps we should check if we are moving right from the exit cell instead of into it?
this.completed();
movementDelay = 1000;
}
// small delay until we can issue the next movement command
setTimeout(() => this.canMove = true, movementDelay);
}
move(e) {
let direction = null;
switch (e.keyCode) {
case 87:
case 38:
direction = 0;
break;
case 68:
case 39:
direction = 1;
break;
case 83:
case 40:
direction = 2;
break;
case 65:
case 37:
direction = 3;
break;
default:
break;
}
if (direction !== null && this.canMove) {
let targetCell = this.currentCell.GetNeighbour(direction);
if (targetCell) {
if (!this.currentCell.walls[direction]) {
this.moveToCell(targetCell);
}
}
}
}
} |
JavaScript | class CompacSizerOutletTypeModel extends BaseModel
{
/**
* CompacSizerOutletTypeModel Constructor
*
* @protected
*/
constructor()
{
super();
/**
* The Compac Sizer Outlet Type ID
*
* @type {string}
* @public
*/
this.id = undefined;
/**
* The Name for this Dynamic Outlet Type
*
* @type {string}
* @public
*/
this.name = undefined;
/**
* The Generic Outlet Type
*
* @type {string}
* @public
*/
this.type = undefined;
/**
* An Optional Description for this Dynamic Outlet Type
*
* @type {string}
* @public
*/
this.description = undefined;
/**
* Whether the Compac Sizer Outlet Type has been deleted
*
* @type {boolean}
* @public
*/
this.deleted = undefined;
/**
* When the Compac Sizer Outlet Type was last updated
*
* @type {Date}
* @public
*/
this.updateTimestamp = undefined;
}
/**
* Create a new **CompacSizerOutletTypeModel** from a JSON Object or JSON String
*
* @static
* @public
* @param {Object<string, any>|string} json A JSON Object or JSON String
* @return {CompacSizerOutletTypeModel}
*/
static fromJSON(json)
{
let model = new CompacSizerOutletTypeModel();
/**
* The JSON Object
*
* @type {Object<string, any>}
*/
let jsonObject = {};
if(typeof json === 'string')
{
jsonObject = JSON.parse(json);
}
else if(typeof json === 'object')
{
jsonObject = json;
}
if('id' in jsonObject)
{
model.id = (function(){
if(typeof jsonObject['id'] !== 'string')
{
return String(jsonObject['id']);
}
return jsonObject['id'];
}());
}
if('name' in jsonObject)
{
model.name = (function(){
if(typeof jsonObject['name'] !== 'string')
{
return String(jsonObject['name']);
}
return jsonObject['name'];
}());
}
if('type' in jsonObject)
{
model.type = (function(){
if(typeof jsonObject['type'] !== 'string')
{
return String(jsonObject['type']);
}
return jsonObject['type'];
}());
}
if('description' in jsonObject)
{
model.description = (function(){
if(typeof jsonObject['description'] !== 'string')
{
return String(jsonObject['description']);
}
return jsonObject['description'];
}());
}
if('deleted' in jsonObject)
{
model.deleted = (function(){
if(typeof jsonObject['deleted'] !== 'boolean')
{
return Boolean(jsonObject['deleted']);
}
return jsonObject['deleted'];
}());
}
if('updateTimestamp' in jsonObject)
{
model.updateTimestamp = (function(){
if(typeof jsonObject['updateTimestamp'] !== 'string')
{
return new Date(String(jsonObject['updateTimestamp']));
}
return new Date(jsonObject['updateTimestamp']);
}());
}
return model;
}
} |
JavaScript | class Objects {
/**
* Will throw exception if someone tries to instantiate this utility class.
*
* @ignore
*/
construct() {
throw '[Objects] Class is not instantiable';
}
/**
* Will return a proper string representation for debugging purposes.
*
* @ignore
*/
static toString() {
return '<utility class Objects>';
}
/**
* Checks for being something else than undefined or null.
*
* @param {any} obj
* The value to be checked
*
* @return {boolean}
* false if obj is null or undefined, otherwise true
*
* @example
* Objects.isSomething(undefined) // false
* Objects.isSomething(null) // false
* Objects.isSomething(0) // true
* Objects.isSomething(false) // true
* Objects.isSomething('') // true
* Objects.isSomething({}) // true
* Objects.isSomething(42) // true
* Objects.isSomething({x: 42}) // true
*/
static isSomething(obj) {
return obj !== null && obj !== undefined;
}
/**
* Checks for being undefined or null.
*
* @param {any} obj
* The value to be checked
*
* @return {boolean}
* true if obj is null or undefined, otherwise false
*
* @example
* Objects.isNothing(undefined) // true
* Objects.isNothing(null) // true
* Objects.isNothing(0) // false
* Objects.isNothing(false) // false
* Objects.isNothing('') // false
* Objects.isNothing({}) // false
* Objects.isNothing(42) // false
* Objects.isNothing({x: 42}) // false
*/
static isNothing(obj) {
return obj === null || obj === undefined;
}
/**
* Converts a value to a string by using the toString method.
*
* @param {any} obj
* The value to be converted
*
* @return {string}
* The string representation of the value
*
* @example
* Objects.asString(undefined) // ''
* Objects.asString(null) // ''
* Objects.asString(42) // '42'
* Objects.asString(true) // 'true'
* Objects.asString(false) // 'false'
* Objects.asString({toString: 'abc'}) // 'abc'
* Objects.asString(' some text ') // ' some text '
*/
static asString(obj) {
var ret;
if (obj === undefined || obj === null) {
ret = '';
} else if (typeof obj === 'string') {
ret = obj;
} else {
ret = obj.toString();
if (typeof ret !== 'string') {
// Normally in this case the JavaScript engine should return undefined.
// Nevertheless, to play save, we handle all cases here.
if (ret === undefined || ret === null) {
ret = '';
} else {
ret = '' + ret;
}
}
}
return ret;
}
/**
* Creates a shallow copy of a given object 'obj'.
* If 'obj' is not a real object or frozen or an immutable
* collection of Facebook's Immutable library or a ClojureScript
* persistent collection then the input argument will be returned as is.
*
* @param {any} obj
* The object to be copied
*
* @return {any}
* A shallow copy of the input object or the unmodified input in case
* of an immutable value.
*
* @example
* Objects.shallowCopy(undefined) // undefined
* Objects.shallowCopy(null) // null
* Objects.shallowCopy('some text') // 'some text'
* Objects.shallowCopy(() => whatever()) // () => whatever()
* Objects.shallowCopy({a: 1, b: {c: 2, d: 3}) // {a: 1, b: {c: 2, d: 3}
* someMutableObject === Objects.shallowCopy(someMutableObject) // false
*/
static shallowCopy(obj) {
var ret;
if (Array.isArray(obj)) {
ret = obj.concat();
} else if (obj && typeof obj === 'object') {
if ((Object.isFrozen(obj) && Object.isSealed(obj))
|| (typeof Immutable === 'object' && Immutable && obj instanceof Immutable.Collection)
|| (typeof cljs === 'object' && cljs && cljs.coll_QMARK_(obj))) {
ret = obj;
} else {
ret = Object.create(obj.constructor);
for (let propName of Object.getOwnPropertyNames(obj)) {
ret[propName] = obj[propName];
}
}
} else {
ret = obj;
}
return ret;
}
/**
* Reads the value referred by a certain key of an associative object.
* Currently supported are plain old JavaScript objects,
* ECMAScript 2015 Maps and WeakMaps and collections from
* Immutable.js and ClojureScript.
*
* @param {any} obj
* The key-value collection
*
* @param {any} key
* The key of the value (Immutable and ClojureScript allow complex keys)
*
* @param {any} [defaultValue=undefined]
* The default value if the key-value collection does not contain the
* given key
*
* @return {any}
* Returns the
*
* @example
* Objects.get(null, 'myKey') // undefined
* Objects.get(null, 'myKey', 42) // 42
* Objects.get({myKey: 100}, 'myKey', 42) // 100
* Objects.get({x: 100}, 'myKey', 42) // 42
* Objects.get([7, 42], 1) // 42
* Objects.get(Immutable.Map({myKey: 100}), 'myKey', 42) // 100
*/
// TODO: Handling of ClojureScript objects not really nice (still working)
static get(obj, key, defaultValue = undefined) {
var ret = undefined;
if (obj !== null && obj !== undefined) {
if (typeof Immutable === 'object' && Immutable && obj instanceof Immutable.Collection) {
ret = obj.get(key)
} else if (obj.meta !== undefined
&& typeof cljs === 'object'
&& cljs
&& (cljs.core.map_QMARK_(obj) || cljs.core.coll_QMARK_(obj))) {
if (typeof key === 'string') {
ret = cljs.core.get(obj, cljs.core.keyword(path), undefined);
}
if (ret === undefined) {
ret = cljs.core.get(obj, key, undefined);
}
} else {
ret = obj[key];
}
}
if (ret === undefined) {
ret = defaultValue;
}
return ret;
}
/**
* Reads the value referred by a certain key of an associative object.
* Currently supported are plain old JavaScript objects, collections
* from Immutable.js and collections from ClojureScript.
*
* @param {any} obj
* The key-value collection
*
* @param {any} keyPath
* The key path of the value (Immutable and ClojureScript allow complex keys).
* Key path should be an array or something other seqable.
*
* @param {any} [defaultValue=undefined]
* The default value if the key-value collection does not contain the
* given key
*
* @return {any}
* Returns the
*
* @example
* const obj = {key1: {key2: 42}}
* Objects.get(null, ['key1', 'key2']) // undefined
* Objects.get(null, ['key1', 'key2'], 100) // 100
* Objects.get(obj, ['key1', 'key2'], 100) // 42
*/
static getIn(obj, keyPath, defaultValue = undefined) {
var ret = obj,
isRealKeyPath = false;
Seq.from(keyPath).forEach(key => {
ret = Objects.get(ret, key);
isRealKeyPath = true;
});
if (!isRealKeyPath || ret === undefined) {
ret = defaultValue;
}
return ret;
}
/**
* Returns the keys of all entries of a given object.
*
* @param {any}
* The object to retrieve the keys names.
* If not a real object than an empty array will be returnded.
*
* @return {string[]}
* The list of all key names.
*
* @example
* Objects.getKeys({a: 1, b: 2, c: 3}); // ['a', 'b', 'c']
* Objects.getKeys(null); // []
* Objects.getKeys('some text') // []
*
* @example
* let proto = {a: 1, b: 2},
* constr = () => {};
*
* constr.prototype = proto;
* let obj = new constr();
* obj.c = 3;
*
* Objects.getKeys(obj); // ['a', 'b', 'c']
*/
// TODO - apidoc and unit tests
static getKeys(obj) {
return Objects.getEntries(obj).map(entry => entry[0]);
}
// TODO - apidoc and unit tests
static getValues(obj) {
return Objects.getEntries(obj).map(entry => entry[1]);
}
// TODO - apidoc and unit tests - to be finished
static getEntries(obj) {
var ret;
if (obj === null || typeof obj !== 'object') {
ret = [];
} else if (typeof obj === 'object' && typeof obj.toEntrySeq === 'function') {
ret = Seq.from(obj.toEntrySeq()).toArray();
} else {
const keys = Object.keys(obj);
ret = [];
for (let key of keys) {
ret.push([key, obj[key]]);
}
}
return ret;
}
/**
* Converts an object to its plain old JavaScript representation.
* The purpose of this method is to convert Immutable and ClojureScript
* collections to their plain JavaScript pendant.
* If already a plain JavaScript object then it will be returned as is.
*
* @param {any} obj
* The object to be converted
*
* @return {any}
* The plain old JavaScript object
*
* @example
* Objects.toJS(undefined) // undefined
* Objects.toJS(null) // null
* Objects.toJS(42) // 42
* Objects.toJS('text') // 'text'
* Objects.toJS([1, 2, 3]) // [1, 2, 3]
* Objects.toJS({x: 42}) // {x: 42}
* Object.toJS(Immutable.Map({x: 42})) // {x: 42}
*/
// TODO: Handling of ClojureScript objects not really nice (still working)
static toJS(obj) {
var ret = obj;
if (obj) {
if (typeof obj.__toJS === 'function') {
ret = obj.__toJS();
} else if (obj.meta && typeof cljs === 'object' && cljs) {
ret = cljs.core.clj__GT_js(obj);
}
}
return ret;
}
static transform(obj, transformationPlan) {
var ret;
if (transformationPlan === null || typeof transformationPlan !== 'object') {
console.error('Illegal transformation plan: ', transformationPlan);
throw new TypeError(`[Objects.transform] Second argument 'transformationPlan' must be an object`);
}
try {
if (obj instanceof Reader) {
ret = new Reader(Transformer.transform(obj.__data, transformationPlan));
} else {
ret = Transformer.transform(obj, transformationPlan);
}
} catch (errorMsg) {
if (typeof errorMsg === 'string') {
throw new TypeError('[Objects.transform] ' + errorMsg);
} else {
// This should never happen!
throw errorMsg;
}
}
return ret;
}
} |
JavaScript | class Snapshot extends Component {
static propTypes = {
history: PropTypes.object,
openProposalsByRoleCount: PropTypes.number,
openProposalsCount: PropTypes.number,
};
themes = ['dark', 'gradient'];
/**
* Entry point to perform tasks required to render
* component.
*/
componentDidMount () {
theme.apply(this.themes);
}
/**
* Component teardown
*/
componentWillUnmount () {
theme.remove(this.themes);
}
/**
* Navigate to previous location
*/
goBack () {
const { history } = this.props;
history.length < 3 ?
history.push('/approval/pending/individual') :
history.goBack();
}
/**
* Render entrypoint
* @returns {JSX}
*/
render () {
const {
openProposalsCount,
openProposalsByRoleCount } = this.props;
return (
<div className='snapshot-container'>
<div className='snapshot-header'>
<Header
as='h1'
id='next-snapshot-header'
inverted>
Requests Snapshot
</Header>
<Button id='next-snapshot-button'
onClick={() => this.goBack()}
icon='close'
size='huge'/>
</div>
<div className='snapshot-sub-container'>
<SnapshotCard
count={openProposalsCount || 0}
status={`Pending across ${
utils.countLabel(openProposalsByRoleCount, 'role')
}`}/>
<SnapshotCard
image={<Image
floated='right'
src={expireGlyph}
className='next-snapshot-glyph'/>}
count={0}
status='About to Expire'/>
<SnapshotCard
count={0}
status='Delegated'/>
<SnapshotCard
count={0}
status='Unattended for 1 week'/>
<SnapshotCard
count={0}
status='Escalated'/>
<SnapshotCard
count={0}
status='Messages'/>
</div>
</div>
);
}
} |
JavaScript | class Login extends Component {
state = {
selected: ''
}
handleChange = (e) => {
e.preventDefault()
this.setState({
selected: e.target.value
})
}
handleDropSelect = (selected) => {
const { dispatch } = this.props
dispatch(setAuthedUser(selected))
}
handleSelect = (e) => {
e.preventDefault()
const { dispatch } = this.props
dispatch(setAuthedUser(this.state.selected))
}
render(){
const { authedUser, users } = this.props
const { from } = this.props.location.state || {from: {pathname: '/homepage'}}
console.log(this.props.location.state)
console.log("Authed user: ", authedUser)
if (authedUser !== null){
return <Redirect to={from} />
}
return(
<div className='main login-main'>
{this.props.location.state !== undefined && (<p>You must login first to view {this.props.location.state.from.pathname}</p>)}
<h1> Select a user to login as</h1>
<DropdownButton id='dropdown-basic-button' title='Select user'>
{Object.keys(users).map((key, index)=> (
<Dropdown.Item key={index} eventKey={`${users[key].id}`} onSelect={(eventKey) => this.handleDropSelect(eventKey)}>{users[key].name} ('{users[key].id}')</Dropdown.Item>
))}
</DropdownButton>
<Link to='/new'>Or, add a new user</Link>
</div>
)
}
} |
JavaScript | class Command extends Base {
constructor(args, location) {
super(location);
const privates = {
args: args,
}
privateProps.set(this, privates);
}
/** @memberof Statement.Command
* @instance
* @returns {Expression.Base[]} an array of expressions for this command */
get arguments() { return privateProps.get(this).args; }
} |
JavaScript | class Pkg extends Cache {
constructor(cwd, options) {
super('data');
if (typeof cwd !== 'string') {
options = cwd;
cwd = process.cwd();
}
this.options = Object.assign({cwd: cwd}, options);
this.cwd = path.resolve(this.options.cwd);
this.path = this.options.path || path.resolve(this.cwd, 'package.json');
this.data = this.read();
}
/**
* Write the `pkg.data` object to the file system at `pkg.path`.
*
* ```js
* pkg.save();
* ```
* @name .save
* @param {Function} `callback` (optional)
* @api public
*/
save(cb) {
if (typeof cb !== 'function') {
write.sync(this.path, this.data);
return;
}
write(this.path, this.data, cb);
return this;
}
/**
* Reads `pkg.path` from the file system and returns an object.
*
* ```js
* const data = pkg.read();
* ```
* @name .read
* @return {undefined}
* @api public
*/
read() {
if (fs.existsSync(this.path)) {
try {
return JSON.parse(fs.readFileSync(this.path, 'utf8'));
} catch (err) {
err.path = this.path;
err.reason = 'Cannot read ' + this.path;
throw err;
}
}
return {};
}
} |
JavaScript | class Countdown extends CountdownBase {
async onCreated() {
super.onCreated();
this._getProgress();
this._createTimer();
this._createPauseTimerButton('15 min break', 220, 15);
this._createPauseTimerButton('30 min break', 290, 30);
this._createPauseTimerButton('60 min break', 360, 60);
}
/**
* Get progress, if any, from session storage.
* @private
*/
_getProgress() {
const progress = JSON.parse(sessionStorage.getItem('progress'));
if (progress) {
this._currentTime = progress.startTime;
this._progressBarInitialWidth = progress.barPosition;
}
}
/**
* Renders the timer for the scene.
* @method
* @private
*/
_createTimer() {
const timer = new Timer(this._currentTime, this._endTime);
timer.y = -75;
this.timer = timer;
this.timer.on(Timer.events.LAST_TEN_SECONDS, () => {
this._finishScene();
});
this.addChild(this.timer);
this._startProgressBar();
}
/**
* Renders the scene's button
* @param {String} text button text
* @param {Number} y button y coordinate value
* @param {Number} duration pause timer duration
* @method
* @private
*/
_createPauseTimerButton(text, y, duration) {
const button = new Button({
width: 300,
height: 50,
text,
});
button.pivot.x = button.width / 2;
button.y = y;
button.on('click', () => {
this._saveProgress();
this.timer.clearInterval();
this.emit(Scene.events.EXIT, {
to: 'break',
data: {
duration,
},
});
});
this.addChild(button);
}
/**
* Save progress to session storage
* @private
*/
_saveProgress() {
const progress = {
startTime: this.timer.getProgress(),
barPosition: this._progressBar.getProgress(),
};
sessionStorage.setItem('progress', JSON.stringify(progress));
}
/**
* Emits a finish event
* @method
* @private
*/
_finishScene() {
sessionStorage.removeItem('progress');
this.emit(Scene.events.EXIT, {
to: 'finalCountdown',
});
}
} |
JavaScript | class scribbleCanvas{
//A new canvas is created with the specified properties
constructor(trainingDataDimensions, canvasSize, pixelSize,
bkgColor, lineColor, lineWeight){
this.dataSize = trainingDataDimensions;
this.canvasSize = canvasSize;
createCanvas(canvasSize, canvasSize);
pixelDensity(pixelSize);
background(bkgColor);
stroke(lineColor);
strokeWeight(lineWeight);
}
//The image data is collected from the canvas for the Network to use
getImageData(){
let img = get();
img.resize(this.dataSize, this.dataSize);
img.filter(INVERT);
img.loadPixels();
let pixels = [];
for(let i = 0; i < img.pixels.length; i++){
if (i % 4 == 0) {
pixels.push(img.pixels[i]/255);
}
}
//This should be turned on for testing compress quality: image(img, 0, 0);
return pixels
}
} |
JavaScript | class appUI{
constructor(dataSize, canvasSize){
this.dataSize = dataSize;
this.canvasSize = canvasSize;
//A new canvas is created using the scribble canvas class
this.cnv = new scribbleCanvas(this.dataSize, this.canvasSize, 1, "white", "black", 15);
//The data is cleaned and made usable and the NN is trained
this.trainData = dataSet.cleanDataSet(100);
this.epoch = 0;
}
//This function draws the user interface
static interface() {
//When the mouse is pressed, a line is drawn from the current position to the previous position
if (mouseIsPressed) line(mouseX, mouseY, pmouseX, pmouseY);
//When the "space" key is pressed, the canvas is wiped clean
if (keyIsPressed && key === " ") background("white");
}
//This function is called when the Neural Network is trained or is asked for a prediction
async useBrain(){
//When "b" is pressed, a new brain is created with customized traits
if (keyIsPressed && key === "b") {
this.machineBrain = new brain(sq(this.dataSize), 0, 28, 10, "Sigmoid");
}
//When "p" is pressed, the canvas data is acquired and pushed into the prediction
if (keyIsPressed && key === "p") {
let predict = this.machineBrain.prediction([this.cnv.getImageData()]);
console.log(predict);
}
//When "t" is pressed, the NN is trained with the shuffled training data
if (keyIsPressed && key === "t") {
this.epoch = await this.machineBrain.train(await this.trainData, this.epoch, 0.1);
console.log(`Epoch ${this.epoch} Complete`);
}
}
} |
JavaScript | class Portal extends React.Component {
componentDidMount() {
this.setMountNode(this.props.container);
// Only rerender if needed
if (!this.props.disable) {
this.forceUpdate(this.props.onRendered);
}
}
componentDidUpdate(prevProps) {
if (prevProps.container !== this.props.container || prevProps.disable !== this.props.disable) {
this.setMountNode(this.props.container);
// Only rerender if needed
if (!this.props.disable) {
this.forceUpdate(this.props.onRendered);
}
}
}
componentWillUnmount() {
this.mountNode = null;
}
setMountNode(container) {
if (this.props.disable) {
this.mountNode = ReactDOM.findDOMNode(this).parentElement;
return;
}
this.mountNode = getContainer(container, document.body);
}
getMountNode = () => {
return this.mountNode;
};
render() {
const { children, disable, unmount } = this.props;
if (unmount) {
return null;
}
if (disable) {
return children;
}
return this.mountNode ? ReactDOM.createPortal(children, this.mountNode) : null;
}
} |
JavaScript | class PrismaClient {
constructor() {
throw new Error(
`PrismaClient is unable to be run in the browser.
In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues`,
)
}
} |
JavaScript | class Client extends abstract_client_1.AbstractClient {
constructor(clientConfig) {
super("ivld.tencentcloudapi.com", "2021-09-03", clientConfig);
}
/**
* 创建智能标签任务。
请注意,本接口为异步接口,**返回TaskId只代表任务创建成功,不代表任务执行成功**。
*/
async CreateTask(req, cb) {
return this.request("CreateTask", req, cb);
}
/**
* 将URL指向的媒资视频文件导入系统之中。
**请注意,本接口为异步接口**。接口返回MediaId仅代表导入视频任务发起,不代表任务完成,您可调用读接口(DescribeMedia/DescribeMedias)接口查询MediaId对应的媒资文件的状态。
当前URL只支持COS地址,其形式为`https://${Bucket}-${AppId}.cos.${Region}.myqcloud.com/${ObjectKey}`,其中`${Bucket}`为您的COS桶名称,Region为COS桶所在[可用区](https://cloud.tencent.com/document/product/213/6091),`${ObjectKey}`为指向存储在COS桶内的待分析的视频的[ObjectKey](https://cloud.tencent.com/document/product/436/13324)
分析完成后,本产品将在您的`${Bucket}`桶内创建名为`${ObjectKey}-${task-start-time}`的目录(`task-start-time`形式为1970-01-01T08:08:08)并将分析结果将回传回该目录,也即,结构化分析结果(包括图片,JSON等数据)将会写回`https://${Bucket}-${AppId}.cos.${Region}.myqcloud.com/${ObjectKey}-${task-start-time}`目录
*/
async ImportMedia(req, cb) {
return this.request("ImportMedia", req, cb);
}
/**
* 创建自定义人物。
输入人物名称,基本信息,分类信息与人脸图片,创建自定义人物
人脸图片可使用图片数据(base64编码的图片数据)或者图片URL(推荐使用COS以减少下载时间,其他地址也支持),原始图片优先,也即如果同时指定了图片数据和图片URL,接口将仅使用图片数据
*/
async CreateCustomPerson(req, cb) {
return this.request("CreateCustomPerson", req, cb);
}
/**
* 删除自定义人脸数据
*/
async DeleteCustomPersonImage(req, cb) {
return this.request("DeleteCustomPersonImage", req, cb);
}
/**
* 查询用户回调设置
*/
async QueryCallback(req, cb) {
return this.request("QueryCallback", req, cb);
}
/**
* 更新自定义人物分类
当L2Category为空时,代表更新CategoryId对应的一级自定义人物类型以及所有二级自定义人物类型所从属的一级自定义人物类型;
当L2Category非空时,仅更新CategoryId对应的二级自定义人物类型
*/
async UpdateCustomCategory(req, cb) {
return this.request("UpdateCustomCategory", req, cb);
}
/**
* 更新自定义人物信息,包括姓名,简要信息,分类信息等
*/
async UpdateCustomPerson(req, cb) {
return this.request("UpdateCustomPerson", req, cb);
}
/**
* 删除自定义分类信息
*/
async DeleteCustomCategory(req, cb) {
return this.request("DeleteCustomCategory", req, cb);
}
/**
* 增加自定义人脸图片,每个自定义人物最多可包含10张人脸图片
请注意,与创建自定义人物一样,图片数据优先级优于图片URL优先级
*/
async AddCustomPersonImage(req, cb) {
return this.request("AddCustomPersonImage", req, cb);
}
/**
* 描述任务信息,如果任务成功完成,还将返回任务结果
*/
async DescribeTaskDetail(req, cb) {
return this.request("DescribeTaskDetail", req, cb);
}
/**
* 创建默认自定义人物类型
*/
async CreateDefaultCategories(req, cb) {
return this.request("CreateDefaultCategories", req, cb);
}
/**
* 描述智能标签任务进度。
请注意,**此接口仅返回任务执行状态信息,不返回任务执行结果**
*/
async DescribeTask(req, cb) {
return this.request("DescribeTask", req, cb);
}
/**
* 描述自定义人物详细信息,包括人物信息与人物信息
*/
async DescribeCustomPersonDetail(req, cb) {
return this.request("DescribeCustomPersonDetail", req, cb);
}
/**
* 创建自定义人物分类信息
当L2Category为空时,将创建一级自定义分类。
当L1Category与L2Category均不为空时,将创建二级自定义分类。请注意,**只有当一级自定义分类存在时,才可创建二级自定义分类**。
*/
async CreateCustomCategory(req, cb) {
return this.request("CreateCustomCategory", req, cb);
}
/**
* 批量描述自定义人物
*/
async DescribeCustomPersons(req, cb) {
return this.request("DescribeCustomPersons", req, cb);
}
/**
* 删除自定义人物
*/
async DeleteCustomPerson(req, cb) {
return this.request("DeleteCustomPerson", req, cb);
}
/**
* 描述媒资文件信息,包括媒资状态,分辨率,帧率等。
如果媒资文件未完成导入,本接口将仅输出媒资文件的状态信息;导入完成后,本接口还将输出媒资文件的其他元信息。
*/
async DescribeMedia(req, cb) {
return this.request("DescribeMedia", req, cb);
}
/**
* 将MediaId对应的媒资文件从系统中删除。
**请注意,本接口仅删除媒资文件,媒资文件对应的视频分析结果不会被删除**。如您需要删除结构化分析结果,请调用DeleteTask接口。
*/
async DeleteMedia(req, cb) {
return this.request("DeleteMedia", req, cb);
}
/**
* 用户设置对应事件的回调地址
### 回调事件消息通知协议
#### 网络协议
- 回调接口协议目前仅支持http/https协议;
- 请求:HTTP POST 请求,包体内容为 JSON,每一种消息的具体包体内容参见后文。
- 应答:HTTP STATUS CODE = 200,服务端忽略应答包具体内容,为了协议友好,建议客户应答内容携带 JSON: `{"code":0}`
#### 通知可靠性
事件通知服务具备重试能力,事件通知失败后会总计重试3次;
为了避免重试对您的服务器以及网络带宽造成冲击,请保持正常回包。触发重试条件如下:
- 长时间(20 秒)未回包应答。
- 应答 HTTP STATUS 不为200。
#### 回调接口协议
##### 分析任务完成消息回调
| 参数名称 | 必选 | 类型 | 描述 |
|---------|---------|---------|---------|
| EventType | 是 | int | 回调时间类型,1-任务分析完成,2-媒资导入完成 |
| TaskId | 是 | String | 任务ID |
| TaskStatus | 是 | [TaskStatus](/document/product/1611/63373?!preview&preview_docmenu=1&lang=cn&!document=1#TaskStatus) | 任务执行状态 |
| FailedReason | 是 | String | 若任务失败,该字段为失败原因 |
##### 导入媒资完成消息回调
| 参数名称 | 必选 | 类型 | 描述 |
|---------|---------|---------|---------|
| EventType | 是 | int | 回调时间类型,1-任务分析完成,2-媒资导入完成 |
| MediaId | 是 | String | 媒资ID |
| MediaStatus | 是 | [MediaStatus](/document/product/1611/63373?!preview&preview_docmenu=1&lang=cn&!document=1#MediaStatus) | 媒资导入状态|
| FailedReason | 是 | String | 若任务失败,该字段为失败原因 |
*/
async ModifyCallback(req, cb) {
return this.request("ModifyCallback", req, cb);
}
/**
* 依照输入条件,描述命中的任务信息,包括任务创建时间,处理时间信息等。
请注意,本接口最多支持同时描述**50**个任务信息
*/
async DescribeTasks(req, cb) {
return this.request("DescribeTasks", req, cb);
}
/**
* 创建自定义人物库
Bucket的格式参考为 `bucketName-123456.cos.ap-shanghai.myqcloud.com`
在调用CreateCustomPerson和AddCustomPersonImage接口之前,请先确保本接口成功调用。当前每个用户只支持一个自定义人物库,一旦自定义人物库创建成功,后续接口调用均会返回人物库已存在错误。
由于人脸图片对于自定义人物识别至关重要,因此自定义人物识别功能需要用户显式指定COS存储桶方可使用。具体来说,自定义人物识别功能接口(主要是CreateCustomPerson和AddCustomPersonImage)会在此COS桶下面新建IVLDCustomPersonImage目录,并在此目录下存储自定义人物图片数据以支持后续潜在的特征更新。
请注意:本接口指定的COS桶仅用于**备份存储自定义人物图片**,CreateCustomPerson和AddCustomPersonImage接口入参URL可使用任意COS存储桶下的任意图片。
**重要**:请务必确保本接口指定的COS存储桶存在(不要手动删除COS桶)。COS存储桶一旦指定,将不能修改。
*/
async CreateCustomGroup(req, cb) {
return this.request("CreateCustomGroup", req, cb);
}
/**
* 批量描述自定义人物分类信息
*/
async DescribeCustomCategories(req, cb) {
return this.request("DescribeCustomCategories", req, cb);
}
/**
* 删除任务信息
请注意,本接口**不会**删除媒资文件
只有已完成(成功或者失败)的任务可以删除,**正在执行中的任务不支持删除**
*/
async DeleteTask(req, cb) {
return this.request("DeleteTask", req, cb);
}
/**
* 描述自定义人物库信息,当前库大小(库中有多少人脸),以及库中的存储桶
*/
async DescribeCustomGroup(req, cb) {
return this.request("DescribeCustomGroup", req, cb);
}
/**
* 依照输入条件,描述命中的媒资文件信息,包括媒资状态,分辨率,帧率等。
请注意,本接口最多支持同时描述**50**个媒资文件
如果媒资文件未完成导入,本接口将仅输出媒资文件的状态信息;导入完成后,本接口还将输出媒资文件的其他元信息。
*/
async DescribeMedias(req, cb) {
return this.request("DescribeMedias", req, cb);
}
} |
JavaScript | class BuildAgentQueue {
/**
* Create a BuildAgentQueue.
* @property {string} queue
*/
constructor() {
}
/**
* Defines the metadata of BuildAgentQueue
*
* @returns {object} metadata of BuildAgentQueue
*
*/
mapper() {
return {
required: false,
serializedName: 'BuildAgentQueue',
type: {
name: 'Composite',
className: 'BuildAgentQueue',
modelProperties: {
queue: {
required: true,
serializedName: 'queue',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class AutoSave extends React.Component {
constructor(props) {
super(props)
this.updateInterval = 5000
this.oldValues = _.cloneDeep(this.props.values)
}
componentDidMount() {
this.timer = setInterval(() => this.save(), this.updateInterval)
}
componentWillUnmount() {
clearInterval(this.timer)
}
save() {
const oldValues = _.omit(this.oldValues, FORM_FIELDS_TO_OMIT)
const currentValues = _.omit(this.props.values, FORM_FIELDS_TO_OMIT)
if (!this.props.disabled && !_.isEqual(oldValues, currentValues)) {
this.props.onSave(this.props.values)
this.oldValues = _.cloneDeep(this.props.values)
}
}
render() {
return this.props.children || null
}
} |
JavaScript | class Place{
position;
direction;
constructor(x, y, direction){
this.position = new Position(x,y);
this.direction = direction;
}
} |
JavaScript | class GraphTypeWrapper {
constructor(value, typeInfo) {
this.value = value;
this.typeInfo = typeof typeInfo === 'number' ? { code: typeInfo } : typeInfo;
}
} |
JavaScript | class UdtGraphWrapper {
constructor(value, udtInfo) {
this.value = value;
if (!udtInfo || !udtInfo.name || !udtInfo.keyspace || !udtInfo.fields) {
throw new TypeError(`udtInfo must be an object with name, keyspace and field properties defined`);
}
this.udtInfo = udtInfo;
}
} |
JavaScript | class MyStaticSiteStack extends CDK.Stack {
constructor(parent, name, props) {
super(parent, name, props);
new StaticSite(this, 'StaticSite', {
domainName: this.node.tryGetContext('domain'),
siteSubDomain: this.node.tryGetContext('subdomain')
});
}
} |
JavaScript | class AppError extends Error {
constructor(statusCode, status, message) {
super(message);
this.statusCode = statusCode;
this.status = status;
this.message = message;
}
} |
JavaScript | class BottomBox extends React.Component {
render() {
if (this.props.imageURLs && this.props.imageURLs.length > 0) {
let images = [];
for(let i=0; i<this.props.imageURLs.length;i++){
let imageDiv = <img key={i.toString()} src={this.props.imageURLs[i]} alt="Mountain View" style={{width:150, height:150}} ></img> ;
images.push(imageDiv);
}
return (
<div className='BottomBox'>
<div className='jsonBox'>
{JSON.stringify(this.props.jsonResponse)}
</div>
<div className='imagesBox'>
{images}
</div>
</div>
);
} else {
return (
<div className='BottomBox'>
<div className='jsonBox'>
{JSON.stringify(this.props.jsonResponse)}
</div>
<div className='imagesBox'>
</div>
</div>
);
}
}
} |
JavaScript | class ClipboardBusinessObject extends BaseClass(IPropertyObservable) {
/**
* Creates a new instance of <code>ClipboardBusinessObject</code>
*/
constructor() {
super()
this.$name = null
this.$value = 0.5
this.$propertyChangedEvent = null
}
/**
* Gets the name of this object.
* @return {string}
*/
get name() {
return this.$name
}
/**
* Sets the name of this object.
* @param {string} value
*/
set name(value) {
if (this.$name !== value) {
this.$name = value
if (this.$propertyChangedEvent !== null) {
this.$propertyChangedEvent(this, new PropertyChangedEventArgs('name'))
}
}
}
/**
* Gets the numeric value of this object.
* @return {number}
*/
get value() {
return this.$value
}
/**
* Sets the numeric value of this object.
* @param {number} v
*/
set value(v) {
if (v < 0) {
this.$value = 0
} else if (v > 1) {
this.$value = 1
} else {
this.$value = v
}
}
/**
* Gets the event fired when the {@link ClipboardBusinessObject#name} of this object changes.
* @return {function(Object, PropertyChangedEventArgs)}
*/
get propertyChangedEvent() {
return this.$propertyChangedEvent
}
/**
* Sets the event fired when the {@link ClipboardBusinessObject#name} of this object changes.
* @param {function(Object, PropertyChangedEventArgs)} value
*/
set propertyChangedEvent(value) {
this.$propertyChangedEvent = value
}
/**
* The event that is fired when the {@link ClipboardBusinessObject#name} of this object changes.
* @param {function(Object, PropertyChangedEventArgs)} value
*/
addPropertyChangedListener(value) {
this.$propertyChangedEvent = delegate.combine(this.$propertyChangedEvent, value)
}
/**
* The event that is fired when the {@link ClipboardBusinessObject#name} of this object changes.
* @param {function(Object, PropertyChangedEventArgs)} value
*/
removePropertyChangedListener(value) {
this.$propertyChangedEvent = delegate.remove(this.$propertyChangedEvent, value)
}
/**
* Creates an instance of ClipboardBusinessObject.
* @return {ClipboardBusinessObject}
*/
static create() {
const newClipboardBusinessObject = new ClipboardBusinessObject()
newClipboardBusinessObject.name = `Name ${++counter}`
return newClipboardBusinessObject
}
} |
JavaScript | class AuthDialog {
toggleVisibilityBasedOnAuth (user) {
if (!user) {
this.show()
} else {
this.hide()
}
}
show = () => {
if (this.isDisplayed()) {
return
}
const template = document.getElementById('dialogs')
const dialog = template.content.querySelector('#authDialog').cloneNode(true)
dialog.removeAttribute('id')
dialog.classList.add('auth-dialog')
dialogPolyfill.registerDialog(dialog)
const form = dialog.querySelector('form')
form.addEventListener('submit', this.onFormSubmit)
if (window.localStorage) {
form.querySelector('#localstorageRequired').remove()
} else {
form.querySelector('[type=submit]').disabled = true
}
document.body.appendChild(dialog)
dialog.showModal()
}
hide = () => {
this.loginDialog?.remove()
}
/**
* Handle dialog form validation
*
* @param {Event} evt
*/
onFormSubmit = async (evt) => {
evt.preventDefault()
const { target: form } = evt
const submit = form.querySelector('button[type=submit]')
const { value } = form.querySelector('[name=username]')
this.setError(false)
submit.disabled = true
if (!value || value.trim().length === 0 || value.length > 32) {
this.setError('Invalid username supplied')
return
}
try {
await database.signIn(value)
AlertService.announce('You are logged in')
} catch (err) {
this.setError(err.toString())
}
}
setError (errorMsg) {
const form = this.loginDialog.querySelector('form')
/** @type {HTMLButtonElement} */
const submit = form.querySelector('button[type=submit]')
/** @type {HTMLInputElement} */
const username = form.querySelector('[name=username]')
/** @type {HTMLDivElement} */
const error = form.querySelector('.form__error')
if (errorMsg) {
username.setAttribute('aria-invalid', 'true')
error.innerHTML = errorMsg
submit.disabled = false
username.focus()
} else {
username.removeAttribute('aria-invalid')
error.innerHTML = ''
}
}
isDisplayed () {
return !!this.loginDialog
}
isNotDisplayed () {
return !this.isDisplayed()
}
/***
*
* @returns {HTMLDialogElement}
*/
get loginDialog () {
return document.querySelector('.auth-dialog')
}
} |
JavaScript | class DateManager {
constructor(date) {
this.date = new Date(date);
this.months = {
0: 31,
1: 28,
2: 31,
3: 30,
4: 31,
5: 20,
6: 31,
7: 31,
8: 30,
9: 31,
10: 30,
11: 31
};
/*We have to know if it is a leap year and set february (month 1) to 29 days*/
if (this.isALeapYear( this.date.getYear)) {
this.months[2]=29;
}
}
// tells if a given year is a leap year (bissextile)
isALeapYear(year) {
/*
Algorithm from wikipedia
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
*/
if (year % 4 !== 0)
return false;
else if (year % 100 !== 0)
return true;
else if (year % 400 !== 0)
return false;
else
return true;
}
//add one day to date
addDay(){
var month = this.date.getMonth();
var day = this.date.getUTCDate();
if(this.months[month] !== this.date.getDay){
day++;
this.date.setDate(day);
}
else{
month++;
this.date.setMonth(month);
this.date.setDate(1);
}
}
subtractDay(){
var month = this.date.getMonth();
var day = this.date.getUTCDate();
if(this.date.getDay!=1){
day--;
this.date.setDate(day);
}
else{
month--;
this.date.setMonth(month);
this.date.setDate(this.months[month]);
}
}
} |
JavaScript | class BeakerBroker extends PolymerElement{// render function
static get template(){return html`
<style>:host {
display: block;
}
:host([hidden]) {
display: none;
}
</style>
<slot></slot>`}// haxProperty definition
static get haxProperties(){return{}}// properties available to the custom element for data binding
static get properties(){return{/**
* Archive
*/archive:{type:"Object",notify:!0},/**
* datUrl
*/datUrl:{type:"String",value:window.location.host,observer:"_datUrlChanged",notify:!0}}}/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/static get tag(){return"beaker-broker"}/**
* life cycle, element is afixed to the DOM
*/connectedCallback(){super.connectedCallback();if(typeof DatArchive===typeof void 0){console.log("Beaker is not available from this site loading methodology")}}/**
* notice dat address has changed, build the object for it
*/async _datUrlChanged(newValue,oldValue){if(typeof DatArchive!==typeof void 0&&newValue){// load current site, set to archive
this.set("archive",new DatArchive(newValue))}}/**
* Write to file
* @usage - this.write('hello.txt', 'things and stuff');
*/async write(path,data){// well that was easy
await this.archive.writeFile(path,data)}/**
* Read to file
* @var path - location of file
* @var type - utf8, base64, hex, binary or specialized ones jpeg / png
* @return Promise() with reference to the data in the file if await / async is active
* @usage - await this.read('index.html'); to get this file
*/async read(path,type){var ftype="utf8",response;// special cases for image types
switch(type){case"jpeg":case"jpg":ftype="binary";var buf=await this.archive.readFile(path,ftype),blob=new Blob([buf],{type:"image/jpeg"});response=URL.createObjectURL(blob);break;case"png":ftype="binary";var buf=await this.archive.readFile(path,ftype),blob=new Blob([buf],{type:"image/png"});response=URL.createObjectURL(blob);break;case"base64":var str=await this.archive.readFile(path,type);response="data:image/png;base64,"+str;break;default:var str=await this.archive.readFile(path,type);response=str;break;}return await response}/**
* life cycle, element is removed from the DOM
*/ //disconnectedCallback() {}
} |
JavaScript | class Helpers {
static nodeResolveAsync(id, opts) {
return new Promise((resolve, reject) => {
resolve_1.default(id, opts, (error, result) => {
if (error) {
reject(error);
}
else {
resolve(result);
}
});
});
}
static fsExistsAsync(path) {
return new Promise((resolve) => {
fs.exists(path, (exists) => {
resolve(exists);
});
});
}
// Based on Path.isDownwardRelative() from @rushstack/node-core-library
static isDownwardRelative(inputPath) {
if (path.isAbsolute(inputPath)) {
return false;
}
// Does it contain ".."
if (Helpers._upwardPathSegmentRegex.test(inputPath)) {
return false;
}
return true;
}
} |
JavaScript | class Notification extends Component {
constructor(props) {
super(props);
this.handleDismiss = this.handleDismiss.bind(this);
this.setDismissTimeout();
}
handleDismiss = () => {
this.props.onDismiss(this.props.id);
}
setDismissTimeout = () => {
if (this.props.autoDismiss) {
this.dismissTimeout = setTimeout(() => this.handleDismiss(), this.props.dismissDelay);
}
}
clearDismissTimeout = () => {
if (this.dismissTimeout) {
clearTimeout(this.dismissTimeout);
}
}
componentWillUnmount() {
this.clearDismissTimeout();
}
render() {
const { description, dismissable, onDismiss, dismissDelay, title, sentryId, requestId, autoDismiss, ...rest } = this.props;
return (
<Alert
className="notification-item"
title={ title && title.replace(/<\/?[^>]+(>|$)/g, '') }
{ ...rest }
actionClose={ dismissable ?
<AlertActionCloseButton
aria-label="close-notification"
variant="plain"
onClick={ this.handleDismiss }
>
<CloseIcon/>
</AlertActionCloseButton> : null
}
onMouseEnter={this.clearDismissTimeout}
onMouseLeave={this.setDismissTimeout}
>
{ (typeof description === 'string') ? description.replace(/<\/?[^>]+(>|$)/g, '') : description }
{
sentryId && <TextContent>
<Text component={ TextVariants.small }>Tracking Id: { sentryId }</Text>
</TextContent>
}
{
requestId && <TextContent>
<Text component={ TextVariants.small }>Request Id: { requestId }</Text>
</TextContent>
}
</Alert>
);
}
} |
JavaScript | class Vsync {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {!Window} */
this.win = win;
// TODO(dvoytenko): polyfill requestAnimationFrame?
}
/**
* @param {!VsyncTaskSpec} task
* @param {!Object<string, *>|udnefined} opt_state
*/
run(task, opt_state) {
let state = opt_state || {};
this.win.requestAnimationFrame(() => {
if (task.measure) {
task.measure(state);
}
task.mutate(state);
});
}
/**
* Runs the mutate operation via vsync.
* @param {function()} mutator
*/
mutate(mutator) {
this.run({mutate: mutator});
}
/**
* @param {!VsyncTaskSpec} task
* @return {function((!Object<string, *>|undefined))}
*/
createTask(task) {
return (opt_state) => {
this.run(task, opt_state);
};
}
/**
* Runs the series of mutates until the mutator returns a false value.
* @param {function(time, time, !Object<string,*>):boolean} mutator The
* mutator callback. Only expected to do DOM writes, not reads. If the
* returned value is true, the vsync task will be repeated, otherwise it
* will be completed.
* @param {number=} opt_timeout Optional timeout that will force the series
* to complete and reject the promise.
* @return {!Promise} Returns the promise that will either resolve on when
* the vsync series are completed or reject in case of failure, such as
* timeout.
*/
runMutateSeries(mutator, opt_timeout) {
return new Promise((resolve, reject) => {
let startTime = timer.now();
let prevTime = 0;
let task = this.createTask({
mutate: (state) => {
let timeSinceStart = timer.now() - startTime;
let res = mutator(timeSinceStart, timeSinceStart - prevTime, state);
if (!res) {
resolve();
} else if (opt_timeout && timeSinceStart > opt_timeout) {
reject('timeout');
} else {
prevTime = timeSinceStart;
task(state);
}
}
});
task({});
});
}
} |
JavaScript | class FormStore extends Store__default['default'] {
constructor(STATE_PROPERTY) {
super(STATE_PROPERTY);
this.createAction("formArrayAdd", (state, {
path,
index
}) => {
const key = Store.normalizeKey(path);
const fields = this.getValidationRules([...key, index]) || {};
if (!fields) {
throw new Error(`FormArray has not been defined at path ${this._stringifyPath(key)}`);
}
let newFields = this._processForm(fields, [...key, index], true); // on doit respecter la structure complète
newFields = Store.getKeyValue(newFields, [...key, index]); // mais seule la nouvelle clé nous intéresse
const newState = state.updateIn(["form", ...key], arr => arr ? arr.insert(index, immutable.fromJS(newFields)) : immutable.List([immutable.fromJS(newFields)]));
return Store.stateWithChanges(state, newState);
});
this.createAction("formArrayRemove", (state, {
path,
index
}) => {
const key = Store.normalizeKey(path);
const list = this._getList(state, key);
const ind = index == null ? list.size - 1 : index;
return Store.stateWithChanges(state, state.deleteIn(["form", ...key, ind]));
});
this.createAction("formArrayMove", (state, {
path,
oldIndex,
newIndex
}) => {
const key = Store.normalizeKey(path);
const list = this._getList(state, key);
const field = list.get(oldIndex);
const newState = state.deleteIn(["form", ...key, oldIndex]).updateIn(["form", ...key], arr => arr.insert(newIndex, field));
return Store.stateWithChanges(state, newState);
});
this.createAction("formArrayReset", (state, {
path
}) => {
const key = Store.normalizeKey(path);
const newState = state.setIn(["form", ...key], immutable.List());
return Store.stateWithChanges(state, newState);
});
const originalResetFormValues = this._reducers[this._getFullActionName("resetFormValues")];
this.createAction("resetFormValues", (state, {
path = []
}) => {
const newState = this._resetAffectedFormArrays(state, {
path
});
return originalResetFormValues(newState, {
path
});
});
const originalSetFormValues = this._reducers[this._getFullActionName("setFormValues")];
this.createAction("setFormValues", (state, {
values,
path = []
}) => {
const newState = this._resetAffectedFormArrays(state, {
values,
path
});
return originalSetFormValues(newState, {
values,
path
});
});
const originalInitFormValues = this._reducers[this._getFullActionName("initFormValues")];
this.createAction("initFormValues", (state, {
values,
path = []
}) => {
const newState = this._resetAffectedFormArrays(state, {
values,
path
});
return originalInitFormValues(newState, {
values,
path
});
});
}
_resetAffectedFormArrays(state, {
values: _values,
path = []
}) {
let newState = state;
const values = _values || this.getFormValuesIn(path, state);
if (this.isField(path)) return newState;
if (Array.isArray(values)) {
if (this._isFormArray(path)) {
const list = newState.getIn(["form", ...path]);
if (list) newState = newState.setIn(["form", ...path], immutable.List());
} else {
values.forEach((value, i) => {
newState = this._resetAffectedFormArrays(newState, {
values: value,
path: [...path, i]
});
});
}
} else if (isPlainObject__default['default'](values)) {
for (const n in values) {
newState = this._resetAffectedFormArrays(newState, {
values: values[n],
path: [...path, n]
});
}
}
return newState;
}
_getList(state, path) {
if (!this._isFormArray(path)) {
throw new Error(`field at key ${this._stringifyPath(path)} is not a FormArray`);
}
return state.getIn(["form", ...path]);
}
_isFormArray(path) {
return this.getValidationRules(path) instanceof FormArray;
}
_getFormArrays(_state, _obj, _path = []) {
const state = _state || this.getState();
const path = Store.normalizeKey(_path);
const obj = _obj || state.getIn(["form", ...path]);
const formArrays = [];
if (this._isFormArray(path)) formArrays.push(path);
for (const [key, value] of obj.entries()) {
const searchKey = [...path, key];
const rules = this.getValidationRules(searchKey);
if (rules instanceof FormArray) formArrays.push(searchKey);
if (value instanceof immutable.Map || value instanceof immutable.List) {
formArrays.push(...this._getFormArrays(state, value, searchKey));
}
}
return formArrays;
}
/**
* Définit la structure des éléments du tableau si on ne l'a pas fait dans defineForm
* @param {String|Array} path chemin du tableau de formulaire
* @param {Object} itemDefinition description de la structure des éléments du tableau
* @returns {undefined}
*/
formArrayDef(path, itemDefinition) {
/* mode strict (pas de redéfinition possible)
const rules = this.getValidationRules([...path, 0])
if (rules) throw new Error(`FormArray has already been defined at path ${this._stringifyPath(path)}`)*/
return this._processForm(new FormArray(itemDefinition), Store.normalizeKey(path));
}
/**
* Ajoute un élément au tableau
* @param {String|Array} path chemin du tableau de formulaire
* @param {Number} ind indice où ajouter l'élément (à la fin par défaut)
* @returns {Number} l'indice où a été ajouté l'élément
*/
formArrayAdd(path, ind) {
let index = ind;
if (index == null) {
const key = Store.normalizeKey(path);
const list = this._getList(this.getState(), key);
index = (list === null || list === void 0 ? void 0 : list.size) || 0;
}
this.execAction("formArrayAdd", {
path,
index
});
return index;
}
/**
* Supprime un élément du tableau
* @param {String|Array} path chemin du tableau de formulaire
* @param {Number} index indice de l'élément à supprimer (le dernier par défaut)
* @returns {undefined}
*/
formArrayRemove(path, index = null) {
return this.execAction("formArrayRemove", {
path,
index
});
}
/**
* Supprime tous les éléments du tableau
* @param {String|Array} path chemin du tableau de formulaire
* @returns {undefined}
*/
formArrayReset(path) {
return this.execAction("formArrayReset", {
path
});
}
/**
* Déplace un élément du tableau
* @param {String|Array} path chemin du tableau de formulaire
* @param {Number} oldIndex indice de l'élément à déplacer
* @param {Number} newIndex indice où déplacer l'élément
* @returns {undefined}
*/
formArrayMove(path, oldIndex, newIndex) {
return this.execAction("formArrayMove", {
path,
oldIndex,
newIndex
});
}
/**
* Renvoie la longueur du tableau
* @param {String|Array} path chemin du du tableau de formulaire
* @param {Immutable} state optionnel, état du store
* @returns {Number} longueur du tableau
*/
getFormArrayLength(path, state) {
const array = this.getState(state).getIn(["form", ...Store.normalizeKey(path)]);
return array.size;
}
/**
* Renvoie un objet permettant de manipuler plus facilement le tableau de formulaire
* @param {String|Array} path chemin du tableau de formulaire
* @returns {Object} objet contenant les méthodes add, remove, move et la propriété length
*/
getFormArray(path) {
const that = this;
return {
add(index = null) {
that.formArrayAdd(path, index);
return this;
},
remove(index = null) {
that.formArrayRemove(path, index);
return this;
},
move(oldIndex, newIndex) {
that.formArrayMove(path, oldIndex, newIndex);
return this;
},
get length() {
return that.getFormArrayLength(path);
}
};
}
_resetFormArrayKeys(path) {
return path.reduce((newPath, arg) => [...newPath, this._isFormArray(newPath) ? 0 : arg], []);
}
getValidationRules(path) {
const resetPath = this._resetFormArrayKeys(path);
return super.getValidationRules(resetPath);
}
_processForm(fields, initialKey = [], skipRule = false) {
const form = {};
const processForm = (field, key = [], skipValue = false) => {
if (isPlainObject__default['default'](field)) {
let hasKey = false;
for (const n in field) {
hasKey = true;
processForm(field[n], [...key, n], skipValue);
}
if (!hasKey && !skipValue) Store.setKeyValue(form, key, {});
} else if (Array.isArray(field)) {
if (!field.length) Store.setKeyValue(form, key, []);
for (let i = 0; i < field.length; i++) processForm(field[i], [...key, i], skipValue);
} else if (field instanceof FormArray) {
if (!skipValue) Store.setKeyValue(form, key, []);
const arr = new FormArray(field.structure);
if (!skipRule) {
Store.setKeyValue(this.validationRules, this._resetFormArrayKeys(key), arr);
}
for (const n in field.structure) processForm(field.structure[n], [...key, 0, n], true);
} else {
if (!skipRule) this.defineFieldRules(key, field);
if (skipValue) return;
Store.setKeyValue(form, key, {
value: null,
initialValue: null,
error: null,
warning: null,
touched: false
});
}
};
processForm(fields, initialKey);
return form;
}
} |
JavaScript | class ScenarioTriggerAfterForm extends FormObject.class {
/**
* Constructor
*
* @param {number} [id=null] An identifier
* @param {number} [delay=null] A delay
* @param {string} [unit=null] A delay unit
* @returns {ScenarioTriggerAfterForm} The instance
*/
constructor(id = null, delay = 0, unit = null) {
super(id);
/**
* @Property("unit");
* @Title("scenario.form.schedule.unit");
* @Default("immediately");
* @Type("string");
* @Enum(["immediately", "seconds", "minutes", "hours", "days"]);
* @EnumNames(["scenario.form.schedule.immediatly", "scenario.form.schedule.secondes", "scenario.form.schedule.minutes", "scenario.form.schedule.hours", "scenario.form.schedule.days"]);
*/
this.unit = unit;
/**
* @Property("delay");
* @Title("scenario.form.schedule.delay");
* @Type("number");
* @Required(false);
* @Default(0);
*/
this.delay = delay;
}
/**
* Convert json data
*
* @param {Object} data Some key / value data
* @returns {ScenarioTriggerAfterForm} A form object
*/
json(data) {
return new ScenarioTriggerAfterForm(data.id, data.delay, data.unit);
}
} |
JavaScript | class CachedImage extends ContextImage { // eslint-disable-line no-unused-vars
/**
* JavaScript cached image constructor
* @constructor
*/
constructor() {
super();
/**
* Image array
* @private
* @type {Array<Image>}
*/
this.images_ = [];
/**
* Cached image array
* @private
* @type {Dictionary<string, number>}
*/
this.caches_ = {};
}
/**
* Load image and return ID
* @override
* @param {string} filePath image file path
* @return {number} image ID
*/
loadImage(filePath) {
let cache = this.caches_[filePath];
if (cache !== undefined) {
return cache;
}
let image = new Image();
image.src = filePath;
this.images_.push(image);
return this.caches_[filePath] = this.images_.length - 1;
}
/**
* Unload image
* @override
* @param {number} imageID Image ID
*/
unloadImage(imageID) {
// TODO: Should be implemented
}
/**
* Get image path
* @override
* @param {number} imageID Image ID
* @return {string} Image path (return null if not exists)
*/
getImagePath(imageID) {
for (let path in this.caches_) {
if (this.caches_.hasOwnProperty(path)) {
if (this.caches_[path] == imageID) {
return path;
}
}
}
return null;
}
/**
* Get image by ID
* @override
* @param {number} id id
* @return {Image} image
*/
getImage(id) {
return this.images_[id];
}
} |
JavaScript | class NCMBQuery {
constructor(ncmb, name) {
this.ncmb = ncmb;
this.className = name;
this.where = {};
this.limit = 100;
this.order = 'createDate';
this.include = '';
this.skip = 0;
}
equalTo(key, value) {
return this.setOperand(key, value);
}
notEqualTo(key, value) {
return this.setOperand(key, value, '$ne');
}
lessThan(key, value) {
return this.setOperand(key, value, '$lt');
}
lessThanOrEqualTo(key, value) {
return this.setOperand(key, value, '$lte');
}
greaterThan(key, value) {
return this.setOperand(key, value, '$gt');
}
greaterThanOrEqualTo(key, value) {
return this.setOperand(key, value, '$gte');
}
in(key, value) {
return this.setOperand(key, value, '$in');
}
exclude(key, value) {
return this.setOperand(key, value, '$nin');
}
exists(key, value) {
return this.setOperand(key, value, '$exists');
}
regularExpressionTo(key, value) {
return this.setOperand(key, value, '$regex');
}
inArray(key, value) {
return this.setOperand(key, value, '$inArray');
}
ninArray(key, value) {
return this.setOperand(key, value, '$ninArray');
}
allInArray(key, value) {
return this.setOperand(key, value, '$all');
}
near(key, value) {
return this.setOperand(key, value, '$nearSphere');
}
withinKilometers(key, value, distance) {
this.setOperand(key, value, '$nearSphere');
this.where[key]['$maxDistanceInKilometers'] = distance;
return this;
}
withinMiles(key, value, distance) {
this.setOperand(key, value, '$nearSphere');
this.where[key]['$maxDistanceInMiles'] = distance;
return this;
}
withinRadians(key, value, distance) {
this.setOperand(key, value, '$nearSphere');
this.where[key]['$maxDistanceInRadians'] = distance;
return this;
}
withinSquare(key, southWest, northEast) {
return this.setOperand(key, { '$box': [southWest, northEast] }, '$within');
}
setOperand(key, value, ope = '') {
if (ope === '') {
this.where[key] = this.changeValue(value);
}
else {
if (!this.where[key])
this.where[key] = {};
this.where[key][ope] = this.changeValue(value);
}
return this;
}
changeValue(value) {
if (value instanceof Date)
return { __type: "Date", iso: value.toISOString() };
return value;
}
fetch() {
this.limit = 1;
return this.fetchAll()[0];
}
fetchAll() {
const req = this.ncmb.Request();
const query = {
where: this.where,
limit: this.limit,
order: this.order,
include: this.include,
skip: this.skip
};
const json = req.get(this.getPath(), query);
return json.results.map(params => {
let obj;
switch (this.className) {
case 'installations':
obj = new this.ncmb.Installation();
break;
case 'push':
obj = new this.ncmb.Push();
break;
default:
obj = this.ncmb.Object(this.className);
break;
}
obj.sets(params);
return obj;
});
}
specialPath() {
return ["roles", "users", "files", "installations", "push"].indexOf(this.className) > -1;
}
getPath() {
let url = `/${this.ncmb.version}/`;
if (this.specialPath()) {
url = `${url}${this.className}`;
}
else {
url = `${url}classes/${this.className}`;
}
return url;
}
} |
JavaScript | class RectSpritesheet extends Spritesheet {
constructor(a) {
super(a);
this.sourceRectSize = a.sourceRectSize;
this.columnCount = Math.floor(this.image.width / this.sourceRectSize.width);
debugLog(`Created ${this.debugDescription}`);
}
get debugDescription() {
return `<${this.constructor.name} img:${Rect.sizeDebugDescription(this.image)} src:${Rect.sizeDebugDescription(this.sourceRectSize)} c|${this.columnCount}>`;
}
draw(c, destRect, spriteIndex, randomSeed) {
// Really simple.
let column = (Number.isInteger(randomSeed) ? randomSeed : 0) % this.columnCount;
let sheetOrigin = new Point(
column * this.sourceRectSize.width,
spriteIndex * this.sourceRectSize.height
);
let sheetRect = new Rect(sheetOrigin, this.sourceRectSize);
this.drawSheetRect(c, destRect, sheetRect);
}
} |
JavaScript | class SolidContinuousSpritesheet extends Spritesheet {
constructor(a) {
super(a);
this.sourceRectSize = a.sourceRectSize;
debugLog(`Created ${this.debugDescription}`);
}
get debugDescription() {
return `<${this.constructor.name} img:${Rect.sizeDebugDescription(this.image)} src:${Rect.sizeDebugDescription(this.sourceRectSize)}>`;
}
draw(c, destRect, spriteIndex, randomSeed) {
let sheetOrigin = new Point(
this.offsetForRandomSeed(randomSeed),
spriteIndex * this.sourceRectSize.height
);
let sheetRect = new Rect(sheetOrigin, this.sourceRectSize);
this.drawSheetRect(c, destRect, sheetRect);
}
offsetForRandomSeed(randomSeed) {
let maxWidth = this.image.width - this.sourceRectSize.width;
if (maxWidth < 0) { return 0; }
return Math.floor(randomSeed * (maxWidth / Identifier.maxRandomSeed)) % maxWidth;
}
} |
JavaScript | class NzTabBodyComponent {
constructor() {
this.active = false;
this.forceRender = false;
}
} |
JavaScript | class NzTabLabelDirective {
/**
* @param {?} elementRef
* @param {?} renderer
*/
constructor(elementRef, renderer) {
this.elementRef = elementRef;
this.disabled = false;
renderer.addClass(elementRef.nativeElement, 'ant-tabs-tab');
}
/**
* @return {?}
*/
getOffsetLeft() {
return this.elementRef.nativeElement.offsetLeft;
}
/**
* @return {?}
*/
getOffsetWidth() {
return this.elementRef.nativeElement.offsetWidth;
}
/**
* @return {?}
*/
getOffsetTop() {
return this.elementRef.nativeElement.offsetTop;
}
/**
* @return {?}
*/
getOffsetHeight() {
return this.elementRef.nativeElement.offsetHeight;
}
} |
JavaScript | class NzTabLinkDirective {
/**
* @param {?=} routerLink
* @param {?=} routerLinkWithHref
*/
constructor(routerLink, routerLinkWithHref) {
this.routerLink = routerLink;
this.routerLinkWithHref = routerLinkWithHref;
}
} |
JavaScript | class NzTabComponent {
/**
* @param {?} elementRef
* @param {?} renderer
*/
constructor(elementRef, renderer) {
this.elementRef = elementRef;
this.renderer = renderer;
this.position = null;
this.origin = null;
this.isActive = false;
this.stateChanges = new Subject();
this.nzForceRender = false;
this.nzDisabled = false;
this.nzClick = new EventEmitter();
this.nzSelect = new EventEmitter();
this.nzDeselect = new EventEmitter();
this.renderer.addClass(elementRef.nativeElement, 'ant-tabs-tabpane');
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes.nzTitle || changes.nzForceRender || changes.nzDisabled) {
this.stateChanges.next();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
this.stateChanges.complete();
}
} |
JavaScript | class NzTabsInkBarDirective {
/**
* @param {?} renderer
* @param {?} elementRef
* @param {?} ngZone
*/
constructor(renderer, elementRef, ngZone) {
this.renderer = renderer;
this.elementRef = elementRef;
this.ngZone = ngZone;
this.nzAnimated = false;
this.nzPositionMode = 'horizontal';
renderer.addClass(elementRef.nativeElement, 'ant-tabs-ink-bar');
}
/**
* @param {?} element
* @return {?}
*/
alignToElement(element) {
if (typeof requestAnimationFrame !== 'undefined') {
this.ngZone.runOutsideAngular((/**
* @return {?}
*/
() => {
requestAnimationFrame((/**
* @return {?}
*/
() => this.setStyles(element)));
}));
}
else {
this.setStyles(element);
}
}
/**
* @param {?} element
* @return {?}
*/
setStyles(element) {
/** when horizontal remove height style and add transform left **/
if (this.nzPositionMode === 'horizontal') {
this.renderer.removeStyle(this.elementRef.nativeElement, 'height');
this.renderer.setStyle(this.elementRef.nativeElement, 'transform', `translate3d(${this.getLeftPosition(element)}, 0px, 0px)`);
this.renderer.setStyle(this.elementRef.nativeElement, 'width', this.getElementWidth(element));
}
else {
/** when vertical remove width style and add transform top **/
this.renderer.removeStyle(this.elementRef.nativeElement, 'width');
this.renderer.setStyle(this.elementRef.nativeElement, 'transform', `translate3d(0px, ${this.getTopPosition(element)}, 0px)`);
this.renderer.setStyle(this.elementRef.nativeElement, 'height', this.getElementHeight(element));
}
}
/**
* @param {?} element
* @return {?}
*/
getLeftPosition(element) {
return element ? element.offsetLeft + 'px' : '0';
}
/**
* @param {?} element
* @return {?}
*/
getElementWidth(element) {
return element ? element.offsetWidth + 'px' : '0';
}
/**
* @param {?} element
* @return {?}
*/
getTopPosition(element) {
return element ? element.offsetTop + 'px' : '0';
}
/**
* @param {?} element
* @return {?}
*/
getElementHeight(element) {
return element ? element.offsetHeight + 'px' : '0';
}
} |
JavaScript | class ScoringFunction {
/**
* Create a ScoringFunction.
* @member {string} fieldName The name of the field used as input to the
* scoring function.
* @member {number} boost A multiplier for the raw score. Must be a positive
* number not equal to 1.0.
* @member {string} [interpolation] A value indicating how boosting will be
* interpolated across document scores; defaults to "Linear". Possible values
* include: 'linear', 'constant', 'quadratic', 'logarithmic'
* @member {string} type Polymorphic Discriminator
*/
constructor() {
}
/**
* Defines the metadata of ScoringFunction
*
* @returns {object} metadata of ScoringFunction
*
*/
mapper() {
return {
required: false,
serializedName: 'ScoringFunction',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'type',
clientName: 'type'
},
uberParent: 'ScoringFunction',
className: 'ScoringFunction',
modelProperties: {
fieldName: {
required: true,
serializedName: 'fieldName',
type: {
name: 'String'
}
},
boost: {
required: true,
serializedName: 'boost',
type: {
name: 'Number'
}
},
interpolation: {
required: false,
serializedName: 'interpolation',
type: {
name: 'Enum',
allowedValues: [ 'linear', 'constant', 'quadratic', 'logarithmic' ]
}
},
type: {
required: true,
serializedName: 'type',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class SidePanelItem extends Lightning.Component {
/**
* Function to render various elements in the side panel item.
*/
static _template() {
return {
Item: {
Title: {
text: {
fontSize: 27,
textColor: 0xffffffff,
},
mountX: 0.5,
alpha: 0,
},
Image: {
x: 0,
},
},
}
}
_init() {
this.tag('Title').patch({ x: this.x_text, y: this.y_text, text: { text: this.data.title } })
this.tag('Image').patch({
src: Utils.asset(this.data.url),
w: this.w,
h: this.h,
scale: this.unfocus,
})
}
/**
* Function to change properties of item during focus.
*/
_focus() {
this.tag('Image').patch({ w: this.w, h: this.h, scale: this.focus })
this.tag('Title').patch({ alpha: 1 })
this.tag('Item').patch({ zIndex: 1 })
}
/**
* Function to change properties of item during unfocus.
*/
_unfocus() {
this.tag('Image').patch({ w: this.w, h: this.h, scale: this.unfocus })
this.tag('Title').patch({ alpha: 0 })
this.tag('Item').patch({ zIndex: 0 })
}
} |
JavaScript | class PmidGdmAddHistory extends Component {
render() {
var history = this.props.history;
var article = history.primary;
var gdm = history.meta.article.gdm;
return (
<div>
<a href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + article.pmid}>PMID:{article.pmid}</a>
<span> added to </span>
<strong>{gdm.gene.symbol}-{gdm.disease.term}-</strong>
<i>{gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}</i>
<span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
}
} |
JavaScript | class PmidGdmDeleteHistory extends Component {
render() {
return <div>PMIDGDMDELETE</div>;
}
} |
JavaScript | class Response{
/**
* Response Contructor
* @param { Number } status_code an http response status code
* @param { String } message a message related to this response
* @param { any } content any type of content you'd like to pass in this response
* @param { Error } error any error you'd like to pass in this response
*/
constructor( status_code, message, content, error = null ){
/** HTTP response status code */
this._stcd = status_code;
/** Message response */
this._msg = message;
/**Content of the response */
this._cnt = content
/** Response error*/
this._err = error;
}
/**
* Get the http response status code
* @returns { Number } The status code number
*/
getStatusCode(){
return this._stcd
}
/**
* Get an object with a message and a content
* @return { Object } A server response
*/
getResponse(){
if( this._err !== null ){
return {
message: this._err.message,
content: this._error
}
}
else if( this._cnt !== null ){
return {
message: this._msg,
content: this._cnt,
}
}
else{
return {
message: "no content",
content: null
}
}
}
} |
JavaScript | class PackageClass extends Generator {
/**
* Declare vars
* @override
* @return {void}
*/
initializing() {
this.props = {};
}
/**
* Prompts the info data of the project.
* @override
* @return {void}
*/
prompting() {
const prompts = require('./prompts.json');
return this.prompt(prompts).then((props) => {
// To access props later use this.props.someAnswer;
this.props = props;
});
}
/**
* Saving configurations and configure the project: package.json, .gitignore
* @override
* @return {void}
*/
configuring() {
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath('package.json'),
this.props
);
this.fs.copy(
this.templatePath('_.gitignore'),
this.destinationPath('.gitignore')
);
}
} |
JavaScript | class CustomTwitchPlayer {
constructor(div_id, width=480, height=320) {
this.options = {
width: width,
height: height,
channel: "{CHANNEL}",
//video: "{VIDEO_ID}"
};
this.current_channel = '';
this.div_id = div_id;
this.player = new Twitch.Player(this.div_id, this.options);
};
pause() {
this.player.pause();
console.log('player paused');
};
setWidth(width) {
this.options.width = width;
$('#' + this.div_id).find('iframe').css('width', width);
};
setHeight(height) {
this.options.height = height;
$('#' + this.div_id).find('iframe').css('height', height);
};
setChannel(channel) {
this.current_channel = channel;
this.player.setChannel(channel);
console.log('watching ' + channel + ' on Twitch!');
};
getDivId() {
return(this.div_id);
};
toString() {
console.log(this.options);
console.log(this.div_id);
console.log(this.player);
};
clear() {
$('#' + this.div_id).empty();
this.player = null;
}
reInitialize() {
if (!this.player)
this.player = new Twitch.Player(this.div_id, this.options);
}
} |
JavaScript | class RouteManager
{
/**
* Constructor
*
* @var {Object} app Instancia de la app
* @constructor
*/
constructor(app)
{
this.router = Router();
this.fileController = new FileController();
this.app = app;
}
/**
* Configura las rutas
*
* @return {void}
*/
config ()
{
this.router.post('/subir-archivo', this.fileController.subirArchivo);
this.router.use(function(req, res) {
res.status(404).json({
error: true,
message: 'Not Found'
});
});
this.app.use('/api', this.router);
}
} |
JavaScript | class InitialResourceStateBuilder extends InitialStateBuilder {
constructor(options, items = []) {
super(options);
this.lists = {};
this.items = {};
if (!isEmpty(items)) {
this.addList(items);
}
}
/**
* Adds a new list to the initial state builder
* @param {Object | Object[]} itemsOrParams Either the params to use to index the list or the list of items that
* make up the list. If no params are specified, the default unscoped list is used.
* @param {Object} [optionalItems=[]] The list of items in the list, if they were not specified as
* the first argument
* @returns {InitialListStateBuilder} A new initial state builder scoped to the new list
*/
addList(itemsOrParams, optionalItems) {
const { items, params = EmptyKey } = extractVariableArguments(['params', 'items'], [itemsOrParams, optionalItems]);
const listStateBuilder = new InitialListStateBuilder(this.options, items);
const key = getListKey(params);
this.lists[key] = listStateBuilder;
return listStateBuilder;
}
/**
* Adds a new item to the initial state builder
* @param {Object} paramsOrValues Either the values of a new item to add to the initial state, outside of any
* list, or the params of the item to use to index it.
* @param {Object} [optionalValues={}] The values of the item, if the first argument was used to specify params
* @returns {InitialItemStateBuilder} A new initial state builder scoped to the new item
*/
addItem(paramsOrValues, optionalValues) {
const { values, params = {} } = extractVariableArguments(['params', 'values'], [paramsOrValues, optionalValues]);
const key = getItemKey([params, values], { keyBy: this.options.keyBy, singular: this.options.singular });
const itemStateBuilder = new InitialItemStateBuilder(this.options, values);
this.items[key] = itemStateBuilder;
return itemStateBuilder;
}
/**
* Generates the initial state the builder has been configured for, in the format suitable to pass to
* the Redux store.
* @returns {ResourcesReduxState} The resources' initial state
*/
build() {
const itemsOutsideOfLists = Object.keys(this.items).reduce((memo, key) => {
const item = this.items[key];
memo[key] = item.build({ status: this.status, metadata: this.metadata });
return memo;
}, {});
const itemsFromLists = Object.values(this.lists).reduce((memo, list) => ({
...memo,
...list.buildItems({ status: this.status, metadata: this.metadata })
}), {});
return {
/**
* Inherit the generic properties of a resource object that should not be available for
* customisation when specifying initial state
*/
...RESOURCES,
/**
* We merge the dictionary of items that are in lists with those that are not
* @type {Object<ResourceItemId, ResourcesItem>}
*/
items: { ...itemsOutsideOfLists, ...itemsFromLists },
/**
* We build the dictionary of lists
*/
lists: Object.keys(this.lists).reduce((memo, key) => {
const list = this.lists[key];
memo[key] = list.build({ status: this.status, metadata: this.metadata });
return memo;
}, {})
};
}
} |
JavaScript | class CharCountCore {
/**
* constructor
* @param {object} Config to initialise the class with
* @return {void}
*/
constructor({
// Core
// -----
element = null,
// Config
// -----
warningThreshold: warning = 25,
dangerThreshold: danger = 10,
expendedThreshold: limit = 100,
// Threshold values
// TODO: Potentially look at percentages as well as fixed figures?
counterClass = 'cc-count',
// DOM interaction classes
emptyClass: classStateIsEmpty = 'cc-is-empty',
fineClass: classStateIsFine = 'cc-is-fine',
warningClass: classStateIsWarning = 'cc-is-warning',
dangerClass: classStateIsDanger = 'cc-is-danger',
expendedClass: classStateIsExpended = 'cc-is-expended',
// DOM state classes
// Callbacks
// -----
onFieldEmpty = (field, remaining) => {},
// Fired when a fields text count is zero; not entirely sure on its continued usefulness
onFieldFine = (field, remaining) => {},
// Fired when a fields text remaining count is a-okay, after coming from another state
onFieldWarning = (field, remaining) => {},
// Fired when the desired warning threshold is reached
onFieldDanger = (field, remaining) => {},
// Fired when the desired danger threshold is reached
onFieldExpended = (field, remaining) => {},
// Fired when the limit is all used up!
} = {}) {
if (element === null)
console.error('Error initialising element!');
this.element = element;
// Element that the class instantiation is in reference to
limit = (this.element.hasAttribute('maxlength')
? parseInt(this.element.getAttribute('maxlength'))
: limit);
// If there is a max length applied to the element, use that instead
this.states = {
empty: new State(0, classStateIsEmpty),
fine: new State(limit, classStateIsFine),
warning: new State(warning, classStateIsWarning),
danger: new State(danger, classStateIsDanger),
expended: new State(0, classStateIsExpended)
};
// Define states
this.activeState = this.states.empty;
this.inputLength = this.element.value.length;
this.remainingCharacters = limit;
// Store current state properties
this.counterClass = counterClass;
this.counter = this.createElementCounter();
// Setup DOM counter
// TODO: Allow for this to be situated at a custom location
this.onFieldEmpty = onFieldEmpty;
this.onFieldFine = onFieldFine;
this.onFieldWarning = onFieldWarning;
this.onFieldDanger = onFieldDanger;
this.onFieldExpended = onFieldExpended;
// Register callbacks
this.bindElement();
// Bind the class to the element
}
/**
* Generate the markup to be placed under the element, allow templating?
* @return {void}
*/
createElementCounter() {
let counterMarkup = `<small class="${this.counterClass} ${this.activeState.colourClass}">${this.remainingCharacters}</small>`;
// Generate counter markup
// TODO: Allow this to be templated?
this.element.insertAdjacentHTML('afterend', counterMarkup);
// Insert the counter after the element in question
return this.element.nextElementSibling;
}
/**
* Update character count for the elements counter
* @return {void}
*/
updateElementCounter() {
this.counter.textContent = this.remainingCharacters;
// Update remaining characters
this.counter.className = `${this.counterClass} ${this.activeState.colourClass}`;
// Set active class
}
/**
* Bind the required events onto the element / determine initial state
* @return {void}
*/
bindElement() {
this.element.addEventListener('input', this.handleInputEvent.bind(this));
// Register the event listener to the DOM elements required
this.updateElementState();
// Calculate initial counts for each element
}
/**
* Initial handler of the event
* @return {void}
*/
handleInputEvent() {
this.updateElementState();
// Update properties, trigger new states and fire events
}
/**
* Updates the internal properties to the latest determined state
* @return {void}
*/
updateElementState() {
this.inputLength = this.element.value.length;
// Update element input length
this.remainingCharacters = (this.states.fine.threshold - this.inputLength);
// Perform count on the element against the limit
this.determineElementState();
// Get the active state determined by the result of the calculation
this.updateElementCounter();
// Update the existing DOM element counter
}
/**
* Determine the element state, with the intention to fire events/manage active state
* @return {void}
*/
determineElementState() {
if (this.inputLength === 0) {
if (!this.states.empty.isActive()) {
this.onFieldEmpty(this.element, this.remainingCharacters);
this.states.empty.isActive(true);
this.activeState = this.states.empty;
}
// Fire callback, set active state
return;
}
// Empty state trigger
if (this.remainingCharacters <= this.states.expended.threshold) {
if (!this.states.expended.isActive()) {
this.onFieldExpended(this.element, this.remainingCharacters);
this.states.expended.isActive(true);
this.activeState = this.states.expended;
}
// Fire callback, set active state
return;
}
// Limit state trigger
if (this.remainingCharacters <= this.states.danger.threshold) {
if (!this.states.danger.isActive()) {
this.onFieldDanger(this.element, this.remainingCharacters);
this.states.danger.isActive(true);
this.activeState = this.states.danger;
}
// Fire callback, set active state
return;
}
// Danger state trigger
if (this.remainingCharacters <= this.states.warning.threshold) {
if (!this.states.warning.isActive()) {
this.onFieldWarning(this.element, this.remainingCharacters);
this.states.warning.isActive(true);
this.activeState = this.states.warning;
}
// Fire callback, set active state
return;
}
// Warning state trigger
if (this.remainingCharacters <= this.states.fine.threshold) {
if (!this.states.fine.isActive()) {
this.onFieldFine(this.element, this.remainingCharacters);
this.states.fine.isActive(true);
this.activeState = this.states.fine;
}
// Fire callback, set active state
return;
}
// Fine state trigger
}
} |
JavaScript | class TaxInfo extends Resource {
static getSchema () {
return {
rate: Number,
region: String,
taxDetails: ['TaxDetail'],
type: String
}
}
} |
JavaScript | class RecordingsAPI {
/**
* Create an instance of the Recordings API client, providing access
* to the `/recordings` endpoint.
*
* @param {object} params
* @param {string} params.username The username to send with the request.
* @param {string} params.password The password to send with the request.
* @param {string} params.baseUrl The base url, without trailing slash,
* of the root Asterisk ARI endpoint. i.e. 'http://myserver.local:8088/ari'.
*/
constructor(params) {
const { username, password } = params;
/** @private */
this._baseUrl = params.baseUrl;
/** @private */
this._request = axios.create({
auth: { username, password },
});
}
/**
* GET /recordings/stored
*
* List all completed recordings.
*
* @returns {Promise.<Array.<StoredRecording>>}
*/
listStored() {
return this._request({
method: "GET",
url: `${this._baseUrl}/recordings/stored`,
});
}
/**
* GET /recordings/stored/{recordingName}
*
* Retrieve the details of a specific stored recording.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* recording to retrieve details about.
* @returns {Promise.<StoredRecording>} Resolves if the recording is sucessfully
* retrieved. Rejects if the specified recording cannot be found (status 404).
*/
getStored(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "GET",
url: `${this._baseUrl}/recordings/stored/${name}`,
});
}
/**
* DELETE /recordings/stored/{recordingName}
*
* Destroy the specified stored recording.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* recording to destroy.
* @returns {Promise} Resolves when the specified recording is destroyed.
* Rejects if the specified recording cannot be found (status 404).
*/
destroyStored(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "DELETE",
url: `${this._baseUrl}/recordings/stored/${name}`,
});
}
/**
* GET /recordings/stored/{recordingName}/file
*
* Retrieve the file associated with the stored recording.
*
* *API available since Asterisk 14.0*
*
* @param {object} params
* @param {string} params.recordingName
* @returns {Promise.<Buffer>} Resolves with the content of the stored
* recording. Rejects when the recording file could not be opened
* (status 403) or when the recording cannot be found (status 404).
*/
getStoredFile(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "GET",
url: `${this._baseUrl}/recordings/stored/${name}/file`,
});
}
/**
* POST /recordings/stored/{recordingName}/copy
*
* Create a copy of the specified stored recording.
*
* *API available since Asterisk 12.5*
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* recording to create a copy of.
* @param {string} params.destinationRecordingName The name for the new copy
* of the recording.
* @returns {Promise.<StoredRecording>} Resolves with the newly copied
* recording when successful. Rejects if the specified recording cannot
* be found (status 404) or if a recording of the same name already exists
* on the system (status 409).
*/
copyStored(params) {
const { recordingName, destinationRecordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "POST",
url: `${this._baseUrl}/recordings/stored/${name}/copy`,
params: { destinationRecordingName },
});
}
/**
* GET /recordings/live/{recordingName}
*
* Retrieve the details of the specified live recording.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to retrieve details about.
* @returns {Promise.<LiveRecording>} Resolves with the specified live
* recording details. Rejects if the live recording cannot be found
* (status 404).
*/
getLive(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "GET",
url: `${this._baseUrl}/recordings/live/${name}`,
});
}
/**
* DELETE /recordings/live/{recordingName}
*
* Stop the specified live recording and discard it.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully cancelled.
* Rejects if the recording cannot be found (status 404).
*/
cancel(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "DELETE",
url: `${this._baseUrl}/recordings/live/${name}`,
});
}
/**
* POST /recordings/live/{recordingName}/stop
*
* Stop the specified live recording and store it.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully stopped.
* Rejects if the recording cannot be found (status 404).
*/
stop(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "POST",
url: `${this._baseUrl}/recordings/live/${name}/stop`,
});
}
/**
* POST /recordings/live/{recordingName}/pause
*
* Pause the specified live recording. Pausing a recording suspends silence
* detection, which will be restarted when the recording is unpaused. Paused
* time is not included in the accounting for maxDurationSeconds.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully paused.
* Rejects if the recording cannot be found (status 404) or if the specified
* recording is not in session. TODO: what does "not in session" mean?
*/
pause(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "POST",
url: `${this._baseUrl}/recordings/live/${name}/pause`,
});
}
/**
* DELETE /recordings/live/{recordingName}/pause
*
* Unpause the specified live recording.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully unpaused.
* Rejects if the recording cannot be found (status 404) or if the specified
* recording is not in session. TODO: what does "not in session" mean?
*/
unpause(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "DELETE",
url: `${this._baseUrl}/recordings/live/${name}/pause`,
});
}
/**
* POST /recordings/live/{recordingName}/mute
*
* Mute the specified live recording. Muting a recording suspends silence
* detection, which will be restarted when the recording is unmuted.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully muted.
* Rejects if the recording cannot be found (status 404) or if the specified
* recording is not in session. TODO: what does "not in session" mean?
*/
mute(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "POST",
url: `${this._baseUrl}/recordings/live/${name}/mute`,
});
}
/**
* DELETE /recordings/live/{recordingName}/mute
*
* Unmute the specified live recording.
*
* @param {object} params
* @param {string} params.recordingName The case-sensitive name of the
* live recording to act upon.
* @returns {Promise} Resolves if the recording is successfully unmuted.
* Rejects if the recording cannot be found (status 404) or if the specified
* recording is not in session. TODO: what does "not in session" mean?
*/
unmute(params) {
const { recordingName } = params;
const name = encodeURIComponent(recordingName);
return this._request({
method: "DELETE",
url: `${this._baseUrl}/recordings/live/${name}/mute`,
});
}
} |
JavaScript | class BinarySearchTree {
constructor() {
this.root = null;
}
insert = (data, left, right) => {
let current;
const node = new Node(data, left, right);
this.root = this.root || node;
if (this.root === node) return;
current = this.root;
while (current) {
let { data } = node;
// priority: equal is put to the left.
if (current.data < data) {
// to the right
if (!current.right) {
current.right = node;
break;
}
current = current.right;
} else {
// to the left
if (!current.left) {
current.left = node;
break;
}
current = current.left;
}
}
};
/**
* preOrder: First access the parent node and then access the left node and finally access the right node
* @param {node} node
* @param {Function} fn
*/
preOrder = (node, fn) => {
if (node) {
fn && fn(node);
this.preOrder(node.left, fn);
this.preOrder(node.right, fn);
}
};
/**
* inOrder: First access the left node and then access then parent node and finally access the right node.
* @param {Node} node
* @param {Function} fn
*/
inOrder = (node, fn) => {
if (node) {
this.inOrder(node.left, fn);
fn && fn(node);
this.inOrder(node.right, fn);
}
};
/**
* postOrder: For priority access from the left node to the right node and finally access the parent node.
* @param {Node} node
* @param {Function} fn
*/
postOrder = (node, fn) => {
if (node) {
this.postOrder(node.left, fn);
this.postOrder(node.right, fn);
fn & fn(node);
}
};
getMin = node => {
let min = node || this.root;
while (min && min.left) {
min = min.left;
}
return min;
};
getMax = node => {
let max = node || this.root;
while (max && max.right) {
max = max.right;
}
return max;
};
/**
* @param { any } data
* @param { Node } node
*/
find = (data, node) => {
let current = node || this.root;
while (current) {
if (current.data === data) {
return current;
} else if (current.data > data) {
current = current.left;
} else {
current = current.right;
}
}
return null;
};
/**
* @param {any} data
* @param {Node} node
*/
contains = (data, node) => {
return !!this.find(data, node);
};
_extractData = (node, predicate) => {
return predicate ? node.data : node;
};
/**
* @param {objec} option {min: bool, max: bool, extractData: bool, node: Node}
*/
get = option => {
const { min, max, extractData = true, node = this.root } = option;
if (min && max) {
return [
this._extractData(this.getMin(node), extractData),
this._extractData(this.getMax(node), extractData),
];
} else if (min || max) {
return min
? this._extractData(this.getMin(node), extractData)
: this._extractData(this.getMax(node), extractData);
}
return this._extractData(node, extractData);
};
/**
* @param {any}
*/
remove = data => {
const removeNode = (node, data) => {
if (!node) {
return node;
}
if (data === node.data) {
if (!node.left && !node.right) {
return null;
} else if (!node.left) {
return node.right;
} else if (!node.right) {
return node.left;
} else {
// get the minimum node in right tree
const temp = this.getMin(node.right);
node.data = temp.data;
node.right = removeNode(node.right, temp.data);
return node;
}
} else if (data < node.data) {
node.left = removeNode(node.left, data);
return node;
} else {
node.right = removeNode(node.right, data);
return node;
}
};
this.root = removeNode(this.root, data);
return this;
};
// util
print() {
if (!this.root) {
return console.log('No root node found');
}
const newline = new Node('|');
const queue = [this.root, newline];
let string = '';
while (queue.length) {
const node = queue.shift();
string += `${node.data ? node.data.toString() : '-'} `;
if (node === newline && queue.length) {
queue.push(newline);
}
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
return string.slice(0, -2).trim();
}
} |
JavaScript | class Webpack {
constructor(name) {
this.name = name;
}
sayHello() {
return `Hello ${this.name}!`;
}
} |
JavaScript | class Output {
/**
* @param @optional {string} body
*/
constructor(body = "") {
this.body = body;
this.temp = null;
}
} |
JavaScript | class CommandArgumentType extends Argument {
constructor(client) {
super(client, 'command');
}
// Currently command has no options so this is the same as baseValidate
validate(val) {
return this.baseValidate(val);
}
// Check if a command is in the registry
baseValidate(val) {
return this.commandHandler.commands.has(val);
}
// Just get the value from the registry
parse(val) {
return this.commandHandler.commands.get(val);
}
// Any string could be at the start of a command
// We could add more validation here if this causes problems
isPossibleStart() {
return true;
}
} |
JavaScript | class LocalesParser {
prepareBlankLocales(fileContents, type) {
let currentLocales = this.parseLocales(fileContents, type);
let placeholders = this.generateLocalePlaceholders(currentLocales);
return this.assembleLocales(fileContents, placeholders, type)
}
parseLocales(fileContents = '', type) {
let locales = 'js' === type ? fileContents.substring(fileContents.indexOf('{'), fileContents.lastIndexOf('}') + 1) : fileContents;
return this.parse(locales, type);
}
generateLocalePlaceholders(locales = {}) {
return Object.keys(locales).reduce((placeholders, locale) => {
placeholders[locale] = '';
return placeholders;
}, {})
}
assembleLocales(fileContents, locales, type) {
let currentLocales = 'js' === type ? fileContents.substring(fileContents.indexOf('{'), fileContents.lastIndexOf('}') + 1) : fileContents;
return fileContents.replace(currentLocales, this.stringify(locales, type));
}
parse(locales, type) {
if ('yaml' === type) {
return YAML.parse(locales) || "";
}
return JSON.parse(locales);
}
stringify(locales, type) {
if ('yaml' === type) {
return YAML.stringify(locales, {
indent: 4,
})
}
return JSON.stringify(locales, null, 4);
}
} |
JavaScript | class GridSheetLogger
{
//instantiating the logger with the class name where this will be used.
constructor(name)
{
this.name=name;
this._enableLogging=true;
}
//this appends the component name to the log message - this is for better log representation on the console.
appendComponentName(...args)
{
if(args && typeof args[0] ==='string')
{
args[0]=this.name+" : "+args[0];
}
return args;
}
// to perform info level logging
info(...args)
{
// adding the component name where this functiona is being called
let argsT=this.appendComponentName(...args);
//checking if the browser supports the info logging and also checking if logging is enabled.
if(console.info && _enableLogging)
{
console.info(...argsT);
}
}
// to perform debug level logging.
debug(...args)
{
// adding the component name where this functiona is being called
let argsT=this.appendComponentName(...args);
//checking if the browser supports the info logging and also checking if logging is enabled.
if(console.debug && _enableLogging)
{
console.debug(...argsT);
}
else if(_enableLogging)
{
this.info(...argsT);
}
}
error(...args)
{
// adding the component name where this functiona is being called
let argsT=this.appendComponentName(...args);
if(console.error && _enableLogging)
{
console.error(...argsT);
}
else if(_enableLogging)
{
this.info(...argsT);
}
}
warn(...args)
{
let argsT=this.appendComponentName(...args);
if(console.warn && _enableLogging)
{
console.warn(...argsT);
}
else if(_enableLogging)
{
this.info(...argsT);
}
}
} |
JavaScript | class LineChart {
constructor(elementName, windowed) {
// Scales and axes
this.x = d3.scaleLinear().range([0, width]);
this.y = d3.scaleLinear().range([height, 0]);
this.xAxis = d3.axisBottom().scale(this.x);
this.yAxis = d3.axisLeft().scale(this.y);
// Initialize SVG elements
this.svg = d3.select(elementName)
.append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 480 320")
.classed("svg-content", true)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Initialise x axis
this.x.domain([0, 1]);
this.svg.append("g")
.attr("transform", "translate(0," + height + ")")
.attr("class", "lineChartXAxis")
.call(this.xAxis);
// x axis label
this.svg.append("text")
.attr("transform",
"translate(" + (width / 2) + " ," +
(height + margin.top + 20) + ")")
.style("text-anchor", "middle")
.text("# flips");
// Initialize y axis
this.y.domain([0, 1]);
this.svg.append("g")
.attr("class", "lineChartYAxis")
.call(this.yAxis);
// y axis label
this.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Rel. freq.");
// Initialize line
this.svg.append("path")
.attr("id", "line_chart_path")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5);
// Cast our functions so we can use them here
var mX = this.x;
var mY = this.y;
// For our full line chart, add a dashed line which shows how the other chart is filtered
if (!windowed) {
// Initial values
this.oldYWindowMin = 0;
this.oldYWindowMax = 1;
this.windowStrokeWidth = 2;
// Initial dashed line for animation
this.svg.append("line")
.attr("id", "top_line")
.attr("class", "line")
.style("stroke-dasharray", ("3, 3"))
.attr("stroke", "grey")
.attr("stroke-width", 2)
.attr("x1", mX(0))
.attr("y1", mY(1))
.attr("x2", mX(1))
.attr("y2", mY(1));
this.svg.append("line")
.attr("id", "bottom_line")
.attr("class", "line")
.style("stroke-dasharray", ("3, 3"))
.attr("stroke", "grey")
.attr("stroke-width", 2)
.attr("x1", mX(0))
.attr("y1", mY(0))
.attr("x2", mX(1))
.attr("y2", mY(0));
}
};
} |
JavaScript | class TestClassOne extends Core.mix( "Core.abstract.Component", "Test.fixture.type.mixin.validating.TestMixinOne" ) {
passingValidate1() {
return this.$validate( "a", {
"isString": true
} );
}
failingValidate1() {
return this.$validate( 1, {
"isString": true
} );
}
paramTest1( someParam ) {
return this.$validateParam( "someParam", someParam, [ "isBoolean", "isString" ] );
}
objTestBasic( obj ) {
return this.$validateObject( "obj", obj, {
a : "isString",
b : "isBoolean"
} );
}
objTestGlobalMergeA( obj ) {
return this.$validateObject( "obj", obj, {
a: "isNumber"
}, "isInteger" );
}
objTestGlobalMergeB( obj ) {
return this.$validateObject( "obj", obj, {
a: "isInteger"
}, "isNumber" );
}
objDynamicTest( obj, propertyOptions, globalOptions ) {
return this.$validateObject( "obj", obj, propertyOptions, globalOptions );
}
} |
JavaScript | class Fire extends Container {
constructor() {
super();
this.fire = new Sprite.from('fire');
this.fire.name = 'fire';
this.glow = new Sprite.from('fire-glow');
this.fire.anchor.set(0.5);
this.glow.anchor.set(0.5, 0.3);
gsap.to(this.glow.scale, {
x: 1.2,
y: 1.2,
yoyo: true,
ease: 'power1.inOut',
duration: 2,
repeat: -1,
});
this.addChild(this.fire);
this.addChild(this.glow);
this._addDisplacementFilter();
}
/**
* Adds a displacement filter to the fire.
* @private
*/
_addDisplacementFilter() {
const displacementSprite = new Sprite.from('displacement-map');
displacementSprite.anchor.set(0.5, 0);
displacementSprite.texture.baseTexture.wrapMode = WRAP_MODES.REPEAT;
displacementSprite.scale.set(10);
const displacementFilter = new filters.DisplacementFilter(displacementSprite);
displacementFilter.padding = 10;
displacementFilter.scale.set(50, 20);
displacementFilter.position = this.fire.position;
this.addChild(displacementSprite);
this.fire.filters = [displacementFilter];
gsap.to(displacementSprite, {
y: -displacementSprite.width,
repeat: -1,
ease: 'linear',
duration: 10,
});
}
} |
JavaScript | class Timer {
#hours;
#minutes;
#seconds;
#totalSeconds;
#countdownID;
constructor(hour = 0, minutes = 0, seconds = 0) {
this.#hours = hour;
this.#minutes = minutes;
this.#seconds = seconds;
this.#totalSeconds = (this.#hours * 60 + this.#minutes) * 60 + this.#totalSeconds;
}
getTotalSeconds() {
return this.#totalSeconds;
}
getHours() {
return this.#hours;
}
getMinutes() {
return this.#minutes;
}
getSeconds() {
return this.#seconds;
}
setTimer(hour, minutes, seconds) {
this.#hours = hour;
this.#minutes = minutes;
this.#seconds = seconds;
this.#totalSeconds = (this.#hours * 60 + this.#minutes) * 60 + this.#seconds;
this.update();
}
update() {
output.updateTimer(this.#hours, this.#minutes, this.#seconds);
}
decrement() {
if (this.getSeconds() > 0) {
this.#seconds -= 1;
} else if (this.getMinutes() > 0) {
this.#minutes -= 1;
this.#seconds = 59;
} else if (this.getHours() > 0) {
this.#hours -= 1;
this.#minutes = 59;
this.#seconds = 59;
}
this.update();
if (this.getHours() === 0 && this.getMinutes() === 0 && this.getSeconds() === 0) {
output.stopTimerCallbackFunction();
setTimeout(function () {
output.sendAlert("Time's up!")
}, 10);
}
}
startTimer() {
this.#countdownID = setInterval(this.decrement.bind(this), 1000);
}
stopTimer() {
clearInterval(this.#countdownID);
}
} |
JavaScript | class Task {
#task;
#title;
#inputTitle;
#hourLabel;
#minuteLabel;
#secondLabel;
#inputHour;
#inputMinute;
#inputSecond;
#buttonGroup;
#minMaxButton;
#minimizeIcon;
#maximizeIcon;
#deleteButton;
#deleteIcon;
#statusIndicator;
#finishedIcon;
#unfinishedIcon;
#hourLabelLineBreaker
#minuteLabelLineBreaker
#expanded;
#selected;
#minimizeCallbackFunction;
#maximizeCallbackFunction;
#taskDoneCallbackFunction;
#taskUndoneCallbackFunction;
constructor() {
this.#task = document.createElement("div");
this.#title = document.createElement("h1");
let newLine = document.createElement("br");
this.#hourLabelLineBreaker = newLine.cloneNode(true);
this.#minuteLabelLineBreaker = newLine.cloneNode(true);
this.#inputTitle = document.createElement("input");
this.#hourLabel = document.createElement("h4")
this.#inputHour = document.createElement("input");
this.#minuteLabel = document.createElement("h4")
this.#inputMinute = document.createElement("input");
this.#secondLabel = document.createElement("h4")
this.#inputSecond = document.createElement("input");
this.#buttonGroup = document.createElement("div");
this.#minMaxButton = document.createElement("button");
this.#minimizeIcon = document.createElement("img");
this.#minimizeIcon.src = "resources/shrink.png";
this.#maximizeIcon = document.createElement("img");
this.#maximizeIcon.src = "resources/expand.png";
this.#minMaxButton.append(this.#minimizeIcon);
this.#statusIndicator = document.createElement("div");
this.#finishedIcon = document.createElement("img");
this.#unfinishedIcon = document.createElement("img");
this.#finishedIcon.src = "resources/finished.png";
this.#unfinishedIcon.src = "resources/unfinished.png";
this.#statusIndicator.appendChild(this.#unfinishedIcon);
this.#deleteButton = document.createElement("button");
this.#deleteIcon = document.createElement("img");
this.#deleteIcon.src = "resources/delete.png";
this.#deleteButton.append(this.#deleteIcon);
this.#buttonGroup.append(this.#minMaxButton, this.#deleteButton);
this.#buttonGroup.classList.add("clearfix", "ButtonGroup");
this.#task.className = "Task";
this.#title.className = "Title";
this.#inputTitle.className = "TitleInput";
this.#hourLabel.className = "TimeLabel";
this.#minuteLabel.className = "TimeLabel";
this.#secondLabel.className = "TimeLabel";
this.#statusIndicator.classList.add("clearfix", "TickStatus");
this.#inputTitle.placeholder = "What are you up to ? ";
this.#inputTitle.type = "text";
this.#inputHour.type = "number";
this.#inputMinute.type = "number";
this.#inputSecond.type = "number";
this.#inputHour.value = "0";
this.#inputMinute.value = "0";
this.#inputSecond.value = "0";
this.#inputHour.min = 0;
this.#inputMinute.min = 0;
this.#inputSecond.min = 0;
this.#hourLabel.innerHTML = "Hours : ";
this.#minuteLabel.innerHTML = "Minutes : ";
this.#secondLabel.innerHTML = "Seconds : ";
this.#expanded = true;
// Callback functions initialization
this.#minimizeCallbackFunction = function (ev) {
ev.stopPropagation();
this.minimize();
}.bind(this);
this.#maximizeCallbackFunction = function (ev) {
ev.stopPropagation();
this.maximize();
}.bind(this);
this.#taskDoneCallbackFunction = function (ev) {
ev.stopPropagation();
this.done();
}.bind(this);
this.#taskUndoneCallbackFunction = function (ev) {
ev.stopPropagation();
this.undone();
}.bind(this);
this.#statusIndicator.addEventListener("click", this.#taskDoneCallbackFunction);
this.#statusIndicator.style.display = "none";
this.#task.append(this.#statusIndicator, this.#title, this.#inputTitle, this.#buttonGroup, newLine,
this.#hourLabel, this.#inputHour, this.#hourLabelLineBreaker,
this.#minuteLabel, this.#inputMinute, this.#minuteLabelLineBreaker, this.#secondLabel, this.#inputSecond);
this.#deleteButton.addEventListener("click", function (ev) {
ev.stopPropagation();
this.delete();
}.bind(this));
this.#minMaxButton.addEventListener("click", this.#minimizeCallbackFunction);
}
minimize() {
this.setExpanded(false);
if (this.#inputTitle.value === "") {
this.delete();
} else {
this.#title.innerHTML = this.#inputTitle.value;
this.#inputTitle.style.visibility = "hidden";
this.#inputTitle.style.width = "0%";
this.#hourLabel.innerHTML = this.#inputHour.value + " Hours ";
this.#minuteLabel.innerHTML = this.#inputMinute.value + " Minutes";
this.#secondLabel.innerHTML = this.#inputSecond.value + " Seconds";
this.#hourLabel.classList.add("TimeLabelMinimized");
this.#minuteLabel.classList.add("TimeLabelMinimized");
this.#secondLabel.classList.add("TimeLabelMinimized");
this.#inputHour.style.display = "none";
this.#inputMinute.style.display = "none";
this.#inputSecond.style.display = "none";
this.#hourLabelLineBreaker.className = "HideLineBreak";
this.#minuteLabelLineBreaker.className = "HideLineBreak";
this.#minMaxButton.replaceChild(this.#maximizeIcon, this.#minimizeIcon);
this.#minMaxButton.removeEventListener("click", this.#minimizeCallbackFunction);
this.#minMaxButton.addEventListener("click", this.#maximizeCallbackFunction);
this.#statusIndicator.style.display = "inline-block";
this.#task.addEventListener("click", this.select.bind(this));
this.saveToStorage();
}
}
maximize() {
this.setExpanded(true);
this.#title.innerHTML = "";
this.#inputTitle.style.visibility = "";
this.#inputTitle.style.width = "70%";
this.#hourLabel.innerHTML = "Hour : ";
this.#minuteLabel.innerHTML = "Minute: ";
this.#secondLabel.innerHTML = "Second: ";
this.#inputHour.style.display = "";
this.#hourLabel.classList.remove("TimeLabelMinimized");
this.#minuteLabel.classList.remove("TimeLabelMinimized");
this.#secondLabel.classList.remove("TimeLabelMinimized");
this.#inputMinute.style.display = "";
this.#inputSecond.style.display = "";
this.#hourLabelLineBreaker.className = "";
this.#minuteLabelLineBreaker.className = "";
this.#minMaxButton.replaceChild(this.#minimizeIcon, this.#maximizeIcon);
this.#minMaxButton.removeEventListener("click", this.#maximizeCallbackFunction);
this.#minMaxButton.addEventListener("click", this.#minimizeCallbackFunction);
this.#statusIndicator.style.display = "none";
}
delete() {
this.#task.remove();
this.removeFromStorage();
}
select() {
// Deselect other tasks
for (let i = 0; i < output.getTasksList().length; i++) {
if (output.getTasksList()[i].isSelected()) {
output.getTasksList()[i].deselect();
break;
}
}
this.#selected = true;
this.#task.classList.add("TaskSelected");
let hour = parseInt(this.#inputHour.value);
let minute = parseInt(this.#inputMinute.value);
let second = parseInt(this.#inputSecond.value);
output.setWorkingTitle(this.#title.innerHTML);
timer.setTimer(hour, minute, second);
}
deselect() {
this.#selected = false;
this.#task.classList.remove("TaskSelected");
}
done() {
this.#title.classList.add("TextStrikethrough");
this.#hourLabel.classList.add("TextStrikethrough");
this.#minuteLabel.classList.add("TextStrikethrough");
this.#secondLabel.classList.add("TextStrikethrough");
this.#statusIndicator.replaceChild(this.#finishedIcon, this.#unfinishedIcon);
this.#statusIndicator.removeEventListener("click", this.#taskDoneCallbackFunction);
this.#statusIndicator.addEventListener("click", this.#taskUndoneCallbackFunction);
this.saveToStorage();
}
undone() {
this.#title.classList.remove("TextStrikethrough");
this.#hourLabel.classList.remove("TextStrikethrough");
this.#minuteLabel.classList.remove("TextStrikethrough");
this.#secondLabel.classList.remove("TextStrikethrough");
this.#statusIndicator.replaceChild(this.#unfinishedIcon, this.#finishedIcon);
this.#statusIndicator.removeEventListener("click", this.#taskUndoneCallbackFunction);
this.#statusIndicator.addEventListener("click", this.#taskDoneCallbackFunction);
this.saveToStorage();
}
saveToStorage() {
let storage = window.localStorage;
let finished = 0;
if (this.#title.classList.contains("TextStrikethrough"))
finished = 1;
storage.setItem(this.#title.innerHTML, this.#inputHour.value + " " + this.#inputMinute.value + " " + this.#inputSecond.value + " " + finished);
}
removeFromStorage() {
window.localStorage.removeItem(this.#title.innerHTML);
}
// Used to reload the tasks based on data stored in session storage
updateSelf(title, hour, minutes, seconds, tick) {
this.#inputTitle.value = title;
this.#inputHour.value = hour;
this.#inputMinute.value = minutes;
this.#inputSecond.value = seconds;
if (tick === 1) {
this.done();
}
this.minimize();
}
getDiv() {
return this.#task;
}
setExpanded(value) {
this.#expanded = value;
}
isExpanded() {
return this.#expanded;
}
isSelected() {
return this.#selected;
}
} |
JavaScript | class Create extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(data) {
createBlogPost(data, this.props.pageState.auth.id)
.then((res) => {
// console.log(res);
this.props.router.push("/posts");
});
}
render() {
console.log('userID:', this.props.pageState.auth.id);
return (
<div>
<Form onSubmit={this.handleSubmit}/>
</div>
);
}
} |
JavaScript | class index extends Component {
// componentDidMount() {
// // whenever dom is ready
// scrollSnapPolyfill();
// }
componentDidMount() {
NProgress.start();
window.addEventListener('load', function() {
NProgress.done();
});
}
goLink() {
window.open('https://github.com/sangjdev', '_blank');
}
render() {
return (
<div className="container pd0">
<div className="page slateblue">
<div className="page__self">
자기소개
<br />
<span>준비 중입니다...</span>
</div>
</div>
<div className="page slategray">
<span onClick={() => this.goLink('')}>
GITHUB
</span>
</div>
</div>
);
}
} |
JavaScript | class HTTPRequest extends AbstractRequest{
/**
* Constructor which takes the nodejs http IncomingMessage and wraps
* it in a custom AbstractRequest object.
*
* @param {IncomingMessage} request
*/
constructor(request) {
super(request);
}
/**
* Returns the origin details for the incoming request, to the best
* of its ability to figure out.
*
* @return {string}
*/
get origin() {
return this.original.socket && this.original.socket.remoteAddress && this.original.socket.remotePort && this.original.socket.remoteAddress+":"+this.original.socket.remotePort || this.headers.referer || this.headers.referrer || this.headers.origin || "";
}
/**
* Returns the method for this request.
*
* @return {string}
*/
get method() {
return this.original.method;
}
/**
* Returns the URL object for this request.
*
* @return {URL}
*/
get url() {
return URL.parse(this.original.url,true);
}
/**
* Returns the path portion of the URL for this request.
* @return {string}
*/
get path() {
return this.url.pathname;
}
/**
* Returns the parsed query object from the URL for this request.
*
* @return {Object}
*/
get query() {
return this.url.query;
}
/**
* Returns the string form of the query/search section of the
* URL for this request.
*
* @return {string}
*/
get querystring() {
return this.url.search.replace(/^\?/,"");
}
/**
* Returns the headers as an object for this request.
*
* @return {Object}
*/
get headers() {
return this.original.headers;
}
/**
* Returns the mime-type portion of the content-type header for this
* request.
*
* @return {string}
*/
get contentType() {
return AwesomeUtils.Request.parseContentType(this.headers && this.headers["content-type"] || "");
}
/**
* Returns the charset (encoding) portion of the content-type header
* for this request. If no encoding is provided, returns "utf-8".
*
* @return {string}
*/
get contentEncoding() {
return AwesomeUtils.Request.parseContentEncoding(this.headers && this.headers["content-type"] || "");
}
/**
* Returns the user-agent header for this request object, if any.
*
* @return {string}
*/
get useragent() {
return this.headers["user-agent"] || "";
}
/**
* Returns a Promise that will resolve when the content body of this
* request, if any, is completely read. The resolve returns a Buffer
* object. AbstractRequest provides helper functions `readText()` and
* `readJSON()` to perform read but return more usable values.
*
* @return {Promise<Buffer>}
*/
read() {
if (this[$CONTENT]) return Promise.resolve(this[$CONTENT]);
return new Promise((resolve,reject)=>{
try {
let buf = Buffer.alloc(0);
this.original.on("data",(chunk)=>{
if (!chunk) return;
buf = Buffer.concat([buf,chunk]);
});
this.original.on("end",()=>{
this[$CONTENT] = buf;
resolve(buf);
});
this.original.resume();
}
catch (ex) {
return reject(ex);
}
});
}
} |
JavaScript | class IWebhookManager {
constructor(discordie) {
this._discordie = discordie;
Utils.privatify(this);
Object.freeze(this);
}
/**
* **Requires logging in with an API token.**
*
* Makes a request to get webhook objects for the specified guild.
* @param {IGuild|String} guild
* @return {Promise<Array<Object>, Error>}
*/
fetchForGuild(guild) {
guild = guild.valueOf();
return rest(this._discordie).webhooks.getGuildWebhooks(guild);
}
/**
* **Requires logging in with an API token.**
*
* Makes a request to get webhook objects for the specified channel.
* @param {IChannel|String} channel
* @return {Promise<Array<Object>, Error>}
*/
fetchForChannel(channel) {
channel = channel.valueOf();
return rest(this._discordie).webhooks.getChannelWebhooks(channel);
}
/**
* **Requires logging in with an API token.**
*
* Makes a request to create a webhook for the channel.
*
* Promise resolves with a webhook object.
* @param {IChannel} channel
* @param {Object} options
* Object with properties `{name: String, avatar: Buffer|String|null}`.
*
* String avatars must be base64 data-url encoded.
* @return {Promise<Object, Error>}
*/
create(channel, options) {
channel = channel.valueOf();
options = options || {};
if (options.avatar instanceof Buffer) {
options.avatar = Utils.imageToDataURL(options.avatar);
}
return rest(this._discordie).webhooks.createWebhook(channel, options);
}
/**
* Makes a request to fetch a webhook object.
*
* Promise resolves with a webhook object (does not contain a `user` object
* if fetched with `token` param).
* @param {Object|String} webhook - Webhook object or id.
* @param {String} token
* Webhook token, not required if currently logged in
* with an account that has access to the webhook.
* @return {Promise<Object, Error>}
*/
fetch(webhook, token) {
const webhookId = webhookToId(webhook);
return rest(this._discordie).webhooks.getWebhook(webhookId, token);
}
/**
* Makes a request to edit the specified webhook.
*
* Promise resolves with a webhook object (does not contain a `user` object
* if edited with `token` param).
* @param {Object|String} webhook - Webhook object or id.
* @param {String} token
* Webhook token, not required and can be set to null if currently logged in
* with an account that has access to the webhook.
* @param {Object} options
* Object with properties `{name: String, avatar: Buffer|String|null}`.
*
* String avatars must be base64 data-url encoded.
* @return {Promise<Object, Error>}
*/
edit(webhook, token, options) {
const webhookId = webhookToId(webhook);
options = options || {};
if (options.avatar instanceof Buffer) {
options.avatar = Utils.imageToDataURL(options.avatar);
}
return rest(this._discordie)
.webhooks.patchWebhook(webhookId, token, options);
}
/**
* Makes a request to delete the specified webhook.
* @param {Object|String} webhook - Webhook object or id.
* @param {String} token
* Webhook token, not required and can be set to null if currently logged in
* with an account that has access to the webhook.
* @return {Promise}
*/
delete(webhook, token) {
const webhookId = webhookToId(webhook);
return rest(this._discordie)
.webhooks.deleteWebhook(webhookId, token);
}
/**
* Makes a request to execute the specified webhook.
*
* > **Note:** Embeds in file uploads are not supported.
* @param {Object|String} webhook - Webhook object or id.
* @param {String} token - Required unless webhook object contains token.
* @param {Object} options
* Refer to [official API documentation](https://discordapp.com/developers/docs/)
* for more information.
* @param {boolean} [wait]
* Wait for server confirmation of message delivery,
* returned promise will contain a raw message object or an error if message
* creation failed.
* @return {Promise}
* @example
* const webhookId = "232330225768333313";
* const token = "EtuNYHGkElBlE7BE266Jk...NzHvccXaUCQUOY64NbFWz9zbQ";
* client.Webhooks.execute(webhookId, token, {content: "text message"});
* client.Webhooks.execute(webhookId, token, {
* // text message
* content: "text message",
* username: "Different Username",
* avatar_url: "https://localhost/test.png",
* tts: false,
* embeds: [{
* color: 0x3498db,
* author: {name: "who dis"},
* title: "This is an embed",
* description: "Nobody will read this anyway",
* url: "http://google.com",
* timestamp: "2016-10-03T03:32:31.205Z",
* fields: [{name: "some field", value: "some value"}],
* footer: {text: "footer text"}
* }]
* });
*
* client.Webhooks.execute(webhookId, token, {
* // file upload
* content: "text message",
* username: "Different Username",
* file: fs.readFileSync("test.png"),
* filename: "test.png"
* });
*/
execute(webhook, token, options, wait) {
const webhookId = webhookToId(webhook);
token = token || webhook.token;
return rest(this._discordie)
.webhooks.executeWebhook(webhookId, token, options, wait);
}
/**
* Makes a request to execute the specified webhook with slack-compatible
* options.
* @param {Object|String} webhook - Webhook object or id.
* @param {String} token - Required unless webhook object contains token.
* @param {Object} options
* Refer to [Slack's documentation](https://api.slack.com/incoming-webhooks)
* for more information.
*
* Discord does not support Slack's `channel`, `icon_emoji`, `mrkdwn`,
* or `mrkdwn_in` properties.
* @param {boolean} [wait]
* Wait for server confirmation of message delivery, defaults to true.
* When set to false, a message that is not saved does not return an error.
* @return {Promise}
* @example
* const webhookId = "232330225768333313";
* const token = "EtuNYHGkElBlE7BE266Jk...NzHvccXaUCQUOY64NbFWz9zbQ";
* client.Webhooks.executeSlack(webhookId, token, {
* text: "text message",
* username: "Different Username"
* });
*/
executeSlack(webhook, token, options, wait) {
const webhookId = webhookToId(webhook);
token = token || webhook.token;
return rest(this._discordie)
.webhooks.executeSlackWebhook(webhookId, token, options, wait);
}
} |
JavaScript | class Collapse extends Component {
/**
* @property _element
* @type null | HTMLElement
* @private
*/
@ref('mainNode') _element = null;
/**
* Collapsed/expanded state
*
* @property collapsed
* @type boolean
* @default true
* @public
*/
@arg
collapsed = true;
/**
* True if this item is expanded
*
* @property active
* @private
*/
active = !this.collapsed;
get collapse() {
return !this.transitioning;
}
get showContent() {
return this.collapse && this.active;
}
/**
* true if the component is currently transitioning
*
* @property transitioning
* @type boolean
* @private
*/
@tracked
transitioning = false;
/**
* The size of the element when collapsed. Defaults to 0.
*
* @property collapsedSize
* @type number
* @default 0
* @public
*/
@arg
collapsedSize = 0;
/**
* The size of the element when expanded. When null the value is calculated automatically to fit the containing elements.
*
* @property expandedSize
* @type number
* @default null
* @public
*/
@arg
expandedSize = null;
/**
* Calculates a hash for style attribute.
*/
get cssStyle() {
if (isNone(this.collapseSize)) {
return {};
}
return {
[this.collapseDimension]: `${this.collapseSize}px`,
};
}
/**
* Usually the size (height) of the element is only set while transitioning, and reseted afterwards. Set to true to always set a size.
*
* @property resetSizeWhenNotCollapsing
* @type boolean
* @default true
* @private
*/
resetSizeWhenNotCollapsing = true;
/**
* The direction (height/width) of the collapse animation.
* When setting this to 'width' you should also define custom CSS transitions for the width property, as the Bootstrap
* CSS does only support collapsible elements for the height direction.
*
* @property collapseDimension
* @type string
* @default 'height'
* @public
*/
@arg
collapseDimension = 'height';
/**
* The duration of the fade transition
*
* @property transitionDuration
* @type number
* @default 350
* @public
*/
@arg
transitionDuration = 350;
@tracked
collapseSize = null;
/**
* The action to be sent when the element is about to be hidden.
*
* @event onHide
* @public
*/
/**
* The action to be sent after the element has been completely hidden (including the CSS transition).
*
* @event onHidden
* @public
*/
/**
* The action to be sent when the element is about to be shown.
*
* @event onShow
* @public
*/
/**
* The action to be sent after the element has been completely shown (including the CSS transition).
*
* @event onShown
* @public
*/
/**
* Triggers the show transition
*
* @method show
* @protected
*/
show() {
this.args.onShow?.();
this.transitioning = true;
this.active = true;
this.collapseSize = this.collapsedSize;
transitionEnd(this._element, this.transitionDuration).then(() => {
if (this.isDestroyed) {
return;
}
this.transitioning = false;
if (this.resetSizeWhenNotCollapsing) {
this.collapseSize = null;
}
this.args.onShown?.();
});
next(this, function () {
if (!this.isDestroyed) {
this.collapseSize = this.getExpandedSize('show');
}
});
}
/**
* Get the size of the element when expanded
*
* @method getExpandedSize
* @param action
* @return {Number}
* @private
*/
getExpandedSize(action) {
let expandedSize = this.expandedSize;
if (expandedSize != null) {
return expandedSize;
}
let collapseElement = this._element;
let prefix = action === 'show' ? 'scroll' : 'offset';
let measureProperty = camelize(`${prefix}-${this.collapseDimension}`);
return collapseElement[measureProperty];
}
/**
* Triggers the hide transition
*
* @method hide
* @protected
*/
hide() {
this.args.onHide?.();
this.transitioning = true;
this.active = false;
this.collapseSize = this.getExpandedSize('hide');
transitionEnd(this._element, this.transitionDuration).then(() => {
if (this.isDestroyed) {
return;
}
this.transitioning = false;
if (this.resetSizeWhenNotCollapsing) {
this.collapseSize = null;
}
this.args.onHidden?.();
});
next(this, function () {
if (!this.isDestroyed) {
this.collapseSize = this.collapsedSize;
}
});
}
@action
_onCollapsedChange() {
let collapsed = this.collapsed;
let active = this.active;
if (collapsed !== active) {
return;
}
if (collapsed === false) {
this.show();
} else {
this.hide();
}
}
@action
_updateCollapsedSize() {
if (!this.resetSizeWhenNotCollapsing && this.collapsed && !this.collapsing) {
this.collapseSize = this.collapsedSize;
}
}
@action
_updateExpandedSize() {
if (!this.resetSizeWhenNotCollapsing && !this.collapsed && !this.collapsing) {
this.collapseSize = this.expandedSize;
}
}
} |
JavaScript | class FileSubSection extends React.Component {
static propTypes = {
path: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
contents: PropTypes.string.isRequired,
startLineNumber: PropTypes.number.isRequired,
items: PropTypes.array.isRequired,
sidebarWidth: PropTypes.number.isRequired,
onHover: PropTypes.func.isRequired,
isCollapsed: PropTypes.bool
};
state = {
isHovering: false,
isCollapsed: false,
currentLineNumber: 0
};
handleMouseEnter = event => {
this.setState({
isHovering: true
});
AnalyticsUtils.logExpandedCodeShow();
return this.props.onHover();
};
handleMouseLeave = event => {
const rect = this.refs.container.getBoundingClientRect();
const { clientX: x, clientY: y } = event;
const { top, bottom, right } = rect;
const PADDING = 20;
const isOnCodeSnippet = y < bottom && y > top && x <= right + PADDING;
const isOutsideWindow = x <= 0;
if (!isOnCodeSnippet || isOutsideWindow) {
this.setState({
isHovering: false
});
}
};
toggleCollapsed = () => {
this.setState({ isCollapsed: !this.state.isCollapsed });
};
getFilename = () => this.props.path.split("/").slice(-1)[0];
renderFileTitle = () => {
return (
<TreeLabel
name={this.getFilename()}
icon={"file"}
iconColor={"#999"}
onClick={this.toggleCollapsed}
hasTriangle={true}
paddingLeft={12}
status={this.getLabelStatus()}
/>
);
};
componentWillReceiveProps(newProps) {
if (newProps.isParentCollapsed !== this.props.isParentCollapsed) {
this.setState({ isCollapsed: newProps.isParentCollapsed });
}
}
componentDidMount() {
if (this.props.isParentCollapsed !== this.state.isCollapsed) {
this.setState({ isCollapsed: this.props.isParentCollapsed });
}
}
scrollToLine = lineNumber => this.setState({ currentLineNumber: lineNumber });
renderSectionItem = (item, key) => (
<BaseSectionItem
{...item}
key={key}
onHover={() => this.scrollToLine(item.lineNumber)}
/>
);
handleMouseOver = event => {
const { clientY: mouseY, clientX: mouseX } = event;
const { sidebarWidth } = this.props;
const isMovingOnFileSection = mouseX < sidebarWidth;
const hasNoValue = !this.state.mouseY;
const isDeltaLarge = Math.abs(mouseY - this.state.mouseY) >= 100;
if (isMovingOnFileSection) {
if (hasNoValue || isDeltaLarge) {
this.setState({ mouseY });
}
}
};
getSnippetStyle = () => {
const { mouseY } = this.state;
const top = mouseY ? Math.max(mouseY - 200, 25) : 25;
return {
left: this.props.sidebarWidth + 2,
top
};
};
renderExpandedCode = () => {
const lineNumbers = this.props.items.map(item => item.lineNumber);
return this.state.isHovering ? (
<ExpandedCode
lineNumbers={lineNumbers}
filePath={this.props.path}
baseLink={this.props.link}
currentLineNumber={this.state.currentLineNumber}
codeSnippet={this.props.contents}
startLineNumber={this.props.startLineNumber}
style={this.getSnippetStyle()}
/>
) : null;
};
render() {
const { isCollapsed } = this.state;
let sectionClassName = "usages-file-section";
sectionClassName += isCollapsed ? " collapsed" : "";
return (
<div
className={sectionClassName}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
onMouseOver={this.handleMouseOver}
ref={"container"}
>
{this.renderFileTitle()}
{isCollapsed ? null : this.renderItems()}
{isCollapsed ? null : this.renderExpandedCode()}
</div>
);
}
} |
JavaScript | class ApplicationDefaults {
/**
* Prepares environment files while opening the application.
* Copies application themes to themes location.
* @return {Promise}
*/
async prepareEnvironment() {
const td = new ThemeDefaults();
await td.prepareEnvironment();
const wd = new WorkspaceDefaults();
await wd.prepareEnvironment();
}
/**
* @param {WindowsManager} vm
*/
async prepareDatabaseUpgrade(vm) {
const db = new DataStore(vm);
await db.ensureDataUpgraded();
}
} |
JavaScript | class AppComponent {
constructor(
) {
this.name = 'Angular 2 Preboot';
}
ngOnInit() {
console.log(`Initializing 'App' component`);
}
} |
JavaScript | class EnvironmentMap {
constructor() {
this.size = envSize;
this.target = new THREE.WebGLRenderTarget(this.size, this.size, { type: THREE.FloatType });
const shadersPromises = [
loadFile('shaders/environment_mapping/vertex.glsl'),
loadFile('shaders/environment_mapping/fragment.glsl')
];
this._meshes = [];
this.loaded = Promise.all(shadersPromises)
.then(([vertexShader, fragmentShader]) => {
this._material = new THREE.ShaderMaterial({
vertexShader: vertexShader,
fragmentShader: fragmentShader,
});
});
}
setGeometries(geometries) {
this._meshes = [];
for (let geometry of geometries) {
this._meshes.push(new THREE.Mesh(geometry, this._material));
}
}
render(renderer) {
const oldTarget = renderer.getRenderTarget();
renderer.setRenderTarget(this.target);
renderer.setClearColor(black, 0);
renderer.clear();
for (let mesh of this._meshes) {
renderer.render(mesh, camera);
}
renderer.setRenderTarget(oldTarget);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.