language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class AclRule { /** * Create an AclRule from an Abstract Syntax Tree. The AST is the * result of parsing. * * @param {AclFile} aclFile - the AclFile for this rule * @param {string} ast - the AST created by the parser * @throws {IllegalModelException} */ constructor(aclFile, ast) { if(!aclFile || !ast) { throw new IllegalModelException('Invalid AclFile or AST'); } this.ast = ast; this.aclFile = aclFile; this.process(); } /** * Visitor design pattern * @param {Object} visitor - the visitor * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ accept(visitor,parameters) { return visitor.visit(this, parameters); } /** * Returns the AclFile that owns this AclRule. * * @return {AclFile} the owning AclFile */ getAclFile() { return this.aclFile; } /** * Process the AST and build the model * * @throws {IllegalModelException} * @private */ process() { this.name = this.ast.id.name; this.noun = new ModelBinding(this, this.ast.noun, this.ast.nounVariable); this.verb = this.ast.verb; this.participant = null; if(this.ast.participant && this.ast.participant !== 'ANY') { this.participant = new ModelBinding(this, this.ast.participant, this.ast.participantVariable); } this.predicate = null; if(this.ast.predicate) { this.predicate = new Predicate(this, this.ast.predicate); } else { this.predicate = new Predicate(this, 'true'); } this.action = this.ast.action; this.description = this.ast.description; } /** * Semantic validation of the structure of this AclRule. * * @throws {IllegalModelException} * @private */ validate() { this.noun.validate(); if(this.participant) { this.participant.validate(); } if(this.predicate) { this.predicate.validate(); } } /** * Returns the name of this AclRule. * * @return {string} the name of the AclRule */ getName() { return this.name; } /** * Returns the noun for this ACL rule. * * @return {ModelBinding} the noun ModelBinding */ getNoun() { return this.noun; } /** * Returns the verb associated with this ACL Rule. * * @return {string} the verb */ getVerb() { return this.verb; } /** * Returns the participant for this ACL rule. Returns null if this rule * does not filter based on participant. * * @return {ModelBinding} the participant ModelBinding or null */ getParticipant() { return this.participant; } /** * Returns the predicate associated with this ACL Rule * * @return {Predicate} the predicate */ getPredicate() { return this.predicate; } /** * Returns the action associated with this ACL Rule. * * @return {string} the action */ getAction() { return this.action; } /** * Returns the description associated with this ACL Rule. * * @return {string} the description */ getDescription() { return this.description; } /** * Returns a new object representing this Acl Rule that is * suitable for serializing as JSON. * @return {Object} A new object suitable for serializing as JSON. */ toJSON() { let result = { name: this.name, noun: this.noun, verb: this.verb, participant: this.participant, predicate: this.predicate, action: this.action, description: this.description }; return result; } }
JavaScript
class Controller { /** * @param {Routable} app */ constructor(app) { this.app = app; } }
JavaScript
class NetworkInterfaceReference extends models['SubResource'] { /** * Create a NetworkInterfaceReference. * @property {boolean} [primary] Specifies the primary network interface in * case the virtual machine has more than 1 network interface. */ constructor() { super(); } /** * Defines the metadata of NetworkInterfaceReference * * @returns {object} metadata of NetworkInterfaceReference * */ mapper() { return { required: false, serializedName: 'NetworkInterfaceReference', type: { name: 'Composite', className: 'NetworkInterfaceReference', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, primary: { required: false, serializedName: 'properties.primary', type: { name: 'Boolean' } } } } }; } }
JavaScript
class ntAtPool { Driver = ntAtDriver init(factory, config) { this.items = {}; this.streamFactory = factory; this.config = config; } open(streamName) { let gsm = this.get(streamName); if (gsm) return Promise.resolve(gsm); if (typeof this.streamFactory != 'function') { return Promise.reject('Invalid stream factory, only function accepted.'); } return ntWork.works([ () => new Promise((resolve, reject) => { this.streamFactory(streamName) .then((stream) => { console.log('%s: Try detecting modem...', streamName); gsm = new ntAtGsm(streamName, stream, this.config); resolve(); }) .catch((err) => reject(err)) ; }), () => new Promise((resolve, reject) => { gsm.detect() .then((driver) => { console.log('%s: Modem successfully detected as %s.', streamName, driver.desc); resolve(); }) .catch((err) => reject(err)) ; }), () => new Promise((resolve, reject) => { gsm.initialize() .then(() => { this.items[streamName] = gsm; console.log('%s: Modem information:', streamName); console.log('-'.repeat(50)); console.log('Manufacturer = %s', gsm.info.manufacturer); console.log('Model = %s', gsm.info.model); console.log('Version = %s', gsm.info.version); console.log('Serial = %s', gsm.info.serial); console.log('IMSI = %s', gsm.info.imsi); console.log('Call monitor = %s', gsm.info.hasCall ? 'yes' : 'no'); console.log('SMS monitor = %s', gsm.info.hasSms ? 'yes' : 'no'); console.log('USSD monitor = %s', gsm.info.hasUssd ? 'yes' : 'no'); console.log('Charsets = %s', gsm.props.charsets.join(', ')); console.log('Default charset = %s', gsm.props.charset); console.log('SMS Mode = %s', gsm.props.smsMode); console.log('Default storage = %s', gsm.props.storage); console.log('SMSC = %s', gsm.props.smsc); console.log('Network operator = %s', gsm.props.network.code); console.log('-'.repeat(50)); resolve(gsm); }) .catch((err) => reject(err)) ; }), ]); } get(streamName) { if (this.items[streamName]) { return this.items[streamName]; } } }
JavaScript
class MockSocket extends EventEmitter { constructor(url) { super() this.url = url // Simulate connection attempt setTimeout((() => { if (!this.url.startsWith('ws://') ) { const err = new Error(`connect ECONNREFUSED ${url}`) this.emit('error', err) this.close(1006) } else { this.emit('open') } }).bind(this), 10) } close(code) { this.emit('close', code) } send() {} terminate() { this.emit('close', 1006) } }
JavaScript
class SwaggerBuilder { /** * The list of routes */ /** * The list of interfaces */ /** * The Swagger Builder constructor. * * @param routes The list of routes * @param interfaces The list of interfaces */ constructor(routes, interfaces) { _defineProperty(this, "_routes", {}); _defineProperty(this, "_interfaces", {}); this._routes = routes; this._interfaces = interfaces; } /** * Method for returning the yaml docs */ getYaml() { return _jsYaml.default.dump({ openapi: "3.0.0", info: { version: _App.default.app.appVersion, title: `${_App.default.app.appName} API`, description: _App.default.app.appDescription }, servers: [{ url: _Config.default.string("http.url"), description: "Default environment" }], paths: this.getPaths(), components: this.getComponents(), tags: this.getTags() }, { forceQuotes: true }); } /** * Method for getting the Components */ getComponents() { const base = { securitySchemes: { BasicAuth: { type: "http", scheme: "basic" }, BearerAuth: { type: "http", scheme: "bearer" } }, schemas: { ErrorMessage: { type: "object", properties: { status: { type: "integer", default: 500 }, message: { type: "string" }, details: { type: "string", default: "" } } } } }; base.schemas = _objectSpread(_objectSpread({}, base.schemas), Object.keys(this._interfaces).reduce((accum, key) => { const value = this._interfaces[key]; const requiredFields = value.properties.filter(property => property.required); return _objectSpread(_objectSpread({}, accum), {}, { [key]: { type: "object", description: value.description || "", properties: value.properties.reduce((accum, property) => { let definition = _objectSpread(_objectSpread({}, property), {}, { name: undefined, required: undefined, arrayType: undefined }); if (property.type !== _DocsInterfaces.BodyParameterType.ARRAY && property.schema) { definition = { $ref: `#/components/schemas/${property.schema}` }; } if (property.type === _DocsInterfaces.BodyParameterType.ARRAY) { definition = { items: property.schema ? { $ref: `#/components/schemas/${property.schema}` } : { type: property.arrayType || _DocsInterfaces.BodyParameterType.STRING } }; } if (property.enumOptions) { definition.enum = property.enumOptions; } return _objectSpread(_objectSpread({}, accum), {}, { [property.name]: definition }); }, {}), required: requiredFields.length > 0 ? requiredFields.map(property => property.name) : undefined } }); }, {})); return base; } /** * Method for getting the tags */ getTags() { const routesList = Object.values(this._routes).map(route => ({ name: route.name, description: route.description || "" })); if (routesList.length === 0) { return {}; } return routesList.map(routeDefinition => ({ name: routeDefinition.name, description: routeDefinition.description || "" })); } /** * Method for getting the paths */ getPaths() { const routesList = Object.values(this._routes).reduce((accum, routeDefinition) => [...accum, ...routeDefinition.routes.map(route => _objectSpread({ tag: routeDefinition.name }, route))], []); if (routesList.length === 0) { return {}; } const routeMapping = routesList.reduce((accum, route) => { const routeGroup = accum[route.path] || {}; routeGroup[route.verb] = route; return _objectSpread(_objectSpread({}, accum), {}, { [route.path]: routeGroup }); }, {}); return Object.keys(routeMapping).reduce((accum, key) => _objectSpread(_objectSpread({}, accum), {}, { [key]: this.displayRouteGroup(Object.values(routeMapping[key])) }), {}); } /** * Method for displaying a Route Group * * @param routeGroup The Route Group to be displayed */ displayRouteGroup(routeGroup) { return routeGroup.reduce((accum, routeDefinition) => { const definition = { summary: routeDefinition.summary || routeDefinition.description || "", description: routeDefinition.description || "", tags: [routeDefinition.tag] }; if (routeDefinition.isAuthenticated) { definition.security = [{ [routeDefinition.basicSpecific ? "BasicAuth" : "BearerAuth"]: [] }]; } const parameters = this.getParameters(routeDefinition); if (parameters) { definition.parameters = parameters; } const queryParameters = this.getQueryParameters(routeDefinition); if (queryParameters) { definition.parameters = [...(definition.parameters || []), ...queryParameters]; } definition.operationId = `${routeDefinition.controllerName}.${routeDefinition.methodName}`; definition.summary = routeDefinition.description || `${routeDefinition.controllerName}.${routeDefinition.methodName}`; definition.responses = this.getDefaultResponse(routeDefinition); const requestBody = this.getRequestBody(routeDefinition); if (requestBody) { definition.requestBody = requestBody; } return _objectSpread(_objectSpread({}, accum), {}, { [routeDefinition.verb]: definition }); }, {}); } /** * Method for getting the Parameters * * @param routeDefinition The definition of the Route for which we want the Parameters */ getParameters(routeDefinition) { const parameters = Object.values(routeDefinition.parameters); if (parameters.length === 0) { return null; } return parameters.map(parameter => ({ name: parameter.name, in: "path", description: parameter.description || '""', required: true, schema: { type: parameter.type } })); } /** * Method for getting the Query Parameters * * @param routeDefinition The definition of the Route for which we want the Parameters */ getQueryParameters(routeDefinition) { const parameters = Object.values(routeDefinition.query || {}); if (parameters.length === 0) { return null; } return parameters.map(parameter => ({ name: parameter.name, in: "query", description: parameter.description || '""', required: parameter.isRequired || false, schema: { type: parameter.isArray ? "array" : parameter.type, items: parameter.isArray ? { type: parameter.type } : undefined } })); } /** * Method to get errors * * @param routeDefinition The definition of the Route for which we want the Errors */ getErrors(routeDefinition) { if (Object.keys(routeDefinition.errors).length === 0) { return {}; } return Object.keys(routeDefinition.errors).reduce((accum, key) => _objectSpread(_objectSpread({}, accum), {}, { [key]: { description: routeDefinition.errors[key], content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorMessage" }, example: { status: key, message: routeDefinition.errors[key] } } } } }), {}); } /** * Method for getting the default Response * * @param routeDefinition The Route definition */ getDefaultResponse(routeDefinition) { let defaultResponse = _HTTPStatus.default.OK; let description = "OK"; let response = {}; if (routeDefinition.responseStatus) { switch (routeDefinition.responseStatus.toString()) { case _HTTPStatus.default.NO_CONTENT.toString(): description = "No Content"; break; case _HTTPStatus.default.CREATED.toString(): description = "Created"; break; case _HTTPStatus.default.ACCEPTED.toString(): description = "Accepted"; break; } defaultResponse = routeDefinition.responseStatus; } if (routeDefinition.response && routeDefinition.response.schema) { let schemaResponse = { schema: { $ref: `#/components/schemas/${routeDefinition.response.schema}` } }; if (routeDefinition.response.isArray) { const isBaseType = ["string", "number", "boolean"].indexOf(routeDefinition.response.schema); schemaResponse = { schema: { items: { $ref: !isBaseType ? `#/components/schemas/${routeDefinition.response.schema}` : undefined, type: !isBaseType ? routeDefinition.response.type : undefined } } }; } response = { content: { "application/json": schemaResponse } }; } return _objectSpread(_objectSpread({ [defaultResponse]: _objectSpread({ description }, response) }, this.getErrors(routeDefinition)), {}, { 500: { description: "General server error", content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorMessage" } } } } }); } /** * Method for getting the Request body * * @param routeDefinition The route definition */ getRequestBody(routeDefinition) { if (!routeDefinition.request || Object.keys(routeDefinition.request).length === 0) { return null; } const base = { description: routeDefinition.description, required: true }; const defaultTag = routeDefinition.request[_DocsInterfaces.DEFAULT_BODY_TAG]; if (defaultTag) { base.content = { "application/json": { schema: { $ref: `#/components/schemas/${defaultTag.schema}` } } }; if (!this._interfaces[defaultTag.schema]) { this._interfaces[defaultTag.schema] = { name: defaultTag.schema, type: _DocsInterfaces.BodyParameterType.OBJECT, properties: [] }; } else { base.description = this._interfaces[defaultTag.schema].description ?? base.description; } return base; } const requiredFields = Object.keys(routeDefinition.request).filter(key => routeDefinition.request[key].required); base.content = { "application/json": { schema: { type: _DocsInterfaces.BodyParameterType.OBJECT, properties: Object.keys(routeDefinition.request).reduce((accum, key) => { const value = routeDefinition.request[key]; return _objectSpread(_objectSpread({}, accum), {}, { [key]: { type: value.type, default: value.default, description: value.description } }); }, {}), required: requiredFields.length > 0 ? requiredFields.map(key => routeDefinition.request[key].name) : undefined } } }; return base; } }
JavaScript
class Progress extends React.Component { state = { name: '', goals: {}, listEntries: [], progress: 20, key: 0, value: 0, }; increase = (key, value) => { this.setState({ [key]: this.state[key] + value, }); } renderForm = () => { const { navigation } = this.props; return ( <Block flex style={styles.container}> <StatusBar barStyle="light-content" /> <Block flex center> {this.renderentries(this.state.listEntries)} </Block> </Block> ) } render() { return ( <Block flex center > <ScrollView style={styles.components} showsVerticalScrollIndicator={false}> {this.renderForm()} </ScrollView> </Block> ); } renderentries = (listEntries) => { //const { navigation } = this.props; listEntries.map(listEntry => { return ( <Text > {listEntry.water} </Text> ); }); }; async componentDidMount() { const value = await AsyncStorage.getItem('user'); const loggedUser = JSON.parse(value); console.log("user" + loggedUser.id); const id = loggedUser.id; console.log("http://InsertYourIpHere:1337/entries?userId=" + id); fetch("http://InsertYourIpHere:1337/entries?userId=" + id, { method: "GET", headers: { Accept: "application/json" } }) .then(response => response.json()) .then(responseJson => { //let tagMap = {}; if (!responseJson) { responseJson = []; console.log(JSON.stringify(responseJson)); } /*responseJson.forEach(function(item) { tagMap[item.id] = item.tags.map(function(tag) { return tag.name + " "}); });*/ this.setState({ entries: responseJson }); //this.setState({ tagMap: tagMap }); responseJson.forEach(function (item) { //tagMap[item.id] = item.tag.map(function(tag) {return tag.name + " "}); }); this.setState({ listEntries: responseJson }); //this.setState({ tagMap: tagMap }); var highestwater = Math.max.apply(Math, this.state.listEntries.map(function (o) { return o.water; })); var higheststeps = Math.max.apply(Math, this.state.listEntries.map(function (o) { return o.steps; })); var highestweight = Math.max.apply(Math, this.state.listEntries.map(function (o) { return o.weight; })); var highestsleep = Math.max.apply(Math, this.state.listEntries.map(function (o) { return o.hours_of_sleep; })); console.log("Last Water: " + highestwater); console.log("Last Steps: " + higheststeps); console.log("Last Weight: " + highestweight); console.log("Last Sleep: " + highestsleep); }) .catch(error => { console.error(error); }); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = {'scores': ''}; this.state = {'stats': ''}; this.state = {'opponents': ''}; this.state = {'player': ''}; this.state = {'sentence': ''}; this.state = {'timer': ''}; this.state = {'backgroundColor': <div className="redBackground" />}; this.state = {'playButtonText': 'CLICK HERE TO START!'}; this.state = {'playButton': <div><div className="button__Wrapper"><button className="buttons__start" onClick={this.startGame.bind(this)}>{this.state.playButtonText}</button> </div><div className="demo">This game is a demo. It is only currently set up to work with the two most popular desktop resolutions.</div></div>}; } componentWillMount(){ this.setState({ 'timer': <div className="timer">Word Launch</div>, 'scores': <div className="scoresWrapper"> <div className="overallScore"> Lifetime<br /> {overallScore} </div> <div className="score"> Score<br /> {score} </div> </div> }); } startGame(){ position = 1; answersCorrect = 0; answersIncorrect = 0; score = 0; x = 0; setTimeout(this.saveTime.bind(this), 3000); setTimeout(this.startRace.bind(this), 3000); this.backgroundController(); this.setRace(); this.setState({ 'playButton': "", 'stats': "", 'scores': <div className="scoresWrapper"> <div className="overallScore"> Lifetime<br /> {overallScore} </div> <div className="score"> Score<br /> {score} </div> </div> }); } backgroundController(){ setTimeout(this.blueBackgroundSpeechStarter.bind(this), 1000); } blueBackgroundSpeechStarter() { this.setState({'backgroundColor': <div className="blueBackground"><TextToSpeech /></div> }); } blueBackground() { this.setState({'backgroundColor': <div className="blueBackground"></div> }); } redBackground() { this.setState({'backgroundColor': <div className="redBackground"></div> }); } // Timer saveTime(){ this.displaySentence(); time = originalTime; this.timer(); } timer(){ if(time > 0 ){ time--; setTimeout(this.timer.bind(this), 1000); if(time > (originalTime/2)){ this.setState({ 'backgroundColor': <div className="blueBackground"></div>, 'timer': <div className="timer">{time}</div> }); } else { this.setState({ 'backgroundColor': <div className="redBackground"></div>, 'timer': <div className="timer"><span className="timer__blinking">{time}</span></div> }); } return(time); } else{ this.setRank(); } } //display sentence displaySentence(){ // console.log("display"); if(i <= currentSentence.length - 1){ tempSentenceHolder += currentSentence[i]; this.setState({ 'sentence':<div className="sentence">{tempSentenceHolder}</div> }); i++ setTimeout(this.displaySentence.bind(this), 50); } else{ this.setAnswerChoices(); i = 0; tempSentenceHolder = ""; } } setAnswerChoices(){ let positionOne = ""; let positionTwo = ""; let positionThree = ""; let correctAnswer = <button className="buttons__answers" onClick={this.correctAnswer.bind(this)}>{currentCorrectAnswer}</button>; let wrongAnswerOne = <button className="buttons__answers" onClick={this.incorrectAnswer.bind(this)}>{currentIncorrectAnswerOne}</button>; let wrongAnswerTwo = <button className="buttons__answers" onClick={this.incorrectAnswer.bind(this)}>{currentIncorrectAnswerTwo}</button>; let randomNumber = Math.floor(Math.random()*3+1); if(randomNumber === 1){ positionOne = correctAnswer; positionTwo = wrongAnswerOne; positionThree = wrongAnswerTwo; } else if(randomNumber === 2){ positionOne = wrongAnswerOne; positionTwo = correctAnswer; positionThree = wrongAnswerTwo; } else if(randomNumber === 3){ positionOne = wrongAnswerOne; positionTwo = wrongAnswerTwo; positionThree = correctAnswer; } this.setState({ 'sentence': <div> <div className="sentence">{tempSentenceHolder}</div> <div className="answerWrapper"> <br /> {positionOne} {positionTwo} {positionThree} </div> </div> }); } correctAnswer(){ answersCorrect ++; score ++; console.log("answersCorrect: " + answersCorrect); if(position < 9){ this.setState({ 'backgroundColor': <div className="blueBackground"><TextToSpeech /></div> }); this.displaySentence(); } this.setState({ 'scores': <div className="scoresWrapper"> <div className="overallScore"> Lifetime<br /> {overallScore} </div> <div className="score"> Score<br /> {score} </div> </div> }); this.moveForward(); } incorrectAnswer(){ console.log("answersIncorrect: " + answersIncorrect); answersIncorrect ++; } //move player setRace(){ this.setState({ 'player': <div> <div className="player"/> <div className="opponentOne"/> <div className="opponentTwo"/> <div className="opponentThree"/> </div> }); // this.startRace();//dev only } startRace(){ this.setState({ 'player': <div className="player"/>, 'opponents': <div> <div className="opponentOneMoving"><div className="opponentShake"></div></div> <div className="opponentTwoMoving"><div className="opponentShake"></div></div> <div className="opponentThreeMoving"><div className="opponentShake"></div></div> </div> }); } moveForward(){ if(position === 1){ position ++; this.setState({ 'player': <div className="playerPosTwo"></div> }); } else if(position === 2){ position ++; this.setState({ 'player': <div className="playerPosThree"></div> }); } else if(position === 3){ position ++; this.setState({ 'player': <div className="playerPosFour"></div> }); } else if(position === 4){ position ++; this.setState({ 'player': <div className="playerPosFive"></div> }); } else if(position === 5){ position ++; this.setState({ 'player': <div className="playerPosSix"></div> }); } else if(position === 6){ position ++; this.setState({ 'player': <div className="playerPosSeven"></div> }); } else if(position === 7){ position ++; this.setState({ 'player': <div className="playerPosEight"></div> }); } else if(position === 8){ position ++; this.setState({ 'player': <div className="playerPosNine"></div> }); } else if(position === 9){ position ++; this.setState({ 'player': <div className="playerPosTen"></div> }); this.setRank(); } } setRank(){ if(answersCorrect === 9 && answersIncorrect === 0 && timeLeft > 15){ tmpRanking = "Captain"; this.blueBackground(); } else if(answersCorrect === 9 && answersIncorrect === 0 && timeLeft < 16){ tmpRanking = "Commander"; this.redBackground(); } else if(answersCorrect === 8 && answersIncorrect === 0){ tmpRanking = "Commander"; this.redBackground(); } else if(answersCorrect === 9 || answersCorrect === 8 || answersCorrect === 7){ tmpRanking = "Lieutenant Commander"; } else if(answersCorrect === 6 || answersCorrect === 5 || answersCorrect === 4){ tmpRanking = "Lieutenant"; } else if(answersCorrect === 3 || answersCorrect === 2){ tmpRanking = "Ensign"; } else if(answersCorrect === 1 ||answersCorrect === 0){ tmpRanking = "Midshipman"; } this.preRaceOver(); } preRaceOver(){ console.log("preRaceOver();"); let tmpLifeTimeScore = overallScore; let tmpScoreTally = timeLeft * score; let tmpOverallScoreTally = tmpScoreTally + overallScore overallScore += tmpOverallScoreTally; this.setState({ 'scores': <div className="scoresWrapper"> <div className="overallScore"> Lifetime<br /> {overallScore} </div> <div className="score"> Score<br /> {score} </div> </div>, 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOneShadow"/> <div className="planetTwoShadow"/> <div className="planetThreeShadow"/> <div className="planetFourShadow"/> <div className="planetFiveShadow"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div>, 'opponents':"", 'sentence': "", 'timer': <div className="rank">{tmpRanking}</div>, 'stats': <div> <div className="answered"> <div className="answeredCorrectly"> You answered {answersCorrect} correctly! </div> <div className="answeredIncorrectly"> You answered {answersIncorrect} incorrectly! </div> </div> <div className="stats__score"> Level Score: {score} <br /> <span className="stats__score__underline">X Time Left: {timeLeft}</span><br /> <span className="stats__score__textColor">+ {tmpScoreTally}</span><br /> <span className="stats__score__underline">+ Lifetime Score: {tmpLifeTimeScore}</span><br /> <span className="stats__score__textColor">+ {tmpOverallScoreTally}</span> </div> <div className="restartGame"> <button className="buttons__restartGame" onClick={this.startGame.bind(this)}>Play Again</button> </div> </div> }); timeLeft = time; time = 0; this.raceOver(); } raceOver(){ if(answersCorrect > 0 && x === 0){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwoShadow"/> <div className="planetThreeShadow"/> <div className="planetFourShadow"/> <div className="planetFiveShadow"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 1 && x === 1){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThreeShadow"/> <div className="planetFourShadow"/> <div className="planetFiveShadow"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 2 && x === 2){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFourShadow"/> <div className="planetFiveShadow"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 3 && x === 3){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFiveShadow"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 4 && x === 4){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFive"/> <div className="planetSixShadow"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 5 && x === 5){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFive"/> <div className="planetSix"/> <div className="planetSevenShadow"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 6 && x === 6){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFive"/> <div className="planetSix"/> <div className="planetSeven"/> <div className="planetEightShadow"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 7 && x === 7){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFive"/> <div className="planetSix"/> <div className="planetSeven"/> <div className="planetEight"/> <div className="planetNineShadow"/> </div> </div> }); setTimeout(this.raceOver.bind(this), 500); } if(answersCorrect > 8 && x === 8){ this.setState({ 'player': <div> <div className="endOfRound"/> <div className="planetsWrapper"> <div className="planetOne"/> <div className="planetTwo"/> <div className="planetThree"/> <div className="planetFour"/> <div className="planetFive"/> <div className="planetSix"/> <div className="planetSeven"/> <div className="planetEight"/> <div className="planetNine"/> </div> </div> }); } x++; } render() { return ( <div className="App"> <div className="app__background" /> {this.state.backgroundColor} <header className="App-header"> {this.state.scores} {this.state.timer} </header> {this.state.sentence} {this.state.stats} {this.state.playButton} {this.state.player} {this.state.opponents} </div> ); } }
JavaScript
class App extends Component { constructor(props){ super(props); this.state = { news: [], newsSelected:[],sortTerm:'published_date' } this.filterTerm('home'); }; filterTerm(term){ var url = "https://api.nytimes.com/svc/topstories/v2/"+term+".json"; url += '?' + $.param({ 'api-key': "6de4f6e977d746b8990a43d2db015ec9" }); $.ajax({ url: url, method: 'GET' }).done((result) => { this.setState({news: result['results']}); }).fail(function(err) { throw err; }); } render(){ return ( <div> <div className="container filter-sort"> <div className="row"> <div className="col-sm text-center"> <Filter onFilterChange={val => this.filterTerm(val)} /> </div> <div className="col-sm text-center"> <Sort onSortChange={val => this.setState({sortTerm: val})}/> </div> </div> </div> <NewsPop news={this.state.newsSelected}/> <NewsList onNewsSelect={(newsSelected) => {this.setState({newsSelected:newsSelected})}} news={this.state.news} sortTerm={this.state.sortTerm}/> </div> ); } componentDidMount(){ $(".news-item").on("click",function(){ $("#modal").css("display","block"); }); $(".close").on("click", function(){ $("#modal").css("display","none"); }); } componentDidUpdate(){ $(".news-item").on("click",function(){ $("#modal").css("display","block"); }); $(".close").on("click", function(){ $("#modal").css("display","none"); }); } }
JavaScript
class Renderer extends React.Component { handleChange = (event) => { const { name, checked } = event.target; this.props.onUpdate({ name, value: checked, }); } render() { const { text, type, number, editable, response, } = this.props; const { options } = type; if (!editable) { return ( <div> <div className="list-style"> <div className="list-style-item"> <div className="list-style-item-ordinal">{number}.</div> <div className="list-style-item-content">{text}</div> </div> </div> { options.filter((option, index) => { const name = `${this.props.name}-${index}`; const checked = response ? response[name] : false; if (checked === true) { return option; } return null; }).join(', ') } </div> ); } return ( <tr> <td> <div className="list-style"> <div className="list-style-item"> <div className="list-style-item-ordinal">{number}.</div> <div className="list-style-item-content">{text}</div> </div> </div> </td> { options.map((option, index) => { const name = `${this.props.name}-${index}`; const value = 2 ** index; const checked = response ? response[name] : false; return ( // eslint-disable-next-line react/no-array-index-key <td key={index}> <Checkbox name={name} value={value} checked={checked} onChange={this.handleChange} /> </td> ); }) } </tr> ); } }
JavaScript
class BrowserResponse extends BaseResponse { constructor (page, assert, res) { /** * The base response class needs headers to be passed * inside constructor. * * Since a browser page visits multiple URL's during * a request, there is no single copy of headers. * * Instead we pass an empty header when starting * and later keeping on updating headers for * each response. */ super(assert, {}) this.page = page /** * Storing initial response */ this._response = null /** * Update the response */ this.updateResponse(res) return new Proxy(this, proxyHandler) } /** * An array of request redirects * * @attribute redirects * * @return {Array} */ get redirects () { return [] } /** * Since a browser page moves between page, we keep * on updating the response to make sure we have * the latest `headers`. * * @method updateResponse * * @return {void} */ updateResponse (response) { debug('consuming response for %s', response.url()) this._response = response /** * Set new status */ this.status = response.status() const headers = response.headers() /** * Parses cookies and split them to array */ const setCookieHeader = headers['set-cookie'] if (typeof (setCookieHeader) === 'string' && setCookieHeader) { headers['set-cookie'] = setCookieHeader.split('\n') } /** * Update headers */ this.updateHeaders(headers) } /** * Returns the current page response text, or * text of a selector. * * @method getText * @async * * @param {Selector} [selector] * * @return {String} */ getText (selector) { return selector ? this.page.$eval(selector, (e) => e.innerText) : this.page.evaluate(() => { return document.body.innerText }) } /** * Returns HTML for a given selector or entire * body * * @method getHtml * @async * * @param {Selector} [selector] * * @return {String} */ getHtml (selector) { return selector ? this.page.$eval(selector, (e) => e.innerHTML) : this.page.content() } /** * Returns page title * * @method getTitle * @async * * @return {String} */ getTitle () { return this.page.title() } /** * Returns a boolean indicating if a checkbox * is checked or not. * * @method isChecked * @async * * @param {Selector} selector * * @return {Boolean} */ isChecked (selector) { return this.page.$eval(selector, (e) => e.checked) } /** * Returns a boolean on whether an element is visible * or not * * @method isVisible * * @param {String} selector * * @return {Boolean} */ isVisible (selector) { return this.page.$eval(selector, (e) => { const styles = document.defaultView.getComputedStyle(e, null) return styles['opacity'] !== '0' && styles['display'] !== 'none' && styles['visibility'] !== 'hidden' }) } /** * Returns value for a given selector * * @method getValue * @async * * @param {Selector} selector * * @return {String} */ getValue (selector) { return this.page.evaluate((s) => { const nodes = document.querySelectorAll(s) if (!nodes.length) { throw new Error('Node not found') } /** * Return value of the selected radio box, if * node is a radio button */ if (nodes[0].type === 'radio') { let checkedValue = null for (const item of nodes) { if (item.checked) { checkedValue = item.value break } } return checkedValue } /** * If node is an select multiple elem */ if (nodes[0].type === 'select-multiple') { const selectedOptions = [] for (const item of nodes[0].options) { if (item.selected) { selectedOptions.push(item.value) } } return selectedOptions } /** * Otherwise return first node value */ return nodes[0].value }, selector) } /** * Returns value for a given attribute. * * @method getAttribute * @async * * @param {Selector} selector * @param {String} attribute * * @return {String} */ getAttribute (selector, attribute) { return this.page.$eval(selector, (e, attr) => e.getAttribute(attr), attribute) } /** * Returns path for the current url * * @method getPath * * @return {String} */ getPath () { return new URL(this.page.url()).pathname } /** * Get query string * * @method getQueryParams * * @return {String} */ getQueryParams () { const params = new URL(this.page.url()).searchParams const paramsHash = {} for (const [name, value] of params) { paramsHash[name] = value } return paramsHash } /** * Returns value for a given key from query params * * @method getQueryParam * * @param {String} key * * @return {String} */ getQueryParam (key) { return this.getQueryParams()[key] } /** * Returns an object of attributes * * @method getAttributes * @async * * @param {Selector} selector * * @return {Object} */ getAttributes (selector) { return this.page.$eval(selector, (e, attr) => { const attrsMap = e.attributes const attrs = {} for (let i = 0; i < attrsMap.length; i++) { const node = attrsMap.item(i) attrs[node.nodeName] = node.value } return attrs }) } /** * Returns a boolean indicating whether an element * exists or not. * * @method hasElement * @async * * @param {String} selector * * @return {Boolean} */ hasElement (selector) { return this.page.evaluate((s) => !!document.querySelector(s), selector) } /** * Returns reference to an element * * @method getElement * @async * * @param {Selector} selector * * @return {Object} */ getElement (selector) { return this.page.$(selector) } /** * Returns reference to the actions chain, which * can be used to interact with the page. * * @method chain * * @return {Object} */ chain () { return new ActionsChain(this) } /** * Closes the current page * * @method close * @async * * @return {void} */ close () { return this.page.close() } /** * Overriding base response assert body, so it * needs to be on this class, but calls * the assert method on actions chain * * @method assertBody * * @return {void} */ assertBody (expected) { return this.chain().assertBody(expected) } }
JavaScript
class Playwright extends _instrumentation.SdkObject { constructor(isInternal) { super({ attribution: { isInternal }, instrumentation: (0, _instrumentation.createInstrumentation)() }, undefined, 'Playwright'); this.selectors = void 0; this.chromium = void 0; this.android = void 0; this.electron = void 0; this.firefox = void 0; this.webkit = void 0; this.options = void 0; this._portForwardingServer = void 0; this.instrumentation.addListener({ onCallLog: (logName, message, sdkObject, metadata) => { _debugLogger.debugLogger.log(logName, message); } }); this.options = { rootSdkObject: this, selectors: new _selectors.Selectors() }; this.chromium = new _chromium.Chromium(this.options); this.firefox = new _firefox.Firefox(this.options); this.webkit = new _webkit.WebKit(this.options); this.electron = new _electron.Electron(this.options); this.android = new _android.Android(new _backendAdb.AdbBackend(), this.options); this.selectors = this.options.selectors; } async _enablePortForwarding() { (0, _utils.assert)(!this._portForwardingServer); this._portForwardingServer = await _socksSocket.PortForwardingServer.create(this); this.options.loopbackProxyOverride = () => this._portForwardingServer.proxyServer(); this._portForwardingServer.on('incomingSocksSocket', socket => { this.emit('incomingSocksSocket', socket); }); } _disablePortForwarding() { if (!this._portForwardingServer) return; this._portForwardingServer.stop(); } _setForwardedPorts(ports) { if (!this._portForwardingServer) throw new Error(`Port forwarding needs to be enabled when launching the server via BrowserType.launchServer.`); this._portForwardingServer.setForwardedPorts(ports); } }
JavaScript
class IntegerFormatter extends InternalFormat.Formatter { /** * Construct the formatter from a client-supplied buffer, to which the result will be appended, * and a specification. Sets {@link #mark} to the end of the buffer. * * @param result destination buffer * @param spec parsed conversion specification */ constructor(result, spec) { // mimic the overloaded Java constructors if (spec === undefined) { spec = result result = ''; } super(result, spec) } /** * Format a {@link BigInteger}, which is the implementation type of Jython <code>long</code>, * according to the specification represented by this <code>IntegerFormatter</code>. The * conversion type, and flags for grouping or base prefix are dealt with here. At the point this * is used, we know the {@link #spec} is one of the integer types. * * @param value to convert * @return this object */ format(value) { // Different process for each format type. switch (String(this.spec.type).toLowerCase()) { case 'd': case InternalFormat.Spec.NONE: case 'u': case 'i': // None format or d-format: decimal this.format_d(value); break; case 'x': // hexadecimal. this.format_x(value, false); break; case 'X': // HEXADECIMAL! this.format_x(value, true); break; case 'o': // Octal. this.format_o(value); break; case 'b': // Binary. this.format_b(value); break; case 'c': // Binary. this.format_c(value); break; case 'n': // Locale-sensitive version of d-format should be here. this.format_d(value); break; default: // Should never get here, since this was checked in caller. throw FormatError.unknownFormat(this.spec.type, "long") } // If the format type is an upper-case letter, convert the result to upper case. if (this.spec.type === String(this.spec.type).toUpperCase()) { this.uppercase(); } // If required to, group the whole-part digits. if (this.spec.grouping) { this.groupDigits(3, ','); } return this; } /** * Format the value as decimal (into {@link #result}). The option for mandatory sign is dealt * with by reference to the format specification. * * @param value to convert */ format_d(value) { let number; if (value < 0) { // Negative value: deal with sign and base, and convert magnitude. this.negativeSign(null); number = String(-1 * value); } else { // Positive value: deal with sign, base and magnitude. this.positiveSign(null); number = String(value); } this.appendNumber(number); } /** * Format the value as hexadecimal (into {@link #result}), with the option of using upper-case * or lower-case letters. The options for mandatory sign and for the presence of a base-prefix * "0x" or "0X" are dealt with by reference to the format specification. * * @param value to convert * @param upper if the hexadecimal should be upper case */ format_x(value, upper) { let base = upper ? "0X" : "0x"; let number; if (value < 0) { // Negative value: deal with sign and base, and convert magnitude. this.negativeSign(base); number = this.toHexString(-1 * value); } else { // Positive value: deal with sign, base and magnitude. this.positiveSign(base); number = this.toHexString(value); } // Append to result, case-shifted if necessary. if (upper) { number = number.toUpperCase(); } this.appendNumber(number); } /** * Format the value as octal (into {@link #result}). The options for mandatory sign and for the * presence of a base-prefix "0o" are dealt with by reference to the format specification. * * @param value to convert */ format_o(value) { let base = "0o"; let number; if (value < 0) { // Negative value: deal with sign and base, and convert magnitude. this.negativeSign(base); number = this.toOctalString(-1 * value); } else { // Positive value: deal with sign, base and magnitude. this.positiveSign(base); number = this.toOctalString(value); } // Append to result. this.appendNumber(number); } /** * Format the value as binary (into {@link #result}). The options for mandatory sign and for the * presence of a base-prefix "0b" are dealt with by reference to the format specification. * * @param value to convert */ format_b(value) { let base = "0b"; let number; if (value < 0) { // Negative value: deal with sign and base, and convert magnitude. this.negativeSign(base); number = this.toBinaryString(-1 * value); } else { // Positive value: deal with sign, base and magnitude. this.positiveSign(base); number = this.toBinaryString(value); } // Append to result. this.appendNumber(number); } /** * Format the value as a character (into {@link #result}). * * @param value to convert */ format_c(value) { this.result += String.fromCharCode(value) } // NOTE: Jython includes two sets of methods (one for BigInteger and one for int). // Removed the second set of methods. /** * Append to {@link #result} buffer a sign (if one is specified for positive numbers) and, in * alternate mode, the base marker provided. The sign and base marker are together considered to * be the "sign" of the converted number, spanned by {@link #lenSign}. This is relevant when we * come to insert padding. * * @param base marker "0x" or "0X" for hex, "0o" for octal, "0b" for binary, "" or * <code>null</code> for decimal. */ positiveSign(base) { // Does the format specify a sign for positive values? let sign = this.spec.sign; if (InternalFormat.Spec.specified(sign) && sign !== '-') { this.result += sign; this.lenSign = 1; } // Does the format call for a base prefix? if (base !== null && this.spec.alternate) { this.result += base this.lenSign += base.length; } } /** * Append to {@link #result} buffer a minus sign and, in alternate mode, the base marker * provided. The sign and base marker are together considered to be the "sign" of the converted * number, spanned by {@link #lenSign}. This is relevant when we come to insert padding. * * @param base marker ("0x" or "0X" for hex, "0" for octal, <code>null</code> or "" for decimal. */ negativeSign(base) { // Insert a minus sign unconditionally. this.result += '-'; this.lenSign = 1; // Does the format call for a base prefix? if (base !== null && this.spec.alternate) { this.result += base this.lenSign += base.length; } } /** * Append a string (number) to {@link #result} and set {@link #lenWhole} to its length . * * @param number to append */ appendNumber(number) { // note that number is a String here this.lenWhole = number.length; this.result += number; } /** * A more efficient algorithm for generating a hexadecimal representation of a byte array. * {@link BigInteger#toString(int)} is too slow because it generalizes to any radix and, * consequently, is implemented using expensive mathematical operations. * * @param value the value to generate a hexadecimal string from * @return the hexadecimal representation of value, with "-" sign prepended if necessary */ toHexString(value) { // Jython does its own implementation, but recoding to simply use JS built-in methods if (value) { return value.toString(16) } return value } /** * A more efficient algorithm for generating an octal representation of a byte array. * {@link BigInteger#toString(int)} is too slow because it generalizes to any radix and, * consequently, is implemented using expensive mathematical operations. * * @param value the value to generate an octal string from * @return the octal representation of value, with "-" sign prepended if necessary */ toOctalString(value) { // Jython does its own implementation, but recoding to simply use JS built-in methods if (value) { return value.toString(8) } return value } /** * A more efficient algorithm for generating a binary representation of a byte array. * {@link BigInteger#toString(int)} is too slow because it generalizes to any radix and, * consequently, is implemented using expensive mathematical operations. * * @param value the value to generate a binary string from * @return the binary representation of value, with "-" sign prepended if necessary */ toBinaryString(value) { if (value) { return value.toString(2); } return value } /** Format specification used by bin(). */ BIN = InternalFormat.fromText("#b"); /** Format specification used by oct(). */ OCT = InternalFormat.fromText("#o"); /** Format specification used by hex(). */ HEX = InternalFormat.fromText("#x"); /** * Convert the object to binary according to the conventions of Python built-in * <code>bin()</code>. The object's __index__ method is called, and is responsible for raising * the appropriate error (which the base {@link PyObject#__index__()} does). * * @param number to convert * @return PyString converted result */ // Follow this pattern in Python 3, where objects no longer have __hex__, __oct__ members. bin(number) { return this.formatNumber(number, this.constructor.BIN); } /** * Convert the object according to the conventions of Python built-in <code>hex()</code>, or * <code>oct()</code>. The object's <code>__index__</code> method is called, and is responsible * for raising the appropriate error (which the base {@link PyObject#__index__()} does). * * @param number to convert * @return PyString converted result */ formatNumber(number, spec) { const f = new this.constructor(spec); f.format(parseInt(number)); return f.getResult(); } // NOTE: removed the Traditional inner class because we're doing the {}-style formatting }
JavaScript
class uv2_vertex{static theWord() { return "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\ \n\ vUv2 = uv2;\n\ \n\ #endif"; }}
JavaScript
class Taxi { constructor(position) { this.position = position; this.available = true; this.path = []; this.moving = false; this.lastPosition = this.position; this.stopped = 0; // Measures how long the taxi has been stationary for this.journeysCompleted = 0; // Create taxi in scene this.object = spawnVehicle('taxi', position); } /** * Generates a path to the destination and starts following * @param {Position} destination * @param {Function} cb */ goto(destination, cb) { this.path = bfs(this.position, destination); this.cb = cb; if (this.position.equals(destination)) this.finishRoute(); } /** * Triggers the journey end callback and finds another journey */ finishRoute() { if (this.cb != undefined) this.cb(); if (this.available && journeyQueue.length > 0) journeyQueue[0].search(); } /** * The new position * @param {Position} newPosition */ setPosition(newPosition) { if (newPosition.isOccupied()) { this.moving = false; return false; } this.moving = true; this.stopped = 0; this.lastPosition = this.position; this.lastPosition.setOccupied(false); // Calculate direction travelled for rotation var dX = newPosition.x - this.position.x, dZ = newPosition.z - this.position.z, r = 0; if (dX == 1) r = 1; if (dZ == -1) r = 2; if (dX == -1) r = 3; this.object.rotation.set(0, r * .5 * Math.PI, 0); newPosition.setOccupied(true); this.position = newPosition; var pos = newPosition.getScenePosition(); this.object.position.x = pos.x; this.object.position.z = pos.z; return true; } /** * Remove the taxi */ dispose() { removeFromScene(this.object); this.position.setOccupied(false); taxis.splice(taxis.indexOf(this), 1); } /** * Called upon simulation tick */ update() { if (this.path.length > 0) { // Go along the path if (this.setPosition(this.path[0])) { this.path = this.path.splice(1); if (this.path.length == 0) this.finishRoute(); } else { // Traffic jam resolution // If the taxi is stopped for more than 3 steps, try to reroute if (this.stopped >= 3) { let valid = this.position.getValidMoves(); // Try to move in a direction var moved = this.setPosition(this.position.getRelativePosition(valid.x, 0)); if (!moved) { moved = this.setPosition(this.position.getRelativePosition(0, valid.z)); } if (moved) { this.path = bfs(this.position, this.path[this.path.length - 1]); } } else { this.stopped++; } } } else { let valid = this.position.getValidMoves(); var moveX = true; // Assume we want to move in the x axis if (valid.x == 0) { moveX = false; // We can't move in the x axis, move z } else if (valid.z != 0) { var rnd = Math.random(); // We can move x or z, move randomly in one direction moveX = rnd >= .5; } // Apply the move if (moveX) this.setPosition(this.position.getRelativePosition(valid.x, 0)); else this.setPosition(this.position.getRelativePosition(0, valid.z)); } } }
JavaScript
class Journey { constructor(origin, destination) { this.origin = origin; this.destination = destination; // Cancel journey if price is too high var B = inputs.baseFare.value , Bh = inputs.baseFare.max / 2 , C = inputs.costPerTile.value , Ch = inputs.costPerTile.max / 2 , Cd = 1 - ((C-Ch) / Bh) , M = inputs.maxMultiplier.value , Mh = inputs.maxMultiplier.max , Mp = .9*M/Mh; var cancel = (B > Bh && eventOccurs(B - Bh + Cd * Mp, Bh)) || (C > Ch && eventOccurs(C - Ch + Cd * Mp, Ch)); if (!cancel) { // Spawn a start and end marker this.startMarker = spawnMarker('startJourney', origin); this.endMarker = spawnMarker('endJourney', destination); this.startTime = clock; this.search(); } else { this.dispose(); } } /** * Estimates the price of the journey based on distance */ calculatePriceEstimate() { var p = journeyQueue.length / getMaxJourneys(); var multiplier = p * p * (inputs.maxMultiplier.value - 1) + 1; return multiplier * inputs.costPerTile.value; } /** * Search for an available taxi */ search() { // Remove this journey from the backlog var index = journeyQueue.indexOf(this); if (index >= 0) journeyQueue.splice(i, 1); // Find the closest available taxi taxi var min = Number.POSITIVE_INFINITY; var taxiIndex = -1; for (var i = 0; i < taxis.length; i++) { if (taxis[i].available == false) continue; var dist = taxis[i].position.distanceTo(this.origin); if (dist < min) { min = dist; taxiIndex = i; } } // Re-add this taxi to the queue if there are no available taxis if (taxiIndex == -1) { journeyQueue.push(this); return; } // Tell the taxi to pick up this journey this.taxi = taxis[taxiIndex]; var road = calculateAdjacentRoadTile(this.origin); this.taxi.available = false; this.taxi.goto(road, this.pickupCallback.bind(this)); } /** * Callback when a passenger is picked up */ pickupCallback() { // Remove the start marker from the scene removeFromScene(this.startMarker); this.startMarker = undefined; this.origin.setOccupied(false); // Calculate the destination position the taxi should travel to var road = calculateAdjacentRoadTile(this.destination); this.taxi.goto(road, this.endJourney.bind(this)); // Update the pickup time output this.pickupTime = clock; var diff = this.pickupTime - this.startTime; var newAvg = (outputs.pickUpTime.value * pickupsCompleted + diff) / (pickupsCompleted + 1); setOutput('pickUpTime', newAvg); pickupsCompleted++; } /** * Callback when a passenger reaches the destination */ endJourney() { removeFromScene(this.endMarker); this.endMarker = undefined; this.destination.setOccupied(false); this.taxi.available = true; this.endTime = clock; var diff = this.endTime - this.pickupTime; var maxCost = inputs.maxMultiplier.value; var easing = function (t) { return t * t; }; var currency = inputs.costPerTile.value / 10; var extra = diff * easing(journeyQueue.length / getMaxJourneys()) * (maxCost - 1); var profit = inputs.baseFare.value + (diff + extra) * currency; modifyOutput('profit', profit); grossProfit += profit; modifyOutput('journeysCompleted', 1); setOutput('profitPerJourney', grossProfit / outputs.journeysCompleted.value); journeys.splice(journeys.indexOf(this), 1); } /** * Called on simulation tick */ update() { // Scale up the size of the start and end markers var diff = clock - this.startTime; var newY = 1 + (3 * diff / 500); if (this.startMarker != undefined) { this.startMarker.scale.y = newY; this.startMarker.position.y = (newY) / 1.6 - .22; } if (this.endMarker != undefined) { this.endMarker.scale.y = newY; this.endMarker.position.y = (newY) / 1.6 - .22; } } /** * Dispose of a taxi */ dispose() { // Update the taxi state if (this.taxi != undefined) { this.taxi.available = true; this.taxi.path = []; } // Increment the 'missed' output modifyOutput('missed', 1); // Remove the start and end markers if applicable if (this.startMarker != undefined) { removeFromScene(this.startMarker); } if (this.endMarker != undefined) { removeFromScene(this.endMarker); } this.origin.setOccupied(false); this.destination.setOccupied(false); // Remove this journey from the backlog var journeyIndex = journeys.indexOf(this); if (journeyIndex >= 0) journeys.splice(journeyIndex, 1); else { // Ensure it isn't added after the constructor has yielded setTimeout(() => { journeyIndex = journeys.indexOf(this); if (journeyIndex >= 0) journeys.splice(journeyIndex, 1); }, 1000); } var queueIndex = journeyQueue.indexOf(this); if (queueIndex >= 0) journeyQueue.splice(queueIndex, 1); } }
JavaScript
class ChatService extends BaseService { constructor() { super('message'); } /** * Pull the current list of channels from the server * * @return {Promise} Promise that resolve to the list of channels */ getChannels() { return new Promise((resolve, reject) => { iosocket.get('/message/channels', (resData, jwres) => { if(jwres.error) { return reject(new ApiError(jwres)); } return resolve(resData); }); }); } }
JavaScript
class AnswerOption extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { selected: false }; } /** * capture the extraneous label click event * * See https://stackoverflow.com/questions/38957978/react-i-cant-stop-propagation-of-a-label-click-within-a-table * Yeah non-obvious :-( * * @param {event} e */ stopBubble(e) { if (e && e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble = true; } } /** * handle the user clicking within the AnswerOption * * a click toggles the checked attribute for the input and the * selected state for this component instance * * A click also reports the state change up the chain * If the question is multi, report the change to onItemSelected * Else treat the change as onQuestionAnswered * * @param {event} event */ handleClick(event) { this.stopBubble(event); let el = document.getElementById(this.props.id); if ( el ) { // toggle the input checked state el.checked = !el.checked; // toggle the component state this.setState( previousState => { return { selected: !previousState.selected }; }); if (!this.props.multi) { // if user can only pick one item, answered this.props.onQuestionAnswered(this.props.type); } else { // play a sound if multi let selectSoundSrc = this.props.answerSoundSrc || null; playSound(selectSoundSrc); // otherwise keep tabs on which items are selected this.props.onItemSelected(this.props.id, this.props.type); } } return false; } render() { let questionOptionClass = "radioCustomButton"; let isSelected = this.state.selected; let ulClasses = "answerOption" + (isSelected ? " answerSelected" : ""); let optionImage = null; if (this.props.imageSrc) { ulClasses += " imgAnswerOption"; optionImage = ( <div className="answerOptionImage"> <img src={this.props.imageSrc} alt={this.props.answer} /> </div> ); } return ( <li className={ulClasses} onClick={this.handleClick}> <div className="answerOptionContainer"> <input type="checkbox" className={questionOptionClass} defaultChecked={isSelected} id={this.props.id} value={this.props.type} /> <label className="radioCustomLabel" htmlFor={this.props.id} onClick={this.stopBubble.bind(this)}> {this.props.content} </label> </div> {optionImage} </li> ); } }
JavaScript
class Input { /** * Used to check user message and decide how to respond. * @param {String} message - received message from the user. */ constructor(message) { this.message = message; } /** * @return {Boolean} If received message is '/start'. */ start() { return this.message === '/start'; } /** * @return {Boolean} If received message is '/watch_all_builds'. */ watchAllBuilds() { return this.message === '/watch_all_builds'; } /** * @return {Boolean} If received message is '/watch_only_failing_builds'. */ watchOnlyFailingBuilds() { return this.message === '/watch_only_failing_builds'; } /** * @return {Boolean} If received message is '/how'. */ isHelp() { return this.message === '/help'; } /** * @return {Boolean} If received message is '/link'. */ isLink() { return this.message === '/link'; } /** * @return {Boolean} If received message is '/start_watching'. */ isStart() { return this.message === '/start_watching'; } /** * @return {Boolean} If received message is '/stop_watching'. */ isStop() { return this.message === '/stop_watching'; } /** * @return {Boolean} If received message includes valid Travis-CI link. */ isValidLink() { return /https:\/\/travis-ci\.org\/\S+\/\S+$/.test(this.message); } }
JavaScript
class CandyGrid { constructor() { /** * @name candies * @memberof CandyGrid * @type Object - [{id: number, piece: Phaser.GameObject}] */ this.candies = []; // Get array value and asign zero, example: {candy-blue: 0, candy-orange: 0, ...} this.candies_availables = candies.reduce((acc, curr) => (acc[curr] = 0, acc), {}); this.actual_candy_to_search = ''; this.initial_candy_position = { x: 0, y: 0 }; } setScene(scene) { this.scene = scene; this.marimbafx = this.scene.sound.add('marimba'); this.marimbaReversefx = this.scene.sound.add('marimba_reverse'); } setPosition(initial_position) { this.initial_candy_position = initial_position; } createNewGrid() { if(this.candies.length > 0) { this.marimbaReversefx.play(); this.scene.tweens.add({ targets: this.candies.map(candy => candy.piece), ease: Phaser.Math.Easing.Linear.In, alpha: 0, scale: 0, duration: 500, delay: (e, o, u, i) => 50 * i, onComplete: () => { this.candies.map((candy) => { candy.piece.destroy(); }); this.reset(); this.createStartGrid(); } }); } else { this.createStartGrid(); } } // Help to create the grid of GameObjects createStartGrid() { this.marimbafx.play(); this.actual_candy_to_search = this.selectRandomCandyToFind(); const distribution_candy = [ { row: Phaser.Math.Between(0, 1), column: Phaser.Math.Between(0, 2) }, { row: Phaser.Math.Between(2, 3), column: Phaser.Math.Between(3, 5) }, { row: Phaser.Math.Between(4, 5), column: Phaser.Math.Between(0, 5) } ]; this.reset(); for (let y = 0; y < grid_size.height; y++) { for (let x = 0; x < grid_size.width; x++) { let candy_random = this.selectRandomCandyToGrid(this.actual_candy_to_search); const candy_x = (x * 40) + this.initial_candy_position.x + 20; const candy_y = (y * 40) + this.initial_candy_position.y + 20; let put_candy_to_search = ''; if(distribution_candy.length > 0) { if(distribution_candy[0].row === y && distribution_candy[0].column === x) { put_candy_to_search = this.actual_candy_to_search; distribution_candy.shift(); } else { put_candy_to_search = candy_random; } } else { put_candy_to_search = candy_random; } const image = this.scene.add.image(candy_x, candy_y, put_candy_to_search) .setName(`${put_candy_to_search}_${IdGenerator()}`) .setInteractive() .setScale(0) .setDepth(candy_y); this.push({ id: GetId(image.name), piece: image, name: GetName(image.name) }); this.scene.tweens.add({ targets: image, ease: Phaser.Math.Easing.Linear.Out, alpha: 1, scale: 1, delay: 50 * (x + y) }); } } this.scene.events.emit('grid-complete', this.actual_candy_to_search); } // Only used the first time push(CandyObject) { this.candies.push(CandyObject); } /** * * * @return {Array<Phaser.GameObjects.Image>} - [GameObject, GameObject, ...] * @memberof CandyGrid */ getCandies() { return this.candies.map(candy => candy.piece); } /** * Get candy by id * * @param {*} id * @return {CandyObject} * @memberof CandyGrid */ getCandy(id) { return this.candies.find((CandyObject) => { return CandyObject.id === id; }); } selectRandomCandyToGrid(candy_to_find) { const random_candy = Phaser.Utils.Array.GetRandom(candies); if(candy_to_find === random_candy) { return this.selectRandomCandyToGrid(candy_to_find); } else { return random_candy; } } // Select one candy to find selectRandomCandyToFind() { this.counter_to_put_candies = 3; return Phaser.Utils.Array.GetRandom(candies); } reset() { this.candies = []; this.candies_availables = candies.reduce((acc, curr) => (acc[curr] = 0, acc), {}); } }
JavaScript
class RedisGraphQLPubSub { constructor(opts) { this.opts = opts; this.publisher = redis.createClient(); this.subscriber = redis.createClient(); this.subscriberRefs = {}; this.subscriptionRefs = {}; this.subId = 0; this.subscribe = this.subscribe.bind(this); this.unsubscribe = this.unsubscribe.bind(this); this.publish = this.publish.bind(this); this.returnAsyncIterator = this.returnAsyncIterator.bind(this); this.publisher.on('error', err => console.log('Redis publisher error: ', err)); this.subscriber.on('error', err => console.log('Redis subscriber error: ', err)); // this.subscriber.on('message', this._onMessage.bind(this)); } // _onMessage(topic, message) { // console.log('_MESSAGE: ', message); // const subscribers = this.subscriptionRefs[topic]; // if (subscribers && message) { // const parsed = JSON.parse(message); // subscribers.forEach(id => this.subscriberRefs[id].handler(parsed)); // } // } subscribe(topic, handler, opts) { console.log('I SUBSCRIBING!: ', topic); this.subId += 1; this.subscriberRefs[this.subId] = { topic, handler }; if (!this.subscriptionRefs[topic]) { this.subscriptionRefs[topic] = []; } if (this.subscriptionRefs[topic].length === 0) { return new Promise((resolve, reject) => { this.subscriber.subscribe(topic, (error) => { if (error) { delete this.subscriberRefs[this.subId]; reject(error); } else { this.subscriptionRefs[topic].push(this.subId); resolve(this.subId); } }); }) } else { this.subscriptionRefs[topic].push(this.subId); return Promise.resolve(this.subId); } } unsubscribe(topic, subId) { if (!this.subscriberRefs[topic] || !this.subscriptionRefs[subId]) { return; } this.subscriptionRefs[topic] = this.subscriptionRefs[topic].filter(s => s !== subId); delete this.subscriberRefs[subId]; if (!this.subscriberRefs[topic].length) { this.subscriber.unsubscribe(topic); } } publish(topic, message) { return this.publisher.publish(topic, message); } returnAsyncIterator(subscriptionName) { let resolver; this.subscriber.on('message', (topic, message) => { message = JSON.parse(message); if (resolver && subscriptionName === topic) { resolver(message); } }); this.subscriber.subscribe(subscriptionName); return { next() { return new Promise(resolve => { resolver = resolve; }) .then(value => ({ value, done: false })); }, throw(err) { return Promise.reject(err); }, return() { return Promise.resolve({ value: undefined, done: true }); }, [$$asyncIterator]() { return this; } }; } }
JavaScript
class AdminUsers extends Component{ constructor(props){ super(props); this.state = { user:'', users:[], data:{}, pagination:[], orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:2, type:'normal', showChange:false, } this.getAdminUsersStatistics = this.getAdminUsersStatistics.bind(this); this.getAdminUsers = this.getAdminUsers.bind(this); this.makePagination = this.makePagination.bind(this); this.orderByLastname = this.orderByLastname.bind(this); this.orderByFirstname = this.orderByFirstname.bind(this); this.orderByFaculty = this.orderByFaculty.bind(this); this.orderByType = this.orderByType.bind(this); this.orderByRegistration = this.orderByRegistration.bind(this); this.chooseLastnameArrow = this.chooseLastnameArrow.bind(this); this.chooseFirstnameArrow = this.chooseFirstnameArrow.bind(this); this.chooseRegistrationArrow = this.chooseRegistrationArrow.bind(this); this.chooseTypeArrow = this.chooseTypeArrow.bind(this); this.chooseFacultyArrow = this.chooseFacultyArrow.bind(this); this.loadPage = this.loadPage.bind(this); this.loadNext = this.loadNext.bind(this); this.loadLast = this.loadLast.bind(this); this.loadFirst = this.loadFirst.bind(this); this.loadPrev = this.loadPrev.bind(this); this.isMorePages = this.isMorePages.bind(this); this.isPrevPage = this.isPrevPage.bind(this); this.isNextPage = this.isNextPage.bind(this); this.handleCheck = this.handleCheck.bind(this); this.handleAllCheck = this.handleAllCheck.bind(this); this.removeMarked = this.removeMarked.bind(this); this.handleClose = this.handleClose.bind(this); this.showChange = this.showChange.bind(this); this.changeType = this.changeType.bind(this); this.onChange = this.onChange.bind(this); } componentWillMount(){ const param = { orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:2, }; this.getAdminUsersStatistics(); this.getAdminUsers(param); } /** * This method show Change type pop-up */ showChange(){ this.setState({ showChange: true, }); } /** * This method close Change type pop-up */ handleClose(){ this.setState({ showChange: false, }); } onChange(e){ const {name, value} = e.target; this.setState({[name]: value}); } /** * This method change user's type */ changeType(e){ e.preventDefault(); const thisUrl = url + "api/getAdminUsers"; const data = { type: this.state.type, users: this.state.users, } axios.post(url +'api/adminChangeUserType', data).then(response=> { this.handleClose(); this.loadPage(thisUrl); }) .catch(error=> { }) } /** * This method get statistics about users */ getAdminUsersStatistics(){ axios.get(url + `api/getAdminUsersStatistics`).then(response => { this.setState({ data: response.data, }) }); } /** * This method get users */ getAdminUsers(param ){ axios.get(url + `api/getAdminUsers`,{params:param}).then(response => { this.setState({ users: response.data.data }) this.makePagination(response.data) }); } /** * Pagination * @param {pagination data} data */ makePagination(data){ let pagination = { current_page: data.current_page, last_page:data.last_page, first_page_url:data.first_page_url, last_page_url:data.last_page_url, next_page_url: data.next_page_url, prev_page_url: data.prev_page_url, } this.setState({ pagination: pagination }) } /** * This method remove all marked users */ removeMarked(){ const thisUrl = url + "api/getAdminUsers"; let data = { users: this.state.users, } axios.post(url + 'api/adminRemoveUsers', data) .then(response=> { this.loadPage(thisUrl) }) .catch(error=> { }) } /** * Methods to set filtering object */ orderByLastname(){ if(this.state.orderByLastname == 1){ const param = { orderByLastname:2, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:2, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); }else{ const param = { orderByLastname:1, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:1, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); } } orderByFirstname(){ if(this.state.orderByFirstname == 1){ const param = { orderByLastname:0, orderByFirstname:2, orderByType:0, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:2, orderByType:0, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); }else{ const param = { orderByLastname:0, orderByFirstname:1, orderByType:0, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:1, orderByType:0, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); } } orderByType(){ if(this.state.orderByType == 1){ const param = { orderByLastname:0, orderByFirstname:0, orderByType:2, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:2, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); }else{ const param = { orderByLastname:0, orderByFirstname:0, orderByType:1, orderByFaculty:0, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:1, orderByFaculty:0, orderByRegistration:0, }) this.getAdminUsers(param); } } orderByFaculty(){ if(this.state.orderByFaculty == 1){ const param = { orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:2, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:2, orderByRegistration:0, }) this.getAdminUsers(param); }else{ const param = { orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:1, orderByRegistration:0, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:1, orderByRegistration:0, }) this.getAdminUsers(param); } } orderByRegistration(){ if(this.state.orderByRegistration == 1){ const param = { orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:2, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:2, }) this.getAdminUsers(param); }else{ const param = { orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:1, }; this.setState({ orderByLastname:0, orderByFirstname:0, orderByType:0, orderByFaculty:0, orderByRegistration:1, }) this.getAdminUsers(param); } } /** * Render arrows */ chooseLastnameArrow(){ if(this.state.orderByLastname == 1 ){ return "sortArrow"; }else if(this.state.orderByLastname == 2 ){ return "sortDownArrow"; } return "sort"; } chooseFirstnameArrow(){ if(this.state.orderByFirstname == 1){ return "sortArrow"; }else if(this.state.orderByFirstname == 2){ return "sortDownArrow"; } return ""; } chooseTypeArrow(){ if(this.state.orderByType == 1){ return "sortArrow"; }else if(this.state.orderByType == 2){ return "sortDownArrow"; } return ""; } chooseFacultyArrow(){ if(this.state.orderByFaculty == 1){ return "sortArrow"; }else if(this.state.orderByFaculty == 2){ return "sortDownArrow"; } return ""; } chooseRegistrationArrow(){ if(this.state.orderByRegistration == 1){ return "sortArrow"; }else if(this.state.orderByRegistration == 2){ return "sortDownArrow"; } return ""; } loadPage(thisUrl){ const param = { orderByLastname:this.state.orderByLastname, orderByFirstname:this.state.orderByFirstname, orderByType:this.state.orderByType, orderByFaculty:this.state.orderByFaculty, orderByRegistration:this.state.orderByRegistration, }; axios.get(thisUrl,{params:param}).then(response => { this.setState({ users: response.data.data, }) this.makePagination(response.data) }); } loadNext(){ this.loadPage(this.state.pagination.next_page_url); } loadPrev(){ this.loadPage(this.state.pagination.prev_page_url); } loadLast(){ this.loadPage(this.state.pagination.last_page_url); } loadFirst(){ this.loadPage(this.state.pagination.first_page_url); } isPrevPage(e){ if(this.state.pagination.prev_page_url == null){ return ; }else{ let value = this.state.pagination.current_page - 1; return <li className="page-item"><a className="page-link" href="#" onClick={this.loadPrev}>{value}</a></li>; } } isNextPage(){ if(this.state.pagination.next_page_url == null){ return ; }else{ let value = this.state.pagination.current_page +1; return <li className="page-item"><a className="page-link" href="#" onClick={this.loadNext}>{value}</a></li>; } } /** * This method render pagination buttons */ isMorePages(){ if (this.state.pagination.next_page_url != null || this.state.pagination.prev_page_url != null){ return( <nav aria-label="Page navigation example"> <ul className="pagination justify-content-center"> <li className="page-item"> <a className="page-link" onClick={this.loadFirst} aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span className="sr-only">Previous</span> </a> </li> {this.isPrevPage()} <li className="page-item"><a className="page-link ActualPage" href="#" >{this.state.pagination.current_page}</a></li> {this.isNextPage()} <li className="page-item"> <a className="page-link" aria-label="Next" onClick={this.loadLast}> <span aria-hidden="true">&raquo;</span> <span className="sr-only">Next</span> </a> </li> </ul> </nav> ); } } handleCheck( event){ let users = this.state.users; users.forEach(user => { if (user.id == event.target.value){ user.isChecked = event.target.checked; } }) this.setState({ users: users }); } handleAllCheck(event){ let users = this.state.users; users.forEach(user => { user.isChecked = event.target.checked; }) this.setState({ users: users }); } render(){ return( <div className="adminPage"> <div> <AdminNavbar history={this.props.history} DeleteUser={this.props.DeleteUser}/> <div className="container-fluid"> <div className="row"> <div className="col-md-2"> </div> <div className="mt-30 col-md-10 col-lg-10 px-4 "> <div className="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 className="h2">Users</h1> </div> <div className="row"> <div className="col-xl-3 col-md-6 mb-4"> <div className="card border-left-dashboard shadow h-100 py-2"> <div className="card-body"> <div className="row no-gutters align-items-center"> <div className="col mr-2"> <div className=" text-dashboard mb-1">All</div> <div className="h5 mb-0 text-count">{this.state.data.all}</div> </div> </div> </div> </div> </div> <div className="col-xl-3 col-md-6 mb-4"> <div className="card border-left-dashboard shadow h-100 py-2"> <div className="card-body"> <div className="row no-gutters align-items-center"> <div className="col mr-2"> <div className=" text-dashboard mb-1">From university</div> <div className="h5 mb-0 text-count">{this.state.data.university}</div> </div> </div> </div> </div> </div> <div className="col-xl-3 col-md-6 mb-4"> <div className="card border-left-dashboard shadow h-100 py-2"> <div className="card-body"> <div className="row no-gutters align-items-center"> <div className="col mr-2"> <div className=" text-dashboard mb-1">Supervisors</div> <div className="h5 mb-0 text-count">{this.state.data.supervisor}</div> </div> </div> </div> </div> </div> <div className="col-xl-3 col-md-6 mb-4"> <div className="card border-left-dashboard shadow h-100 py-2"> <div className="card-body"> <div className="row no-gutters align-items-center"> <div className="col mr-2"> <div className=" text-dashboard mb-1">Somebody else</div> <div className="h5 mb-0 text-count">{this.state.data.normal}</div> </div> </div> </div> </div> </div> </div> <div className="table-responsive col-md-12 col-lg-12"> <table className="table table-striped table-sm" id="dataTable" width="100%" cellSpacing="0"> <thead> <tr> <th></th> <th className="headerHover" onClick={this.orderByLastname} data-toggle="tooltip" data-placement="bottom" title="Order by lastname">Lastname <span className={this.chooseLastnameArrow() } /></th> <th className="headerHover" onClick={this.orderByFirstname} data-toggle="tooltip" data-placement="bottom" title="Order by firstname">Firstname <span className={this.chooseFirstnameArrow() } /></th> <th className="headerHover" onClick={this.orderByType} data-toggle="tooltip" data-placement="bottom" title="Order by type">Type <span className={this.chooseTypeArrow() } /></th> <th className="headerHover" onClick={this.orderByFaculty} data-toggle="tooltip" data-placement="bottom" title="Order by faculty">Faculty <span className={this.chooseFacultyArrow() } /></th> <th className="headerHover" onClick={this.orderByRegistration} data-toggle="tooltip" data-placement="bottom" title="Order by registration date">Registration<span className={this.chooseRegistrationArrow() } /></th> <th className="headerHover">Action</th> </tr> </thead> <tfoot> <tr> <th><input onChange={this.handleAllCheck} type="checkbox" /> </th> <th>All </th> <th></th> <th></th> <th></th> <th></th> </tr> </tfoot> <tbody> {this.state.users.map(user => ( <tr key={user.id}> <td><input onChange={this.handleCheck} type="checkbox" checked={user.isChecked} value={user.id} /></td> <td>{user.lastname}</td> <td>{user.firstname} </td> <td>{user.type}</td> <td>{user.faculty}</td> <td>{user.created}</td> <td><UsersPopup user={user} getData={this.loadPage}/></td> </tr> ))} </tbody> </table> <button type="button" className="btn button-admin ml-10" onClick={this.removeMarked}>Remove</button> <button type="button" className="btn button-admin ml-10" onClick={this.showChange}>Change type</button> {this.isMorePages()} </div> </div> </div> </div> </div> <Modal show={this.state.showChange} onHide={this.handleClose}> <Modal.Body> <button type="button" class="close" onClick={this.handleClose}> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <div className="text-center"> <h3><i className="fa fa-lock fa-4x"></i></h3> <h2 className="text-center">Change users type?</h2> <p>You can change type of marked users type here.</p> <div className="panel-body"> <form className="form" method="post" onSubmit={this.changeType}> <div className="form-group"> <label className="FormField_Label" htmlFor="inputState">Type</label> <select id="inputState" className="form-control" placeholder="Choose some type" name="type" ref="type" value={this.state.type} onChange={this.onChange} > <option value='normal'>normal</option> <option value='university'>university</option> <option value='supervisor'>supervisor</option> <option value='admin'>admin</option> </select> </div> <div className="form-group"> <Button className="FormField_Button" type="submit" > Change Type </Button> </div> </form> </div> </div> </Modal.Body> </Modal> </div> ) } }
JavaScript
class Histogram extends Widget { //region Config static get type() { return 'histogram'; } static get $name() { return 'Histogram'; } static get defaultConfig() { return { /** * An array of data objects used to drive the histogram. The property/properties used * are defined in the {@link #config-series} option. * @config {Object[]} * @default */ data : null, /** * The values to represent in bar form. * @config {Number[]} */ values : null, /** * Each item in the array must contain two properties: * - `type` A String, either `'bar'` or `'outline'` * - `field` A String, the name of the property to use from the data objects in the {@link #config-data} option. * @config {Object[]} */ series : null, /** * By default, the bars are scaled based upon the detected max value across all the series. * A specific top value to represent the 100% height may be configured. * @config {Number} */ topValue : null, element : { children : [{ ns, tag : 'svg', reference : 'svgElement', width : '100%', height : '100%', preserveAspectRatio : 'none', children : [{ ns, tag : 'g', reference : 'scaledSvgGroup' }, { ns, tag : 'g', reference : 'unscaledSvgGroup' }] }] }, /** * By default, all bars are rendered, even those with zero height. Configure this as `true` * to omit zero height bars. * @config {Number} */ omitZeroHeightBars : null, monitorResize : true, /** * A Function which returns a CSS class name to add to a rectangle element. * The following parameters are passed: * @param {Object} series - The series being rendered * @param {Object} rectConfig - The rectangle configuration object * @param {Object} datum - The datum being rendered * @param {Number} index - The index of the datum being rendered * @config {Function} */ getRectClass : null, /** * A Function which returns the tooltip text to display when hovering a bar. * The following parameters are passed: * @param {Object} series - The series being rendered * @param {Object} rectConfig - The rectangle configuration object * @param {Object} datum - The datum being rendered * @param {Number} index - The index of the datum being rendered * @config {Function} */ getBarTip : null, /** * A Function which returns the text to render inside a bar. * The following parameters are passed: * @param {Object} datum - The datum being rendered * @param {Number} index - The index of the datum being rendered * @config {Function} */ getBarText : null }; } //endregion //region Init construct(config) { super.construct(config); this.scheduleRefresh = this.createOnFrame(this.refresh, [], this, true); this.refresh(); } set tip(tip) { if (this.tip) { this.tip.destroy(); } if (tip) { this._tip = new Tooltip(Object.assign({ owner : this, forElement : this.svgElement, forSelector : 'rect', listeners : { beforeShow : 'up.onBeforeTipShow' } }, tip)); } else { this._tip = null; } } onElementResize() { super.onElementResize(...arguments); const svgRect = this.svgElement.getBoundingClientRect(); this.scaledSvgGroup.setAttribute('transform', `scale(${svgRect.width} ${svgRect.height})`); } onBeforeTipShow({ source : tip }) { const index = parseInt(tip.activeTarget.dataset.index); tip.html = tip.contentTemplate({ histogram : this, index }); } set series(value) { const me = this, series = me._series = {}; for (const id in value) { // Providing // // "series" : { // "foo" : false // ... // // disables the "foo" serie (that could be defined on a prototype level for example) if (value[id] !== false) { const data = series[id] = Object.assign({}, value[id]); // support type & field provided on config prototype level if (!data.type && value[id].type) { data.type = value[id].type; } if (!data.field && value[id].field) { data.field = value[id].field; } if (!('order' in series)) { data.order = typePrio[data.type]; } data.id = id; } } me.scheduleRefresh(); } get series() { return this._series; } set data(data) { const me = this; // TODO: // me.topValue = undefined; me._data = data; // Calculate the top value from all the series if (!me.topValue) { const fields = Object.values(me.series).map(getField); for (let i = 0, { length } = data; i < length; i++) { for (let j = 0, { length } = fields; j < length; j++) { me.topValue = Math.max(me.topValue || 0, data[i][fields[j]]); } } } me.scheduleRefresh(); } get data() { return this._data; } set topValue(value) { this._topValue = value; this.scheduleRefresh(); } get topValue() { return this._topValue; } // Must exist from the start because configuration setters call it. // Once configured, will be replaced with a function which schedules a refresh for the next animation frame. scheduleRefresh() { } refresh() { const me = this, { series, _tip } = me, histogramElements = []; for (const id in series) { const data = series[id], elConfig = me[`draw${StringHelper.capitalizeFirstLetter(data.type)}`](data); if (Array.isArray(elConfig)) { histogramElements.push.apply(histogramElements, elConfig); } else { histogramElements.push(elConfig); } } histogramElements.sort(byDatasetOrder); DomSync.syncChildren({ domConfig : { children : histogramElements }, configEquality : returnFalse }, me.scaledSvgGroup); DomSync.syncChildren({ domConfig : { children : me.drawText() } }, me.unscaledSvgGroup); if (_tip && _tip.isVisible) { me.onBeforeTipShow({ source : _tip }); } } drawBar(series) { const me = this, { topValue, data, omitZeroHeightBars, barStyle } = me, { field, order } = series, defaultWidth = 1 / data.length, children = []; let width; for (let index = 0, x = 0, { length } = data; index < length; index++, x += width) { const datum = data[index], value = datum[field], // limit height with topValue otherwise the histogram looks fine // yet the bar tooltip picks wrong Y-coordinate and there is an empty space between it and the bar height = (value > topValue ? topValue : value) / topValue, y = 1 - height, rectConfig = (datum.rectConfig = { ns, tag : 'rect', dataset : {} }); // use either provided width or the calculated value width = datum.width || defaultWidth; if (barStyle) { rectConfig.style = barStyle; } else { delete rectConfig.style; } Object.assign(rectConfig.dataset, { index, order }); Object.assign(rectConfig, { x, y, width, height, class : me.callback('getRectClass', me, [series, rectConfig, datum, index]) }); const barTip = me.callback('getBarTip', me, [series, rectConfig, datum, index]); if (barTip) { rectConfig.dataset.btip = barTip; } else { delete rectConfig.dataset.btip; } if (height || !omitZeroHeightBars) { children.push(rectConfig); } } return children; } drawOutline(series) { const me = this, { topValue, data } = me, { field, order } = series, defaultWidth = 1 / data.length, coords = ['M 0,1'], result = series.outlineElement || (series.outlineElement = { ns, tag : 'path', dataset : { order } }); let barWidth, command1 = 'M', command2 = 'L'; for (let i = 0, x = 0, { length } = data; i < length; i++) { const barHeight = 1 - data[i][field] / topValue; // use either provided with or the calculated value barWidth = data[i].width || defaultWidth; coords.push(`${command1} ${x},${barHeight} ${command2} ${x += barWidth},${barHeight}`); command1 = command2 = ''; } // coords.push('1,1'); result.d = coords.join(' '); return result; } drawText() { const me = this, { data } = me, defaultWidth = 1 / data.length, y = '100%', unscaledSvgGroups = []; for (let index = 0, width, x = 0, { length } = data; index < length; index++, x += width) { width = data[index].width || defaultWidth; const barText = me.callback('getBarText', me, [data[index], index]); if (barText) { unscaledSvgGroups.push({ ns, tag : 'text', className : 'b-bar-legend', html : me.callback('getBarText', me, [data[index], index]), x : `${(x + width / 2) * 100}%`, y, dataset : { index } }); } } return unscaledSvgGroups; } //endregion // Injectable method getBarText(datum, index) { return ''; } // Injectable method getBarTip(series, rectConfig, datum, index) { } // Injectable method getRectClass(series, rectConfig, datum, index) { return ''; } }
JavaScript
class Guild { /** * Instantiates a new Guild */ constructor (discordGuild) { this.discordGuild = discordGuild // this.audioPlayer = AudioPlayer.getForGuild(discordGuild) this.data = null // Handle external changes Core.data.subscribe('event.GuildData', message => { if (message.type === 'updated' && message.guild === this.discordGuild.id) { this.init() } }) } /** * Initializes guild data */ async init () { const data = await Core.data.get(`Guild:${this.discordGuild.id}`) this.data = Object.assign(Guild.defaultData(), data, { save: () => this.saveData() }) return this } /** * Should return data that will be used for default on new guilds * @return {object} */ static defaultData () { return {} } /** * Saves guild data */ async saveData () { await Core.data.set(`Guild:${this.discordGuild.id}`, this.data) // Notify other instances about the change Core.data.set('event.GuildData', { type: 'updated', guild: this.discordGuild.id }) } }
JavaScript
class GuildManager { constructor () { this._guilds = {} this.Guild = Guild } getGuild (guild) { if (!guild) return Promise.resolve({ data: { }, saveData () { } }) if (!this._guilds[guild.id]) this._guilds[guild.id] = new Guild(guild) if (!this._guilds[guild.id].data) return this._guilds[guild.id].init() return Promise.resolve(this._guilds[guild.id]) } }
JavaScript
class Login extends FunctionBrick { /** * @override */ setupUpdate(context, runCoreUpdate, clear) { const [incomingFlow, incomingUser, incomingPassword] = this.getInputs(); // Listen on `user` and 'password' input updates. Null or undefined value will be considered as empty strings. let username = ''; let password = ''; context.observe(incomingUser, true).subscribe((inputValue) => { username = inputValue !== null ? inputValue : ''; }); context.observe(incomingPassword, true).subscribe((inputValue) => { password = inputValue !== null ? inputValue : ''; }); // Run runCoreUpdate only when incoming flow is triggered. context.observe(incomingFlow, true).subscribe((timestamp) => { if (timestamp) { // Execute the action only if the control flow has a value. runCoreUpdate([username, password]); } else { clear(); } }); } /** * Executed when the control flow is triggered * * @protected * @param {!Context} context * @param {string} username * @param {string} password * @param {function(number)} onSuccess * @param {function(!ErrorFlow)} dispatchErrorFlow * @param {function(number)} onFailure */ onUpdate(context, [username, password], [onSuccess, onFailure, dispatchErrorFlow]) { Auth.loginSRP(username, password).then(() => { const currentState = Auth.getState() switch (currentState) { case AuthState.AUTHENTICATED: onSuccess(Date.now()); break; case AuthState.GUEST: // Invalid credentials onFailure(Date.now()); break; case AuthState.ERROR: // Authentication error dispatchErrorFlow(ErrorFlow.create('Authentication error', 2)); break; case AuthState.DISCONNECTED: // Server unreachable dispatchErrorFlow(ErrorFlow.create('The server is unreachable', 1)); break; default: } }).catch(() => { dispatchErrorFlow(ErrorFlow.create('Authentication error', 2)); }) } }
JavaScript
class FileDatasource extends TextDatasource { /** * Constructor for the file datasource * @param {Credentials} credentials The credentials instance with which to * use to configure the datasource */ constructor(credentials) { super(credentials); const { data: credentialData } = getCredentials(credentials.id); const { datasource: datasourceConfig } = credentialData; const { path } = datasourceConfig; this._filename = path; this.mkdir = pify(fs.mkdir); this.readFile = pify(fs.readFile); this.stat = pify(fs.stat); this.unlink = pify(fs.unlink); this.writeFile = pify(fs.writeFile); this.type = "file"; fireInstantiationHandlers("file", this); } get baseDir() { return path.dirname(this.path); } /** * The file path * @type {String} * @memberof FileDatasource */ get path() { return this._filename; } /** * Ensure attachment paths exist * @returns {Promise} * @memberof FileDatasource * @protected */ async _ensureAttachmentsPaths(vaultID) { const attachmentsDir = path.join(this.baseDir, ".buttercup", vaultID); await this.mkdir(attachmentsDir, { recursive: true }); } /** * Get encrypted attachment * - Loads the attachment contents from a file into a buffer * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @returns {Promise.<Buffer|ArrayBuffer>} * @memberof FileDatasource */ async getAttachment(vaultID, attachmentID) { await this._ensureAttachmentsPaths(vaultID); const attachmentPath = path.join(this.baseDir, ".buttercup", vaultID, `${attachmentID}.${ATTACHMENT_EXT}`); return this.readFile(attachmentPath); } /** * Get attachment details * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @returns {AttachmentDetails} The attachment details * @memberof FileDatasource */ async getAttachmentDetails(vaultID, attachmentID) { await this._ensureAttachmentsPaths(vaultID); const filename = `${attachmentID}.${ATTACHMENT_EXT}`; const filePath = path.join(this.baseDir, ".buttercup", vaultID, filename); const fileStat = await this.stat(filePath); return { id: attachmentID, vaultID, name: filename, filename: filePath, size: fileStat.size, mime: null }; } /** * Load from the filename specified in the constructor using a password * @param {Credentials} credentials The credentials for decryption * @returns {Promise.<LoadedVaultData>} A promise resolving with archive history * @memberof FileDatasource */ load(credentials) { return this.hasContent ? super.load(credentials) : this.readFile(this.path, "utf8").then(contents => { this.setContent(contents); return super.load(credentials); }); } /** * Put encrypted attachment data * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @param {Buffer|ArrayBuffer} buffer The attachment data * @param {Object} details * @returns {Promise} * @memberof FileDatasource */ async putAttachment(vaultID, attachmentID, buffer, details) { await this._ensureAttachmentsPaths(vaultID); const attachmentPath = path.join(this.baseDir, ".buttercup", vaultID, `${attachmentID}.${ATTACHMENT_EXT}`); await this.writeFile(attachmentPath, buffer); } /** * Remove an attachment * @param {String} vaultID The ID of the vault * @param {String} attachmentID The ID of the attachment * @returns {Promise} * @memberof FileDatasource */ async removeAttachment(vaultID, attachmentID) { await this._ensureAttachmentsPaths(vaultID); const attachmentPath = path.join(this.baseDir, ".buttercup", vaultID, `${attachmentID}.${ATTACHMENT_EXT}`); await this.unlink(attachmentPath); } /** * Save archive history to a file * @param {Array.<String>} history The archive history to save * @param {Credentials} credentials The credentials to save with * @returns {Promise} A promise that resolves when saving is complete * @memberof FileDatasource */ save(history, credentials) { return super.save(history, credentials).then(encrypted => this.writeFile(this.path, encrypted)); } /** * Whether or not the datasource supports attachments * @returns {Boolean} * @memberof FileDatasource */ supportsAttachments() { return true; } /** * Whether or not the datasource supports bypassing remote fetch operations * @returns {Boolean} True if content can be set to bypass fetch operations, * false otherwise * @memberof FileDatasource */ supportsRemoteBypass() { return true; } }
JavaScript
class SingleConnectionBroadcaster { constructor(sendConnection, opts = _1.DEFAULT_PROVIDER_OPTIONS) { this.sendConnection = sendConnection; this.opts = opts; } getRecentBlockhash(commitment = "processed") { return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { const result = yield this.sendConnection.getRecentBlockhash(commitment); return result.blockhash; }); } /** * Broadcasts a signed transaction. * * @param tx * @param confirm * @param opts * @returns */ broadcast(tx, _a = this.opts) { var { printLogs = true } = _a, opts = (0, tslib_1.__rest)(_a, ["printLogs"]); return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { if (tx.signatures.length === 0) { throw new Error("Transaction must be signed before broadcasting."); } const rawTx = tx.serialize(); if (printLogs) { return new _1.PendingTransaction(this.sendConnection, yield this.sendConnection.sendRawTransaction(rawTx, opts)); } return yield (0, _1.suppressConsoleErrorAsync)(() => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { // hide the logs of TX errors if printLogs = false return new _1.PendingTransaction(this.sendConnection, yield this.sendConnection.sendRawTransaction(rawTx, opts)); })); }); } /** * Simulates a transaction with a commitment. * @param tx * @param commitment * @returns */ simulate(tx, { commitment = "processed", verifySigners = true, } = { commitment: "processed", verifySigners: true, }) { return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { if (verifySigners && tx.signatures.length === 0) { throw new Error("Transaction must be signed before simulating."); } return yield (0, simulateTransactionWithCommitment_1.simulateTransactionWithCommitment)(this.sendConnection, tx, commitment); }); } }
JavaScript
class MultipleConnectionBroadcaster { constructor(connections, opts = _1.DEFAULT_PROVIDER_OPTIONS) { this.connections = connections; this.opts = opts; } getRecentBlockhash(commitment) { var _a; if (commitment === void 0) { commitment = (_a = this.opts.commitment) !== null && _a !== void 0 ? _a : "processed"; } return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { const result = yield Promise.any(this.connections.map((conn) => conn.getRecentBlockhash(commitment))); return result.blockhash; }); } _sendRawTransaction(encoded, options) { return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { return yield Promise.any(this.connections.map((connection) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { return new _1.PendingTransaction(connection, yield connection.sendRawTransaction(encoded, options)); }))); }); } /** * Broadcasts a signed transaction. * * @param tx * @param confirm * @param opts * @returns */ broadcast(tx, _a = this.opts) { var { printLogs = true } = _a, opts = (0, tslib_1.__rest)(_a, ["printLogs"]); return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { if (tx.signatures.length === 0) { throw new Error("Transaction must be signed before broadcasting."); } const rawTx = tx.serialize(); if (printLogs) { return yield this._sendRawTransaction(rawTx, opts); } return yield (0, _1.suppressConsoleErrorAsync)(() => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { // hide the logs of TX errors if printLogs = false return yield this._sendRawTransaction(rawTx, opts); })); }); } /** * Simulates a transaction with a commitment. * @param tx * @param commitment * @returns */ simulate(tx, { commitment = "processed", verifySigners = true, } = { commitment: "processed", verifySigners: true, }) { return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { if (verifySigners && tx.signatures.length === 0) { throw new Error("Transaction must be signed before simulating."); } return yield Promise.any(this.connections.map((connection) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () { return yield (0, simulateTransactionWithCommitment_1.simulateTransactionWithCommitment)(connection, tx, commitment); }))); }); } }
JavaScript
class Application extends eventemitter3_1.default { constructor(options, applicationId, applicationName, instanceId, processingClient, instanceStream, inputSchema, outputSchema) { super(); this._audioClientStreams = []; //#region lifecycle this._state = ApplicationState.Initial; this._concurrency = 0; //#endregion //#region stream reconnects this._healthcheck = async () => { const api = new rest.DiagnosticsApi(this.account, this.log); try { this.log.debug(`requesting a server healthcheck`); await api.getInstanceLimits({ instanceId: this._instanceId }); this.log.debug(`healthcheck ok`); } catch (error) { this.log.warn(`healthcheck found connection issues; trying to reconnect`); this.log.debug(error); if (this._healthcheckIntervalHandle) { clearInterval(this._healthcheckIntervalHandle); this._healthcheckIntervalHandle = undefined; } await this._reconnect(); } }; this._handleStreamError = async (error) => { await this._reconnect(error); }; //#endregion //#region external call handlers // cannot type better because of variance problems // eslint-disable-next-line @typescript-eslint/ban-types this._externals = new Map(); this._handleRpcRequest = async (request) => { const { jobId, requestId, method, parameters } = request; if (this._state !== ApplicationState.Running) { this.emit("error", log_1.logAndReturn(this.log, new errors.Error("application is not running"))); this._processingClient .sendRpcError({ instanceId: this._instanceId, rpcError: { jobId, requestId, method, message: "application instance was not running" }, }) .catch((error) => this.emit("error", error)); return; } const conv = this._activeConversationsByJobId.get(jobId); if (conv === undefined) { this.emit("error", log_1.logAndReturn(this.log, new errors.InternalError())); this._processingClient .sendRpcError({ instanceId: this._instanceId, rpcError: { jobId, requestId, method, message: "internal error" }, }) .catch((error) => this.emit("error", error)); } const externalHandler = this._externals.get(method); if (externalHandler === undefined) { this.emit("error", log_1.logAndReturn(this.log, new errors.ExternalNotFoundError(method))); this._processingClient .sendRpcError({ instanceId: this._instanceId, rpcError: { jobId, requestId, method, message: `external function ${method} not found`, }, }) .catch((error) => this.emit("error", error)); return; } let result; try { result = await externalHandler(parameters, conv); } catch (error) { const errorMessage = (error === null || error === void 0 ? void 0 : error.message) ? String(error.message) : String(error); this.log.warn(`external function error: ${errorMessage}`, error); this._processingClient .sendRpcError({ instanceId: this._instanceId, rpcError: { jobId, requestId, method, message: errorMessage }, }) .catch((error) => this.emit("error", error)); return; } this._processingClient .sendRpcResponse({ instanceId: this._instanceId, rpcResponse: { jobId, requestId, method, result }, }) .catch((error) => this.emit("error", error)); }; this._handleJobTimedOut = (jobId, jobKey) => { this._activeConversationsByJobId.delete(jobId); this.emit("_jobTimedOut", jobId, jobKey); }; this._handleJobRejected = (jobId, jobKey, jobData) => { this._activeConversationsByJobId.delete(jobId); this.emit("_jobRejected", jobId, jobKey, jobData); }; this._handleJobStarting = (jobId, jobKey, jobData) => { this.emit("_jobStarting", jobId, jobKey, jobData); }; this._activeConversationsByJobId = new Map(); this._handleJobFailed = (jobId, jobKey, jobData) => { this._activeConversationsByJobId.delete(jobId); this.emit("_jobFailed", jobId, jobKey, jobData); }; this._handleJobCompleted = (jobId, jobKey, jobData) => { this._activeConversationsByJobId.delete(jobId); this.emit("_jobCompleted", jobId, jobKey, jobData); }; this._handleJobRecordIdReady = (jobId, jobKey, recordId) => { this.emit("_jobRecordIdReady", jobId, recordId); }; this._handleJobAdditionalInformation = (jobId, jobKey, data) => { this.emit("_jobAdditionalInformation", jobId, data); }; this._handleJobEvent = (jobId, jobEvent) => { this.emit("_jobEvent", jobId, jobEvent); }; //#endregion //#region logging this._handleDebugLog = (jobId, message) => { this.log.info(message, { jobId, label: "application" }); this.emit("_jobDebugLog", jobId, message); }; //#endregion //#region stt provider /** * An {@link SttDispatcher} callback that selects a speech-to-text engine * for all new conversations. If not set explicitly, a `"default"` * {@link SttProviderName | STT provider} will be used. * * @deprecated use {@link Conversation.audio.stt} instead */ this.sttDispatcher = () => "default"; //#endregion //#region tts provider /** * A {@link TtsDispatcher} callback that selects a text-to-speech engine * for all new conversations. If not set explicitly, a `"default"` * {@link TtsProviderName | TTS provider} will be used. * * @deprecated use {@link Conversation.audio.tts} instead */ this.ttsDispatcher = () => "default"; /** * A {@link CustomTtsProvider} callback to use when the {@link TtsProviderName | TTS provider} * is set to `"custom"` in {@link Conversation.audio.tts}. */ this.customTtsProvider = () => { // imitates an error thrown by a user-supplied connection provider // thus, no custom errors or explicit logging here; it all happens at call site throw new Error("customTtsProvider was not set"); }; this._handleTtsRequest = async (request) => { const { requestId, messageId, text, voiceInfo } = request; try { if (this.customTtsProvider === undefined) { throw new Error("no TTS provider is set"); } let result = await this.customTtsProvider(text, voiceInfo); // have to use duck typing since Fetch API may not be present if (!(result instanceof audio.Audio)) { result = await audio.fromFetchResponse(result); } await this._externalTtsClient.sendAudioData({ instanceId: this._instanceId, requestId, messageId, audio: { format: result._format, data: result._data, }, }); } catch (error) { try { await this._externalTtsClient.sendAudioError({ instanceId: this._instanceId, requestId, messageId, error: { type: error.name, message: error.message, details: "" }, }); } catch (error) { this.emit("error", error); } if (error instanceof errors.Error) { this.emit("error", error); } else { this.emit("error", log_1.logAndReturn(this.log, new errors.CustomTtsProviderError(error))); } } }; //#endregion //#region audio client management this._handleAudioClientConnect = (audioClientId) => { const clientStream = this._processingClient.audioClientStream({ audioClientId }); this._audioClientStreams.push(clientStream); clientStream.on("error", this._handleStreamError); clientStream.on("inviteRequest", this._handleAudioClientInviteRequest); }; this._handleAudioClientInviteRequest = (audioClientId, additionalInfo, roomId) => { this.emit("_audioClientInviteRequest", audioClientId, additionalInfo, roomId); }; //#endregion //#region disposable this._isDisposed = false; this.log = options.log.child({ label: `app:${instanceId.slice(-6)}`, applicationId, instanceId, applicationName, }); this.log.info(`applicationId: ${applicationId}`); this.log.info(`applicationName: ${applicationName}`); this.log.info(`instanceId: ${instanceId}`); this._applicationZip = options.applicationZip; this.account = options.account; this._healthcheckInterval = options.healthcheckInterval; this._reconnectInterval = options.reconnectInterval; this._maxReconnectCount = options.maxReconnectCount; this.applicationId = applicationId; this.applicationName = applicationName; this._instanceId = instanceId; this.customerId = options.customerId; this.groupId = options.groupId; this._processingClient = processingClient; this._instanceStream = instanceStream; this.inputSchema = inputSchema; this.outputSchema = outputSchema; this._runtimeStream = processingClient.runtimeStream({ instanceId }); this._debugStream = processingClient.debugStream({ instanceId }); this._audioServerStream = processingClient.audioServerStream({ instanceId }); this._externalTtsClient = new grpc.externalTtsProtocol.ExternalTtsClient(options.account, this.log); this._audioRequestStream = this._externalTtsClient.audioRequestStream({ instanceId }); this._instanceStream.on("error", this._handleStreamError); this._runtimeStream.on("error", this._handleStreamError); this._debugStream.on("error", this._handleStreamError); this._audioServerStream.on("error", this._handleStreamError); this._audioRequestStream.on("error", this._handleStreamError); this._instanceStream.on("jobTimedOut", this._handleJobTimedOut); this._instanceStream.on("jobRejected", this._handleJobRejected); this._instanceStream.on("jobStarting", this._handleJobStarting); this._instanceStream.on("jobFailed", this._handleJobFailed); this._instanceStream.on("jobCompleted", this._handleJobCompleted); this._instanceStream.on("jobRecordIdReady", this._handleJobRecordIdReady); this._instanceStream.on("jobAdditionalInformation", this._handleJobAdditionalInformation); this._runtimeStream.on("rpcRequest", this._handleRpcRequest); this._debugStream.on("jobEvent", this._handleJobEvent); this._debugStream.on("debugLog", this._handleDebugLog); this._audioServerStream.on("connect", this._handleAudioClientConnect); this._audioRequestStream.on("request", this._handleTtsRequest); this.queue = new queue_1.ConversationQueue(this, this.log); this.queue.on("error", (error) => this.emit("error", error)); this.incoming = new incoming_1.IncomingRequestManager(this, this.log); this.incoming.on("error", (error) => this.emit("error", error)); this._healthcheckIntervalHandle = setInterval(this._healthcheck, this._healthcheckInterval); } /** @internal */ static _deploy(options) { const processingClient = new grpc.processing.ProcessingClient(options.account, options.log); const instanceStream = processingClient.registerInstanceStream({ ...options, concurrency: 0, sdkVersion: sdkVersion, }); return new Promise((resolve, reject) => { var _a; (_a = options.cancelToken) === null || _a === void 0 ? void 0 : _a._onCancel(options.log, (error) => { instanceStream.cancel(); reject(error); }); instanceStream.on("progress", ({ scopes, description, percent }) => { options.log.info(`${scopes.join(": ")}: ${description} ${percent}%`); }); if (options.onProgress !== undefined) { instanceStream.on("progress", options.onProgress); } instanceStream.on("error", (error) => { instanceStream.cancel(); processingClient.close(); reject(error); }); instanceStream.on("success", (applicationId, instanceId, applicationName, inputSchema, outputSchema) => { options.log.info("application deployed"); instanceStream.removeAllListeners(); resolve(new Application(options, applicationId, applicationName, instanceId, processingClient, instanceStream, inputSchema, outputSchema)); }); }); } /** * Start the deployed application, enabling it to receive incoming requests * and run queued conversations. * * @param options.concurrency max number of conversations to run at once */ async start(options) { var _a; if (this._state === ApplicationState.Running) { log_1.logAndThrow(this.log, new errors.Error("application is already running")); } this._state = ApplicationState.Running; this._concurrency = (_a = options === null || options === void 0 ? void 0 : options.concurrency) !== null && _a !== void 0 ? _a : 1; await this._processingClient.setInstanceConcurrency({ instanceId: this._instanceId, concurrency: this._concurrency, }); this.log.info(`application started with concurrency ${this._concurrency}`); } /** * Stop the running application, disabling the creation of new conversations. * Conversations that are already running are unaffected. */ async stop() { if (this._state !== ApplicationState.Running) { log_1.logAndThrow(this.log, new errors.Error("application is not running")); } this._state = ApplicationState.Stopped; this._concurrency = 0; await this._processingClient.setInstanceConcurrency({ instanceId: this._instanceId, concurrency: this._concurrency, }); this.log.info("application stopped"); } async _reconnect(error) { for (let reconnectCount = 0; reconnectCount < this._maxReconnectCount; reconnectCount += 1) { if (!error || (error instanceof errors.ConnectionError && error.reconnectable)) { try { await this._attemptReconnection(reconnectCount); return; } catch (reconnectError) { error = reconnectError; } } else { this.emit("error", error); return; } } this.log.info("reconnection limit reached"); } async _attemptReconnection(reconnectCount) { // TODO: is this okay? for (const conv of this._activeConversationsByJobId.values()) { this.emit("_jobFailed", conv._jobId, conv._jobKey, { msg: "connection error" }); } this._activeConversationsByJobId.clear(); this._audioServerStream.cancel(); for (const stream of this._audioClientStreams) stream.cancel(); this._audioClientStreams = []; this._debugStream.cancel(); this._runtimeStream.cancel(); this._instanceStream.cancel(); this._audioRequestStream.cancel(); if (this._healthcheckIntervalHandle) { clearInterval(this._healthcheckIntervalHandle); this._healthcheckIntervalHandle = undefined; } const interval = typeof this._reconnectInterval === "number" ? this._reconnectInterval : this._reconnectInterval(reconnectCount); this.log.info(`reconnecting in ${interval} ms`); await new Promise((cb) => setTimeout(cb, interval)); this.log.info("reconnecting"); this._instanceStream = this._processingClient.registerInstanceStream({ applicationZip: this._applicationZip, concurrency: this._concurrency, instanceId: this._instanceId, groupId: this.groupId, sdkVersion: sdkVersion, }); await new Promise((resolve, reject) => { this._instanceStream.on("error", (error) => { this._instanceStream.removeAllListeners(); reject(error); }); this._instanceStream.on("success", (applicationId, instanceId) => { this._instanceStream.removeAllListeners(); this.applicationId = applicationId; this._instanceId = instanceId; resolve(); }); }); this._runtimeStream = this._processingClient.runtimeStream({ instanceId: this._instanceId }); this._debugStream = this._processingClient.debugStream({ instanceId: this._instanceId }); this._audioServerStream = this._processingClient.audioServerStream({ instanceId: this._instanceId, }); this._audioRequestStream = this._externalTtsClient.audioRequestStream({ instanceId: this._instanceId, }); this._instanceStream.on("error", this._handleStreamError); this._runtimeStream.on("error", this._handleStreamError); this._debugStream.on("error", this._handleStreamError); this._audioRequestStream.on("error", this._handleStreamError); this._instanceStream.on("jobTimedOut", this._handleJobTimedOut); this._instanceStream.on("jobRejected", this._handleJobRejected); this._instanceStream.on("jobStarting", this._handleJobStarting); this._instanceStream.on("jobFailed", this._handleJobFailed); this._instanceStream.on("jobCompleted", this._handleJobCompleted); this._instanceStream.on("jobRecordIdReady", this._handleJobRecordIdReady); this._instanceStream.on("jobAdditionalInformation", this._handleJobAdditionalInformation); this._runtimeStream.on("rpcRequest", this._handleRpcRequest); this._debugStream.on("jobEvent", this._handleJobEvent); this._debugStream.on("debugLog", this._handleDebugLog); this._audioServerStream.on("connect", this._handleAudioClientConnect); this._audioRequestStream.on("request", this._handleTtsRequest); this._healthcheckIntervalHandle = setInterval(this._healthcheck, this._healthcheckInterval); this.log.info(`reconnected with instanceId ${this._instanceId}`); } /** @internal */ async _executeConnectionProvider(conv) { try { if (this.connectionProvider === undefined) throw new Error("connectionProvider was not set"); const connection = await this.connectionProvider(conv); if (connection === undefined) throw new Error("connection provider returned no connection"); return connection; } catch (error) { log_1.logAndThrow(this.log, new errors.ConnectionProviderError(error)); } } /** @internal */ async _addSessionConfig(config) { let configJson; try { configJson = JSON.stringify(config); } catch (error) { this.log.debug(error); log_1.logAndThrow(this.log, new errors.InternalError("session config is not serializable to JSON", error)); } if (configJson === undefined) { log_1.logAndThrow(this.log, new errors.InternalError("session config is not serializable to JSON")); } const configZip = await zip.file("config.json", configJson, this.log); return await this._processingClient.addSessionConfig({ instanceId: this._instanceId, configZip, }); } /** @internal */ async _configureSession(conversation, executionOptions) { var _a, _b; const config = {}; if (executionOptions.channel === "audio") { config.type = "audio"; config.channel = { type: "sip", configName: (_b = (_a = conversation.sip) === null || _a === void 0 ? void 0 : _a.config) !== null && _b !== void 0 ? _b : "default", }; config.stt = stt._makeSttSessionConfig(conversation.audio.stt, this.log); config.tts = tts._makeTtsSessionConfig(conversation.audio.tts, this.log); config.vad = { delayAtStartup: conversation.audio.vadStartupDelay, interlocutorPauseDelay: conversation.audio.vadPauseDelay, }; config.noiseVolume = conversation.audio.noiseVolume; } else if (executionOptions.channel === "text") { config.type = "text"; } config.saveLog = true; return await this._processingClient.addSessionConfig({ instanceId: this._instanceId, configZip: await zip.file("config.json", JSON.stringify(config), this.log), }); } /** * Set an [external call] handler for this application. * * The handler is called with all the call arguments passed as a dictionary, * as well as the current {@link Conversation} object. It can return a JSON-serializable * value, possibly wrapped in a promise, which then is treated as the call's return value. * As a special case, `undefined` gets converted to `null`. * * [external call]: https://docs.dasha.ai/en-us/default/dasha-script-language/external-functions */ setExternal(name, fn) { this._externals.set(name, fn); } //#endregion //#region job lifecycle /** @internal */ async _enqueueJob(jobKey, options) { const result = await this._processingClient.enqueueJob({ instanceId: this._instanceId, jobs: [ { jobId: jobKey, priority: options.priority, after: options.after, before: options.before, }, ], }); return { jobId: result[0].assignedJobId }; } /** @internal */ async _acceptJob(jobId, options) { await this._processingClient.acceptJob({ instanceId: this._instanceId, jobId, ...options }); } /** @internal */ async _rejectJob(jobId) { await this._processingClient.rejectJob({ instanceId: this._instanceId, jobId }); } /** @internal */ _bindConversation(jobId, conv) { this._activeConversationsByJobId.set(jobId, conv); } //#endregion //#region conversations /** * Create a single {@link Conversation}. * * @param input conversation's input data; * can also be set later with {@link Conversation.input} */ createConversation(input) { if (this._state !== ApplicationState.Running) { log_1.logAndThrow(this.log, new errors.Error("application is not running")); } return new conversation_1.SingleConversation(this, input, this.log); } /** @internal */ async _executeSttDispatcher(conv) { try { const providerName = await this.sttDispatcher(conv); if (providerName === undefined) throw new Error("stt dispather returned no provider name"); return stt._makeSttSessionConfig(providerName, this.log); } catch (error) { log_1.logAndThrow(this.log, new errors.SttDispatcherError(error)); } } /** @internal */ async _executeTtsDispatcher(conv) { try { const providerName = await this.ttsDispatcher(conv); if (providerName === undefined) throw new Error("tts dispatcher returned no provider name"); return tts._makeTtsSessionConfig(providerName, this.log); } catch (error) { log_1.logAndThrow(this.log, new errors.TtsDispatcherError(error)); } } /** @internal */ _getAudioClientEndpoint(audioClientId, roomId) { return JSON.stringify({ roomId, type: "grpc", customerId: this.customerId, applicationName: this.applicationName, groupId: this.groupId, otherAudioClientIds: [audioClientId], }); } // TODO: audio client docs /** * Get the audio client credentials for use with this application. */ async getAudioClientAccount() { const api = new rest.MiscApi(this.account, this.log); const token = await api.getAudioClientAuthToken({ customerId: this.customerId, applicationName: this.applicationName, groupId: this.groupId, }); return { ...this.account, apiKey: token }; } //#endregion //#region call recordings /** @internal */ _getRecordingUrl(callId) { return `${account_1.getBaseHttpUrl(this.account)}/api/v1/records/${callId}`; } /** * Close the connection with the application, freeing all local resources. */ dispose() { if (this._isDisposed) return; this._isDisposed = true; this.queue._dispose(); this.incoming._dispose(); this._audioRequestStream.cancel(); this._externalTtsClient.close(); this._audioServerStream.cancel(); for (const stream of this._audioClientStreams) stream.cancel(); this._debugStream.cancel(); this._runtimeStream.cancel(); this._instanceStream.cancel(); this._processingClient.close(); if (this._healthcheckIntervalHandle) { clearInterval(this._healthcheckIntervalHandle); this._healthcheckIntervalHandle = undefined; } this.removeAllListeners(); this.log.info("application disposed of"); } }
JavaScript
class WidgetPlacementInstance extends ElementInstance { /** * When this function is finished, then the form should be ready to * be rendered as a string. * @function * @async * @param {Object} [data={}] * The initialization data. */ async init(data={}) { return await super.init(merge({ // TODO: Translate. availableWidgetsTitle: "Available Widgets", }, data)); } /** * Call the * [RenderableInstance.commit()]{@link Defiant.Plugin.Theme.RenderableInstance#commit} * for all renderable instances in this container and join them into a single * string. * * If a `wrap` RenderableInstance has been specified, then the string that was * joined together will now become the `content` of that RenderableInstance. * @function * @async * @returns {String} * The final string that should be provided to the user. */ async commit() { // Add the CSS and Javascript. this.context.engine.library.require(this.context, 'LayoutWidgetPlacement'); return await this.renderable.templateFunction(this.data); //return await super.commit(); } }
JavaScript
class BasicNetwork { constructor() { this.structure = new NeuralStructure(this); } /** * Add a layer to the neural network. If there are no layers added this * layer will become the input layer. This function automatically updates * both the input and output layer references. * * @param layer {BasicLayer} * The layer to be added to the network. */ addLayer(layer) { layer.network = this; this.structure.addLayer(layer); } /** * Add to a weight. * @param fromLayer {number} The from layer. * @param fromNeuron {number} The from neuron. * @param toNeuron {number} The to neuron. * @param value {number} The value to add. */ addWeight(fromLayer, fromNeuron, toNeuron, value) { const old = this.getWeight(fromLayer, fromNeuron, toNeuron); this.setWeight(fromLayer, fromNeuron, toNeuron, old + value); } /** * Get the weight between the two layers. * @param fromLayer {number} The from layer. * @param fromNeuron {number} The from neuron. * @param toNeuron {number} The to neuron. * @return {number} The weight value. */ getWeight(fromLayer, fromNeuron, toNeuron) { this.structure.requireFlat(); return this.structure.flat.getWeight(fromLayer, fromNeuron, toNeuron); } /** * Set the weight between the two specified neurons. The bias neuron is always * the last neuron on a layer. * @param fromLayer {number} The from layer. * @param fromNeuron {number} The from neuron. * @param toNeuron {number} The to neuron. * @param value {number} The to value. */ setWeight(fromLayer, fromNeuron, toNeuron, value) { this.structure.requireFlat(); const fromLayerNumber = this.getLayerCount() - fromLayer - 1; const toLayerNumber = fromLayerNumber - 1; if (toLayerNumber < 0) { throw new NeuralNetworkError("The specified layer is not connected to another layer: " + fromLayer); } const weightBaseIndex = this.structure.flat.weightIndex[toLayerNumber]; const count = this.structure.flat.layerCounts[fromLayerNumber]; const weightIndex = weightBaseIndex + fromNeuron + (toNeuron * count); this.structure.flat.setWeight(value, weightIndex); } /** * Get the total (including bias and context) neuron cont for a layer. * @param layer {number} The layer. * @return {number} The count. */ getLayerTotalNeuronCount(layer) { this.structure.requireFlat(); const layerNumber = this.getLayerCount() - layer - 1; return this.structure.flat.layerCounts[layerNumber]; } /** * Get the neuron count. * @param layer {number} The layer. * @return {number} The neuron count. */ getLayerNeuronCount(layer) { this.structure.requireFlat(); const layerNumber = this.getLayerCount() - layer - 1; return this.structure.flat.layerFeedCounts[layerNumber]; } /** * @return {number} The layer count. */ getLayerCount() { this.structure.requireFlat(); return this.structure.flat.layerCounts.length; } /** * @returns {FlatNetwork} */ getFlat() { return this.structure.flat; } /** * Calculate the error for this neural network. We always calculate the error * using the "regression" calculator. Neural networks don't directly support * classification, rather they use one-of-encoding or similar. So just using * the regression calculator gives a good approximation. * * @param input {Array} * @param output {Array} * @return {Number} The error percentage. */ calculateError(input, output) { return ErrorUtil.calculateRegressionError(this, input, output); } /** * Calculate the total number of neurons in the network across all layers. * * @return {number} The neuron count. */ calculateNeuronCount() { let result = 0; for (let layer of this.structure.layers) { result += layer.getNeuronCount(); } return result; } /** * Classify the input into a group. * @param {Array} input The input data to classify. * @return {number} The group that the data was classified into. */ classify(input) { return this.winner(input); } /** * Clear any data from any context layers. */ clearContext() { if (this.structure.flat != null) { this.structure.flat.clearContext(); } } /** * Determines the randomizer used for resets. This will normally return a * Nguyen-Widrow randomizer with a range between -1 and 1. If the network * does not have an input, output or hidden layers, then Nguyen-Widrow * cannot be used and a simple range randomize between -1 and 1 will be * used. Range randomizer is also used if the activation function is not * TANH, Sigmoid, or the Elliott equivalents. * * @return the randomizer */ getRandomizer() { let useNWR = true; const validNwrActivationFunctions = [ 'ActivationTANH', 'ActivationSigmoid', 'ActivationElliott', 'ActivationElliottSymmetric' ]; const layerCount = this.getLayerCount(); for (let i = 0; i < layerCount; i++) { const af = this.getActivation(i); if (!_.find(validNwrActivationFunctions, af.constructor.name)) { useNWR = false; break; } } if (layerCount < 3) { useNWR = false; } return useNWR ? new NguyenWidrowRandomizer() : new RangeRandomizer(-1, 1); } /** * Determine the winner for the specified input. This is the number of the * winning neuron. * * @param input {Array} * The input patter to present to the neural network. * @return {number} The winning neuron. */ winner(input) { const output = this.compute(input); return _.max(output); } /** * Compute the output for this network. * * @param input {Array} * The input. * @return {Array} * The output. */ compute(input) { try { return this.structure.flat.compute(input); } catch (ex) { throw new NeuralNetworkError( "Index exception: there was likely a mismatch between layer sizes, or the size of the input presented to the network.", ex); } } /** * Get the activation function for the specified layer. * @param layer {number} The layer. * @return {ActivationFunction} The activation function. */ getActivation(layer) { this.structure.requireFlat(); const layerNumber = this.getLayerCount() - layer - 1; return this.structure.flat.activationFunctions[layerNumber]; } /** * Reset the weight matrix and the bias values. This will use a * Nguyen-Widrow randomizer with a range between -1 and 1. If the network * does not have an input, output or hidden layers, then Nguyen-Widrow * cannot be used and a simple range randomize between -1 and 1 will be * used. * */ randomize() { this.structure.finalizeStructure(); this.getRandomizer().randomize(this); } /** * Determine if the specified layer is biased. * @param l {Number} The layer number. * @return {Boolean} True, if the layer is biased. */ isLayerBiased(l) { this.structure.requireFlat(); const layerNumber = this.getLayerCount() - l - 1; return this.structure.flat.layerCounts[layerNumber] != this.structure.flat.layerFeedCounts[layerNumber]; } /** * Get the bias activation for the specified layer. * @param l {Number} The layer. * @return {Number} The bias activation. */ getLayerBiasActivation(l) { if (!this.isLayerBiased(l)) { throw new NeuralNetworkError("Error, the specified layer does not have a bias: " + l); } this.structure.requireFlat(); const layerNumber = this.getLayerCount() - l - 1; const layerOutputIndex = this.structure.getFlat().layerIndex[layerNumber]; const count = this.structure.getFlat().layerCounts[layerNumber]; return this.structure.getFlat().layerOutput[layerOutputIndex + count - 1]; } /** * @inheritDoc */ getInputCount() { this.structure.requireFlat(); return this.structure.getFlat().getInputCount(); } /** * @inheritDoc */ getOutputCount() { this.structure.requireFlat(); return this.structure.getFlat().getOutputCount(); } /** * @return {number} The length of an encoded array. */ encodedArrayLength() { this.structure.requireFlat(); return this.structure.flat.getEncodeLength(); } /** * @returns {Object} */ toJSON() { let flatNetworkJSON = this.structure.flat.toJSON(); flatNetworkJSON.type = 'BasicNetwork'; return flatNetworkJSON; } /** * @param obj {Object} */ fromJSON(obj) { let activationFunc; let funcName; this.structure = new NeuralStructure(this); const that = this; _.eachRight(obj.layerFeedCounts, function (neuronCount, index) { funcName = _.toLower(_.trimStart(obj.activationFunctions[index], 'Activation')); activationFunc = new ActivationFunctions[funcName](); that.addLayer(new BasicLayer(activationFunc, obj.biasActivation[index], neuronCount)) }); this.randomize(); this.getFlat().fromJSON(obj); } }
JavaScript
class Upload extends React.Component { state = { file: null, loading: false, selected: false, loadedFile: null, init: false, images: [], }; static contextType = AuthContext; componentWillMount() { if (!this.state.init) this.getImages(); } getImages = async () => { this.setState({ init: true }); await this.context.getUserImages(); this.setState({ init: true, images: this.context.userImages }); }; //Handles user upload handleDrop = (acceptedFiles) => { const reader = new FileReader(); const file = acceptedFiles[0]; this.setState({ file: file, loading: true, selected: true, }); reader.addEventListener("load", () => { this.setState({ loading: false, loadedFile: reader.result, }); }); reader.readAsDataURL(file); }; submit = () => { this.props.handleSubmit(this.state.file); }; render() { var imgs; //Shows the user's images if they have uploaded any if (this.state.images.length > 0) { imgs = ( <div> <h3 className="bodyText mb-5">Your Images:</h3> <Masonry className="masonry-grid" elementType="div" options={masonryOptions} disableImagesLoaded={false} > {this.state.images.map((obj, index) => { return ( <div className="grid-img" key={index}> <Image rounded alt={obj.image_url} src={"/file/" + obj.file_id} style={{ width: 300 }} /> </div> ); })} </Masonry> </div> ); } else { imgs = <h1>No Images Yet!</h1>; } return ( <Container className="m-10"> <h3 className="pb-4">Add Image: </h3> <Dropzone onDrop={this.handleDrop} accept="image/*"> {({ getRootProps, getInputProps }) => ( <section> <div {...getRootProps({ className: "dropzone" })}> <input {...getInputProps()} /> <p> Drag 'n' drop some your image here, or just click anywhere to select one! </p> <aside> {this.state.selected ? ( this.state.loading ? ( <Spinner animation="grow" /> ) : ( <Image style={{ maxHeight: 400, width: "auto" }} fluid src={this.state.loadedFile} className="thumbImg" /> ) ) : ( "" )} </aside> </div> </section> )} </Dropzone> <Button disabled={this.state.file === null} size="lg" block className="mt-3" onClick={this.submit} > Upload </Button> <div style={{ marginTop: 25 }}>{imgs}</div> </Container> ); } }
JavaScript
class Operacion { constructor(op_izquierda, op_derecha, operacion, linea, columna) { this.linea = linea; this.columna = columna; this.op_izquierda = op_izquierda; this.op_derecha = op_derecha; this.operador = operacion; } getTipo(ent) { const valor = this.getValorImplicito(ent); if (typeof (valor) === 'boolean') { return Tipo_1.Tipo.BOOL; } else if (typeof (valor) === 'string') { return Tipo_1.Tipo.STRING; } else if (typeof (valor) === 'number') { if (this.isInt(Number(valor))) { return Tipo_1.Tipo.INT; } return Tipo_1.Tipo.DOUBLE; } else if (valor === null) { return Tipo_1.Tipo.NULL; } return Tipo_1.Tipo.VOID; } getValorImplicito(ent) { if (this.operador !== 'menos_unario' && this.operador !== 'not') { let op1 = this.op_izquierda.getValorImplicito(ent); let op2 = this.op_derecha.getValorImplicito(ent); //suma if (this.operador == 'suma') { if (typeof (op1 === "number") && typeof (op2 === "number")) { return op1 + op2; } else if (op1 === "string" || op2 === "string") { if (op1 == null) op1 = "null"; if (op2 == null) op2 = "null"; return op1.ToString() + op2.ToString(); } else { console.log("Error de tipos de datos no permitidos realizando una suma"); return null; } } //resta else if (this.operador == 'resta') { if (typeof (op1 === "number") && typeof (op2 === "number")) { return op1 - op2; } else if (op1 === "string" || op2 === "string") { if (op1 == null) op1 = "null"; if (op2 == null) op2 = "null"; return op1.ToString() - op2.ToString(); } else { console.log("Error de tipos de datos no permitidos realizando una suma"); return null; } } //multiplicación else if (this.operador == 'mult') { if (typeof (op1 === "number") && typeof (op2 === "number")) { return op1 * op2; } else { console.log("Error de tipos de datos no permitidos realizando una suma"); return null; } } //division else if (this.operador == 'div') { if (typeof (op1 === "number") && typeof (op2 === "number")) { if (op2 === 0) { console.log("Resultado indefinido, no puede ejecutarse operación sobre cero."); return null; } return op1 / op2; } else { console.log("Error de tipos de datos no permitidos realizando una suma"); return null; } } //modulo else if (this.operador == 'mod') { if (typeof (op1 === "number") && typeof (op2 === "number")) { if (op2 === 0) { console.log("Resultado indefinido, no puede ejecutarse operación sobre cero."); return null; } return op1 % op2; } else { console.log("Error de tipos de datos no permitidos realizando una suma"); return null; } } //or else if (this.operador == 'or') { if (typeof (op1 === "boolean") && typeof (op2 === "boolean")) { if (op1 || op2) { return true; } return false; } else { console.log("Error de tipos de datos no permitidos realizando una operacion logica"); return null; } } //and else if (this.operador == 'and') { if (typeof (op1 === "boolean") && typeof (op2 === "boolean")) { if (op1 && op2) { return true; } return false; } else { console.log("Error de tipos de datos no permitidos realizando una operacion logica"); return null; } } } else { let op1 = this.op_izquierda.getValorImplicito(ent); if (this.operador == 'menos_unario') { if (typeof (op1 === "number")) { return -1 * op1; } else { console.log("Error de tipos de datos no permitidos realizando una operación unaria"); return null; } } } return null; } isInt(n) { return Number(n) === n && n % 1 === 0; } }
JavaScript
class Todos extends Component { onDrag = (mutation = [0, 0]) => { const [src, dst] = mutation; this.props.attemptSwapTodo(src, dst); }; render() { const { entries } = this.props; return ( <section className={styles.container}> <Card header="Todos" className={styles.inner} as="div"> <AddTodo /> {/* <Draggable.Group disableRootEvents as="ol" className="todos" onChange={this.onDrag} > */} <ol> {entries.map(({ value, done }) => ( /* <Draggable.Target key={value} as="li"> {({ eventHandlers, targetActive }) => ( <Todo active={targetActive} value={value} done={done} key={value} onMouseDown={eventHandlers.onPanStart} /> )} </Draggable.Target> */ <Todo key={value} value={value} done={done} /> ))} {/* </Draggable.Group>*/} </ol> </Card> </section> ); } }
JavaScript
class Task extends Component { constructor(props) { super(props) // retrieve the db ref this.task = Firebase.task(this.props.task._id) } _onValueCallback(snapshot) { // Update component state here } componentDidMount() { // Normally you can add the listener here. // But there is no need to since the parent component is already listening to changes // on all tasks this.task.on('value', this._onValueCallback , (err) => { console.log(err) }) } componentWillUnmount() { this.task.off('value', this._onValueCallback) } toggleChecked() { // Set the checked property to the opposite of its current value this.task.update({ 'checked': !this.props.task.checked }) } deleteThisTask() { this.task.remove() } togglePrivate() { this.task.update({ 'private': !this.props.task.private }) } render() { // Give tasks a different className when they are checked off, // so that we can style them nicely in CSS const taskClassName = classnames({ checked: this.props.task.checked, private: this.props.task.private, }); return ( <li className={taskClassName}> <button className="delete" onClick={this.deleteThisTask.bind(this)}> &times; </button> <input type="checkbox" readOnly checked={!!this.props.task.checked} onClick={this.toggleChecked.bind(this)} /> { this.props.showPrivateButton ? ( <button className="toggle-private" onClick={this.togglePrivate.bind(this)}> { this.props.task.private ? 'Private' : 'Public' } </button> ) : ''} <span className="text"> <strong>{this.props.task.username}</strong>: {this.props.task.text} </span> </li> ); } }
JavaScript
class UserController extends Controller { /** * 查询用户数量 */ async userTotal() { const { ctx } = this; const users = await ctx.service.user.findAll(); this.ctx.body = { total: users.length }; } }
JavaScript
class TodoProcess extends WorkProcess { constructor(process_obj) { super(process_obj); return this; } static async createOrUpdate(process_args, project_args, program_args) { let work_process = await WorkProcess.WorkProcess(process_args, project_args, program_args) .then(work_process => { return (work_process); }); return new TodoProcess(work_process); } static async findById(id) { let work_process = await WorkProcess.findById(id, function(err, work_process) { return work_process; }); return new TodoProcess(work_process); } static async findByProjectId(projectId) { let processes = await WorkProcess.find({workProject: projectId}, function(err, processes) { return processes; }); return processes.map(work_process => new TodoProcess(work_process)); } static async findByArgs(process_args, project_args, program_args) { let project = await TodoProject.findByArgs(project_args, program_args); if(project === null) { return null} let work_process = await WorkProcess.findOne({name: process_args.name, workProject: project._id}, function(err, work_process) { return work_process; }); return new TodoProcess(work_process); } static async createOrUpdateByProjectId(projectId, process_args) { var args = Object.create( process_args ); // prevent this function from modifying projects_args args.workProject = await TodoProject.findById(projectId) if(args.workProject === null) { return null; } let work_process = await WorkProcess.findOneAndUpdate({name: args.name, workProject: args.workProject._id}, args, { upsert: true, new: true, overwrite: true, function(err, model) { } }) return new TodoProcess(work_process); } static async findTasksByProcessId(id) { return await WorkTask.find({workProcess: id}, function(err, tasks) { return tasks; }) } //static async deleteById(id) { static async deleteById(id) { // return await WorkProcess.findByIdAndDelete(id); let tasks = await TodoProcess.findTasksByProcessId(id) if(tasks.length !== 0) { let work_process = await TodoProcess.findById(id) console.error("Can't delete WorkProcess: (" + work_process.name + ') because it still has the following process(es)') tasks.forEach(function(task) { console.error(task.name); }); throw new Error('WorkProcess not empty still referenced by process(es)'); } return await WorkProcess.findByIdAndRemove(id); } static async findAll() { return WorkProcess.find(); } }
JavaScript
class SceneButton extends React.Component { constructor(props) { super(props); this.default = { title: 'Default', enabled: true, roundness: 0.5, textColor: [0.75,0.75,0.75,1], textSize: 0.08, width: 0.0, height: 0.0, }; this.state = this.default; this.onButtonClick = this.onButtonClick.bind(this); } renderButton({ title, enabled = true, roundness = 0.5, textColor = [1,1,1,1], textSize = 0.08, width = 0.0, height = 0.0, onClick = () => {}, }) { return ( <button enabled={enabled} textColor={textColor} textSize={textSize} roundness={roundness} width={width} height={height} onClick={onClick} >{title}</button> ); } renderHeader(text) { return <text textAlignment={'right'} textSize={0.09} boundsSize={{ boundsSize: [0.4, 0.1], wrap: true }}>{text}</text>; } onButtonClick(param) { return () => { this.setState(param); }; } render () { return ( <view localPosition={this.props.localPosition}> <gridLayout localPosition={[0,-0.2,0]} columns={4} alignment={'bottom-center'}> {this.renderHeader('Text:')} {this.renderButton({ title: 'short', onClick: this.onButtonClick({ title: 'CTA'})})} {this.renderButton({ title: 'mid', onClick: this.onButtonClick({ title: 'Custom button'})})} {this.renderButton({ title: 'long', onClick: this.onButtonClick({ title: 'Lorem ipsum dolor sit amet'})})} {this.renderHeader('Text size:')} {this.renderButton({ title: '0.1', onClick: this.onButtonClick({ textSize: 0.1 })})} {this.renderButton({ title: '0.2', onClick: this.onButtonClick({ textSize: 0.2 })})} {this.renderButton({ title: '0.3', onClick: this.onButtonClick({ textSize: 0.3 })})} {this.renderHeader('Color:')} {this.renderButton({ title: 'red', textColor: 'red', onClick: this.onButtonClick({ textColor: 'red' })})} {this.renderButton({ title: 'green', textColor: 'green', onClick: this.onButtonClick({ textColor: 'green' })})} {this.renderButton({ title: 'cyan', textColor: 'cyan', onClick: this.onButtonClick({ textColor: 'cyan' })})} {this.renderHeader('Roundness:')} {this.renderButton({ title: '0.0', roundness: 0.0, onClick: this.onButtonClick({ roundness: 0.0 })})} {this.renderButton({ title: '0.5', roundness: 0.3, onClick: this.onButtonClick({ roundness: 0.3 })})} {this.renderButton({ title: '1.0', roundness: 1.0, onClick: this.onButtonClick({ roundness: 1.0 })})} {this.renderHeader('Width:')} {this.renderButton({ title: '0.2', onClick: this.onButtonClick({ width: 0.2 })})} {this.renderButton({ title: '0.5', onClick: this.onButtonClick({ width: 0.5 })})} {this.renderButton({ title: '1.0', onClick: this.onButtonClick({ width: 1.0 })})} {this.renderHeader('Height:')} {this.renderButton({ title: '0.1', onClick: this.onButtonClick({ height: 0.1 })})} {this.renderButton({ title: '0.2', onClick: this.onButtonClick({ height: 0.2 })})} {this.renderButton({ title: '0.5', onClick: this.onButtonClick({ height: 0.5 })})} {this.renderHeader('Misc:')} {this.renderButton({ title: 'default', onClick: this.onButtonClick(this.default)})} {this.renderButton({ title: 'enable', onClick: this.onButtonClick({ enabled: true })})} {this.renderButton({ title: 'disable', onClick: this.onButtonClick({ enabled: false })})} </gridLayout> <gridLayout localPosition={[0,-0.55,0]} alignment={'top-center'}> {this.renderButton(this.state)} </gridLayout> </view> ); } }
JavaScript
class DeleteProperties extends botbuilder_dialogs_1.Dialog { /** * Initializes a new instance of the [DeleteProperties](xref:botbuilder-dialogs-adaptive.DeleteProperties) class. * @param properties Optional. Collection of property paths to remove. */ constructor(properties) { super(); /** * Collection of property paths to remove. */ this.properties = []; if (properties) { this.properties = properties.map((property) => new adaptive_expressions_1.StringExpression(property)); } } getConverter(property) { switch (property) { case 'properties': return new PropertiesConverter(); case 'disabled': return new adaptive_expressions_1.BoolExpressionConverter(); default: return super.getConverter(property); } } /** * Called when the [Dialog](xref:botbuilder-dialogs.Dialog) is started and pushed onto the dialog stack. * @param dc The [DialogContext](xref:botbuilder-dialogs.DialogContext) for the current turn of conversation. * @param options Optional. Initial information to pass to the dialog. * @returns A `Promise` representing the asynchronous operation. */ beginDialog(dc, options) { return __awaiter(this, void 0, void 0, function* () { if (this.disabled && this.disabled.getValue(dc.state)) { return yield dc.endDialog(); } if (this.properties && this.properties.length > 0) { for (let i = 0; i < this.properties.length; i++) { dc.state.deleteValue(this.properties[i].getValue(dc.state)); } } return yield dc.endDialog(); }); } /** * @protected * Builds the compute Id for the [Dialog](xref:botbuilder-dialogs.Dialog). * @returns A `string` representing the compute Id. */ onComputeId() { return `DeleteProperties[${this.properties.map((property) => property.toString()).join(',')}]`; } }
JavaScript
class ParseResult { constructor(value, error) { this.value = value; this.error = error; } /** * Construct a successful parse result * * @param {*} value - the parsed value, which may not be undefined * @returns {ParseResult} a successful ParseResult with the parsed value */ static success(value) { return new ParseResult(value, undefined); } /** * Construct a parse failure result * @param {string} error - the error message to save in the ParseResult * @returns {ParseResult} a failed ParseResult with the error message */ static failure(error) { return new ParseResult(undefined, error); } isSuccess() { return this.value !== undefined; } isFailure() { return !this.isSuccess(); } }
JavaScript
class Puppet { constructor(browser, page){ this.browser = browser this.page = page } defaults(options){ return _.defaultsDeep(options, { puppeteer: undefined, keep_puppet: false, authenticated: false, headless: process.env.HEADLESS != undefined ? process.env.HEADLESS == 'true' : true, servico: undefined }) } build(options){ options = this.defaults(options) return new Promise(resolve => { if(options.puppeteer == undefined){ puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], headless: options.headless }).then(browser => { this.browser = browser browser.newPage().then(page => { this.page = page resolve() }) }) }else{ this.browser = options.puppeteer.browser this.page = options.puppeteer.page resolve() } }) } destroy(options, attempt){ options = this.defaults(options) if(options.keep_puppet && attempt) attempt.puppeteer = this.spread() else this.browser.close() } spread(){ return { browser: this.browser, page: this.page } } }
JavaScript
class EntwinePointTileLayer extends PointCloudLayer { /** * Constructs a new instance of Entwine Point Tile layer. * * @constructor * @extends PointCloudLayer * * @example * // Create a new point cloud layer * const points = new EntwinePointTileLayer('EPT', * { * source: new EntwinePointTileSource({ * url: 'https://server.geo/ept-dataset', * } * }); * * View.prototype.addLayer.call(view, points); * * @param {string} id - The id of the layer, that should be unique. It is * not mandatory, but an error will be emitted if this layer is added a * {@link View} that already has a layer going by that id. * @param {Object} config - Configuration, all elements in it * will be merged as is in the layer. For example, if the configuration * contains three elements `name, protocol, extent`, these elements will be * available using `layer.name` or something else depending on the property * name. See the list of properties to know which one can be specified. * @param {string} [config.crs=ESPG:4326] - The CRS of the {@link View} this * layer will be attached to. This is used to determine the extent of this * layer. Default to `EPSG:4326`. * @param {number} [config.skip=1] - Read one point from every `skip` points * - see {@link LASParser}. */ constructor(id, config) { super(id, config); this.isEntwinePointTileLayer = true; const resolve = this.addInitializationStep(); this.whenReady = this.source.whenReady.then(() => { this.root = new EntwinePointTileNode(0, 0, 0, 0, this, -1); this.root.bbox.min.fromArray(this.source.boundsConforming, 0); this.root.bbox.max.fromArray(this.source.boundsConforming, 3); this.extent = Extent.fromBox3(config.crs || 'EPSG:4326', this.root.bbox); return this.root.loadOctree().then(resolve); }); } get spacing() { return this.source.spacing; } }
JavaScript
class Labels extends InstancePlugin { //region Config static get $name() { return 'Labels'; } static get defaultConfig() { return { /** * CSS class to apply to label elements * @config {String} * @default */ labelCls : 'b-sch-label', /** * Top label configuration object. May contain the following properties: * @param {String} field The name of a field in one of the associated records, * {@link Scheduler.model.EventModel EventModel} or {@link Scheduler.model.ResourceModel ResourceModel}. * The record from which the field value is drawn will be ascertained by checking for field definitions by * the specified name. * @param {Function} renderer A function, which when passed an object containing `eventRecord`, * `resourceRecord`, `assignmentRecord` and `domConfig` properties, returns the HTML to display as the * label * @param {Object} thisObj The `this` reference to use in the `renderer`. * @param {Object|Core.widget.Field} editor If the label is to be editable, a field configuration object * with a `type` property, or an instantiated Field. **The `field` property is mandatory for editing to * work**. * @config {Object} * @default */ top : null, /** * Right label configuration object. May contain the following properties: * @param {String} field The name of a field in one of the associated records, * {@link Scheduler.model.EventModel EventModel} or {@link Scheduler.model.ResourceModel ResourceModel}. * The record from which the field value is drawn will be ascertained by checking for field definitions by * the specified name. * @param {Function} renderer A function, which when passed an object containing `eventRecord`, * `resourceRecord`, `assignmentRecord` and `domConfig` properties, returns the HTML to display as the * label * @param {Object} thisObj The `this` reference to use in the `renderer`. * @param {Object|Core.widget.Field} editor If the label is to be editable, a field configuration object * with a `type` property, or an instantiated Field. **The `field` property is mandatory for editing to * work**. * @config {Object} * @default */ right : null, /** * Bottom label configuration object. May contain the following properties: * @param {String} field The name of a field in one of the associated records, * {@link Scheduler.model.EventModel EventModel} or {@link Scheduler.model.ResourceModel ResourceModel}. * The record from which the field value is drawn will be ascertained by checking for field definitions by * the specified name. * @param {Function} renderer A function, which when passed an object containing `eventRecord`, * `resourceRecord`, `assignmentRecord` and `domConfig` properties, returns the HTML to display as the * label * @param {Object} thisObj The `this` reference to use in the `renderer`. * @param {Object|Core.widget.Field} editor If the label is to be editable, a field configuration object * with a `type` property, or an instantiated Field. **The `field` property is mandatory for editing to * work**. * @config {Object} * @default */ bottom : null, /** * Left label configuration object. May contain the following properties: * @param {String} field The name of a field in one of the associated records, * {@link Scheduler.model.EventModel EventModel} or {@link Scheduler.model.ResourceModel ResourceModel}. * The record from which the field value is drawn will be ascertained by checking for field definitions by * the specified name. * @param {Function} renderer A function, which when passed an object containing `eventRecord`, * `resourceRecord`, `assignmentRecord` and `domConfig` properties, returns the HTML to display as the * label * @param {Object} thisObj The `this` reference to use in the `renderer`. * @param {Object|Core.widget.Field} editor If the label is to be editable, a field configuration object * with a `type` property, or an instantiated Field. **The `field` property is mandatory for editing to * work**. * @config {Object} * @default */ left : null, thisObj : null, /** * What action should be taken when focus moves leaves the cell editor, for example when clicking outside. * May be `'complete'` or `'cancel`'. * @config {String} * @default */ blurAction : 'cancel' }; } // Plugin configuration. This plugin chains some of the functions in Grid. static get pluginConfig() { return { chain : ['onEventDataGenerated'] }; } //endregion //region Init & destroy construct(scheduler, config) { const me = this; if (scheduler.isVertical) { throw new Error('Labels feature is not supported in vertical mode'); } me.scheduler = scheduler; super.construct(scheduler, config); if (me.top || me.bottom || me.left || me.right) { me.updateHostClasslist(); // rowHeight warning, not in use //const labelCount = !!me.topLabel + !!me.bottomLabel; //if (scheduler.rowHeight < 60 - labelCount * 12) console.log('') } } updateHostClasslist() { const { top, bottom } = this, { classList } = this.scheduler.element; classList.remove('b-labels-topbottom'); classList.remove('b-labels-top'); classList.remove('b-labels-bottom'); // OR is correct. This means that there are labels above OR below. if (top || bottom) { classList.add('b-labels-topbottom'); if (top) { classList.add('b-labels-top'); } if (bottom) { classList.add('b-labels-bottom'); } } } onLabelDblClick(event) { const me = this, target = event.target; if (target && !me.scheduler.readOnly) { const { side } = target.dataset, labelConfig = me[side], { editor, field } = labelConfig; if (editor) { const eventRecord = this.scheduler.resolveEventRecord(event.target); if (!(editor instanceof Editor)) { labelConfig.editor = new Editor({ appendTo : me.scheduler.element, blurAction : me.blurAction, inputField : editor, scrollAction : 'realign' }); } labelConfig.editor.startEdit({ target, align : editorAlign[side], matchSize : false, record : eventRecord, field }); event.stopImmediatePropagation(); return false; } } } set top(top) { this._top = this.processLabelSpec(top, 'top'); this.updateHostClasslist(); } get top() { return this._top; } set right(right) { this._right = this.processLabelSpec(right, 'right'); this.updateHostClasslist(); } get right() { return this._right; } set bottom(bottom) { this._bottom = this.processLabelSpec(bottom, 'bottom'); this.updateHostClasslist(); } get bottom() { return this._bottom; } set left(left) { this._left = this.processLabelSpec(left, 'left'); this.updateHostClasslist(); } get left() { return this._left; } processLabelSpec(labelSpec, side) { if (typeof labelSpec === 'function') { labelSpec = { renderer : labelSpec }; } else if (typeof labelSpec === 'string') { labelSpec = { field : labelSpec }; } // Allow us to mutate ownProperties in the labelSpec without mutating outside object else if (labelSpec) { labelSpec = Object.setPrototypeOf({}, labelSpec); } else { return; } const { scheduler } = this, { eventStore, resourceStore, taskStore, id } = scheduler, { field, editor } = labelSpec; // If there are milestones, and we are changing the available height // either by adding a top/bottom label, or adding a top/bottom label // then during the next dependency refresh, milestone width must be recalculated. if (topBottom[side]) { scheduler.milestoneWidth = null; } if (eventStore && !taskStore) { labelSpec.recordType = 'event'; } else { labelSpec.recordType = 'task'; } // Find the field definition or property from whichever store and cache the type. if (field) { let fieldDef, fieldFound = false; if (eventStore && !taskStore) { fieldDef = eventStore.modelClass.fieldMap[field]; if (fieldDef) { labelSpec.fieldDef = fieldDef; labelSpec.recordType = 'event'; fieldFound = true; } // Check if it references a property else if (Reflect.has(eventStore.modelClass.prototype, field)) { labelSpec.recordType = 'event'; fieldFound = true; } } if (!fieldDef && taskStore) { fieldDef = taskStore.modelClass.fieldMap[field]; if (fieldDef) { labelSpec.fieldDef = fieldDef; labelSpec.recordType = 'task'; fieldFound = true; } // Check if it references a property else if (Reflect.has(resourceStore.modelClass.prototype, field)) { labelSpec.recordType = 'task'; fieldFound = true; } } if (!fieldDef && resourceStore) { fieldDef = resourceStore.modelClass.fieldMap[field]; if (fieldDef) { labelSpec.fieldDef = fieldDef; labelSpec.recordType = 'resource'; fieldFound = true; } // Check if it references a property else if (Reflect.has(resourceStore.modelClass.prototype, field)) { labelSpec.recordType = 'resource'; fieldFound = true; } } //<debug> // We couldn't find the requested field in the modelClass // for either of the stores. if (!fieldFound) { throw new Error(`Scheduler ${id} labels ${side} field ${field} does not exist in either eventStore or resourceStore`); } //</debug> if (editor) { if (typeof editor === 'boolean') { scheduler.editor = { type : 'textfield' }; } else if (typeof editor === 'string') { scheduler.editor = { type : editor }; } EventHelper.on({ element : scheduler.timeAxisSubGrid.element, delegate : '.b-sch-label', dblclick : 'onLabelDblClick', thisObj : this }); } } //<debug> if (!labelSpec.field && !labelSpec.renderer) { throw new Error(`Scheduler ${scheduler.id} labels ${side} must either have a field or a renderer`); } //</debug> return labelSpec; } doDisable(disable) { super.doDisable(disable); if (this.client.isPainted) { this.client.refresh(); } } //endregion onEventDataGenerated(data) { const me = this; if (!me.disabled) { // Insert all configured labels for (const side of sides) { if (me[side]) { const { field, fieldDef, recordType, renderer, thisObj } = me[side], domConfig = { tag : 'label', className : { [me.labelCls] : 1, [`${me.labelCls}-${side}`] : 1 }, dataset : { side, taskFeature : `label-${side}` } }; let value; const eventRecordProperty = `${recordType}Record`, eventRecord = data[eventRecordProperty]; // If there's a renderer, use that by preference if (renderer) { value = renderer.call(thisObj || me.thisObj || me, { [eventRecordProperty] : eventRecord, resourceRecord : data.resourceRecord, assignmentRecord : data.assignmentRecord, domConfig }); } else { value = eventRecord[field]; // If it's a date, format it according to the Scheduler's defaults if (fieldDef && fieldDef.type === 'date' && !renderer) { value = DateHelper.format(value, me.client.displayDateFormat); } } domConfig.html = value || '\xa0'; data.wrapperChildren.push(domConfig); } } } } }
JavaScript
class PointTranslator { constructor(origin, interval) { this.origin = origin; this.interval = interval; } /** * Change a grid-based coordinate to a full-resolution pixel coordinate. */ gridToPixel(point) { let [x, y] = point; x = x * this.interval + this.origin[0]; y = this.origin[1] - y * this.interval; return [x, y]; } /** * Change a full-resolution pixel coordinate to a grid-based coordinate. */ pixelToGrid(point) { let [x, y] = point; x = Math.round((x - this.origin[0]) / this.interval); y = Math.round((this.origin[1] - y) / this.interval); return [x, y]; } }
JavaScript
class TypeVariable { /** */ constructor( name = '<anon>' ) { this.name = name; this.id = TypeVariable.nextId++; this.instance = null; } /** * Type variables should look like `'a`. If the variable has an instance, that * should be used for the string instead. * * @return {string} */ toString() { return this.name + ' ::= ' + ( this.instance ? this.instance.toString() : "'" + String.fromCharCode( 0x61 + this.id ) ); } }
JavaScript
class FunctionType extends TypeOperator { /** * @param {Array<TypeVariable>} types * @param {string} [identifier] */ constructor( types, identifier ) { super( "->", types, identifier ); } }
JavaScript
class Tweet extends Component { render() { return ( <div> {//username //timestamp //tweet text //reply button (and acounter) //like button (and acounter) } </div> ) } }
JavaScript
class OeCombo extends mixinBehaviors([IronFormElementBehavior, PaperInputBehavior], PolymerElement) { static get is() { return 'oe-combo'; } static get template() { return html` <style> :host { display: block; } :host(:focus){ outline:none; } span.required { vertical-align: bottom; color: var(--paper-input-container-invalid-color, var(--google-red-500)); @apply --oe-required-mixin; } paper-input-container { display: inline-block; width: 100%; } input{ @apply --paper-input-container-shared-input-style; } input::-webkit-input-placeholder { color: var(--paper-input-container-color, --secondary-text-color); } input:-moz-placeholder { color: var(--paper-input-container-color, --secondary-text-color); } input::-moz-placeholder { color: var(--paper-input-container-color, --secondary-text-color); } input:-ms-input-placeholder { color: var(--paper-input-container-color, --secondary-text-color); } paper-item { cursor: pointer; } input::-ms-clear { @apply --paper-input-container-ms-clear; } .iron-selected { background: var(--combo-selected-backgroud, #e0e0e0); } #dropdownicon { cursor: pointer; } paper-icon-button{ width:24px; height:24px; padding:0px; } .droplist paper-item { --paper-item-selected: { background-color: #ccc; } --paper-item-focused: { background-color: transparent; } --paper-item-focused-before: { background-color: transparent; } } .droplist paper-item:hover { background-color: #DDD; @apply --oe-combo-item-hover; } iron-input { @apply --iron-input; } label{ @apply --oe-label-mixin; } paper-input-error{ @apply --oe-input-error; } </style> <div id="cover" style="position:relative;"> <paper-input-container no-label-float="[[noLabelFloat]]" always-float-label="[[_computeAlwaysFloatLabel(alwaysFloatLabel,placeholder)]]" auto-validate$="[[autoValidate]]" disabled$="[[disabled]]" invalid="[[invalid]]"> <slot slot="prefix" name="prefix" ></slot> <label slot="label" hidden$="[[!label]]"> <oe-i18n-msg msgid=[[label]]>[[label]]</oe-i18n-msg> <template is="dom-if" if={{required}}> <span class="required" aria-label=" "> *</span> </template> </label> <div slot="input" id="templateDiv"></div> <iron-input slot="input" id="[[_inputId]]" bind-value="{{displayValue}}" invalid="{{invalid}}" validator="[[validator]]" on-keyup="_keyup" on-keydown="_keydown" on-change="_onChange"> <input role="combobox" aria-labelledby$="[[_ariaLabelledBy]]" aria-describedby$="[[_ariaDescribedBy]]" disabled$="[[disabled]]" prevent-invalid-input="[[preventInvalidInput]]" required$="[[required]]" autocomplete$="[[autocomplete]]" inputmode$="[[inputmode]]" name$="[[name]]" placeholder$="[[placeholder]]" readonly$="[[readonly]]" size$="[[size]]" autocapitalize$="[[autocapitalize]]" autocorrect$="[[autocorrect]]" tabindex$="[[tabindex]]" autosave$="[[autosave]]" results$="[[results]]" accept$="[[accept]]" multiple$="[[multiple]]" /> </iron-input> <div slot="suffix"> <paper-icon-button id="dropdownicon" on-tap="_dropdownClick" icon="arrow-drop-down"></paper-icon-button> <template is="dom-if" if={{showRefresh}}> <paper-icon-button icon="refresh" on-tap="_fetchListData"></paper-icon-button> </template> </div> <paper-input-error invalid={{invalid}} slot="add-on"> <oe-i18n-msg id="i18n-error" msgid={{errorMessage}} placeholders={{placeholders}}></oe-i18n-msg> </paper-input-error> </paper-input-container> <div> <dom-if if=[[_dropdownAttached]] id="dropdownContainer"> <template> <iron-dropdown id="dropdown" scroll-action="[[scrollAction]]" no-animations vertical-align="[[_verticalAlign]]" vertical-offset="[[_verticalOffset]]" no-auto-focus opened=[[expand]]> <paper-material slot="dropdown-content" class="droplist" tabindex="-1" disabled$="[[disabled]]"> <paper-listbox id="menu" role="listbox" aria-labelledby$="[[_ariaLabelledBy]]" multi$="[[multi]]"> <template is="dom-repeat" id="itemlist" items="{{_suggestions}}"> <paper-item role="option" on-tap="onItemSelected" data-item=[[item]] disabled$="[[disabledoption]]"> ${this.itemTemplate} </paper-item> </template> </paper-listbox> </paper-material> </iron-dropdown> </template> </dom-if> </div> </div> `; } static get itemTemplate() { if(window.OEUtils && window.OEUtils.componentDefaults && window.OEUtils.componentDefaults["oe-combo"]){ return window.OEUtils.componentDefaults["oe-combo"].itemTemplate; } return html`<span>[[_getDisplayValue(item)]]</span>`; } static get properties() { return { /** * Property within the listdata to be used for display */ displayproperty: String, /** * Property of the selected record, that is set as current value. * When records are plain strings, leave this property undefined */ valueproperty: String, _readonly: { type: Boolean, value: false }, /** * Flag to set for enabling combo to choose multiple values */ multi: { type: Boolean, value: false }, /** * When multi is true, this flag exposes value as comma separated text instead of an array */ valueAsText: { type: Boolean, value: false }, /** * When set to true, the selected value is shown as the template given for the combo * */ showTemplate: { type: Boolean, value: false, observer: '_showTemplateChanged' }, /** * Current selected value */ value: { type: Object, notify: true }, invalid: { type: Boolean, value: false, notify: true, reflectToAttribute: true }, /** * Selected record in the list. `value` equals `selectedItem`[`valueproperty`]. * When records are plain strings, it is same as `value` * */ selectedItem: { type: Object, notify: true }, /** * Selected records from the list. `value` equals `selectedItem`[`valueproperty`]. * When records are plain strings, it is same as `value` */ selectedItems: { type: Array, notify: true }, /** * Flag to control whether refresh button is displayed or not. */ showRefresh: { type: Boolean, value: false }, /** * Flag to control whether only the filtered values should be displayed. */ showFilteredOnly: { type: Boolean, value: false }, /** Disable caching of listdata */ disableCache: { type: Boolean, value: false }, _suggestions: { type: Array, notify: true }, /** * Key specifies the unique key to fetch data from cache(oeCache). * Incase, there is no data for the key specified in the cache and listurl is specified, * the data is fetched from the listurl and set in the cache for this key. */ listkey: { type: String, notify: true, observer: '_fetchListData' }, /** * Array of records to be displayed in dropdown. Can be array of primitives as well as objects. * When items are objects, you should specify `displayproperty` and `valueproperty`. */ listdata: { type: Array, notify: true, value:function(){ return []; }, observer: '_listDataChanged' }, /** * URL from where data to be displayed in dropdown, should be fetched */ listurl: { type: String, notify: true, observer: '_fetchListData' }, /** * Flag to set to enable entering values not present in the listdata */ allowFreeText: { type: Boolean, value: false }, expand: { type: Boolean, value: false, observer: '_expandChange' }, sort: { type: Boolean, value: false }, verticalOffset: { type: String }, /** * scrollAction binded to iron-dropdown * * "lock" - Prevents scrolling of body * * "refit" - Moves the dropdown based on scroll * * "cancel" - Closes the dropdown on scroll */ scrollAction: { type: String }, verticalAlign: { type: String }, _dropdownAttached: { type: Boolean, value: false }, /** * Fired when the element item is selected * * @event pt-item-confirmed * @param {Object} detail contains the item selected */ /** * Fired when the new listdata is fetched to update the cache store. * * @event oe-update-cache * @param {Object} detail contains the key as hashed listurl and detail the listadata */ /** * Fired when the value of the field is changed by the user * * @event oe-field-changed */ }; } static get observers() { return ['_setDisplayAndValidate(value,listdata)']; } /** * Override paper-input-behavior focus-blur handler * @param {FocusEvent} event */ _focusBlurHandler(event) { IronControlState._focusBlurHandler.call(this, event); // Forward the focus to the nested input. if (this.focused && !this._shiftTabPressed && this._focusableElement && !this.expand) { this._focusableElement.focus(); } } _onChange(eve) { eve.stopPropagation(); if (this.multi) { this.validate(); return; } if (this.displayValue && this.displayValue != this._getDisplayValue(this.selectedItem)) { var matchedRecord = this._matchedResults.find(function (rec) { return this.displayValue === this._getDisplayValue(rec); }.bind(this)); if (matchedRecord) { this._setSelectedItem(matchedRecord); } else if (this.allowFreeText) { var newValue = this.displayValue; if (this.valueproperty || this.displayproperty) { newValue = {}; if (this.valueproperty) { newValue[this.valueproperty] = this.displayValue; } if (this.displayproperty) { newValue[this.displayproperty] = this.displayValue; } } this._setSelectedItem(newValue); } else { //this.setValidity(false, 'invalidValue'); this.validate(); } } else { this.validate(); } } /** * Returns a reference to the focusable element. Overridden from * PaperInputBehavior to correctly focus the native input. * * @return {!HTMLElement} */ get _focusableElement() { return PolymerElement ? this.inputElement._inputElement : this.inputElement; } /** * Event listener to set the value based on the user selection, * when `multi` is set as true. * @param {Event} e selected-items-changed event by paper-listbox */ _selectedItemsChanged(e) { if (this.multi) { //Check if this is triggered on setting value. if (this.$.menu.selectedValues.sort().join() === this.__prevSelectedValues) { return; } var items = e.detail.value; if (items && items.length > 0) { this.selectedItems = []; var values = []; for (var i = 0; i < items.length; i++) { var item = items[i].dataItem; this.push('selectedItems', item); values.push(this._getItemValue(item)); } if (this.valueAsText) { this.value = values.join(','); } else { this.value = values; } } else { this.displayValue = ""; if (this.valueAsText) { this.value = undefined; } else { this.value = []; } } this.fire('pt-item-confirmed', item); this.setValidity(true, undefined); } } /** * Check of cache store in OEUtils namespace and add event listeners. * If cache is present set the cached data in `listdata` else call `_fetchData` */ _fetchListData() { var self = this; /* If List-Key is present, check if cache exists and set it on listdata */ if (!self.disableCache && OEUtils.oeCache && (this.listkey || this.listurl)) { var listkey = this.listkey || this.hashFunc(this.listurl); window.addEventListener('oe-cache-' + listkey + '-updated', function (e) { self.set('listdata', e.detail); }); var cacheValue = OEUtils.oeCache[listkey]; if (cacheValue) { this.set('listdata', cacheValue); } else { if (this.listurl) { OEUtils.oeCache[listkey] = []; self._fetchData(); } } } else { //no cache available hence fetch data this._fetchData(); } } /** * Fetches the listdata based on the `listurl` and fires * event 'oe-update-cache' to update the cache store * @event oe-update-cache */ _fetchData() { if (this.listurl) { var self = this; var ajaxCall = document.createElement('oe-ajax'); ajaxCall.contentType = 'application/json'; ajaxCall.handleAs = 'json'; ajaxCall.url = this.listurl; ajaxCall.method = 'get'; ajaxCall.addEventListener('response', function (event) { self.set('listdata', event.detail.response); var listkey = self.listkey || self.hashFunc(self.listurl); if (self.disableCache) { return; } self.fire('oe-update-cache', { key: listkey, data: event.detail.response }); }); ajaxCall.addEventListener('error', function (event) { // eslint-disable-line no-unused-vars self.fire("error", event); console.error('error fetching the list'); }); ajaxCall.generateRequest(); } } _listDataChanged(newV, oldV) { // eslint-disable-line no-unused-vars if (this.listdata) { var self = this; if (this.sort) { this.listdata.sort(this.sortData.bind(this)); } this.listMeta = this.listdata.map(function (d) { var metaObj = { value: self._getItemValue(d), display: self._getDisplayValue(d) }; metaObj.searchKey = metaObj.display.toLocaleLowerCase(); return metaObj; }); } } /** * Custom validation of oe-combo to check based on allowFreeText and other flags */ _validate() { var isValid = true; if (!this.allowFreeText && this.displayValue && (!this.selectedItem && !this.selectedItems)) { this.setValidity(false, 'invalidValue'); isValid = false; } else if (!this.allowFreeText && (!this.multi && this.displayValue != this._getDisplayValue(this.selectedItem))) { this.setValidity(false, 'invalidValue'); isValid = false; } else if (this.required && (!this.value || (this.value === this._invalidValue)) && !this.disabled) { this.setValidity(false, 'valueMissing'); isValid = false; } if (!isValid) { this.value = this._invalidValue; } return isValid; } _validateArrayItems(value, listItems, menuList) { var selectedItemsIndex = []; var selectedItems = []; var displayValues = []; for (var idx = 0, len = listItems.length; idx < len; idx++) { var item = listItems[idx]; if (value.indexOf(this._getItemValue(item)) !== -1) { selectedItems.push(item); selectedItemsIndex.push(idx); displayValues.push(this._getDisplayValue(item)); } } this.displayValue = displayValues.join(', '); this.set('selectedItems', selectedItems); this.set('__prevSelectedValues', selectedItemsIndex.sort().join()); if (selectedItems.length === value.length) { menuList && menuList.set('selectedValues', selectedItemsIndex); this.setValidity(true, undefined); } else { this.setValidity(false, 'invalidValue'); } } /** * Observer function listening to changes in `value` and `listdata` * Computes the display of the oe-combo and selects the correct values from paper-listbox, * based on `value` set on the element. * * @param {string|Array} newV value set on element * @param {Array} newL listdata of the element */ _setDisplayAndValidate(newV, newL) { // eslint-disable-line no-unused-vars if (this.value === this._invalidValue) { return; } if (!this.isConnected) { return; } var menuList = this.$.menu; var listItems = (this._suggestions && this._suggestions.length > 0) ? this._suggestions : this.listdata; if (this.value === null || this.value === undefined || this.value === '' || !this.listdata) { //if value or listdata is not present this.displayValue = ''; this.set('selectedItem', undefined); this.setValidity(true, undefined); if (this.showTemplate) { this.__setTemplateItem(null); } if (menuList) { menuList._selectMulti(); menuList.selectedValues = []; } return; } if (this.multi) { //Multiple selection sets displayValue,selectedItems,validity if (typeof this.value === "string") { if (this.valueAsText) { var arrValue = this.value.split(','); this._validateArrayItems(arrValue, listItems, menuList); } else { try { //parse the value to get the array var valueArr = JSON.parse(this.value); if (Array.isArray(valueArr)) { this.set('value', valueArr); return; } } catch (e) { this.displayValue = ''; this.setValidity(false, 'invalidValue'); return; } } } else if (Array.isArray(this.value)) { this._validateArrayItems(this.value, listItems, menuList); } else { for (let idx = 0, len = listItems.length; idx < len; idx++) { let item = listItems[idx]; if (this.value === this._getItemValue(item)) { //Match found this.displayValue = this._getDisplayValue(item); this.set('selectedItems', [item]); this.setValidity(true, undefined); //Select the item in paper-list menuList && menuList.select(idx); return; } } } } else { //Single selection sets displayValue,selectedItem,validity for (let idx = 0, len = listItems.length; idx < len; idx++) { let item = listItems[idx]; if (this.value === this._getItemValue(item)) { //Match found this.displayValue = this._getDisplayValue(item); this.selectedItem = item; this.setValidity(true, undefined); if (this.showTemplate) { this.__setTemplateItem(item); } //Select the item in paper-list menuList && menuList.select(idx); return; } } //Match not found if (typeof this.value === 'object') { this.displayValue = this._getDisplayValue(this.value); this.selectedItem = this.value; this.setValidity(true, undefined); } else if (this.allowFreeText) { this.displayValue = this.value; this.selectedItem = this.value; this.setValidity(true, undefined); } else { this.setValidity(false, 'invalidValue'); } } } static get _invalidValue() { return {}; } /** * Constructor gets the light-dom element for templating */ constructor() { super(); this._invalidValue = OeCombo._invalidValue; if (!this.ctor && !this.multi) { this.childTemplate = this.queryEffectiveChildren('template[item-template]'); } } /** * Connected callback to attach event listeners and * handle templating of the listbox */ connectedCallback() { super.connectedCallback(); this.setAttribute("role", "combobox"); if (!this.multi) { this.boundClickHandler = this._closeIfApplicable.bind(this); } else { this._readonly = true; } this._suggestions = []; this._setDisplayAndValidate(); if (this.childTemplate) { /** * When a custom template is provided for list items , * The dropdown is attached when the component is attached so as to change the template of the dom-repeat */ this._initDropdown(function () { const itemList = this.shadowRoot.querySelector('#itemlist'); this.__customTemplatize(itemList, this.childTemplate); }.bind(this)); } } /** * Key down event listener for oe-combo */ _keydown(e) {// eslint-disable-line no-unused-vars if (!this.readonly) { if (e.keyCode == 40 || e.keyCode == 38) { e.preventDefault(); } else if (e.keyCode == 13 && this.expand) { e.stopPropagation(); } else if (e.keyCode == 9 && this.expand) { this.set('expand', false); } } } /** * Observer to `showTemplate`. * CSS management to display the template instead of the input box. * @param {boolean} e flag to show template */ _showTemplateChanged(e) {// eslint-disable-line no-unused-vars if (this.showTemplate) { this.shadowRoot.querySelector('#templateDiv').style.display = "flex"; this.inputElement.readonly = true; // this._inputElement && (this._focusableElement.type = "hidden"); } else { this.shadowRoot.querySelector('#templateDiv').style.display = "none"; this.inputElement.style.display = "inline-block"; // this._focusableElement && (this._focusableElement.type = "text"); } } /** * Key up event listener to handle 'Up/Down/Enter' keys and other keys as search term. * @param {Event} e */ _keyup(e) { if (!this.readonly) { if (e.keyCode == 40) { //down button this._handleDownEvent(e); } else if (e.keyCode == 38) { //up //this._handleUpEvent(e); } else if (e.keyCode == 13) { //Enter this._handleEnterEvent(e); } else if (e.keyCode == 37 || e.keyCode == 39) { //ignore for left/right arrow keys } else if (e.keyCode == 27) { //escape key this.set('expand', false); } else if (e.keyCode != 9) { //ignore tab in //Pass only the unselected text for search var searchTerm = this.displayValue; if (this._focusableElement.selectionStart > 0) { searchTerm = searchTerm.substring(0, this._focusableElement.selectionStart); } this._search(e, searchTerm.trim()); } } } /** * Down key listener to open and display the menu box. * Once opened traverse the list data * @param {Event} e Key up event */ _handleDownEvent(e) { // eslint-disable-line no-unused-vars if (!this.sort || this._suggestions.length == 0) { this._suggestions = this.listdata; this._menuOpen(false); } this.async(function () { var suggestionsMenu = this.$.menu; var itemsList = suggestionsMenu.querySelector('#itemlist'); itemsList.render(); suggestionsMenu._updateItems(); if (suggestionsMenu && typeof (suggestionsMenu) != 'undefined') { suggestionsMenu.focus(); if (typeof suggestionsMenu.focusedItem === 'undefined') { suggestionsMenu._setFocusedItem(suggestionsMenu.items[0]); } } }, 300); } /** * Select the focused Item from the listbox using the 'Enter' key * @param {Event} e Key up event */ _handleEnterEvent(e) { // eslint-disable-line no-unused-vars if (this.expand) { var suggestionsMenu = this.$.menu; if (suggestionsMenu && typeof (suggestionsMenu) != 'undefined' && !this.multi) { var selectedItem = suggestionsMenu.focusedItem; if (typeof (selectedItem) != 'undefined') { this._setSelectedItem(selectedItem.dataItem); } this._focusableElement.focus(); } } } /** * Close menu and empty the list */ _menuClose() { this._suggestions = []; this.set('expand', false); } /** * Based on the position of the element in screen, * Computes alighnment , offset and opens the menu. * @param {boolean} sort Sort option for listdata */ _menuOpen(sort) { var elementPos = (window.innerHeight / this.getBoundingClientRect().top); var showDropDownAbove = elementPos > 0 && elementPos < 1.7; if (this.verticalAlign !== undefined) { this.set('_verticalAlign', this.verticalAlign); } else { this.set('_verticalAlign', showDropDownAbove ? 'bottom' : 'top'); } if (this.verticalOffset !== undefined) { this.set('_verticalOffset', this.verticalOffset); } else { this.set('_verticalOffset', showDropDownAbove ? 55 : -8); } this._initDropdown(function () { this.set('expand', true); }.bind(this)); if (sort) this.set('sort', true); else this.set('sort', false); } _initDropdown(cb) { function onRender() { this.$.dropdownContainer.removeEventListener('dom-change', onRender); this.$.dropdown = this.shadowRoot.querySelector('#dropdown'); this.fire('combo-dropdown-attached', this.$.dropdown); this.$.menu = this.$.dropdown.querySelector('#menu'); this.$.menu.addEventListener('selected-items-changed', this._selectedItemsChanged.bind(this)); cb(); if (this.value) { this._setDisplayAndValidate(); } } if (this._dropdownAttached) { cb(); } else { this.$.dropdownContainer.addEventListener('dom-change', onRender.bind(this)); this.set('_dropdownAttached', true); } } /** * Shows all the listdata items when drop down arrow clicks * It will check for open if not it will add class open and it will add to suggestions */ _dropdownClick(e) { // eslint-disable-line no-unused-vars e.stopPropagation(); if (this.expand) { this._menuClose(); } else { if (this.listdata) { this.set('_suggestions', this.listdata); this._menuOpen(false); var suggestionsMenu = this.$.menu; this.async(function () { if (suggestionsMenu && typeof (suggestionsMenu) != 'undefined') { suggestionsMenu.focus(); if (typeof suggestionsMenu.focusedItem === 'undefined') { suggestionsMenu._setFocusedItem(suggestionsMenu.items[0]); } } }, 500); } } } /** * It will execute when the expand property changes * And adds event listener for click on html when it open (expand = true) */ _expandChange() { var hold = document.querySelector('html'); var self = this; if (this.expand) { this.$.dropdown.style.width = this.offsetWidth + 'px'; hold.addEventListener('click', self.boundClickHandler); } else { hold.removeEventListener('click', self.boundClickHandler); } } _closeIfApplicable(event) { var self = this; var eventPath = event.path || (event.composedPath && event.composedPath()); if (event.target !== self && eventPath.indexOf(self.$.dropdownicon) === -1) { // console.log('closed due to click event', eventPath); this._menuClose(); } } /** * on-tap of a list item it is selected */ onItemSelected(e) { if (this.multi) { return; } e.stopPropagation(); var item = e.model.item; this._setSelectedItem(item); this._focusableElement.focus(); } __setTemplateItem(item) { var self = this; var templateDiv = this.shadowRoot.querySelector('#templateDiv'); templateDiv.innerHTML = ""; if (!item) { this.inputElement.style.zIndex = ""; this.inputElement.style.position = ""; this.inputElement.style.display = ""; return; } var repeater = this.shadowRoot.querySelector('#itemlist'); var menu = this.shadowRoot.querySelector('#menu'); if (!menu || !repeater || !templateDiv) { return; } function handleTemplateClone() { var selected = Array.from(menu.children).find(function (el) { return repeater.itemForElement(el) === item; }); if (selected) { templateDiv.appendChild(selected.children[0]); self.inputElement.style.zIndex = -1; self.inputElement.style.position = "absolute"; self.inputElement.style.display = "none"; } self._menuClose(); } if (repeater.items.length !== this.listdata.length) { this.set('_suggestions', this.listdata.slice()); repeater.render(); this.async(function () { handleTemplateClone(); }, 0); } else { handleTemplateClone(); } } /** * Returns the display property of the item or the item * @param {Object} item object from the list * @return {string} Display string for the item */ _getDisplayValue(item) { var ret = item; if (ret && this.displayproperty) { ret = ret[this.displayproperty]; } return (ret !== null && ret !== undefined) ? ret.toString() : ''; } /** * Returns the value property of the item or the item * @param {Object} item object from the list * @return {Any} value of the item. */ _getItemValue(item) { var ret = item; if (ret && this.valueproperty) { ret = ret[this.valueproperty]; } return ret; } /** * It will fire when we type any key except ['enter', 'up', 'down'] */ _search(e, term) { var self = this; if (term == '') { self._menuClose(); self.value = undefined; self.selectedItem = undefined; if (!self.required) { self.setValidity(true, undefined); } return; } var results = self._findMatchedObjects(term); /* if (results.length == 1 && e.keyCode != 8) { //there is exactly only one match. set it directly. //no need to open the menu. self._setSelectedItem(results[0]); //get length of current displayvalue and make remaining as selected this.inputElement.inputElement.setSelectionRange(term.length, self.displayValue.length); } else { */ this._matchedResults = results; self._menuOpen(true); var suggestionsMenu = self.$.menu; if (self.allowFreeText && results.length === 0) { var newValue = self.displayValue; if (self.valueproperty || self.displayproperty) { newValue = {}; if (self.valueproperty) { newValue[self.valueproperty] = self.displayValue; } if (self.displayproperty) { newValue[self.displayproperty] = self.displayValue; } } self._setSelectedItem(newValue); } else if (suggestionsMenu && typeof (suggestionsMenu) != 'undefined') { suggestionsMenu.select(0); self._focusableElement.focus(); } } /** * Finds the matched objects * TODO: Check regular expression for all the possible cases and for valid expression also. */ _findMatchedObjects(val) { var match = [], results = [], unmatch = []; var searchVal = val.toLocaleLowerCase(); //replacing special characters from the string with space from regular expression // val = val.replace(/[`~!@#$%^&*()|+\=?;:'",.<>\{\}\[\]\\\/]/gi, ''); // eslint-disable-line // var regEx = new RegExp(val, 'i'); // var regEx2 = new RegExp('^' + val, 'i'); //loop through out the list for checking the object's matches on val for (var idx = 0; idx < this.listdata.length; idx++) { var item = this.listdata[idx]; var itemMeta = this.listMeta[idx]; var searchIdx = itemMeta.searchKey.indexOf(searchVal); if (searchIdx !== -1) { // if the data contains the key push to the match array match.push(item); results.push(item); } else { unmatch.push(item); } } if (this.showFilteredOnly) { this.set('_suggestions', match); } else { this.set('_suggestions', match.concat(unmatch)); } return results; } /** * Set the value to the value property * This will be the final step for selecting the listed items * @param {Object} item Selected Item */ _setSelectedItem(item) { this.selectedItem = item; this.displayValue = this._getDisplayValue(item); if (this.valueproperty) { this.value = item ? item[this.valueproperty] : undefined; } else { this.value = item; } this.fire('pt-item-confirmed', item); // value-change will perform validation anyway. //this.setValidity(true, undefined); this._menuClose(); this.async(function () { this.fire('change'); if (this.fieldId) { this.fire('oe-field-changed', { fieldId: this.fieldId, value: this.value }); } }); } /** * Sorts data based on displayproperty * Kept method as public so that user can overwrite it if needed */ sortData(a, b) { var displayValueA = this._getDisplayValue(a).toString(); var displayValueB = this._getDisplayValue(b).toString(); return displayValueA.toLowerCase().localeCompare(displayValueB.toLowerCase()); } /** * Reset the fields in the component, * removes 'value',displayValue and error state. */ __resetComponent() { this.value = undefined; //or null if(this.$.menu) { this.$.menu.selected = undefined; } this._setDisplayAndValidate(); } __isItemSelected(item){ let selected = this.multi ? this.selectedItems : [this.selectedItem]; return Array.isArray(selected) && selected.indexOf(item) !== -1; } }
JavaScript
class PgClient { constructor({ databaseUrl }) { this._init({ databaseUrl }) } _init({ databaseUrl }) { this._databaseUrl = databaseUrl; this._client = new pg.Client(this._databaseUrl); this._client.connect(); } /** * request is send by each member. * They are to be stored into requests table with this method. */ storeRequest({ member, team, start_time, end_time, availability, callback }) { winston.log('debug', arguments); this._client.query({ text: "INSERT INTO requests (member, team, start_time, end_time, availability) VALUES($1, $2, $3, $4, $5)", values: [member, team, start_time, end_time, availability] }, function(err, results) { if (err) { winston.log('error', 'Storing request failed: error' + err); return callback(err, null); } callback(null, results); }); } /** * Return the requests in given time span. * Time span is assumed to be like one week, one month. * when a shift table is fixed. */ requestsInTimespan({ time, callback }) { // TODO: Return the request of all members in given time span } /** * Store the optimized shift table into shift. * */ storeShift({ shift, callback }) { // TODO: Store the given shift } /** * Register a member in existing team. */ registerMember({ team, name, callback }) { this._client.query({ text: "INSERT INTO members (team, name) VALUES($1, $2)", values: [team, name] }, function(err, results) { if (err) { winston.log('error', 'Registering team failed'); return callback(err, null); } callback(null, results); }); } /** * Register a new team */ registerTeam ({ name, callback }) { this._client.query({ text: "INSERT INTO teams (name) VALUES($1)", values: [name] }, function(err, results) { if (err) { winston.log('error', 'Registering team failed'); return callback(err, null); } callback(null, results); }); } }
JavaScript
class Grid { /** * @param {array[]} graph (array of arrays, 5x5) */ constructor(graph) { this.graph = graph; } /** * * @param {string} letter * @param {CellCoords} cell */ setCellLetter(letter, cell) { const {rowNumber, columnNumber} = cell; this.graph[rowNumber][columnNumber] = letter; } valueAt(row, column) { return this.graph[row][column]; } /** * number of cells remaining that don't have a letter assigned * @returns {*} */ cellsRemaining() { return this.graph.reduce((emptyCells, row) => { return emptyCells + row.filter(cell => cell === "_").length; }, 0) } }
JavaScript
class EntryHandlerKeywordIncluded extends EntryHandlerKeyword_1.EntryHandlerKeyword { constructor() { super('@included'); } async handle(parsingContext, util, key, keys, value, depth) { if (typeof value !== 'object') { parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found illegal @included '${value}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE)); } const valueUnliased = await util.unaliasKeywords(value, keys, depth, await parsingContext.getContext(keys)); if ('@value' in valueUnliased) { parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @included @value node '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE)); } if ('@list' in valueUnliased) { parsingContext.emitError(new jsonld_context_parser_1.ErrorCoded(`Found an illegal @included @list node '${JSON.stringify(value)}'`, jsonld_context_parser_1.ERROR_CODES.INVALID_INCLUDED_VALUE)); } parsingContext.emittedStack[depth] = false; } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class ItemHelper extends SvelteComponentDev { constructor(options) { super(options); init(this, options, instance$3, create_fragment$3, safe_not_equal, { reviewMode: 0, handleReviewClick: 3 }, add_css$3); dispatch_dev("SvelteRegisterComponent", { component: this, tagName: "ItemHelper", options, id: create_fragment$3.name }); const { ctx } = this.$$; const props = options.props || {}; if (/*handleReviewClick*/ ctx[3] === undefined && !('handleReviewClick' in props)) { console.warn("<ItemHelper> was created without expected prop 'handleReviewClick'"); } } get reviewMode() { throw new Error("<ItemHelper>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); } set reviewMode(value) { throw new Error("<ItemHelper>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); } get handleReviewClick() { throw new Error("<ItemHelper>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); } set handleReviewClick(value) { throw new Error("<ItemHelper>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); } }
JavaScript
class VideoApi { /** * Instantiates a new video player * * @param {Object} properties - Options to send to the video player * @param {Function} dispatcher - Callback to the main video event dispatcher */ constructor(properties, dispatcher) { this._properties = properties; this._dispatcher = dispatcher; this._player = null; } /** * Gets the duration of a video; *must* be implemented in the child class * * @throws {Error} */ get duration() { throw new Error('`duration` must be implemented in the child class'); } /** * Gets the current position of a video; *must* be implemented in the child class * * @throws {Error} */ get position() { throw new Error('`position` must be implemented in the child class'); } /** * Initializes a video API; *must* be implemented in the child class * * @throws {Error} * @returns {void} */ initialize() { throw new Error('`initialize()` must be implemented in the child class'); } }
JavaScript
class Migration12 extends Migration { constructor(configuration) { super(configuration); this._logger = configuration.logger; this._client = configuration.client; this._config = configuration.config; this._index = configuration.config.get('kibana.index'); this._defaultDashboardTitleYml = configuration.config.get('investigate_core.default_dashboard_title'); this._type = 'config'; this._query = { query: { bool: { filter: [ { term: { _id: 'kibi' } } ] } } }; } static get description() { return 'Migrate investigate_core:default_dashboard_title property to advanced settings'; } async _fetchDashboards() { if (!this._dashboards) { this._dashboards = await this.scrollSearch(this._index, 'dashboard'); } } async count() { let count = 0; if (!this._defaultDashboardTitleYml) { return count; } await this._fetchDashboards(); const dashboardWithTitleFromYmlFound = _.find(this._dashboards, d => d._source.title === this._defaultDashboardTitleYml); if (!dashboardWithTitleFromYmlFound) { this._logger.warning('[' + this._defaultDashboardTitleYml + '] is set as investigate_core.default_dashboard_title' + ' in investigate.yml but dashboard cannot be found.'); return count; } const objects = await this.scrollSearch(this._index, this._type, this._query); _.each(objects, (object) => { if(!this._doesDashboardExist(object._source['kibi:defaultDashboardId'])) { count++; } }); return count; } _doesDashboardExist(dashboardId) { if (!dashboardId) { return false; } const found = _.find(this._dashboards, d => d._id === dashboardId); return Boolean(found); } async upgrade() { let upgraded = 0; if (!this._defaultDashboardTitleYml) { return upgraded; } let body = ''; this._logger.info(`Updating investigate_core.default_dashboard_title from config`); await this._fetchDashboards(); let defaultDashboardId; const dashboardWithTitleFromYmlFound = _.find(this._dashboards, d => d._source.title === this._defaultDashboardTitleYml); if (dashboardWithTitleFromYmlFound) { defaultDashboardId = dashboardWithTitleFromYmlFound._id; } else { this._logger.info(this._defaultDashboardTitleYml + ` dashboard cannot be found.`); return upgraded; } const objects = await this.scrollSearch(this._index, this._type, this._query); for (const obj of objects) { // check if kibi:defaultDashboardId contains a valid dashboard id if (!this._doesDashboardExist(obj._source['kibi:defaultDashboardId'])) { body += JSON.stringify({ update: { _index: obj._index, _type: obj._type, _id: obj._id } }) + '\n' + JSON.stringify({ doc: { 'kibi:defaultDashboardId': defaultDashboardId } }) + '\n'; upgraded++; } } if (upgraded > 0) { await this._client.bulk({ refresh: true, body: body }); } return upgraded; } }
JavaScript
class Database extends cdk.Construct { /** @param {{networking:Networking=, parameters:Parameters=}} props */ constructor(scope, props, id = 'Database') { super(scope, id); // Create a subnet group from private subnets of our vpc const dbSubnetGroup = new rds.CfnDBSubnetGroup(this, 'DBSubnetGroup', { dbSubnetGroupDescription: 'Drone CI database cluster subnet group', subnetIds: props.networking.vpc.privateSubnets.map(subnet => subnet.subnetId), }); // Create a security group that opens up the database to our subnet const dbSecurityGroup = new ec2.SecurityGroup(this, 'DBSecurityGroup', { allowAllOutbound: true, vpc: props.networking.vpc, }); // Create a serverless Aurora Postgres database const db = new rds.CfnDBCluster(this, 'DBCluster', { databaseName: 'drone', dbClusterIdentifier: 'one-click-drone-db', dbSubnetGroupName: dbSubnetGroup.ref, vpcSecurityGroupIds: [dbSecurityGroup.securityGroupId], engineMode: 'serverless', engine: 'aurora-postgresql', engineVersion: '10.7', // minimum postgre-sql compatible version masterUsername: props.parameters.DatabaseUsername, masterUserPassword: props.parameters.DatabasePassword, storageEncrypted: true, backupRetentionPeriod: 1, deletionProtection: false, port: 5432, // postgre-sql's default port scalingConfiguration: { autoPause: true, secondsUntilAutoPause: 1800, // half an hour of inactivity }, }); // Configure the security group and expose database endpoint dbSecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(db.port)); dbSecurityGroup.addIngressRule(ec2.Peer.anyIpv6(), ec2.Port.tcp(db.port)); /** @private */ this._db = db; } get host() { return this._db.attrEndpointAddress; } get port() { return this._db.attrEndpointPort; } }
JavaScript
class Token { constructor(options = {}) { const { storageSystem } = options; if (!storageSystem) { return new ErrorHandler(ERROR.NO_STORAGE); } this.storage = new Storage(storageSystem); this.key = 'default_jwt_access_token_key'; } /** * @description Stores token * @param token: String */ store(token) { if (!this.isValid(token)) { return false } return this.storage.setItem(this.key, token); } /** * @description Gets stored token * @returns String */ get() { return this.storage.getItem(this.key) } /** * @description Decodes a token. A falsy token will return {}. * @param token: String * @returns Object */ decode(token) { if (!this.isValid(token)) { return {} } try { return jwtDecode(token); } catch (err) { return {} } } /** * @description Returns expiration date as Unix Timestamp (ms) or null. * @param token: String * @returns Number || null */ getExpirationDate(token) { if (!this.isValid(token)) { return null } const decodedToken = this.decode(token); return decodedToken.exp || null; } /** * @description Returns true/false if token is expired or not (with minute precision) * @param token: String * @returns Boolean */ isExpired(token) { if (!this.isValid(token)) { return true } let expirationDate = this.getExpirationDate(token); if (!expirationDate) { new ErrorHandler(ERROR.NO_EXP_DATE); return true } const exp = new Date(expirationDate).valueOf(); const now = new Date().valueOf(); return exp < now } /** * @description Checks if token is valid, by checking its existence. * You can optionally use a validation function as a secondary param. * @param token: String * @param validationFunc: Function * @returns Boolean */ isValid(token, validationFunc) { if (validationFunc && typeof validationFunc === 'function') { return validationFunc(token); } return !!token } /** * @description Removes token from storage */ remove() { return this.storage.removeItem(this.key) } }
JavaScript
class ConnectedMongoClient extends AsyncObject { constructor(mongoClient, url, options) { super(mongoClient, url, options || {}); } definedAsyncCall() { return (mongoClient, url, options, callback) => { mongoClient.connect(url, options, callback); } } }
JavaScript
class TileMap { constructor(tilemapName) { this.tilemapName = tilemapName; this.tileset = null; this.tileWidth = 0; this.tileHeight = 0; this.width = 0; this.height = 0; this.offsetX = 0; this.offsetY = 0; this.tiles = null; this.collision = null; } async load() { const response = await fetch(`data/tilemaps/${this.tilemapName}.json`), data = await response.json(); this.tileset = new TileSet(data.tileset); this.offsetX = data.offset.x; this.offsetY = data.offset.y; this.tiles = data.tiles; this.width = this.tiles[0].length; this.height = this.tiles.length; this.collision = data.collision; await this.tileset.load(); this.tileWidth = this.tileset.tileWidth; this.tileHeight = this.tileset.tileHeight; } draw(g, meX, meY) { g.save(); { g.translate(this.offsetX * this.tileWidth, this.offsetY * this.tileHeight); for (let y = 0; y < this.height; ++y) { for (let x = 0; x < this.width; ++x) { let tile = this.tiles[y][x]; const maxDist = Math.max(Math.abs(x - meX), Math.abs(y - meY)) if (tile == 0) { if (maxDist <= 3) { tile = 2; } else if (maxDist <= 8) { tile = 3; } } this.tileset.draw(g, tile, x, y); } } } g.restore(); } isClear(x, y) { x -= this.offsetX; y -= this.offsetY; return x < 0 || this.width <= x || y < 0 || this.height <= y || this.collision[y][x] != 1; } // Use Bresenham's line algorithm (with integer error) // to draw a line through the map, cutting it off if // it hits a wall. getClearTile(x, y, dx, dy) { const x1 = x + dx, y1 = y + dy, sx = x < x1 ? 1 : -1, sy = y < y1 ? 1 : -1; dx = Math.abs(x1 - x); dy = Math.abs(y1 - y); let err = (dx > dy ? dx : -dy) / 2; while (x !== x1 || y !== y1) { const e2 = err; if (e2 > -dx) { if (this.isClear(x + sx, y)) { err -= dy; x += sx; } else { break; } } if (e2 < dy) { if (this.isClear(x, y + sy)) { err += dx; y += sy; } else { break; } } } return { x, y }; } }
JavaScript
class GetChannelVideoList extends ServiceBase { /** * Constructor for channel video details service. * * @param {object} params * @param {object} params.current_user * @param {number} params.channel_id * @param {string} [params.pagination_identifier] * @param {number} [params.filter_by_tag_id] * * @augments ServiceBase * * @constructor */ constructor(params) { super(); const oThis = this; oThis.currentUser = params.current_user; oThis.channelId = params.channel_id; oThis.paginationIdentifier = params[paginationConstants.paginationIdentifierKey] || null; oThis.filterByTagId = params[paginationConstants.filterByTagIdKey] || null; oThis.limit = oThis._defaultPageLimit(); oThis.page = 1; oThis.videoIds = []; oThis.channelVideoDetails = {}; oThis.responseMetaData = {}; oThis.videoDetails = []; oThis.tokenDetails = {}; oThis.usersVideosMap = {}; } /** * Async perform. * * @returns {Promise<void>} * @private */ async _asyncPerform() { const oThis = this; await oThis._validateAndSanitizeParams(); await oThis._fetchVideoIds(); oThis._addResponseMetaData(); const promisesArray = [oThis._setTokenDetails(), oThis._getVideos()]; await Promise.all(promisesArray); oThis._setChannelVideoList(); return oThis._prepareResponse(); } /** * Validate and sanitize. * * @sets oThis.page * * @returns {Promise<*|result>} * @private */ async _validateAndSanitizeParams() { const oThis = this; if (oThis.paginationIdentifier) { const parsedPaginationParams = oThis._parsePaginationParams(oThis.paginationIdentifier); oThis.page = parsedPaginationParams.page; // Override paginationTimestamp number. } // Validate whether channel exists or not. await oThis._validateChannel(); // Validate limit. return oThis._validatePageSize(); } /** * Fetch and validate channel. * * @returns {Promise<never>} * @private */ async _validateChannel() { const oThis = this; const cacheResponse = await new ChannelByIdsCache({ ids: [oThis.channelId] }).fetch(); if (cacheResponse.isFailure()) { return Promise.reject(cacheResponse); } const channelObject = cacheResponse.data[oThis.channelId]; if ( !CommonValidators.validateNonEmptyObject(channelObject) || channelObject.status !== channelsConstants.activeStatus ) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'a_s_c_gvl_1', api_error_identifier: 'resource_not_found', params_error_identifiers: ['invalid_channel_id'], debug_options: { channelId: oThis.channelId, channelDetails: channelObject } }) ); } } /** * Fetch video ids. * * @return {Promise<void>} * @private */ async _fetchVideoIds() { const oThis = this; if (oThis.filterByTagId) { await oThis._fetchVideosFromChannelTagVideos(); } else { await oThis._fetchVideosFromChannelVideos(); } } /** * Fetch videos from channel tag videos. * * @sets oThis.videoIds, oThis.channelVideoDetails * * @returns {Promise<never>} * @private */ async _fetchVideosFromChannelTagVideos() { const oThis = this; const cacheResponse = await new ChannelTagVideoIdsByTagIdAndChannelIdPaginationCache({ tagId: oThis.filterByTagId, channelId: oThis.channelId, limit: oThis.limit, page: oThis.page }).fetch(); if (cacheResponse.isFailure()) { return Promise.reject(cacheResponse); } oThis.videoIds = cacheResponse.data.videoIds || []; oThis.channelVideoDetails = cacheResponse.data.channelVideoDetails; } /** * Fetch video ids from channel videos. * * @sets oThis.videoIds, oThis.channelVideoDetails * * @returns {Promise<never>} * @private */ async _fetchVideosFromChannelVideos() { const oThis = this; const cacheResponse = await new ChannelVideoIdsByChannelIdPaginationCache({ channelId: oThis.channelId, limit: oThis.limit, page: oThis.page }).fetch(); if (cacheResponse.isFailure()) { return Promise.reject(cacheResponse); } oThis.videoIds = cacheResponse.data.videoIds || []; oThis.channelVideoDetails = cacheResponse.data.channelVideoDetails; } /** * Add next page meta data. * * @sets oThis.responseMetaData * * @returns {void} * @private */ _addResponseMetaData() { const oThis = this; const nextPagePayloadKey = {}; if (oThis.videoIds.length >= oThis.limit) { nextPagePayloadKey[paginationConstants.paginationIdentifierKey] = { page: oThis.page + 1 }; } oThis.responseMetaData = { [paginationConstants.nextPagePayloadKey]: nextPagePayloadKey, [paginationConstants.filterByTagIdKey]: oThis.filterByTagId }; } /** * Fetch token details. * * @sets oThis.tokenDetails * * @returns {Promise<result>} * @private */ async _setTokenDetails() { const oThis = this; const tokenResp = await new GetTokenService().perform(); if (tokenResp.isFailure()) { return Promise.reject(tokenResp); } oThis.tokenDetails = tokenResp.data.tokenDetails; } /** * Get videos. * * @sets oThis.usersVideosMap * * @returns {Promise<result>} * @private */ async _getVideos() { const oThis = this; const userVideosObj = new GetUserVideos({ currentUserId: oThis.currentUser ? oThis.currentUser.id : 0, videoIds: oThis.videoIds, isAdmin: false }); const response = await userVideosObj.perform(); if (response.isFailure()) { return Promise.reject(response); } oThis.usersVideosMap = response.data; } /** * Set channel video list. * * @set oThis.videoDetails * * @returns {*|result} * @private */ _setChannelVideoList() { const oThis = this; for (let index = 0; index < oThis.videoIds.length; index++) { const videoId = oThis.videoIds[index]; if (CommonValidators.validateNonEmptyObject(oThis.usersVideosMap.fullVideosMap[videoId])) { const channelVideoDetail = oThis.usersVideosMap.fullVideosMap[videoId]; channelVideoDetail.isPinned = oThis.channelVideoDetails[videoId].pinnedAt ? 1 : 0; oThis.videoDetails.push(channelVideoDetail); } } } /** * Prepare final response. * * @returns {*|result} * @private */ _prepareResponse() { const oThis = this; return responseHelper.successWithData({ [entityTypeConstants.channelVideoList]: oThis.videoDetails, [entityTypeConstants.videoDetailsMap]: oThis.usersVideosMap.videoDetailsMap, [entityTypeConstants.channelsMap]: oThis.usersVideosMap.channelsMap, [entityTypeConstants.videoDescriptionsMap]: oThis.usersVideosMap.videoDescriptionMap, [entityTypeConstants.currentUserUserContributionsMap]: oThis.usersVideosMap.currentUserUserContributionsMap, [entityTypeConstants.currentUserVideoContributionsMap]: oThis.usersVideosMap.currentUserVideoContributionsMap, [entityTypeConstants.currentUserVideoRelationsMap]: oThis.usersVideosMap.currentUserVideoRelationsMap, [entityTypeConstants.pricePointsMap]: oThis.usersVideosMap.pricePointsMap, usersByIdMap: oThis.usersVideosMap.usersByIdMap, tags: oThis.usersVideosMap.tags, linkMap: oThis.usersVideosMap.linkMap, imageMap: oThis.usersVideosMap.imageMap, videoMap: oThis.usersVideosMap.videoMap, [entityTypeConstants.userProfileAllowedActions]: oThis.usersVideosMap.userProfileAllowedActions, tokenUsersByUserIdMap: oThis.usersVideosMap.tokenUsersByUserIdMap, tokenDetails: oThis.tokenDetails, meta: oThis.responseMetaData }); } /** * Returns default page limit. * * @returns {number} * @private */ _defaultPageLimit() { return paginationConstants.defaultChannelVideoListPageSize; } /** * Returns minimum page limit. * * @returns {number} * @private */ _minPageLimit() { return paginationConstants.minChannelVideoListPageSize; } /** * Returns maximum page limit. * * @returns {number} * @private */ _maxPageLimit() { return paginationConstants.maxChannelVideoListPageSize; } /** * Returns current page limit. * * @returns {number} * @private */ _currentPageLimit() { const oThis = this; return oThis.limit; } }
JavaScript
class Resource { /** * @method constructor * @constructor * @param {ima.http.HttpAgent} http * @param {string} url - API URL (Base server + api specific path.) * @param {app.base.EntityFactory} entityFactory * @param {ima.cache.Cache} cache */ constructor(http, url, entityFactory, cache) { /** * Handler for HTTP requests. * * @property _http * @private * @type {ima.http.HttpAgent} */ this._http = http; /** * API URL for specific resource. * * @property _apiUrl * @private * @type {string} */ this._apiUrl = url; /** * Cache for caching parts of request response. * * @property _cache * @private * @type {ima.cache.Cache} */ this._cache = cache; /** * Factory for creating entities. * * @property _entityFactory * @private * @type {app.base.EntityFactory} */ this._entityFactory = entityFactory; /** * @property _defaultOptions * @type {Object<string, number>} * @default { ttl: 3600000, timeout: 2000, repeatRequest: 1 } * */ this._defaultOptions = { ttl: 3600000, timeout: 2000, repeatRequest: 1 }; } /** * Gets 1 entity from http and returns Entity. * * @method getEntity * @param {String} [id=null] ID for get entity from API. * @param {Object} [data={}] * @param {Object} [options={}] Possible keys { ttl: {number}(in ms), timeout: {number}(in ms), repeatRequest: {number} } * @param {Boolean} [force=false] Forces request, doesn't use cache. * @return {Array<app.base.BaseEntity>} */ getEntity(id = null, data = {}, options = {}, force = false) { var url = this._getUrl(id); options = this._getOptions(options); if (force) { this._clearCacheForRequest(url, data); } return this._http .get(url, data, options) .then((result) => { return this._entityFactory.createEntityList(result.body); }, (error) => { throw error; }); } /** * Posts data to http and returns new Entity. * * @method createEntity * @param {Object} [data={}] * @param {Object} [options={}] Possible keys { ttl: {number}(in ms), timeout: {number}(in ms), repeatRequest: {number} } * @return {app.base.BaseEntity} */ createEntity(data = {}, options = {}) { var url = this._getUrl(); options = this._getOptions(options); return this._http .post(url, data, options) .then((result) => { return this._entityFactory.createEntity(result.body); }, (error) => { throw error; }); } /** * Return request url. * * @method _getUrl * @private * @param {String} [id=null] * @return {String} */ _getUrl(id = null) { var url = this._apiUrl; if (id) { url += '/' + id; } return url; } /** * Return request options. * * @method _getOptions * @private * @param {Object} options * @return {Object} */ _getOptions(options) { return Object.assign(this._defaultOptions, options); } /** * Clear data in cache for request. * * @method _clearCacheForRequest * @param {String} url * @param {Object} data */ _clearCacheForRequest(url, data) { var cacheKey = this._http.getCacheKey(url, data); this._cache.delete(cacheKey); } }
JavaScript
class IssueReporter { /** * @param {Object} defaults - The default texts to be used when creating an issue * @param {string=} defaults.title - Default issue title * @param {string=} defaults.body - Default issue body * @param {string=} defaults.error - Default error to be reported * @param {string=} defaults.footer - Default footer information */ constructor(defaults) { this.defaults = Object.assign({}, defaults); } /** * Create an issue in the repository with the defined title and body * @param {Object} config - Github context and config * @param {Object} config.github - An octokit object * @param {Object} config.owner - Repository owner * @param {Object} config.repo - Repository * @param {Object} texts - The texts to be used in the issue. * If not provided, the defaults are used. * @param {string=} texts.title - Issue title. * If not provided and no default exists an error will be thrown * @param {string=} texts.body - Issue body * @param {string=} texts.error - Error to be reported * @param {string=} texts.footer - Footer information * @returns {Object} Issue creation result or null, if it wasn't created * @async */ async createIssue({ github, owner, repo }, { title, body, error, footer, } = {}) { const issueTexts = { title: title || this.defaults.title, body: this.createIssueBody(body, error, footer), }; if (!issueTexts.title) { throw new Error('A title is required for creating an issue'); } // Just create a new issue if there is not an open issue with same title const issueExists = await IssueReporter.checkOpenIssues({ github, owner, repo }, issueTexts.title); if (!issueExists) { const issue = Object.assign(issueTexts, { owner, repo }); return github.issues.create(issue); } return null; } /** * Create an issue body with body message, error and a footer * @param {string=} body - Issue body * @param {string=} error - Error to be reported * @param {string=} footer - Footer information * @returns {string} An issue body in the specified format */ createIssueBody(body, error, footer) { const bodyLines = []; if (body || this.defaults.body) { bodyLines.push(body || this.defaults.body); } if (error || this.defaults.error) { // Format the error in markdown with ``` bodyLines.push(`\`\`\`\n${error || this.defaults.error}\n\`\`\``); } if (footer || this.defaults.footer) { bodyLines.push(footer || this.defaults.footer); } return bodyLines.join('\n\n'); } /** * Check if an issue already exists with same title * @param {Object} config - Github context and config * @param {Object} config.github - An octokit object * @param {Object} config.owner - Repository owner * @param {Object} config.repo - Repository * @param {string} title - The title of the issue to find * @returns {boolean} True if an issue with same title was found * @async @static */ static async checkOpenIssues({ github, owner, repo }, title) { let currentPage = 1; let lastPage = false; while (!lastPage) { const params = { owner, repo, state: 'open', per_page: 100, page: currentPage, }; const result = await github.issues.getForRepo(params); const issues = result.data; // For now, compare just the title and ignore pull requests const issue = issues.find(i => (i.title === title && !i.pull_request)); if (typeof issue !== 'undefined') { return true; } if (issues.length < 100) { lastPage = true; } currentPage += 1; } return false; } }
JavaScript
class test { constructor(){ } async checkNetworRequirements(){ await this.checkICES() await this.checkSignalingServer() } async checkICES(){ } async checkSignalingServer(){ } async checkConnectivity(){ } }
JavaScript
class For extends _node.Node { // Provide a node instance /** * Construct a new For node */ constructor() { super("For"); this.inputs = [new _socket.InputSocket("From", this, _type.Types.NUMBER, 0), new _socket.InputSocket("To", this, _type.Types.NUMBER, 0)]; this.outputs = [new _socket.OutputSocket("Index", this, _type.Types.NUMBER, 0)]; this.nexts = [new _socket.NextSocket("Out", this), new _socket.NextSocket("Do", this)]; this.prev = new _socket.PrevSocket("In", this); } /** * Clone this node * @param {Function} factory The factory class function */ clone(factory = For.instance) { return super.clone(factory); } /** * The process function */ async process() { await this.evaluateInputs(); // Save the current program's node let prevCurrentNode = this.program.currentNode; // Set the "Index" output value to Index this.output("Index").value = parseInt(this.input("From").value); // Re evaluate inputs in case of Condition depends on Index output await this.evaluateInputs(); // Let's cycle from "From" to "To" values for (let index = parseInt(this.input("From").value); index < parseInt(this.input("To").value); index++) { // Set the "Index" output value to Index this.output("Index").value = index; // If there's a node connected to the "Do" next socket... if (this.next("Do").peer?.node) { // Execute a sub program beginning on that node await this.program.processFrom(this.next("Do").peer.node); } } // Restore the current program's node this.program.currentNode = prevCurrentNode; return this.getFlowResult(this.next("Out")); } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class Routes extends React.Component { render() { return ( <Router> <AppNavbar /> <Route exact path="/" component={Home} /> <Route path="/Manage" component={Manage} /> <Route path="/Assess" component={Assess} /> <Route path="/Assessment" component={Assessment} /> <Route path="/Clients" component={Clients} /> <Route path="/Users" component={Users} /> </Router> ); } }
JavaScript
class FilterProps extends AdjustFunction { /** * Constructor */ constructor() { super(); this._propNames = null; } /** * Sets the names for the prop to copy. * * @param aNames Array|String The name of the props to copy. * * @return FilterProps self */ setNames(aNames) { this._propNames = aNames; return this; } /** * Filters the props. * * @param aData * The data to adjust * @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing. * * @return * The modified data */ adjust(aData, aManipulationObject) { //console.log("wprr/manipulation/adjustfunctions/FilterProps::adjust"); let returnObject = new Object(); let currentArray; if(this._propNames) { if(this._propNames instanceof Array) { currentArray = this._propNames; } else { currentArray = this._propNames.split(","); } let currentArrayLength = currentArray.length; for(let i = 0; i < currentArrayLength; i++) { let currentName = currentArray[i]; if(aData[currentName] !== undefined) { returnObject[currentName] = aData[currentName]; } } } return returnObject; } /** * Creates a new instance of this class. * * @param aNames Array|String The name of the props to copy. * * @return FilterProps The new instance. */ static create(aNames = null) { let newFilterProps = new FilterProps(); newFilterProps.setNames(aNames); return newFilterProps; } }
JavaScript
class Stack extends Array { // Default pop(): remove the top item from the stack. // Default push(item): add an item to the top of the stack. peek () { let top = this[this.length - 1] console.log(top) return top } isEmpty () { return this.length === 0 } }
JavaScript
class CommentBox extends Component { constructor(props) { super(props); this.state = { comment: '' }; } handleChange(event){ this.setState({ comment: event.target.value }); } handleSubmit(event){ // keep the form from submitting to itself event.preventDefault(); // new after having wired up the Container with the action creators this.props.saveComment(this.state.comment); this.setState({ comment: ''}); } render() { return ( <form onSubmit={this.handleSubmit.bind(this)} className="comment-box"> <h4>Add a comment</h4> <textarea value={this.state.comment} onChange={this.handleChange.bind(this)} /> <div> <button action="submit">Submit Comment</button> </div> </form> ) } }
JavaScript
class QueryResultsView { /** * Create a QueryResultsView object */ constructor() { this.queryResultsDiv = document.getElementById("query_results_div"); this.queryResultsHeader = document.getElementById("query_results_header"); this.queryMessageDiv = document.getElementById("query_message_div"); this.queryResultsList = document.getElementById("query_results_list"); } /** * Respond to an error * * @param {!string} message - an error message */ error(message) { console.log("QueryResultsView.error enter"); this.queryResultsHeader.style.display = "none"; while (this.queryResultsList.firstChild) { this.queryResultsList.removeChild(this.queryResultsList.firstChild); } this.queryMessageDiv.innerHTML = message; } /** * Shows the results * * @param {!QueryResults} dictionaries - holds the query results */ next(qResults) { console.log("QueryResultsView.next enter"); this.queryResultsHeader.style.display = "block"; while (this.queryResultsList.firstChild) { this.queryResultsList.removeChild(this.queryResultsList.firstChild); } const r = qResults.results; const msg = `${r.length} terms found for query ${qResults.query}`; this.queryMessageDiv.innerHTML = msg; const tList = document.createElement("ul"); r.forEach((term) => { const entries = term.getEntries(); const cn = entries[0].getChinese(); const pinyin = entries[0].getPinyin(); const en = entries[0].getEnglish(); const li = document.createElement("li"); const txt = `${cn} ${pinyin} - ${en}`; const tNode = document.createTextNode(txt); li.appendChild(tNode); tList.appendChild(li); }); this.queryResultsList.appendChild(tList); } }
JavaScript
class Button extends PureComponent { static propTypes = { children: PropTypes.node.isRequired, style: PropTypes.object.isRequired, kind: PropTypes.oneOf(kinds).isRequired, type: PropTypes.oneOf(types).isRequired, onClick: PropTypes.func.isRequired, } static defaultProps = { style: {}, kind: "normal", type: "button", onClick: () => null, } render () { const {children} = this.props const {kind} = this.props const {type} = this.props const {onClick} = this.props const {style} = this.props const combineStyle = mergeDeepRight(prop(kind)(styles))(style) return <button type={type} className={cxs(combineStyle)} onClick={onClick}> {children} </button> } }
JavaScript
class ErrorEvent extends BaseEvent { /** * @param {Error} error error object. */ constructor(error) { super(EventType.ERROR); /** * @type {Error} */ this.error = error; } }
JavaScript
class MapboxVectorLayer extends VectorTileLayer { /** * @param {Options} options Layer options. At a minimum, `styleUrl` and `accessToken` * must be provided. */ constructor(options) { const declutter = 'declutter' in options ? options.declutter : true; const source = new VectorTileSource({ state: SourceState.LOADING, format: new MVT(), }); super({ source: source, background: options.background, declutter: declutter, className: options.className, opacity: options.opacity, visible: options.visible, zIndex: options.zIndex, minResolution: options.minResolution, maxResolution: options.maxResolution, minZoom: options.minZoom, maxZoom: options.maxZoom, renderOrder: options.renderOrder, renderBuffer: options.renderBuffer, renderMode: options.renderMode, map: options.map, updateWhileAnimating: options.updateWhileAnimating, updateWhileInteracting: options.updateWhileInteracting, preload: options.preload, useInterimTilesOnError: options.useInterimTilesOnError, properties: options.properties, }); if (options.accessToken) { this.accessToken = options.accessToken; } const url = options.styleUrl; applyStyle(this, url, options.layers || options.source, { accessToken: this.accessToken, }) .then(() => { source.setState(SourceState.READY); }) .catch((error) => { this.dispatchEvent(new ErrorEvent(error)); const source = this.getSource(); source.setState(SourceState.ERROR); }); if (this.getBackground() === undefined) { applyBackground(this, options.styleUrl, { accessToken: this.accessToken, }); } } }
JavaScript
class ActionFactory { /** * Creates concrete `Action` instance based on menu location. * * @author Roman Pushkin ([email protected]) * @date 2016-05-26 * @version 1.1 * @since 0.1.0 * @param {User} user - {@link User} instance. Action is created * based on the following variables: * - `user.state.menuLocation` (optional) - menu location * - `user.state.locale` (optional) - locale (`en`, `ru`, etc.) * @return {Object} Instance of `Action` */ static fromMenuLocation(user) { const route = user.state.menuLocation || 'default'; return this.fromRoute({ user, route }); } /** * Creates concrete `Action` instance based on route. * * @author Roman Pushkin ([email protected]) * @date 2016-08-21 * @version 1.1 * @since 0.1.0 * @param {Object} obj - hash of parameters * @param {User} obj.user - {@link User} instance. * @param {string} obj.route - route key from {@link Routes}. * @return {Object} Instance of `Action` */ static fromRoute(obj) { const user = obj.user; const route = obj.route; const builder = routes[route]; if (!builder) { throw new Error(`Can't find route key "${route}" in routes`); } return builder({ i18n: initLocale(user), user }); // eslint-disable-line new-cap } }
JavaScript
class Dashboard extends React.Component { constructor(props) { super(props); this.state = { feeds : getFeeds() }; } componentDidMount() { window.setInterval(() => { this.setState({ feeds: getFeeds() }) }, 5000) } render() { return ( <div className="dashboard" > <LineChart className="part" data={this.state.feeds[0].data} title={this.state.feeds[0].title} color="#C8032B" /> <BarChart className="part" data = {this.state.feeds[1].data} title = {this.state.feeds[1].title} color="#C8032B" /> </div> ); } }
JavaScript
class AgencyProfileForm extends Component { constructor(props) { super(props); let data = props.agencyData; if (!data) { data = { tableContent: { agencyNumber: "", name: "", status: "", region: "", city: "", staff: "", dateOfInitialPartnership: "", standAloneFreezer: 0, freezerFridge: 0, chestFreezer: 0, singleDoorFreezer: 0, freezerFridgeCombo: 0, walkInFreezer: 0, doubleDoorFridge: 0, sideBySideFridge: 0, singleDoorFridge: 0, walkInFridge: 0, dryStorageClimateControl: 0, dryStorageNonClimateControl: 0, pickUpTruck: 0, van: 0, car: 0, }, mainSiteAddress: "", sanDiegoDistrict: "", countyDistrict: "", stateAssemblyDistrict: "", stateSenateDistrict: "", federalCongressionalDistrict: "", additionalAddresses: [""], billingAddress: "", billingZipcode: "", contacts: [ { contact: "", position: "", phoneNumber: "", email: "", }, ], scheduledNextVisit: "", dateOfMostRecentAgreement: "", fileAudit: "", monitored: "", foodSafetyCertification: "", distributionDays: { monday: false, tuesday: false, wednesday: false, thursday: false, friday: false, saturday: false, sunday: false, }, distributionStartTimes: { monday: "", tuesday: "", wednesday: "", thursday: "", friday: "", saturday: "", sunday: "", }, distributionExcludedTimes: { monday: "", tuesday: "", wednesday: "", thursday: "", friday: "", saturday: "", sunday: "", }, distributionStartDate: "", distributionFrequency: "", userSelectedDates: [], userExcludedDDates: [], userExcludedRDates: [], pantry: false, mealProgram: false, homeboundDeliveryPartner: false, largeScaleDistributionSite: false, residentialFacility: false, retailRescueDays: { monday: false, tuesday: false, wednesday: false, thursday: false, friday: false, saturday: false, sunday: false, }, retailRescueStartTimes: { monday: "", tuesday: "", wednesday: "", thursday: "", friday: "", saturday: "", sunday: "", }, retailRescueExcludedTimes: { monday: "", tuesday: "", wednesday: "", thursday: "", friday: "", saturday: "", sunday: "", }, retailRescueLocations: { monday: "", tuesday: "", wednesday: "", thursday: "", friday: "", saturday: "", sunday: "", }, youth: false, senior: false, homeless: false, veteran: false, healthcare: false, college: false, disabilitySpecific: false, residential: false, immigrant: false, }; } else { data = { ...data }; data.tableContent = { ...data.tableContent }; data.additionalAddresses = [...data.additionalAddresses]; data.contacts = data.contacts.map((obj) => ({ ...obj })); data.distributionDays = { ...data.distributionDays }; data.distributionStartTimes = { ...data.distributionStartTimes }; data.retailRescueDays = { ...data.retailRescueDays }; data.retailRescueStartTimes = { ...data.retailRescueStartTimes }; data.retailRescueLocations = { ...data.retailRescueLocations }; // unfix date/time formats // ISO 8601 format: "YYYY-MM-DDThh:mm" (literal T) for (const day of DAYS_OF_WEEK) { if (data.distributionDays[day]) { const timeString = data.distributionStartTimes[day]; data.distributionStartTimes[day] = timeString.slice(11, 16); } if (data.retailRescueDays[day]) { const timeString = data.retailRescueStartTimes[day]; data.retailRescueStartTimes[day] = timeString.slice(11, 16); } } } this.state = data; } /** * Helper function that processes this component's state into the format * expected by the agency schema (see backend/routes/agency.js). * @returns An object matching the agency schema populated with values from * this component's state */ prepareData() { const data = { ...this.state }; data.tableContent = { ...data.tableContent }; data.tableContent.phone = data.contacts[0].phoneNumber; // fix distribution and retail rescue formats // ISO 8601 format: "YYYY-MM-DDThh:mm" (literal T) const timeBase = `${AgencyProfileForm.fixDate(data.distributionStartDate)}T`; data.distributionStartTimes = { ...data.distributionStartTimes }; data.retailRescueStartTimes = { ...data.retailRescueStartTimes }; data.retailRescueLocations = { ...data.retailRescueLocations }; for (const day of DAYS_OF_WEEK) { if (data.distributionDays[day]) { // this day is selected, so fix the time format const time = data.distributionStartTimes[day]; // "hh:mm" data.distributionStartTimes[day] = timeBase + time; } else { // not selected data.distributionStartTimes[day] = ""; } if (data.retailRescueDays[day]) { // this day is selected, so fix the time format const time = data.retailRescueStartTimes[day]; // "hh:mm" data.retailRescueStartTimes[day] = timeBase + time; } else { // not selected data.retailRescueStartTimes[day] = ""; data.retailRescueLocations[day] = ""; } } // Remove empty strings in additionalAddresses data.additionalAddresses = data.additionalAddresses.filter((x) => x !== ""); // extra fields will be ignored by mongoose return data; } /** * Changes date format from MM/DD/YYYY to YYYY-MM-DD. * @param {String} date Date string with format MM/DD/YYYY * @returns Date string with format YYYY-MM-DD */ static fixDate(date) { return `${date.slice(6)}-${date.slice(0, 2)}-${date.slice(3, 5)}`; } /** * Callback to handle when the user makes changes to any input field. Updates * the state with the given key and value, if the key already exists in the * state. * @param {String} key The key to update in the state * @param {Any} newValue The new value to set for the key */ handleInputChange = (key, newValue) => { const index = key.indexOf("."); if (index !== -1) { const key1 = key.slice(0, index); const key2 = key.slice(index + 1); if (key1 in this.state && key2 in this.state[key1]) { this.setState((prevState) => { const updated = { ...prevState[key1] }; updated[key2] = newValue; return { [key1]: updated }; }); } } else if (key in this.state) { this.setState({ [key]: newValue }); } }; /** * Returns whether the input field corresponding to the given key passed * validation (or has not been validated yet). * @param {String} key The key of the field to check */ isValid = (key) => { const { errors } = this.state; return errors === undefined || !errors.includes(key); }; /** * Appends an empty string to the array of addresses in the component's state. */ addAddress = () => { const addresses = this.state.additionalAddresses; const updatedAddresses = addresses.slice(); updatedAddresses.push(""); this.setState({ additionalAddresses: updatedAddresses, }); }; /** * Removes the last element in the array of addresses in the component's * state. */ removeAddress = () => { const addresses = this.state.additionalAddresses; const updatedAddresses = addresses.slice(); updatedAddresses.pop(); this.setState({ additionalAddresses: updatedAddresses, }); }; /** * Appends a blank contact object to the array of contacts in the component's * state. */ addContact = () => { const { contacts } = this.state; const updatedContacts = contacts.slice(); updatedContacts.push({ contact: "", position: "", phoneNumber: "", email: "", }); this.setState({ contacts: updatedContacts, }); }; /** * Removes the last element in the array of contact objects in the component's * state. */ removeContact = () => { const { contacts } = this.state; const updatedContacts = contacts.slice(); updatedContacts.pop(); this.setState({ contacts: updatedContacts, }); }; /** * Handles form submission. */ submitForm = () => { const { history, agencyData, editing } = this.props; const formData = this.prepareData(); let url = `${BACKEND_URL}/agency/`; if (editing) { url += agencyData._id; } if (editing) { // delete all notes from changed recurring events - will exec max 6 times for (const day of Object.keys(formData.distributionStartTimes)) { if ( formData.distributionStartTimes[day] === "" || formData.distributionStartTimes[day] !== agencyData.distributionStartTimes[day] ) { const recurringID = `${agencyData._id}${ agencyData.distributionStartTimes[day] }${day.substring(0, 2)}D`; const milisecFromEpoch = new Date(agencyData.distributionStartTimes[day]).getTime(); fetch(`${BACKEND_URL}/notes/`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getJWT()}`, }, body: JSON.stringify({ rID: recurringID, tFE: milisecFromEpoch, }), }).catch((error) => console.error(error)); } // also handle retail rescue notes if ( formData.retailRescueStartTimes[day] === "" || formData.retailRescueStartTimes[day] !== agencyData.retailRescueStartTimes[day] ) { const recurringID = `${agencyData._id}${ agencyData.retailRescueStartTimes[day] }${day.substring(0, 2)}R`; const milisecFromEpoch = new Date(agencyData.retailRescueStartTimes[day]).getTime(); fetch(`${BACKEND_URL}/notes/`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getJWT()}`, }, body: JSON.stringify({ rID: recurringID, tFE: milisecFromEpoch, }), }).catch((error) => console.error(error)); } } // delete notes of any events that were removed for (const currDate of formData.userExcludedDDates) { if (!agencyData.userExcludedDDates.includes(currDate)) { const noteID = `${formData._id}${currDate}D`; fetch(`${BACKEND_URL}/notes/${noteID}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getJWT()}`, }, }).catch((error) => console.error(error)); } } } fetch(url, { method: editing ? "POST" : "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getJWT()}`, }, body: JSON.stringify(formData), }) .then((response) => { response.json().then((data) => { if (!response.ok) { if (data.fields) { const errors = data.fields.filter((x) => x !== null); this.setState({ errors }); const message = `${errors.length} error(s) found!`; alert(message); } } else if (history) { history.goBack(); } }); }) .catch((error) => console.error(error)); }; /** * Handles form cancellation. */ cancelForm = () => { const { history } = this.props; if (history) { history.goBack(); } }; render() { const data = this.state; const { editing } = this.props; return ( <div className="form-body"> <h1 className="form-title"> {editing ? "Update Agency Profile." : "Add a New Agency Profile."} </h1> <form> <div className="form-section" id="main"> <FormSectionHeader title="Quick Information" /> <FormRow> <FormCol> <InputText label="Agency Number" value={data.tableContent.agencyNumber} stateKey="tableContent.agencyNumber" onChange={this.handleInputChange} leftmost required valid={this.isValid("tableContent.agencyNumber")} /> </FormCol> <FormCol> <InputText label="Agency Name" value={data.tableContent.name} stateKey="tableContent.name" onChange={this.handleInputChange} required wide valid={this.isValid("tableContent.name")} /> </FormCol> </FormRow> <FormRow> <FormCol> <InputText label="Main Site Address" value={data.mainSiteAddress} stateKey="mainSiteAddress" onChange={this.handleInputChange} leftmost required wide valid={this.isValid("mainSiteAddress")} /> </FormCol> <FormCol> <InputText label="City" value={data.tableContent.city} stateKey="tableContent.city" onChange={this.handleInputChange} required valid={this.isValid("tableContent.city")} /> </FormCol> </FormRow> <FormRow> <FormCol> <InputDropdown label="Agency Status" options={["Onboarding", "Active", "Inactive", "On Hold"]} value={data.tableContent.status} stateKey="tableContent.status" onChange={this.handleInputChange} leftmost required valid={this.isValid("tableContent.status")} /> </FormCol> </FormRow> </div> <div className="form-section" id="location"> <FormSectionHeader title="Location and Addresses" /> <FormRow> <FormCol> <InputText label="Region" value={data.tableContent.region} stateKey="tableContent.region" onChange={this.handleInputChange} leftmost required valid={this.isValid("tableContent.region")} /> </FormCol> </FormRow> <FormRow> <FormCol> <InputText label="San Diego District" value={data.sanDiegoDistrict} stateKey="sanDiegoDistrict" onChange={this.handleInputChange} leftmost required valid={this.isValid("sanDiegoDistrict")} /> </FormCol> <FormCol> <InputText label="County District" value={data.countyDistrict} stateKey="countyDistrict" onChange={this.handleInputChange} required valid={this.isValid("countyDistrict")} /> </FormCol> <FormCol> <InputText label="State Assembly District" value={data.stateAssemblyDistrict} stateKey="stateAssemblyDistrict" onChange={this.handleInputChange} required valid={this.isValid("stateAssemblyDistrict")} /> </FormCol> </FormRow> <FormRow> <FormCol> <InputText label="State Senate District" value={data.stateSenateDistrict} stateKey="stateSenateDistrict" onChange={this.handleInputChange} leftmost required valid={this.isValid("stateSenateDistrict")} /> </FormCol> <FormCol> <InputText label="Federal Congressional District" value={data.federalCongressionalDistrict} stateKey="federalCongressionalDistrict" onChange={this.handleInputChange} required valid={this.isValid("federalCongressionalDistrict")} /> </FormCol> </FormRow> <AddressList items={data.additionalAddresses} stateKey="additionalAddresses" onChange={this.handleInputChange} /> <FormRow> <FormCol> <InputText label="Billing Address" value={data.billingAddress} stateKey="billingAddress" onChange={this.handleInputChange} leftmost required wide valid={this.isValid("billingAddress")} /> </FormCol> <FormCol> <InputText label="Billing Zipcode" value={data.billingZipcode} stateKey="billingZipcode" onChange={this.handleInputChange} required valid={this.isValid("billingZipcode")} /> </FormCol> </FormRow> <FormRow> <span className="small-button-span"> <SmallButton text="Add Address" symbol="+" onClick={this.addAddress} /> {data.additionalAddresses.length > 1 && ( <SmallButton text="Remove Address" symbol="-" alignRight onClick={this.removeAddress} /> )} </span> </FormRow> </div> <div className="form-section" id="contacts"> <FormSectionHeader title="Contacts" /> <ContactsList items={data.contacts} stateKey="contacts" onChange={this.handleInputChange} validCheck={this.isValid} /> <FormRow> <span className="small-button-span"> <SmallButton text="Add Contact" symbol="+" onClick={this.addContact} /> {data.contacts.length > 1 && ( <SmallButton text="Remove Contact" symbol="-" alignRight onClick={this.removeContact} /> )} </span> </FormRow> </div> <div className="form-section" id="compliance"> <FormSectionHeader title="Compliance" /> <FormRow> <FormCol> <InputDate label="Scheduled Next Visit" value={data.scheduledNextVisit} stateKey="scheduledNextVisit" onChange={this.handleInputChange} leftmost required valid={this.isValid("scheduledNextVisit")} /> </FormCol> <FormCol> <InputDate label="Date of Most Recent Agreement" value={data.dateOfMostRecentAgreement} stateKey="dateOfMostRecentAgreement" onChange={this.handleInputChange} required valid={this.isValid("dateOfMostRecentAgreement")} /> </FormCol> <FormCol> <InputDate label="Date of Initial Partnership" value={data.tableContent.dateOfInitialPartnership} stateKey="tableContent.dateOfInitialPartnership" onChange={this.handleInputChange} required valid={this.isValid("tableContent.dateOfInitialPartnership")} /> </FormCol> </FormRow> <FormRow> <FormCol> <InputDate label="File Audit" value={data.fileAudit} stateKey="fileAudit" onChange={this.handleInputChange} leftmost valid={this.isValid("fileAudit")} /> </FormCol> <FormCol> <InputDate label="Monitored" value={data.monitored} stateKey="monitored" onChange={this.handleInputChange} required valid={this.isValid("monitored")} /> </FormCol> <FormCol> <InputDate label="Food Safety Certification" value={data.foodSafetyCertification} stateKey="foodSafetyCertification" onChange={this.handleInputChange} required valid={this.isValid("foodSafetyCertification")} /> </FormCol> </FormRow> </div> <div className="form-section" id="distribution"> <FormSectionHeader title="Distribution" /> <FormRow> <FormCol> <DistributionDays values={[ { title: "Monday", selected: data.distributionDays.monday, time: data.distributionStartTimes.monday, stateKey: "distributionDays.monday", timeStateKey: "distributionStartTimes.monday", }, { title: "Tuesday", selected: data.distributionDays.tuesday, time: data.distributionStartTimes.tuesday, stateKey: "distributionDays.tuesday", timeStateKey: "distributionStartTimes.tuesday", }, { title: "Wednesday", selected: data.distributionDays.wednesday, time: data.distributionStartTimes.wednesday, stateKey: "distributionDays.wednesday", timeStateKey: "distributionStartTimes.wednesday", }, { title: "Thursday", selected: data.distributionDays.thursday, time: data.distributionStartTimes.thursday, stateKey: "distributionDays.thursday", timeStateKey: "distributionStartTimes.thursday", }, { title: "Friday", selected: data.distributionDays.friday, time: data.distributionStartTimes.friday, stateKey: "distributionDays.friday", timeStateKey: "distributionStartTimes.friday", }, { title: "Saturday", selected: data.distributionDays.saturday, time: data.distributionStartTimes.saturday, stateKey: "distributionDays.saturday", timeStateKey: "distributionStartTimes.saturday", }, { title: "Sunday", selected: data.distributionDays.sunday, time: data.distributionStartTimes.sunday, stateKey: "distributionDays.sunday", timeStateKey: "distributionStartTimes.sunday", }, ]} onChange={this.handleInputChange} validCheck={this.isValid} /> </FormCol> <FormCol> <InputDate label="Start Date" value={data.distributionStartDate} stateKey="distributionStartDate" onChange={this.handleInputChange} required valid={this.isValid("distributionStartDate")} /> <InputText label="Weekly Frequency" value={data.distributionFrequency} stateKey="distributionFrequency" onChange={this.handleInputChange} required valid={this.isValid("distributionFrequency")} /> </FormCol> <FormCol> <CheckboxList label="Check Boxes if Available/Correct." gutter onChange={this.handleInputChange} options={[ { title: "Pantry", selected: data.pantry, stateKey: "pantry", }, { title: "Meal Program", selected: data.mealProgram, stateKey: "mealProgram", }, { title: "Homebound Delivery Partner", selected: data.homeboundDeliveryPartner, stateKey: "homeboundDeliveryPartner", }, { title: "Large Scale Distribution Site", selected: data.largeScaleDistributionSite, stateKey: "largeScaleDistributionSite", }, { title: "Residential Facility or Group Home", selected: data.residentialFacility, stateKey: "residentialFacility", }, ]} /> </FormCol> </FormRow> <FormRow> <FormCol> <Calendar label="Customize Distribution Schedule" distributionStartDate={data.distributionStartDate} distributionFrequency={data.distributionFrequency} distributionDays={[ data.distributionDays.sunday, data.distributionDays.monday, data.distributionDays.tuesday, data.distributionDays.wednesday, data.distributionDays.thursday, data.distributionDays.friday, data.distributionDays.saturday, ]} distributionStartTimes={[ data.distributionStartTimes.sunday, data.distributionStartTimes.monday, data.distributionStartTimes.tuesday, data.distributionStartTimes.wednesday, data.distributionStartTimes.thursday, data.distributionStartTimes.friday, data.distributionStartTimes.saturday, ]} distributionExcludedTimes={[ data.distributionExcludedTimes.sunday, data.distributionExcludedTimes.monday, data.distributionExcludedTimes.tuesday, data.distributionExcludedTimes.wednesday, data.distributionExcludedTimes.thursday, data.distributionExcludedTimes.friday, data.distributionExcludedTimes.saturday, ]} userSelectedDates={data.userSelectedDates} userExcludedDates={data.userExcludedDDates} onChange={this.handleInputChange} validCheck={this.isValid} /> </FormCol> <FormCol> <DateList dates={data.userSelectedDates} stateKey="userSelectedDates" onChange={this.handleInputChange} validCheck={this.isValid} /> </FormCol> </FormRow> </div> <div className="form-section" id="capacity"> <FormSectionHeader title="Capacity" /> <FormRow> <FormCol> <IncrementerBoxList label="Storage and Type:" subLabel="Select Quantity if Storage Type is Available" options={[ { title: "Stand Alone Freezer", value: data.tableContent.standAloneFreezer, stateKey: "tableContent.standAloneFreezer", }, { title: "Freezer Fridge", value: data.tableContent.freezerFridge, stateKey: "tableContent.freezerFridge", }, { title: "Chest Freezer", value: data.tableContent.chestFreezer, stateKey: "tableContent.chestFreezer", }, { title: "Single-Door Stand Alone Freezer", value: data.tableContent.singleDoorFreezer, stateKey: "tableContent.singleDoorFreezer", }, { title: "Freezer-Refrigerator Combo", value: data.tableContent.freezerFridgeCombo, stateKey: "tableContent.freezerFridgeCombo", }, { title: "Walk-in Freezer", value: data.tableContent.walkInFreezer, stateKey: "tableContent.walkInFreezer", }, { title: "Double-Door Stand Alone Fridge", value: data.tableContent.doubleDoorFridge, stateKey: "tableContent.doubleDoorFridge", }, { title: "Side By Side Fridge", value: data.tableContent.sideBySideFridge, stateKey: "tableContent.sideBySideFridge", }, { title: "Single-Door Stand Alone Fridge", value: data.tableContent.singleDoorFridge, stateKey: "tableContent.singleDoorFridge", }, { title: "Walk-in Fridge", value: data.tableContent.walkInFridge, stateKey: "tableContent.walkInFridge", }, { title: "Dry Storage (Climate Controlled)", value: data.tableContent.dryStorageClimateControl, stateKey: "tableContent.dryStorageClimateControl", }, { title: "Dry Storage (Non-Climate Controlled)", value: data.tableContent.dryStorageNonClimateControl, stateKey: "tableContent.dryStorageNonClimateControl", }, ]} onChange={this.handleInputChange} twoColumns /> </FormCol> </FormRow> <FormRow> <FormCol> <IncrementerBoxList label="Transport and Type:" subLabel="Select Quantity if Transport Type is Available" options={[ { title: "Pick-up Truck", value: data.tableContent.pickUpTruck, stateKey: "tableContent.pickUpTruck", }, { title: "Van", value: data.tableContent.van, stateKey: "tableContent.van", }, { title: "Car", value: data.tableContent.car, stateKey: "tableContent.car", }, ]} onChange={this.handleInputChange} /> </FormCol> </FormRow> </div> <div className="form-section" id="retail-rescue"> <FormSectionHeader title="Retail Rescue" /> <RetailRescueDays values={[ { title: "Monday", selected: data.retailRescueDays.monday, time: data.retailRescueStartTimes.monday, location: data.retailRescueLocations.monday, stateKey: "retailRescueDays.monday", timeStateKey: "retailRescueStartTimes.monday", locationStateKey: "retailRescueLocations.monday", }, { title: "Tuesday", selected: data.retailRescueDays.tuesday, time: data.retailRescueStartTimes.tuesday, location: data.retailRescueLocations.tuesday, stateKey: "retailRescueDays.tuesday", timeStateKey: "retailRescueStartTimes.tuesday", locationStateKey: "retailRescueLocations.tuesday", }, { title: "Wednesday", selected: data.retailRescueDays.wednesday, time: data.retailRescueStartTimes.wednesday, location: data.retailRescueLocations.wednesday, stateKey: "retailRescueDays.wednesday", timeStateKey: "retailRescueStartTimes.wednesday", locationStateKey: "retailRescueLocations.wednesday", }, { title: "Thursday", selected: data.retailRescueDays.thursday, time: data.retailRescueStartTimes.thursday, location: data.retailRescueLocations.thursday, stateKey: "retailRescueDays.thursday", timeStateKey: "retailRescueStartTimes.thursday", locationStateKey: "retailRescueLocations.thursday", }, { title: "Friday", selected: data.retailRescueDays.friday, time: data.retailRescueStartTimes.friday, location: data.retailRescueLocations.friday, stateKey: "retailRescueDays.friday", timeStateKey: "retailRescueStartTimes.friday", locationStateKey: "retailRescueLocations.friday", }, { title: "Saturday", selected: data.retailRescueDays.saturday, time: data.retailRescueStartTimes.saturday, location: data.retailRescueLocations.saturday, stateKey: "retailRescueDays.saturday", timeStateKey: "retailRescueStartTimes.saturday", locationStateKey: "retailRescueLocations.saturday", }, { title: "Sunday", selected: data.retailRescueDays.sunday, time: data.retailRescueStartTimes.sunday, location: data.retailRescueLocations.sunday, stateKey: "retailRescueDays.sunday", timeStateKey: "retailRescueStartTimes.sunday", locationStateKey: "retailRescueLocations.sunday", }, ]} onChange={this.handleInputChange} validCheck={this.isValid} /> </div> <div className="form-section" id="demographics"> <FormSectionHeader title="Demographics" /> <CheckboxList label="Check Boxes if Applicable." options={[ { title: "Youth", selected: data.youth, stateKey: "youth", }, { title: "Senior", selected: data.senior, stateKey: "senior", }, { title: "Homeless", selected: data.homeless, stateKey: "homeless", }, { title: "Veteran/Military", selected: data.veteran, stateKey: "veteran", }, { title: "Healthcare", selected: data.healthcare, stateKey: "healthcare", }, { title: "College/University", selected: data.college, stateKey: "college", }, { title: "Disability Specific (Physical or Mental)", selected: data.disabilitySpecific, stateKey: "disabilitySpecific", }, { title: "Residential", selected: data.residential, stateKey: "residential", }, { title: "Immigrant", selected: data.immigrant, stateKey: "immigrant", }, ]} onChange={this.handleInputChange} twoColumns /> </div> <div className="form-section" id="staff"> <FormRow> <FormCol> <h2 className="form-section-title" style={{ marginTop: 7, marginRight: 24 }}> Assigned Staff </h2> </FormCol> <FormCol> <InlineDropdown label={null} options={["Mia", "Charlie", "Eli", "Kate"]} value={data.tableContent.staff} stateKey="tableContent.staff" onChange={this.handleInputChange} valid={this.isValid("tableContent.staff")} /> </FormCol> </FormRow> </div> <div className="form-section"> <div className="form-button-container"> <FormButton title={editing ? "Save Profile" : "Create Profile"} type="primary" onClick={this.submitForm} /> <FormButton title="Cancel" type="secondary" onClick={this.cancelForm} /> </div> </div> </form> </div> ); } }
JavaScript
class InitEnv { constructor() { console.log(buildEnv, appName, 'buildEnv, appName '); this.notLoginUrl = `//${buildEnv === "online" ? "" : "pre."}zxhj618.com/login`; this.baseUrl = `//${buildEnv === "online" ? "" : "pre-"}main-service.zxhj618.com`; this.mallUrl = `//${buildEnv === "online" ? "" : "pre-"}saas-mall.zxhj618.com`; this.cookieName = this.matchCookieName(); this.homePage = `//${buildEnv === "online" ? "" : "pre."}zxhj618.com`; this.rentMallUrl = `//${buildEnv === 'online' ? 'rent-mall' : 'pre-rent-mall'}.zxhj618.com`; this.domain = process.env.NODE_ENV === "production" ? "domain=zxhj618.com;" : ""; } matchCookieName() { let result = []; switch (appName) { case "ZXHJ": result = `zxhj-${buildEnv === "online" ? "token" : "preToken"}`; break; case "SAAS": result = `${buildEnv === "online" ? "token" : "pre-token"}`; break; default: break; } return result; } }
JavaScript
class Universal_avatar extends baseResource_1.baseResource { constructor(connector, Model, settings) { super(connector, Model, settings); /** * * * @method createAvatarFromTemporary * @memberOf Universal_avatar# * @param {Object} options An object containing options to pass to the Jira API. * @param {string} options.type type * @param {string} options.owningObjectId owningObjectId * @param {string} options.cropperWidth cropperWidth * @param {string} options.cropperOffsetX cropperOffsetX * @param {string} options.cropperOffsetY cropperOffsetY * @param {string} options.url url * @param {string} options.needsCropping needsCropping * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used * @param [callback] if supplied, called with result of api call * @return {Promise.<any>} result of api call */ this.createAvatarFromTemporary = (...args) => { if (args.length === 0) { throw new Error("options must be passed"); } let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null; let options = ((typeof args[0]) === 'object') ? args[0] : {}; return this.makeRequest('createAvatarFromTemporary', 'POST', 'rest/api/2/universal_avatar/type/:type/owner/:owningObjectId/avatar', options, callback); }; /** * Deletes avatar * * @method deleteAvatar * @memberOf Universal_avatar# * @param {Object} options An object containing options to pass to the Jira API. * @param {string} options.type type * @param {string} options.owningObjectId owningObjectId * @param {string} options.id id * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used * @param [callback] if supplied, called with result of api call * @return {Promise.<any>} result of api call */ this.deleteAvatar = (...args) => { if (args.length === 0) { throw new Error("options must be passed"); } let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null; let options = ((typeof args[0]) === 'object') ? args[0] : {}; return this.makeRequest('deleteAvatar', 'DELETE', 'rest/api/2/universal_avatar/type/:type/owner/:owningObjectId/avatar/:id', options, callback); }; /** * * * @method getAvatars * @memberOf Universal_avatar# * @param {Object} options An object containing options to pass to the Jira API. * @param {string} options.type type * @param {string} options.owningObjectId owningObjectId * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used * @param [callback] if supplied, called with result of api call * @return {Promise.<any>} result of api call */ this.getAvatars = (...args) => { if (args.length === 0) { throw new Error("options must be passed"); } let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null; let options = ((typeof args[0]) === 'object') ? args[0] : {}; return this.makeRequest('getAvatars', 'GET', 'rest/api/2/universal_avatar/type/:type/owner/:owningObjectId', options, callback); }; /** * Creates temporary avatarname of file being uploadedsize of file * * @method storeTemporaryAvatar * @memberOf Universal_avatar# * @param {Object} options An object containing options to pass to the Jira API. * @param {string} options.type type * @param {string} options.owningObjectId owningObjectId * @param {string} options.filename filename name of file being uploaded * @param {string} options.size size size of file * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used * @param [callback] if supplied, called with result of api call * @return {Promise.<any>} result of api call */ this.storeTemporaryAvatar = (...args) => { if (args.length === 0) { throw new Error("options must be passed"); } let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null; let options = ((typeof args[0]) === 'object') ? args[0] : {}; return this.makeRequest('storeTemporaryAvatar', 'POST', 'rest/api/2/universal_avatar/type/:type/owner/:owningObjectId/temp', options, callback); }; /** * * * @method storeTemporaryAvatarUsingMultiPart * @memberOf Universal_avatar# * @param {Object} options An object containing options to pass to the Jira API. * @param {string} options.type type * @param {string} options.owningObjectId owningObjectId * @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If not supplied, the default token (if set) is used * @param [callback] if supplied, called with result of api call * @return {Promise.<any>} result of api call */ this.storeTemporaryAvatarUsingMultiPart = (...args) => { if (args.length === 0) { throw new Error("options must be passed"); } let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null; let options = ((typeof args[0]) === 'object') ? args[0] : {}; return this.makeRequest('storeTemporaryAvatarUsingMultiPart', 'POST', 'rest/api/2/universal_avatar/type/:type/owner/:owningObjectId/temp', options, callback); }; this.methods = []; this.register(); } }
JavaScript
class Controller extends FilterActionsCtrl { /** * Constructor. * @param {!angular.Scope} $scope The Angular scope. * @param {!angular.JQLite} $element The root DOM element. * @ngInject */ constructor($scope, $element) { super($scope, $element); /** * The context menu for feature action nodes. * @type {Menu<layerMenu.Context>|undefined} */ this['contextMenu'] = node.getMenu(); /** * Flag for whether to show default feature actions. * @type {boolean} */ this['showDefaultActions'] = true; /** * Flag for whether to show default feature actions. * @type {boolean|undefined} */ this['hasDefaultActions'] = undefined; DataManager.getInstance().listen(DataEventType.SOURCE_REMOVED, this.onSourceRemoved_, false, this); } /** * @inheritDoc */ disposeInternal() { super.disposeInternal(); DataManager.getInstance().unlisten(DataEventType.SOURCE_REMOVED, this.onSourceRemoved_, false, this); } /** * Close the feature action window if the source was removed * * @param {DataEvent} event * @private */ onSourceRemoved_(event) { if (event && event.source) { if (this.entryType && this.entryType == event.source.getId()) { this.close(); } } } /** * @inheritDoc * @export */ apply() { super.apply(); if (this.entryType) { var dm = DataManager.getInstance(); var source = dm.getSource(this.entryType); if (source) { var manager = FeatureActionManager.getInstance(); manager.processItems(source.getId(), source.getFeatures(), true); } } } /** * @inheritDoc */ getColumns() { return getColumns(this.entryType); } /** * @inheritDoc */ getExportName() { return getExportName(this.entryType); } /** * @inheritDoc * @export */ editEntry(opt_entry) { if (this.entryType) { editEntry(this.entryType, opt_entry); } } /** * @inheritDoc */ onSearch() { super.onSearch(); if (this['hasDefaultActions'] === undefined && this.scope['entries'] && this.scope['entries'].length > 0) { this['hasDefaultActions'] = this.scope['entries'].some((node) => { return node.getId() != TreeSearch.NO_RESULT_ID && node.getEntry().isDefault(); }); apply(this.scope); } } /** * Toggles showing default feature actions. * @export */ toggleDefaultActions() { this.treeSearch.setShowDefaultActions(this['showDefaultActions']); this.onSearch(); } }
JavaScript
class App extends Component { // Takes input from employees.json file and allows us to change it without having to reaccess data. state = { "employees": employees, "filteredEmployees": employees }; // Filters the data so that only employs that work in a given location are shown. handleLocationChange= location=>{ let array=[]; if(location !== "all"){ array=this.state.employees.filter(employee => employee.Region === location); }else{ array=this.state.employees; } this.setState({ filteredEmployees: array }); } // Sorts data by the option chosen by the user. handleSortChange= sortOption => { let array=[]; array=this.state.filteredEmployees.sort((a, b) => { if (a[sortOption] < b[sortOption]) { return -1; } if (a[sortOption] > b[sortOption]) { return 1; } return 0; }); this.setState({filteredEmployees: array}); } // Send data to EmployeeList to be rendered, then renders final results. render() { return ( <div className="container p-4 mr-auto ml-auto" style={styles.container}> <EmployeeList employees={this.state.filteredEmployees} locationChange={this.handleLocationChange} sortChange={this.handleSortChange}/> </div> ); } }
JavaScript
class Timestamp extends CommonBase { /** {Timestamp} The maximum valid timestamp. */ static get MAX_VALUE() { return new Timestamp(MAX_SECS - 1, USECS_PER_SEC - 1); } /** {Timestamp} The minimum valid timestamp. */ static get MIN_VALUE() { return new Timestamp(MIN_SECS, 0); } /** * Constructs an instance from a millisecond-granularity time value, such as * might have been returned from `Date.now()`. * * @param {Int} msec Milliseconds since the Unix Epoch. * @returns {Timestamp} An appropriately-constructed instance of this class. */ static fromMsec(msec) { return Timestamp.fromUsec(msec * 1000); } /** * Constructs an instance from a microsecond-granularity time value. * * @param {Int} usec Microseconds since the Unix Epoch. * @returns {Timestamp} An appropriately-constructed instance of this class. */ static fromUsec(usec) { const [secs, usecs] = Timestamp._splitUsecs(usec); return new Timestamp(secs, usecs); } /** * Constructs an instance from the return value of `Date.now()`. * * @returns {Timestamp} An appropriately-constructed instance of this class. */ static now() { return Timestamp.fromMsec(Date.now()); } /** * Checks a value which must be of type `Timestamp` or be `null`. * * @param {*} value Value to check. * @returns {Timestamp|null} `value`. */ static orNull(value) { if (value === null) { return null; } try { return Timestamp.check(value); } catch (e) { // Higher-fidelity error. throw Errors.badValue(value, 'TimeStamp|null'); } } /** * Constructs an instance. * * @param {Int} secs Seconds since the Unix Epoch. Must be in the "reasonable" * range as described in the class header. * @param {Int} usecs Additional microseconds. Must be a whole number less * than 1000000. */ constructor(secs, usecs) { super(); /** Seconds since the Unix epoch. */ this._secs = TInt.range(secs, MIN_SECS, MAX_SECS); /** Additional microseconds. */ this._usecs = TInt.range(usecs, 0, USECS_PER_SEC); Object.freeze(this); } /** {Int} The number of seconds since the Unix Epoch. */ get secs() { return this._secs; } /** * {Int} The additional microseconds. This is always a value in the range * `[0..999999]`. */ get usecs() { return this._usecs; } /** * Adds the indicated number of msec to this instance's value, returning a new * instance. * * @param {Int} addMsec Amount to add. It can be negative. * @returns {Timestamp} An appropriately-constructed instance. */ addMsec(addMsec) { TInt.check(addMsec); return this.addUsec(addMsec * 1000); } /** * Adds the indicated number of usec to this instance's value, returning a new * instance. * * @param {Int} addUsec Amount to add. * @returns {Timestamp} An appropriately-constructed instance. */ addUsec(addUsec) { TInt.check(addUsec); let [secs, usecs] = Timestamp._splitUsecs(addUsec); secs += this._secs; usecs += this._usecs; // Bump up `secs` if `usecs` overflows. **Note:** `_splitUsecs()` always // returns non-negative values for `usecs`, therefore we don't need to check // for underflow. if (usecs >= USECS_PER_SEC) { usecs -= USECS_PER_SEC; secs++; } return new Timestamp(secs, usecs); } /** * Compares this to another instance, returning the usual integer result of * comparison. * * @param {Timestamp} other Timestamp to compare to. * @returns {Int} `0` if the two have equal values; `-1` if this instance * comes before `other`; or `1` if this instance comes after `other`. */ compareTo(other) { Timestamp.check(other); let thisValue = this._secs; let otherValue = other._secs; if (thisValue === otherValue) { // Seconds match, so compare based on usecs. thisValue = this._usecs; otherValue = other._usecs; } if (thisValue === otherValue) { return 0; } else if (thisValue < otherValue) { return -1; } else { return 1; } } /** * Gets reconstruction arguments for this instance. * * @returns {array<*>} Reconstruction arguments. */ deconstruct() { return [this._secs, this._usecs]; } /** * Compares this to another instance for equality. * * @param {Timestamp} other Timestamp to compare to. * @returns {boolean} `true` if the two have equal values, or `false` if not. */ equals(other) { return this.compareTo(other) === 0; } /** * Custom inspector function, as called by `util.inspect()`. This is always of * the form `Timestamp(<secs>.<usecs>)` where `<usecs>` is always six digits * long. * * @param {Int} depth_unused Current inspection depth. * @param {object} opts_unused Inspection options. * @returns {string} The inspection string form of this instance. */ [inspect.custom](depth_unused, opts_unused) { // A little cheeky, but this left-pads the usecs with zeroes. const usecs = ('' + (this._usecs + USECS_PER_SEC)).slice(1); return `${this.constructor.name}(${this._secs}.${usecs})`; } /** * Splits a microseconds time value (either absolute or relative) into * separate seconds and microseconds values. If given a negative value, the * resulting `secs` will be negative, but `usecs` will always be non-negative. * * @param {Int} fullUsecs Microseconds since the Unix Epoch. * @returns {array<Int>} A two element array of `[secs, usecs]`. */ static _splitUsecs(fullUsecs) { TInt.check(fullUsecs); const secs = Math.floor(fullUsecs / USECS_PER_SEC); const usecs = fullUsecs - (secs * USECS_PER_SEC); return [secs, usecs]; } }
JavaScript
class RME { constructor() { this.instance = this; this.completeRun = function() {}; this.runner = function() {}; this.onrmestoragechange = function(state) {}; this.components = {}; this.rmeState = {}; } complete() { this.completeRun(); } start() { this.runner(); } setComplete(runnable) { this.completeRun = runnable; } setRunner(runnable) { this.runner = runnable; return this.instance; } addComponent(runnable) { var comp = runnable(); for(var p in comp) { if(comp.hasOwnProperty(p)) { this.components[p] = comp[p]; } } } getComponent(name, props) { return this.components[name].call(props); } setRmeState(key, value) { this.rmeState[key] = value; this.onrmestoragechange(this.rmeState); } getRmeState(key) { return this.rmeState[key]; } /** * Runs a runnable script immedeately */ static run(runnable) { if(runnable && Util.isFunction(runnable)) RME.getInstance().setRunner(runnable).start(); } /** * Waits until body has been loaded and then runs a runnable script */ static ready(runnable) { if(runnable && Util.isFunction(runnable)) RME.getInstance().setComplete(runnable); } static component(runnable, props) { if(runnable && Util.isFunction(runnable)) RME.getInstance().addComponent(runnable); else if(runnable && Util.isString(runnable)) return RME.getInstance().getComponent(runnable, props); } static storage(key, value) { if(!Util.isEmpty(key) && !Util.isEmpty(value)) RME.getInstance().setRmeState(key, value); else if(!Util.isEmpty(key) && Util.isEmpty(value)) return RME.getInstance().getRmeState(key); } static script(source, id, type, text, defer, crossOrigin, charset, async) { if(!Util.isEmpty(source)) { var sc = new Elem("script").setSource(source); if(!Util.isEmpty(id)) sc.setId(id); if(!Util.isEmpty(type)) sc.setType(type); if(!Util.isEmpty(text)) sc.setText(text); if(!Util.isEmpty(defer)) sc.setAttribute("defer", defer); if(!Util.isEmpty(crossOrigin)) sc.setAttribute("crossOrigin", crossOrigin); if(!Util.isEmpty(charset)) sc.setAttribute("charset", charset); if(!Util.isEmpty(async)) sc.setAttribute("async", async); RME.config().addScript(sc); } } static onrmestoragechange(listener) { if(listener && Util.isFunction(listener)) RME.getInstance().onrmestoragechange = listener; } static config() { return { addScript: function(elem){ var scripts = Tree.getScripts(); var lastScript = Elem.wrap(scripts[scripts.length -1]); lastScript.after(elem); }, removeScript: function(sourceOrId) { if(sourceOrId.indexOf("#") === 0) { Tree.getHead().remove(Tree.get(sourceOrId)); } else { var scripts = Tree.getScripts(); for(var s in scripts) { if(scripts.hasOwnProperty(s)) { var src = scripts[s].src !== null ? scripts[s].src : ""; if(src.search(sourceOrId) > -1 && src.search(sourceOrId) === src.length - sourceOrId.length) { Tree.getHead().remove(Elem.wrap(scripts[s])); break; } } } } } } } static getInstance() { if(!this.instance) this.instance = new RME(); return this.instance; } }
JavaScript
class Http { constructor(config) { config.contentType = config.contentType === undefined ? Http.JSON : config.contentType; if(config.useFetch) { this.self = new FetchRequest(); } else if(window.Promise) { this.self = new PromiseAjax(config).instance(); } else { this.self = new Ajax(config); } } instance() { return this.self; } static get(url, requestContentType) { return new Http({method: "GET", url: url, data: undefined, contentType: requestContentType}).instance(); } static post(url, data, requestContentType) { return new Http({method: "POST", url: url, data: data, contentType: requestContentType}).instance(); } static put(url, data, requestContentType) { return new Http({method: "PUT", url: url, data: data, contentType: requestContentType}).instance(); } static delete(url, requestContentType) { return new Http({method: "DELETE", url: url, data: undefined, contentType: requestContentType}).instance(); } static do(config) { return new Http(config).instance(); } static fetch() { return new Http({useFetch: true}).instance(); } }
JavaScript
class FetchRequest { constructor() {} get(url, init) { if(!init) init = {}; init.method = "GET"; return this.do({url: url, init: init, contentType: Http.JSON}); } post(url, body, init) { if(!init) init = {}; init.method = "POST"; init.body = body; return this.do({url: url, init: init, contentType: Http.JSON}); } put(url, body, init) { if(!init) init = {}; init.method = "PUT"; init.body = body; return this.do({url: url, init: init, contentType: Http.JSON}); } delete(url, init) { if(!init) init = {}; init.method = "DELETE"; return this.do({url: url, init: init, contentType: Http.JSON}); } do(config) { if(!config.init) config.init = {}; if(config.contentType) { if(!config.init.headers) config.init.headers = new Headers({}) config.init.headers.set("Content-Type", config.contentType); } if(config.method) { config.init.method = config.method; } return fetch(config.url, config.init); } }
JavaScript
class ConfigLoader { /** * Loads a resource and returns a new {Config} object * @returns {Config} The Config */ load() { console.warn( "This method is a Raw NoOp. Expect consumers to provide concrete implementation via subclass" ); } }
JavaScript
class ReactWWComponent { constructor(element) { this._tag = element.type.toLowerCase(); this._currentElement = element; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._wrapperState = null; this._topLevelWrapper = null; this._nodeWithLegacyProperties = null; this._rootNodeID = null; } /** * Mounting the root component. * * @internal * @param {string} rootID - The root ID for this node. * @param {ReactReconcileTransaction} transaction * @param {object} context */ mountComponent(transaction, parent, hostInfo, context) { this._rootNodeID = 'c' + guid++; const node = this.mountNode(transaction, parent, this._currentElement); // Mounting children let childrenToUse = this._currentElement.props.children; childrenToUse = childrenToUse === null ? [] : [].concat(childrenToUse); if (childrenToUse.length) { this.mountChildren(childrenToUse, transaction, context); } // Rendering the rootNode ReactWWIDOperations.getRoot(this._rootNodeID).render(); return this; } /** * Mounting the node itself. * * @param {Node} parent - The parent node. * @param {ReactElement} element - The element to mount. * @return {Node} - The mounted node. */ mountNode(transaction, parent, element) { const { props, type } = element, { children, ...restProps } = props; let { eventHandlers, options } = extractEventHandlers(restProps); const parentNode = parent instanceof WorkerDomNodeStub ? parent : ReactWWIDOperations.get(parent._rootNodeID); const node = new WorkerDomNodeStub(this._rootNodeID, type, options, parentNode.bridge ); ReactWWIDOperations.add(this._rootNodeID, node, parentNode.reactId); parentNode.addChild(node); transaction.getReactMountReady().enqueue(function(){ this.node.addEventHandlers(this.eventHandlers); }, { node, eventHandlers }); return node; } /** * Receive a component update. * * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal * @overridable */ receiveComponent(nextElement, transaction, context) { const { props: { children, ...restProps } } = nextElement, { eventHandlers, options } = extractEventHandlers(restProps); let node = ReactWWIDOperations.get(this._rootNodeID); node.setAttributes(options); //node.addEventHandlers(eventHandlers); this.updateChildren(children, transaction, context); //ReactWWIDOperations.rootNode.render(); <- No real need to update the parent also return this; } /** * Dropping the component. */ unmountComponent() { this.unmountChildren(); const node = ReactWWIDOperations.get(this._rootNodeID); node.removeEventHandlers(); // Unmounting should not remove Child // THey will be removed when they are replaced in markup // Or when REMOVE_NODE in Child openrations is called //var parent = ReactWWIDOperations.getParent(node.reactId); //parent.removeChild(node); const root = ReactWWIDOperations.getRoot(this._rootNodeID); ReactWWIDOperations.drop(this._rootNodeID); this._rootNodeID = null; root.render(); } /** * Getting a public instance of the component for refs. * * @return {Node} - The instance's node. */ getPublicInstance() { return ReactWWIDOperations.get(this._rootNodeID); } getHostNode() { return ReactWWIDOperations.get(this._rootNodeID); } }
JavaScript
class ContractClient { constructor (web3Manager, contractABI, contractRegistryKey, getRegistryAddress) { this.web3Manager = web3Manager this.web3 = web3Manager.getWeb3() this.contractABI = contractABI this.contractRegistryKey = contractRegistryKey this.getRegistryAddress = getRegistryAddress // Once initialized, contract address and contract are set up this._contractAddress = null this._contract = null // Initialization setup this._isInitialized = false this._isInitializing = false } /** Inits the contract if necessary */ async init () { // No-op if we are already initted if (this._isInitialized) return // If we are already initting, wait until we are initted and return if (this._isInitializing) { let interval await new Promise((resolve, reject) => { interval = setInterval(() => { if (this._isInitialized) resolve() }, CONTRACT_INITIALIZING_INTERVAL) setTimeout(() => { reject(new Error('Initialization timeout')) }, CONTRACT_INITIALIZING_TIMEOUT) }) clearInterval(interval) return } // Perform init this._isInitializing = true try { this._contractAddress = await this.getRegistryAddress(this.contractRegistryKey) this._contract = new this.web3.eth.Contract( this.contractABI, this._contractAddress ) this._isInitialized = true } catch (e) { console.error(`Failed to initialize contract ${JSON.stringify(this.contractABI)}`, e) } this._isInitializing = false } /** Gets the contract address and ensures that the contract has initted. */ async getAddress () { await this.init() return this._contractAddress } /** * Gets a contract method and ensures that the contract has initted * The contract can then be invoked with .call() or be passed to a sendTransaction. * @param {string} methodName the name of the contract method */ async getMethod (methodName, ...args) { await this.init() if (!(methodName in this._contract.methods)) { throw new Error(`Contract method ${methodName} not found in ${Object.keys(this._contract.methods)}`) } return this._contract.methods[methodName](...args) } }
JavaScript
class List extends Component { constructor() { super(); this.state = { formOpen: false, approvalOpen: false, resultsMessage: '' }; this.toggleFormVisibility = this.toggleFormVisibility.bind(this); } async componentDidMount() { await this.props.getUserTokenPositions(this.props.userAccount); } componentWillReceiveProps(nextProps) { if (nextProps.listOrderError !== null) { this.setState({ resultsMessage: `Error: ${this.props.listOrderError}`, approvalOpen: false, formOpen: false }); } else if (nextProps.listOrderId) { this.setState({ resultsMessage: `List Order result ${this.props.listOrderId}`, approvalOpen: true, formOpen: false }); } else if (this.props.listOrderApproveError) { this.setState({ resultsMessage: `Error: ${this.props.listOrderApproveError}`, sendFundsOpen: false, formOpen: false }); } else if (this.props.listOrderApproved) { this.setState({ resultsMessage: `Order approval confirmed`, sendFundsOpen: false, formOpen: false }); } } handleApproveClick = async e => { const approveDetails = { selectedToken: this.props.selectedToken, amount: this.props.tokenAmt }; await this.props.sendApproveOrder(approveDetails, this.props.userAccount); if (this.props.listOrderApproveError) { this.setState({ resultsMessage: `Error: ${this.props.listOrderApproveError}`, sendFundsOpen: false, formOpen: false }); } else { this.setState({ resultsMessage: `Order approval confirmed`, sendFundsOpen: false, formOpen: false }); } }; toggleFormVisibility() { this.setState({ formOpen: !this.state.formOpen }); } render() { return ( <div className="container"> <div id="list-button"> <button className="btn btn-info" onClick={this.toggleFormVisibility}> List Order </button> </div> <Collapse isOpen={this.state.formOpen}> <div id="list-form"> <h4 className="center-text">Place Order</h4> <ListFormContainer /> </div> </Collapse> <Collapse isOpen={this.state.approvalOpen}> <div id="approval"> <h4 className="center-text">Order Placed</h4> <button className="btn btn-success" onClick={this.handleApproveClick} > Approve Order </button> </div> </Collapse> {this.state.resultsMessage && ( <div id="results-message" className="text-center"> {this.state.resultsMessage} </div> )} </div> ); } }
JavaScript
class Provider { /** * @api public * @returns {Promise} */ recognize () { throw new Error('Method "recognize" is not implemented'); } /** * @api public * @returns {Object} */ isResponseSuccessful () { throw new Error('Method "isResponseSuccessful" is not implemented'); } /** * @api public * @returns {Object} */ normalizeResult () { throw new Error('Method "normalizeResult" is not implemented'); } /** * @api publc * @returns {String} */ get name () { return this.constructor.name; } }
JavaScript
class SimpleNavigation extends Control { constructor(options) { options = options || {}; super(options); this.camera = null; this.speed = options.speed || 1.0; } oninit() { this.camera = this.renderer.activeCamera; this.renderer.events.on("keypress", input.KEY_W, this.onCameraMoveForward, this); this.renderer.events.on("keypress", input.KEY_S, this.onCameraMoveBackward, this); this.renderer.events.on("keypress", input.KEY_A, this.onCameraStrifeLeft, this); this.renderer.events.on("keypress", input.KEY_D, this.onCameraStrifeRight, this); this.renderer.events.on("keypress", input.KEY_UP, this.onCameraLookUp, this); this.renderer.events.on("keypress", input.KEY_DOWN, this.onCameraLookDown, this); this.renderer.events.on("keypress", input.KEY_LEFT, this.onCameraTurnLeft, this); this.renderer.events.on("keypress", input.KEY_RIGHT, this.onCameraTurnRight, this); this.renderer.events.on("keypress", input.KEY_Q, this.onCameraRollLeft, this); this.renderer.events.on("keypress", input.KEY_E, this.onCameraRollRight, this); } onCameraMoveForward(event) { var camera = this.camera; camera.slide(0, 0, -this.speed); camera.update(); } onCameraMoveBackward(event) { var camera = this.camera; camera.slide(0, 0, this.speed); camera.update(); } onCameraStrifeLeft(event) { var camera = this.camera; camera.slide(-this.speed, 0, 0); camera.update(); } onCameraStrifeRight(event) { var camera = this.camera; camera.slide(this.speed, 0, 0); camera.update(); } onCameraLookUp(event) { var cam = this.camera; cam.pitch(0.5); cam.update(); } onCameraLookDown(event) { var cam = this.camera; cam.pitch(-0.5); cam.update(); } onCameraTurnLeft(event) { var cam = this.camera; cam.yaw(0.5); cam.update(); } onCameraTurnRight(event) { var cam = this.camera; cam.yaw(-0.5); cam.update(); } onCameraRollLeft(event) { var cam = this.camera; cam.roll(-0.5); cam.update(); } onCameraRollRight(event) { var cam = this.camera; cam.roll(0.5); cam.update(); } }
JavaScript
class Chloroquine { // Constants static STORAGE_LABEL = 'Chloroquine' static TAGS_TO_SCAN = '*' // Map of terms to replace mappings = {} // HTML document & elemens to replace terms elements = [] /** * Class constructor * @param {HTMLDocument} document: The page to find terms to replace * @param {Object} mappings: Term mappings object */ constructor(document, mappings) { // If document passed, set elements if (document && (Object.keys(document).length > 0)) { this.elements = Array.from( document.getElementsByTagName(Chloroquine.TAGS_TO_SCAN) ) } // If term mappings passed, set it and run replacements if (mappings && (Object.keys(mappings).length > 0)) { // Set term mappings this.setMappings(mappings) // Run replacement this.runReplacements() } } /** * Run terms replacements */ runReplacements() { // For all mappings Object.keys(this.mappings).forEach((key) => { // Replace in elements if (this.elements.length > 0) { this.replace(this.elements, key, this.mappings[key]) } }) } /** * Function responsible to replace the terms * @param {Array} elements: Array of HTML elements * @param {String} from: Term to search for * @param {String} to: Replacement term */ replace(elements, from, to) { // For all elements elements.forEach((element) => { // Into all its child nodes element.childNodes.forEach((node) => { // For node type(s) switch (node.nodeType) { // Type 3 (Text node) case 3: { // Replace nodeValue if it contains the term to replace if (node.nodeValue.includes(from)) { node.nodeValue = node.nodeValue.replace(from, to) } } } }) }) } /** * Add term to mappings * @param {String} from: Term to add to mappings * @param {String} to: Replacement term to add to mappings */ addMap(from, to) { this.mappings[from] = to } /** * Remove term from mappings * @param {String} from: Term to search for removal */ removeMap(from) { delete this.mappings[from] } /** * Set term mappings using mappings param * @param {Object} mappings: Term mappings object */ setMappings(mappings) { this.mappings = mappings } /** * Return term mappings */ getMappings() { return this.mappings } }
JavaScript
class Pipeline2dRGB extends React.Component { constructor(props) { super(props); this.imageId = 'pipeline2d-rgb-image'; this.canvasWidth = 1000; this.canvasHeight = 600; this.canvas = null; this.state = { isRecording: false }; this.changeInput = pipelineChangeInput.bind(this); this.componentDidMount = pipelineComponentDidMount.bind(this); } /** * Do edge detection pipeline on inputted image */ process() { const size = 190; this.canvas = document.getElementById(`${this.imageId}-canvas`); const context = this.canvas.getContext('2d'); // Clear canvas context.clearRect(0, 0, this.canvas.width, this.canvas.height); context.drawImage(this.img, 0, 200, size, size); let imgData = context.getImageData(0, 200, size, size); let source = new Array2D([...imgData.data], imgData.width, imgData.height, 4); let rSource = new Array2D([...imgData.data], imgData.width, imgData.height, 4); let gSource = new Array2D([...imgData.data], imgData.width, imgData.height, 4); let bSource = new Array2D([...imgData.data], imgData.width, imgData.height, 4); filterColor(rSource, 1, 0, 0); fillArray(imgData.data, rSource.data, imgData.data.length); context.putImageData(imgData, 400, 0); filterColor(gSource, 0, 1, 0); fillArray(imgData.data, gSource.data, imgData.data.length); context.putImageData(imgData, 400, 200); filterColor(bSource, 0, 0, 1); fillArray(imgData.data, bSource.data, imgData.data.length); context.putImageData(imgData, 400, 400); grayscale(source); fillArray(imgData.data, source.data, imgData.data.length); context.putImageData(imgData, 800, 200); // Draw lines context.lineWidth = 2; context.beginPath(); canvasArrowCurveX(context, 0 + size, 200 + size / 2, 400, 0 + size / 2); canvasArrowCurveX(context, 0 + size, 200 + size / 2, 400, 200 + size / 2); canvasArrowCurveX(context, 0 + size, 200 + size / 2, 400, 400 + size / 2); canvasArrowCurveX(context, 400 + size, 0 + size / 2, 800, 200 + size / 2); canvasArrowCurveX(context, 400 + size, 200 + size / 2, 800, 200 + size / 2); canvasArrowCurveX(context, 400 + size, 400 + size / 2, 800, 200 + size / 2); context.stroke(); } render() { return e('div', { className: 'demo-container' }, e('div', { style: { display: 'flex', flexDirection: 'row' } }, e(ImageUploader, { imageId: this.imageId, defaultImage: '/static/24-Perception/images/test.png', processHandler: () => this.process(), changeHandler: () => this.changeInput('image'), }, null), e(WebcamCapture, { imageId: this.imageId, isRecording: this.state.isRecording, processHandler: () => this.process(), changeHandler: () => this.changeInput('webcam'), }, null), e('div', { style: { display: 'flex', flex: 1 } }, null), e('div', { className: 'dropdown' }, e('a', { className: 'btn btn-info dropdown-toggle', 'data-toggle': 'dropdown', }, 'Presets ', e('b', { className: 'caret' }, null)), e('ul', { className: 'dropdown-menu dropdown-menu-right' }, e('li', null, e('a', { href: "#", onClick: (e) => { e.preventDefault(); this.changeInput('image'); this.img.src = "/static/third-party/leds.jpg"; this.process(); } }, 'RGB') ), e('li', null, e('a', { href: "#", onClick: (e) => { e.preventDefault(); this.changeInput('image'); this.img.src = "/static/third-party/piripiri.jpg"; this.process(); } }, 'Red-Green') ), e('li', null, e('a', { href: "#", onClick: (e) => { e.preventDefault(); this.changeInput('image'); this.img.src = "/static/24-Perception/images/world.jpg"; this.process(); } }, 'Green-Blue') ), ), ), ), e('br', null, null), e('canvas', { id: `${this.imageId}-canvas`, width: this.canvasWidth, height: this.canvasHeight, style: { width: '100%', } }, null), ); } }
JavaScript
class InfoModalBodyContent extends Component { constructor(props) { super(props); this.state = { show: false }; } getContentStageInfoBody() { if(this.props.contentStage == 'Draft') { return <p>Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” and unlikely ready for comment. Content at this Level should not be used. This is the initial status assigned to newly created content.</p>; } else if(this.props.contentStage == 'Comment Only') { return <p>Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” but is ready for viewing and comment. Content at this Level should not be used.</p>; } else if(this.props.contentStage == 'Trial Use') { return <p>Content that the Authors and Publisher believe is ready for User viewing, testing and/or comment. It is generally “complete”, but not final. Content at this Level should not be used to support public health response.</p>; } else if(this.props.contentStage == 'Published') { return <p>A publicly available version of content that is ready for viewing, downloading, comments, and use for public health response. Content that is automatically updated to this stage at the time it is made public.</p>; } else if(this.props.contentStage == 'Retired') { return <p>Content that is no longer the most recent version (not latest). However, this content could be used with no known risk.</p>; } else if(this.props.contentStage == 'Duplicate') { return <p>Content that the Author and Publisher believe is either syntactically or conceptually a duplicate of other content in the SDP-V repository. Content marked as “Duplicate” should not be used when creating new SDP-V Surveys. If content marked as “Duplicate” is used on an existing SDP-V Survey, it should be replaced during the next revision. This content stage is assigned whenever users curate their public Surveys using the curation wizard. This content stage cannot be assigned by users outside of the curation wizard.</p>; } } getVisibilityInfoBody() { if(this.props.visibility == 'private') { return <p>Private content is only visible to the user who authored it, users that belong to a group that the content is added to, and to all Publishers in the system. Content with this visibility can be modified until the author or authoring group is ready to make the content public. When content is initially created or imported into the Vocabulary Service, it is created with private visibility. <br/><br/>Whenever an author or authoring group is ready to share their content publicly, an author must send a publish request to their program Publisher to change the visibility to public.</p>; } else if(this.props.visibility == 'public') { return <p>Public content is visible to everyone who visits the Vocabulary Service website including users without authenticated accounts. This allows for authors to share their Vocabulary Service content with a wide public health audience. Once a version is made public, it cannot be undone; however authors can request that public content is “retired” which hides the content from dashboard search results. <br/><br/>An author can use the “content stage” attribute to indicate the maturity of a specific version of public content (like published or trial use) or can create a new version when updates are necessary. </p>; } } getVersionInfoBody() { return <p>The version independent ID is an API parameter that uniquely identifies a particular response set, question, section, or SDP-V survey. If a version is not specified, the API will return the most recent version of vocabulary.</p>; } getTagInfoBody() { return <p>Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. Tags are weighted in the dashboard search result algorithm so users are presented with search results that have been tagged with the same keyword(s) entered in the dashboard search bar. <br/> <br/> Keyword tags can be changed (added or deleted) at any time by the author(s) to meet user needs and to optimize search results. The history of tags is not saved on the change history tab; tags are not versioned.</p>; } getVersionIndependentIDInfoBody() { return <p>The version independent ID is an API parameter that uniquely identifies a particular response set, question, section, or SDP-V survey. If a version is not specified, the API will return the most recent version of vocabulary.</p>; } getCodeSystemMappingsInfoBody() { return <p>FROM MODAL.</p>; } codeMappingHelpModal(){ return <div> <h2 clasName='no-padding-top'>Purpose</h2> <p>The purpose of the Code System Mappings table is to identify the governed concepts from code systems like LOINC, SNOMED, PHIN VADS, etc that are associated with response sets, questions, sections, or surveys in SDP-V. That is, the Code System Mappings table identifies how content in SDP-V is represented in another code system.<br/>The Code System Mappings table should only include mapping to governed concepts. Non-governed concepts or keywords should not be added to the Code System Mappings table. If you would like to add keywords to your response set, question, section, or survey to facilitate content discovery or organization, please see the “Keyword Tags” help documentation for information on how to use the “Tags” feature.</p> <p><strong>Mutability: </strong>Any changes to entries in the Code System Mappings table are versioned since code system mappings are a property of the vocabulary itself. This allows users to update the Code System Mappings while maintaining legacy mappings in older SDP-V content versions if needed.</p> <p><strong>Discoverability: </strong>Code System Mappings table fields are included in the dashboard search algorithm so other users can find questions, sections, and surveys with specific concept names, concept identifiers or code system identifiers in SDP-V. For instance, a user can enter “27268008” into the dashboard search box to find content in SDP-V associated with that concept identifier. </p> <h2>Example Code System Mappings Table</h2> <table className="set-table table"> <caption><strong></strong></caption> <thead> <tr> <th id="concept-name">Concept Name</th> <th id="concept-identifier">Concept Identifier</th> <th id="code-sytem-identifier">Code System Identifier</th> </tr> </thead> <tbody> <tr> <td headers="concept-name">Genus Salmonella (organism)</td> <td headers="concept-identifier">27268008</td> <td headers="code-sytem-identifier">2.16.840.1.113883.6.96</td> </tr> <tr> <td headers="concept-name">Genus Campylobacter (organism)</td> <td headers="concept-identifier">35408001</td> <td headers="code-sytem-identifier">2.16.840.1.113883.6.96</td> </tr> </tbody> </table><br/> <p><strong>How to Search for Previously Used Code Mappings</strong><br/>To determine if a code system mapping has been used before in SDP-V, start typing in the concept name column of the table. A drop-down list of all previously used concept names that match the text entered in the field will appear. A user can navigate the list and select a concept name that was previously used. If a concept name is selected from the list, the concept identifier and code system identifier fields will be populated with existing values already entered in SDP-V.</p> <p><strong>How to Search for Code Mappings from an External Code Systems</strong><br/>Rather than requiring you to copy and paste codes from other code systems, SDP-V allows you to search for codes from specific external code systems by clicking on the “Search for external coded items” magnifying glass icon to the right of the code system mappings header. This opens the Search Codes dialog box. You may select a particular code system from the drop-down menu, or enter a search term to search across multiple code systems. This code search functionality searches codes from PHIN VADS. You may add coded values from these search results to the code mappings table by clicking the “Add” selection beside each result.</p> <p><strong>How to Create a New Code System Mapping</strong><br/>A new code system mapping may be created by simply typing a new concept name, concept identifier, and code system identifier. A new code mapping should only be created if an existing code mapping does not meet a user’s needs.</p> </div>; } getMarkAsReviewedInfoBody() { return <p>After review, if no good replacements are found in the system, clicking “Mark as Reviewed” will mark this response set as reviewed on today’s date and will filter out these suggestions from future results. Only new response sets added to SDP-V after the “marked as reviewed” date will be suggested when returning to curate this survey so that the author can focus on the new suggestions.<br/><br/>The date filter may be removed at any time by clicking “Show all past suggestions“. </p>; } render() { if(this.props.enum == 'contentStage') { return this.getContentStageInfoBody(); } else if (this.props.enum == 'visibility') { return this.getVisibilityInfoBody(); } else if (this.props.enum == 'version') { return this.getVersionInfoBody(); } else if (this.props.enum == 'tags') { return this.getTagInfoBody(); } else if (this.props.enum == 'versionIndependentID') { return this.getVersionIndependentIDInfoBody(); } else if (this.props.enum == 'codeSystemMappings') { return this.getCodeSystemMappingsInfoBody(); } else if (this.props.enum == 'codeMappingHelpModal') { return this.codeMappingHelpModal(); } else if (this.props.enum == 'markAsReviewed') { return this.getMarkAsReviewedInfoBody(); } } }
JavaScript
class mxXmlRequest { constructor(url, params, method, async, username, password) { this.url = url; this.params = params; this.method = method || 'POST'; this.async = async != null ? async : true; this.username = username; this.password = password; } /** * Variable: url * * Holds the target URL of the request. */ url = null; /** * Variable: params * * Holds the form encoded data for the POST request. */ params = null; /** * Variable: method * * Specifies the request method. Possible values are POST and GET. Default * is POST. */ method = null; /** * Variable: async * * Boolean indicating if the request is asynchronous. */ async = null; /** * Boolean indicating if the request is binary. This option is ignored in IE. * In all other browsers the requested mime type is set to * text/plain; charset=x-user-defined. Default is false. * * @default false */ // binary: boolean; binary = false; /** * Specifies if withCredentials should be used in HTML5-compliant browsers. Default is false. * * @default false */ // withCredentials: boolean; withCredentials = false; /** * Variable: username * * Specifies the username to be used for authentication. */ username = null; /** * Variable: password * * Specifies the password to be used for authentication. */ password = null; /** * Holds the inner, browser-specific request object. */ // request: any; request = null; /** * Specifies if request values should be decoded as URIs before setting the * textarea value in {@link simulate}. Defaults to false for backwards compatibility, * to avoid another decode on the server this should be set to true. */ // decodeSimulateValues: boolean; decodeSimulateValues = false; /** * Returns {@link binary}. */ // isBinary(): boolean; isBinary() { return this.binary; } /** * Sets {@link binary}. * * @param value */ // setBinary(value: boolean): void; setBinary(value) { this.binary = value; } /** * Returns the response as a string. */ // getText(): string; getText() { return this.request.responseText; } /** * Returns true if the response is ready. */ // isReady(): boolean; isReady() { return this.request.readyState === 4; } /** * Returns the document element of the response XML document. */ // getDocumentElement(): XMLDocument; getDocumentElement() { const doc = this.getXml(); if (doc != null) { return doc.documentElement; } return null; } /** * Returns the response as an XML document. Use {@link getDocumentElement} to get * the document element of the XML document. */ // getXml(): XMLDocument; getXml() { let xml = this.request.responseXML; // Handles missing response headers in IE, the first condition handles // the case where responseXML is there, but using its nodes leads to // type errors in the mxCellCodec when putting the nodes into a new // document. This happens in IE9 standards mode and with XML user // objects only, as they are used directly as values in cells. if (xml == null || xml.documentElement == null) { xml = parseXml(this.request.responseText); } return xml; } /** * Returns the status as a number, eg. 404 for "Not found" or 200 for "OK". * Note: The NS_ERROR_NOT_AVAILABLE for invalid responses cannot be cought. */ // getStatus(): number; getStatus() { return this.request != null ? this.request.status : null; } /** * Creates and returns the inner {@link request} object. */ // create(): any; create() { const req = new XMLHttpRequest(); // TODO: Check for overrideMimeType required here? if (this.isBinary() && req.overrideMimeType) { req.overrideMimeType('text/plain; charset=x-user-defined'); } return req; } /** * Send the <request> to the target URL using the specified functions to * process the response asychronously. * * Note: Due to technical limitations, onerror is currently ignored. * * @param onload Function to be invoked if a successful response was received. * @param onerror Function to be called on any error. Unused in this implementation, intended for overriden function. * @param timeout Optional timeout in ms before calling ontimeout. * @param ontimeout Optional function to execute on timeout. */ // send(onload: Function, onerror: Function, timeout?: number, ontimeout?: Function): void; send(onload, onerror, timeout, ontimeout) { this.request = this.create(); if (this.request != null) { if (onload != null) { this.request.onreadystatechange = () => { if (this.isReady()) { onload(this); this.request.onreadystatechange = null; } }; } this.request.open( this.method, this.url, this.async, this.username, this.password ); this.setRequestHeaders(this.request, this.params); if (window.XMLHttpRequest && this.withCredentials) { this.request.withCredentials = 'true'; } if ( document.documentMode == null && window.XMLHttpRequest && timeout != null && ontimeout != null ) { this.request.timeout = timeout; this.request.ontimeout = ontimeout; } this.request.send(this.params); } } /** * Sets the headers for the given request and parameters. This sets the * content-type to application/x-www-form-urlencoded if any params exist. * * @example * ```JavaScript * request.setRequestHeaders = function(request, params) * { * if (params != null) * { * request.setRequestHeader('Content-Type', * 'multipart/form-data'); * request.setRequestHeader('Content-Length', * params.length); * } * }; * ``` * * Use the code above before calling {@link send} if you require a * multipart/form-data request. * * @param request * @param params */ // setRequestHeaders(request: any, params: any): void; setRequestHeaders(request, params) { if (params != null) { request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); } } /** * Creates and posts a request to the given target URL using a dynamically * created form inside the given document. * * @param doc Document that contains the form element. * @param target Target to send the form result to. */ // simulate(doc: any, target: any): void; simulate(doc, target) { doc = doc || document; let old = null; if (doc === document) { old = window.onbeforeunload; window.onbeforeunload = null; } const form = doc.createElement('form'); form.setAttribute('method', this.method); form.setAttribute('action', this.url); if (target != null) { form.setAttribute('target', target); } form.style.display = 'none'; form.style.visibility = 'hidden'; const pars = this.params.indexOf('&') > 0 ? this.params.split('&') : this.params.split(); // Adds the parameters as textareas to the form for (let i = 0; i < pars.length; i += 1) { const pos = pars[i].indexOf('='); if (pos > 0) { const name = pars[i].substring(0, pos); let value = pars[i].substring(pos + 1); if (this.decodeSimulateValues) { value = decodeURIComponent(value); } const textarea = doc.createElement('textarea'); textarea.setAttribute('wrap', 'off'); textarea.setAttribute('name', name); write(textarea, value); form.appendChild(textarea); } } doc.body.appendChild(form); form.submit(); if (form.parentNode != null) { form.parentNode.removeChild(form); } if (old != null) { window.onbeforeunload = old; } } }
JavaScript
class ElCollapseItemComponent extends Component { /** * unique identification of the panel * * @property name * @type {string | number} * @public */ @argument name = null; /** * title of the panel * * @property title * @type {string} * @public */ @argument title = null; /** * disable the collapse item * * @property disabled * @type {boolean} * @default false * @public */ @argument disabled = false; @argument selected = ''; get active() { if (typeof this.selected === 'string') { return this.name === this.selected; } else { return this.selected.includes(this.name); } } @action handleClick() { this.args.click?.(this.name); } }
JavaScript
class Dhyaan { /** * Create new Dhyaan */ constructor() { this.middleware = {}; } /** * Add a middleware function to the handler list. * @param {string} middleware Name of the middleware function. * @param {function} func The middleware function. */ add(middleware, func) { this.middleware[middleware] = func; } /** * Add multiple middleware functions to the handler list. * @param {list} middlewares List of names of the middleware functions. * @param {list} funcs The list middleware functions. */ addMultiple(middlewares, funcs) { if (middlewares.length != funcs.length) return; for (const middleware in middlewares) { if (Object.prototype.hasOwnProperty.call(middlewares, middleware)) { this.middleware[middlewares[middleware]] = funcs[middleware]; } } } }
JavaScript
class Sequence extends Collection { /** * Sequence constructor * * @param {Function} complete function to be called on complete * @param {Function} recover function to be called on recover */ constructor(complete, recover) { super(complete, recover); this._current = undefined; this._passed = []; this._stopped = false; } /** * Runs all tasks in the collection */ run() { super.run(); this._stopped = false; this._next(); } /** * Stops all tasks in the collection * * @param {boolean} skip force the stopped task to be skipped * @return {boolean} stopped stopped status */ stop(skip = false) { this._stopped = true; this._running = false; const current = this.current; if (current !== undefined) { if (skip === true) { this._resetCurrent(true, true); } else { if (this.tasks.indexOf(current) === -1) { this.unshift(current); } } return current.stop() || this.tasks.length > 0; } else { return false; } } /** * Resets a stopped collection * * @return {boolean} reset reset status */ reset() { if (super.reset()) { this._passed = []; return true; } else { return false; } } /** * Runs next in the sequence * * @protected */ _next() { if (this._stopped) return; if (this.tasks.length > 0) { this.__next.run(); } else { this._complete(); } } /** * Complete * * Runs complete task * * @protected */ _complete() { this._resetCurrent(true); super._complete(); } /** * Recover * * Runs recover task * * @protected */ _recover(error) { if (this._stopped) return; if (this.tasks.length > 0) { const task = this.__next; task.recover(error); if (!task.running && !task.done) { this._resetCurrent(true); super._recover(error); } } else { this._complete(); } } /** * Resets current * * @protected */ _resetCurrent(unchain = false, resetAfterComplete = false) { if (this._current !== undefined) { if (unchain) { this._unchainTask(this._current); } if (resetAfterComplete) { Injector.resetAfterComplete( this._current, 'sequenceAfterComplete' ); } this._current = undefined; } } /** * Gets next task from the loop * * @return {Task} task next task * @protected */ get __next() { this._current = this.tasks.length > 0 ? Injector.afterComplete( this.tasks.shift(), (error, ...args) => { Injector.resetAfterComplete( this._current, 'sequenceAfterComplete' ); if ( this._passed.length === 0 || this._passed.indexOf(this._current) === -1 ) { this._passed.push(this._current); } this._resetCurrent(true); if (error === undefined) { this._next(); } else { this._recover(error); } }, 'sequenceAfterComplete' ) : undefined; return this._current; } /** * Gets the current task * * @return {Task} task current task */ get current() { return this._current; } /** * Gets the passed task(s) * * @return {Array<Task>} task passed task(s) */ get passed() { return this._passed; } }