text
stringlengths
7
3.69M
import React, { Component } from 'react'; class EditUser extends Component { constructor(props) { super(props); this.state = { id: this.props.userEditObject.id, name: this.props.userEditObject.name, phone: this.props.userEditObject.phone, level: this.props.userEditObject.level } } isChange = (event) => { let name = event.target.name; let value = event.target.value; this.setState({ [name]: value }); } saveClick = () => { let infoEdit = {}; infoEdit.id = this.state.id; infoEdit.name = this.state.name; infoEdit.phone = this.state.phone; infoEdit.level = this.state.level; this.props.getUserEditInfo(infoEdit) this.props.changeEditStatus(); } render() { let userEditObject = this.props.userEditObject; return ( <div className="col-12 edit-user"> <form> <button className="close" onClick={() => this.props.changeEditStatus()}> <i className="fa fa-times"></i> </button> <div className="card"> <div className="card-body"> <h4 className="card-title">Edit user</h4> </div> <div className="card-body"> <div className="form-group"> <input onChange={(event) => this.isChange(event)} defaultValue={userEditObject.name} type="text" name="name" className="form-control" placeholder="Name" /> </div> <div className="form-group"> <input onChange={(event) => this.isChange(event)} defaultValue={userEditObject.phone} type="text" name="phone" className="form-control" placeholder="Phone" /> </div> <div className="form-group"> <select onChange={(event) => this.isChange(event)} defaultValue={userEditObject.level} className="custom-select" name="level" > <option value={0}>Choose level</option> <option value={1}>Admin</option> <option value={2}>Manager</option> <option value={3}>Member</option> </select> </div> <div className="form-group"> <input type="button" value="Save" className="btn btn-block btn-primary" onClick={() => this.saveClick()} /> </div> </div> </div> </form> </div> ); } } export default EditUser;
import { delay } from './Utils'; export const ERR_COULD_NOT_DECRYPT = 'Could not decrypt.'; const digest = async (text) => { const pwUtf8 = new TextEncoder().encode(text); return await crypto.subtle.digest('SHA-256', pwUtf8); }; const ab2str = buffer => { let bytes = new Uint8Array(buffer).reduce((str, byte) => str + String.fromCharCode(byte), ''); return window.btoa(bytes); }; const str2ab = str => { const raw = window.atob(str); return new Uint8Array(raw.length).map((char, index) => raw.charCodeAt(index)); }; export const encryptText = async (textIn, password) => { const inUtf8 = new TextEncoder().encode(textIn); const pwHash = await digest(password); const rawIv = crypto.getRandomValues(new Uint8Array(12)); const alg = { name: 'AES-GCM', iv: rawIv }; const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']); const encBuffer = await crypto.subtle.encrypt(alg, key, inUtf8); const plainText = ab2str(encBuffer); const iv = ab2str(rawIv); return { iv, plainText }; }; export const decryptText = async (input, iv, password, delayTime=0) => { const ctBuffer = str2ab(input); const pwHash = await digest(password); const alg = { name: 'AES-GCM', iv: str2ab(iv) }; const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']); let ptBuffer; try { ptBuffer = await crypto.subtle.decrypt(alg, key, ctBuffer); } catch (err) { await delay(delayTime); throw new Error(ERR_COULD_NOT_DECRYPT); } const plainText = new TextDecoder().decode(ptBuffer); return { plainText }; }; export const test = async (input, iv, password, expected) => { try { const { plainText } = await decryptText(input, iv, password); if (plainText === expected){ return { success: true }; } return { success: false, error: 'Message decryption successful, but returned value does not match expected value' }; } catch (err) { return { success: false, error: 'Invalid or incorrect password'}; } };
const express = require('express'); const pool = require('../modules/pool'); const router = express.Router(); const { rejectUnauthenticated, rejectNonAdmin } = require('../modules/authentication-middleware'); router.get('/', rejectUnauthenticated, (req, res) => { const queryText = ` SELECT "user".id, "user".username FROM "user" WHERE "authorization" = 100; `; pool .query(queryText) .then(result => { res.send(result.rows); }) .catch(err => { console.error('error getting admin info:', err); res.sendStatus(500); }) }); // Get request for info in the Mission Table router.get('/mission', rejectUnauthenticated, (req, res) => { const queryText = `SELECT * FROM mission WHERE "missionActive" = TRUE ORDER BY "startDate" ASC;`; pool.query(queryText) .then(result => { res.send(result.rows); }) .catch(err => { console.log('ERROR: Get all Missions', err); res.sendStatus(500); }) }) // End of Get route router.post('/mission', rejectNonAdmin, (req, res) => { let mission = req.body; if (mission.missionLink === ''){ mission.missionLink = '#0'; }; if (mission.applyLink === '') { mission.applyLink = '#0'; }; //define query text const queryText = `INSERT INTO mission ("name", "location", "startDate", "endDate", "missionLink", "applyLink", "missionActive") VALUES ($1, $2, $3, $4, $5, $6, $7);`; //use pool to contact the server pool.query(queryText, [mission.name, mission.location, mission.startDate, mission.endDate, mission.missionLink, mission.applyLink, mission.missionActive]) .then( result => { res.sendStatus(201); }) .catch( err => { console.log('error is', err); res.sendStatus(500); }) }) router.put('/mission/:id', rejectNonAdmin, (req, res) => { const queryText = `UPDATE mission SET "startDate" = $1, "endDate" = $2, "location" = $3, "name" = $4, "missionLink" = $5, "applyLink" = $6, "missionActive" = $7 WHERE "mission_id" = $8;`; let mission = req.body; pool.query(queryText, [mission.startDate, mission.endDate, mission.location, mission.name, mission.missionLink, mission.applyLink, mission.missionActive, mission.mission_id]) .then( result => { res.sendStatus(200) }) .catch( err => { res.sendStatus(500); }) }) module.exports = router;
const mongoose = require('mongoose'); //Define a schema const Schema = mongoose.Schema; const StocksArchievesSchema = new Schema({ date: { type: Date, required: true, }, symbol: { type: String, trim: true, required: true, }, open: { type: Number, required: true, }, close: { type: Number, required: true, }, low: { type: Number, required: true, }, high: { type: Number, required: true, }, volume: { type: Number, required: true, }, deleted_at: { type: String, default: null }, updated_at: { type: Date, default: Date.now } }); module.exports = mongoose.model('stocks_archieves', StocksArchievesSchema)
const assert = require('assert') const Decorator = require('../decorator') const Room = require('../room') const PaintCan = require('../paint_can') describe('painter decorator', function() { describe('room', function(){ let room; this.beforeEach(function() { room = new Room( 5, 6, 2 ); }); it('should have an area in square meters', function () { const actual = room.squareMeters(); assert.strictEqual( actual, 60); }); it('should start not being painted', function() { const actual = room.paintedAmount; assert.strictEqual(actual, 0) }); it('should be able to be painted', function() { room.paintedAmount = 10 const actual = room.paintedAmount; assert.strictEqual(actual, 10) }); }); describe('paint can', function(){ let paintCan beforeEach(function() { paintCan = new PaintCan(10) }); it('should have a number of liters of paint', function () { const actual = paintCan.liters assert.strictEqual(actual, 10) }); it('should be able to check if it is empty', function() { paintCan.removePaint(5) const actual = paintCan.liters assert.strictEqual(actual, 5) }) it('should be able to empty itself of paint', function() { paintCan.emptyCan() const actual = paintCan.liters assert.strictEqual(actual, 0) }) }); describe('decorator', function() { let decorator beforeEach(function () { decorator = new Decorator() }) it('should start with an empty paint stock', function() { const actual = decorator.paintStock assert.strictEqual(actual, 0) }) it('should be able to add a can of paint to paint stock', function() { decorator.addCan() const actual = decorator.paintStock assert.strictEqual(actual, 1) }) it('should be able to calculate total liters in stock', function() { decorator.addCan() decorator.addCan() const actual = decorator.totalLiters() assert.strictEqual(actual, 20) }) it('should be able to calculate wether it has enough paint to paint a room', function() { decorator.addCan() decorator.addCan() let room = new Room(5, 6, 2) const actual = room.squareMeters() < decorator.totalLiters() assert.strictEqual(actual, false) }) it('should be able to paint room if has enough paint in stock', function() { decorator.addCan() decorator.addCan() decorator.addCan() decorator.addCan() decorator.addCan() decorator.addCan() decorator.addCan() let room = new Room(5, 6, 2) const actual = room.squareMeters() < decorator.totalLiters() assert.strictEqual(actual, true) }) }) });
import React from 'react'; import './header.scss'; import classNames from 'classnames'; import {array, bool, func, string} from 'prop-types'; import {Button} from '../button/Button'; import {MediumText} from '../medium-text/MediumText'; import {UniversalLink} from '../universal-link/UniversalLink'; import {MobileMenu, MobileMenuType} from '../mobile-menu/MobileMenu'; export class Header extends React.Component { static propTypes = { className: string, onContactClick: func, contactPopupShown: bool, portfolioMode: bool, items: array }; static defaultProps = { onContactClick() { } }; state = { scrollY: 0 }; handleScroll = event => { this.setState({scrollY: window.scrollY}); }; componentDidMount() { this.setState({scrollY: window.scrollY}); window.addEventListener('scroll', this.handleScroll); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } render() { const {scrollY} = this.state; const {className, onContactClick, contactPopupShown, portfolioMode, items} = this.props; return ( <div className={classNames('header header_portfolio-mode', { 'header_header-without-shadow': scrollY === 0 || contactPopupShown, 'header_contact-popup-shown': contactPopupShown }, className)}> <div className="header__container" data-aos={portfolioMode ? null : 'fade-down'} data-aos-duration={portfolioMode ? null : '1000'}> <div className="header__menu-container"> <UniversalLink noStyle={true} href="/"> <div className="header__title-with-logo"> <div className="header__logo-image"> </div> <div className="header__title"> Furnas </div> </div> </UniversalLink> <UniversalLink noStyle={true} href="/#do"> <MediumText className="header__title header__menu-title"> Что делаем </MediumText> </UniversalLink> <UniversalLink noStyle={true} href="/#how"> <MediumText className="header__title header__menu-title"> Как работаем </MediumText> </UniversalLink> <UniversalLink noStyle={true} href="/#portfolio"> <MediumText className="header__title header__menu-title"> Портфолио </MediumText> </UniversalLink> </div> <div> {contactPopupShown && <div className="header__close-contact-popup-button" onClick={onContactClick}> </div>} {!contactPopupShown && <UniversalLink noStyle={true} href="/#contact"> <Button className="header__button"> Связаться </Button> </UniversalLink>} {!contactPopupShown && <MobileMenu onContactClick={onContactClick} portfolioMode={portfolioMode} menuType={portfolioMode ? MobileMenuType.PORTFOLIO : MobileMenuType.HOME} items={items}/>} </div> </div> </div> ); } }
"use strict"; var fs = require('fs'); var csv = require('csv2'); var through = require('through2'); var _ = require('underscore'); var argv = require('yargs') .usage('Denormalize two files, joining on --join <colname>.\nUsage: $0 --join col1 path/to/file1 path/to/file2') .example('$0 --join --output path/to/joined_file col1 path/to/file1 path/to/file2 ', 'Join ount the lines in the given file') .demand('join') .alias('j', 'join') .describe('j', 'Join on col') .demand('output') .alias('o', 'output') .describe('o', 'Where to output') .demand('select') .alias('s', 'select') .describe('s', 'Columns to select for output') .demand(2) .describe('Need two files as input') .argv; var readers = []; argv._.forEach( function(path){ var reader = read_all_csv(); readers.push(reader); fs.createReadStream(path) .pipe(csv()) .pipe(through({ objectMode: true },reader)) ; }); process.on('exit', function() { var headers = argv.s.split(',').map( function(item){return item.trim();}); console.log(headers); var a = readers[0].data(); var b = readers[1].data(); Object.keys(a).forEach(function(key){ if(b.hasOwnProperty(key)){ console.error(key); console.error(_.flatten(_.zip(a[key],b[key]))); } }); }); function read_all_csv(){ var key_col = 0; var is_header_line = true; var headers; var data = {}; function pipe(chunk,enc,callback){ if(is_header_line){ headers = chunk.slice(); for(key_col = 0; key_col < headers.length; key_col++){ if(headers[key_col].toLowerCase() === argv.j.toLowerCase()){ break; } } is_header_line = false; } else { data[chunk[key_col]] = chunk.slice(1); } callback(); } pipe.headers = function(){ return headers; }; pipe.data = function(){ return data; }; return pipe; }
nose_x=0; nose_y=0; function preload() { clown_nose_image=loadImage("Clown_nose.png"); } function setup() { canvas=createCanvas(400,400); canvas.center(); video=createCapture(VIDEO); video.size(400,400); video.hide(); pose_load=ml5.poseNet(video,model_loaded); pose_load.on("pose",gotresults); } function model_loaded() { console.log("model has been loaded"); } function gotresults(results) { // if (error) { // console.log(error); // } else { if (results.length>0) { console.log(results); console.log("nose x : "+results[0].pose.nose.x); nose_x=results[0].pose.nose.x-25; console.log("nose y : "+results[0].pose.nose.y); nose_y=results[0].pose.nose.y-25; } //} } function draw() { image(video,0,0,400,400); image(clown_nose_image,nose_x,nose_y,70,70); } function take_pic() { save('clown_pic.png'); }
// array con las 12 imagenes (6 imagenes repetidas 2 veces) var srcList = ["images/alce.jpg", "images/epelante.jpg", "images/nena.jpg", "images/peces.jpg", "images/unichancho.jpg", "images/zapas.jpg", "images/alce.jpg", "images/epelante.jpg", "images/nena.jpg", "images/peces.jpg", "images/unichancho.jpg", "images/zapas.jpg"] var click1 = { src: "", element: "" } var click2 = { src: "", element: "" } var clicks = 0; var maxMoves = 0; var rankingList = JSON.parse(localStorage.getItem("rankingStorage")); var tries = 0; // comienza el juego function startGame() { if($("#nameInput").val() == "") { $(".name-error").removeClass("hidden"); $(".name-error").addClass("show"); setTimeout( function() { $(".name-error").removeClass("show"); $(".name-error").addClass("hidden"); }, 2000) } else { $("#homeMenu").removeClass("show"); $("#homeMenu").addClass("hidden"); $("#boardCont").removeClass("hidden"); $("#boardCont").addClass("show"); $("#name-sel").html( $("#nameInput").val() ); } } // mueve la posicion de los elementos del array de manera random function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } // acomoda las imagenes en el tablero function placeImg() { var i = 0; var randomSrc = shuffle(srcList); $(".img").each(function() { $(this).attr("src", randomSrc[i]) i++ }) } // contador de clicks function clickCounter() { clicks++ } // contador de tries function triesCounter() { tries++ $("#tries").html("") $("#tries").append(tries) } // selector de nivel $(".dif-but").on("click", function() { var startButton = $(this).attr("id"); startGame(); placeImg(); flipBoxes(); function setDif(n, dif) { maxMoves = n; $("#tries-sel").html(maxMoves); $("#dif-sel").html(dif); } if (startButton == "easyBut") { setDif(18, "FACIL"); } else if (startButton == "normalBut") { setDif(12, "INTERMEDIO"); } else if (startButton == "hardBut") { setDif(9, "EXPERTO"); } }) // girar las cartas function flipBoxes() { $(".box").on("click", function() { $(this).removeClass("flipper"); $(this).children(".front-img").addClass("hidden"); $(this).children(".back-img").removeClass("hidden"); clickCounter(); if ( clicks == 2 ) { click2.src = $(this).children(".back-img").children("img")[0].src; click2.element = $(this); if ( click1.element.attr("id") != click2.element.attr("id") ) { triesCounter(); if ( click1.src == click2.src ) { clicks = 0 $(click1.element).addClass("matched"); $(click2.element).addClass("matched"); } else { setTimeout(function() { $(click1.element).children(".front-img").removeClass("hidden"); $(click1.element).children(".back-img").addClass("hidden"); $(click2.element).children(".front-img").removeClass("hidden"); $(click2.element).children(".back-img").addClass("hidden"); $(click1.element).addClass("flipper"); $(click2.element).addClass("flipper"); clicks = 0 }, 500); } checkWinningCondition(); } else { clicks = 1; } } else if (clicks == 1) { click1.src = $(this).children(".back-img").children("img")[0].src; click1.element = $(this); } }) } // checkea si ganaste o perdiste function checkWinningCondition() { var matchedList = $(".matched").length; if( tries == maxMoves ) { matchedList != 12 ? youLost() : youWon() } else if ( tries <= maxMoves ) { if (matchedList == 12) { youWon(); } } } // perdiste function youLost() { showResults(); $(".you-lose").removeClass("hidden"); $(".player-info").removeClass("show"); $(".player-info").addClass("hidden"); } // ganaste (agrega la info del user al ranking) function youWon() { showResults(); $(".you-won").removeClass("hidden"); var obj = { name: $("#nameInput").val(), level: $("#dif-sel").html(), tries: tries } if ( rankingList == null ) { rankingList = [] } else { rankingList = rankingList; } rankingList.push(obj) localStorage.setItem("rankingStorage", JSON.stringify(rankingList)) appendRanking() } // muestra el cartel de perdiste/ganaste function showResults() { $(".win-lose").removeClass("hidden"); $(".win-lose").addClass("show"); $(".main-container").addClass("opacity"); $(".box").addClass("disableClick"); $("#player-name").html( $("#nameInput").val() ) $("#player-tries").html(tries) $("#triesSpan").html(tries) } // appendear el ranking function appendRanking() { for (var i = 0 ; i < rankingList.length ; i++) { var playerName = "<p>" + rankingList[i].name + "</p>" var playerLevel = "<p>" + rankingList[i].level + "</p>" var playerTries = "<p>" + rankingList[i].tries + "</p>" $(".player-name").append(playerName) $(".player-level").append(playerLevel) $(".player-tries").append(playerTries) } } // jugar otra vez $("#playAgainBut").on("click", function() { window.location.reload(); })
// A METTRE DANS FICHIER A PART //\\ ATTENTION //\\ Pour le bon fonctionnement du verificateur les input doivent avoir comme id : 'inp_' au debut // exemple : inp_nom , inp_prenom , inp_ville ... // Si vous voulez les appeller autrement il faudra modifier la partie de code dans le JS après " var message = 'Vous devez renseigner obligatoirement'; " function requiredInput(selectors){ var lesMessages = new Array(); //ce tableau dans l'êtat est une simple base , l'utilisation peut être modulaire en fonction du besoin lesMessages['nom'] = "<br>- le nom"; //si autre input obligatoire ajouter ici le message correspondant lesMessages['prenom'] = "<br>- le prenom "; lesMessages['ville'] = "<br>- la ville "; lesMessages['cp'] = "<br>- le code postal "; lesMessages['tel'] = "<br>- le N° de téléphone "; lesMessages['mel'] = "<br>- le mel "; lesMessages['adresse'] = "<br>- l'adresse "; lesMessages['commentaire'] = "<br>- le commentaire "; var message = 'Vous devez renseigner obligatoirement'; for(var i = 0; i< selectors.length; i++){ if($('#inp_'+selectors[i]).val() ==''){ message += lesMessages[selectors[i]]; $('#inp_'+selectors[i]).css('border', '1px solid #F00'); }else{ $('#inp_'+selectors[i]).css('border', '1px solid #dbdbdb'); } } if (message != 'Vous devez renseigner obligatoirement') { /* Pour recentrer le bloc */ $('#inputObli').html(message); var largeur_message = $('#inputObli').width(); var position_gauche = ((largeur_fenetre - largeur_message) / 2 ); $('#inputObli').css('margin-left', position_gauche + 'px'); $('#inputObli').show(); setTimeout(function () { $('#inputObli').hide(); }, 4000); }else{ return true; } } //A METTRE DANS LE MEDIA.INI ;verifInput.js media.verifInput.scripts[] = "%MEDIA_BASE_URL%/verifInput/verifInput.js" //A METTRE DANS LE STYLE .messageOK { position: absolute; padding: 15px 40px; border: 5px solid #000; border-radius: 5px; box-shadow: 3px 3px 10px #000; background-color: #FFF; color: #F60; font-weight: bolder; font-size: 1.5em; z-index: 10000; display: none; } //A METTRE DANS LE PHTML <div class="messageOK" id="inputObli"></div> var selectors = ['nom','prenom','adresse','ville','cp','tel','mel','commentaire']; // input obligatoire if(requiredInput(selectors)) { //... code en cas de succés }
const { Category } = require('../model/Category'); const { Recipe } = require('../model/Recipe'); const { DefaultResponses } = require('../common/DefaultResponses'); function getFirstsRecipes(req, res, parsedCategories) { Recipe.find((err, recipes) => { if (err) { const errorResponse = DefaultResponses.unHandledError; res.status(errorResponse.error.errorCode); return res.json(errorResponse); } const parsedRecipes = []; recipes.forEach((recipe) => { parsedRecipes.push(recipe.parse()); }); return res.json({ user: req.user, categories: parsedCategories, recipes: parsedRecipes, }); }); } function getCategories(req, res) { Category.find((err, categories) => { if (err) { const errorResponse = DefaultResponses.unHandledError; res.status(errorResponse.error.errorCode); return res.json(errorResponse); } const parsedCategories = []; categories.forEach((category) => { parsedCategories.push(category.parse()); }); return getFirstsRecipes(req, res, parsedCategories); }); } // obtain the home screen, so for now it send the categories function getDashboard(req, res) { getCategories(req, res); } exports.getDashboard = getDashboard;
DocsApp.constant('BUILDCONFIG', { "ngVersion": "1.4.6", "version": "1.0.0-rc1", "repository": "https://github.com/angular/material", "commit": "49e11ca338fd1ce2026927a2a93269f3ee7b6509", "date": "2015-10-21 09:38:54 +0100" });
var TrackViewModes = { FORCE_ARM: 0, SELECT: 1, MUTE: 2, SOLO: 3, ARM: 4 }; var TrackViewBasicMode = { TRACK: 0, EFX: 1 }; var TrackTypes = { Instrument: 0, Audio: 1, Group: 2, Effect: 3, Master: 4, Empty: 5 }; var TrackTypeMapping = { "Instrument": TrackTypes.Instrument, "Audio": TrackTypes.Audio, "Group": TrackTypes.Group, "Effect": TrackTypes.Effect, "Master": TrackTypes.Master, "EMPTY": TrackTypes.Empty }; function TrackViewState() { this.armed = false; this.exists = false; this.basecolor = 0; this.selected = false; this.mute = false; this.solo = false; this.color = function (mode) { if (!this.exists) { return 0; } // if (this.basecolor === 0) { // return 0; // } switch (mode) { case TrackViewModes.SELECT: return this.basecolor + (this.selected ? 2 : 0); case TrackViewModes.MUTE: return 12 + (this.mute ? 2 : 0); case TrackViewModes.SOLO: return 20 + (this.solo ? 2 : 0); case TrackViewModes.ARM: return 4 + (this.armed ? 2 : 0); } }; this.setType = function (typeName) { if (typeName in TrackTypeMapping) { this.type = TrackTypeMapping[typeName]; } }; this.type = TrackTypes.Empty; } /** * @param {TrackBankContainer} trackBankContainer * @param {TrackBankContainer} efxTrackBankContainer * */ function TrackViewContainer(trackBankContainer, efxTrackBankContainer) { var mixerView = new TrackView(trackBankContainer, this, TrackViewBasicMode.TRACK); var efxView = new TrackView(efxTrackBankContainer, this, TrackViewBasicMode.EFX); this.mode = TrackViewModes.SELECT; currentView = mixerView; this.enter = function () { currentView.enter(); }; this.exit = function () { currentView.exit(); }; this.handleEvent = function (index, value) { currentView.handleEvent(index, value); }; this.update = function () { currentView.update(); }; this.toMixerView = function () { if (currentView !== mixerView) { currentView.exit(); currentView = mixerView; currentView.enter(); } }; this.toEffectView = function () { if (currentView !== efxView) { currentView.exit(); currentView = efxView; currentView.enter(); } }; this.getMixerView = function () { return mixerView; }; this.getEffectView = function () { return efxView; }; this.enterMuteMode = function () { this.mode = TrackViewModes.MUTE; mixerView.update(); efxView.update(); }; this.enterSoloMode = function () { this.mode = TrackViewModes.SOLO; mixerView.update(); efxView.update(); }; this.enterArmMode = function () { this.mode = TrackViewModes.ARM; mixerView.update(); efxView.update(); }; this.toDefaultMode = function () { this.mode = TrackViewModes.SELECT; mixerView.update(); efxView.update(); }; this.inArmMode = function () { return this.mode === TrackViewModes.ARM; }; this.canArm = function () { return mixerView.isActive(); }; } /** * @param {TrackBank} trackBank * @param {TrackViewContainer} parent * */ function TrackView(trackBank, parent, basemode) { var active = false; var states = []; for (var ic = 0; ic < 8; ic++) { states.push(new TrackViewState()); } this.isActive = function () { return active; }; this.enter = function () { active = true; this.update(); }; this.exit = function () { active = false; }; this.trackStates = function () { return states; }; this.update = function () { if (!active) { return; } for (var i = 0; i < 8; i++) { sendToJam(i, states[i].color(parent.mode)); } }; this.handleEvent = function (index, value) { if (value === 0) { return; } var track = trackBank.getTrack(index); if (modifiers.isShiftDown()) { switch (index) { case 0: applicationControl.showNoteEditor(); break; case 1: applicationControl.getApplication().activateEngine(); break; case 3: applicationControl.getApplication().previousProject(); break; case 4: applicationControl.getApplication().nextProject(); break; case 6: host.showPopupNotification("Save Project"); applicationControl.invokeAction("Save"); break; case 7: applicationControl.showDevices(); break; } return; } switch (parent.mode) { case TrackViewModes.SELECT: if (modifiers.isDuplicateDown()) { if (states[index].exists) { track.duplicate(); } } else if (modifiers.isDpadRightDown()) { if (basemode === TrackViewBasicMode.TRACK) { applicationControl.getApplication().createInstrumentTrack(-1); } else { applicationControl.getApplication().createEffectTrack(-1); } } else if (modifiers.isClearDown()) { if (states[index].exists) { applicationControl.focusTrackHeaderArea(); track.makeVisibleInArranger(); track.selectInMixer(); applicationControl.getApplication().remove(); } } else { if (states[index].exists) { track.selectInMixer(); trackBank.selectClipInSlot(index); track.makeVisibleInMixer(); } else { if (basemode === TrackViewBasicMode.TRACK) { if (modifiers.isSelectDown()) { applicationControl.getApplication().createAudioTrack(-1); } else { applicationControl.getApplication().createInstrumentTrack(-1); } } else { applicationControl.getApplication().createEffectTrack(-1); } } } break; case TrackViewModes.MUTE: track.getMute().toggle(); break; case TrackViewModes.SOLO: track.getSolo().toggle(); break; case TrackViewModes.ARM: track.getArm().toggle(); break; } }; var sendToJam = function (index, color) { if (!active) { return; } controls.groupRow.sendValue(index, color); }; function registerTrack(track, tindex) { track.addColorObserver(function (red, green, blue) { states[tindex].basecolor = convertColor(red, green, blue); if (parent.mode === TrackViewModes.SELECT) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.getArm().addValueObserver(function (val) { states[tindex].armed = val; if (parent.mode === TrackViewModes.SELECT || parent.mode === TrackViewModes.ARM) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.getSolo().addValueObserver(function (val) { states[tindex].solo = val; if (parent.mode === TrackViewModes.SOLO) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.getMute().addValueObserver(function (val) { states[tindex].mute = val; if (parent.mode === TrackViewModes.MUTE) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.exists().addValueObserver(function (val) { states[tindex].exists = val; if (parent.mode === TrackViewModes.SELECT) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.addIsSelectedInMixerObserver(function (val) { states[tindex].selected = val; if (parent.mode === TrackViewModes.SELECT) { sendToJam(tindex, states[tindex].color(parent.mode)); } }); track.addTrackTypeObserver(16, "EMPTY", function (type) { states[tindex].setType(type); }); } for (var i = 0; i < 8; i++) { registerTrack(trackBank.getTrack(i), i); } }
//fill every paragraph with the last one's content. var text = document.getElementsByTagName('p'); var replace = document.querySelector('.dog').innerText for (var i = 0; i < text.length; i++) { text[i].innerText = replace; }
import React from "react"; // @material-ui/core components import { makeStyles } from "@material-ui/core/styles"; // @material-ui/icons import Chat from "@material-ui/icons/Chat"; import VerifiedUser from "@material-ui/icons/VerifiedUser"; import Fingerprint from "@material-ui/icons/Fingerprint"; import CreditCard from "@material-ui/icons/CreditCard"; import Public from "@material-ui/icons/Public"; import SyncAlt from "@material-ui/icons/Public"; // core components import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; import InfoArea from "components/InfoArea/InfoArea.js"; import CardMedia from '@material-ui/core/CardMedia'; import banner from "assets/img/banner3.png"; import styles from "assets/jss/material-kit-react/views/landingPageSections/productStyle.js"; import { Card } from "rebass"; const useStyles = makeStyles(styles); export default function ProductSection() { const classes = useStyles(); const cardStyles = { card: { margin: "120px auto 50px", maxWidth: 345, overflow: "visible", paddingTop: "10px", paddingBottom: "10px", }, media: { margin: "0px auto 0", width: "90%", height: 156, // borderRadius: "4px", // boxShadow: "0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23)", position: "relative", zIndex: 1000 } }; const useCardStyles = makeStyles(cardStyles); const cardClasses = useCardStyles(); return ( <div className={classes.section}> <GridContainer justify="center"> <GridItem xs={12} sm={12} md={8}> <h2 id="how" className={classes.title} style={{color:"#000"}}>How It Works</h2> <h5 className={classes.description}> HoneyDex is a smart contract deployed on the Ethereum blockchain, which creates ETH escrow smart contracts for ETH to BTC swaps. ETH is locked in a HoneyDex agreement and is only transferred to the buyer once the agreed upon BTC amount is received at the sender's BTC address. Bitcoin data is provided by a network of decentralised Chainlink oracles. </h5> {/* <CardMedia className={cardClasses.media} image={banner}/> */} </GridItem> </GridContainer> <div ><br/><br/> <GridContainer> <GridItem xs={12} sm={12} md={4}> <InfoArea title="Trustless" description="Locked up ETH is held in a newly created smart contract on the Ethereum blockchain. Bitcoin payment confirmation is queried using Chainlink's network of decentralised oracles." icon={Public} iconColor="info" vertical /> </GridItem> <GridItem xs={12} sm={12} md={4}> <InfoArea title="No Sign-Ups" description="No need to sign up with personal information or undergo KYC verification." icon={Fingerprint} iconColor="success" vertical /> </GridItem> <GridItem xs={12} sm={12} md={4}> <InfoArea title="Interoperable" description="Starting off with ETH to BTC trades, HoneyDex's generic and secure cross-chain swap implementation using Chainlink allows anonymous trades between ETH and any other chain." icon={SyncAlt} iconColor="danger" vertical /> </GridItem> </GridContainer> </div> </div> ); }
// dependents const express = require("express"); const { ApolloServer } = require("apollo-server-express"); //gql const { readFileSync } = require("fs"); const typeDefs = readFileSync("./schema.graphql").toString("utf-8"); const resolvers = require("./resolvers"); const path = require("path"); // const cors = require("cors"); // const PORT = process.env.PORT || 4000; require("dotenv").config(); // start server async function startApolloServer() { const server = new ApolloServer({ typeDefs, resolvers }); await server.start(); const app = express(); server.applyMiddleware({ app }); app.use(express.static(path.join(__dirname, "client", "build"))); app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "client", "build", "index.html")); }); await new Promise((resolve) => app.listen({ port: process.env.PORT || 4000 }, resolve) ); console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`); return { server, app }; } try { require("./databases/database-connection"); startApolloServer(); } catch (error) { console.error("Could not start Application due to", error); process.exit(-1); } // to be deleted //heroku // app.use(cors()); // app.use( // "/graphql", // graphqlHTTP({ // schema, // graphiql: true, // }) // ); // app.use(express.static("public")); // app.get("*", (req, res) => { // res.sendFile(path.resolve(__dirname, "public", "index.html")); // }); // app.use(express.static(path.join(__dirname, "client", "build"))); // app.get("*", (req, res) => { // res.sendFile(path.join(__dirname, "client", "build", "index.html")); // }); // app.use(express.urlencoded({ extended: true })); // app.use(express.json()); // if (process.env.NODE_ENV === "production") { // app.use(express.static(path.join(__dirname, "/client/build"))); // } // app.get("*", (req, res) => { // res.sendFile(path.join(__dirname, "/client/build/index.html")); // });
import React from 'react' import { Title } from 'bypass/ui/title' import { Container } from 'bypass/ui/page' import { ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout' import { Condition } from 'bypass/ui/condition' import { Button } from 'bypass/ui/button' import { Preview } from './preview' import { Format } from './format' import CardFormat from './CardFormat' import Hint from './Hint' import Stat from './Stat' const Mobile = ({ formatString, rawData, errors, limit, toCheck, onSaveFormat, onLoadFormat, onCheck, onChangeFormatString, onCheckFormatString, onChangeRawData, onPreview, }) => ( <Container> <RowLayout> <Layout> <Title size='small'> {__i18n('LANG.SERVICE.ADD_TO_CHECK')} </Title> </Layout> <Layout basis='10px' /> <Layout> <Format indent errors={errors} value={formatString} onChange={onChangeFormatString} onBlur={onCheckFormatString} /> </Layout> <Layout basis='10px' /> <Layout> <ColumnLayout> <Layout grow={1} > <Button fill type='light' size='small' onClick={onSaveFormat}> {__i18n('CHECK.SAVE_TPL_LABEL')} </Button> </Layout> <Layout grow={1}> <Button fill type='light' size='small' onClick={onLoadFormat}> {__i18n('CHECK.LOAD_TPL_LABEL')} </Button> </Layout> </ColumnLayout> </Layout> <Layout basis='10px' /> <Layout> <CardFormat indent value={rawData} onChange={onChangeRawData} /> </Layout> <Layout basis='10px' /> <Layout> <Hint color /> </Layout> <Layout basis='10px' /> <Layout> <Stat center limit={limit} /> </Layout> <Layout basis='10px' /> <Layout> <Button fill disabled={!formatString.length} onClick={onPreview}> {__i18n('CHECK.PREVIEW')} </Button> </Layout> <Layout basis='10px' /> <Layout> <Condition match={toCheck.cards.length}> <Preview {...toCheck} /> </Condition> </Layout> <Layout basis='10px' /> <Layout> <Button fill disabled={!toCheck.cards.length} onClick={onCheck}> {__i18n('LANG.BUTTONS.CHECK_CARDS')} </Button> </Layout> </RowLayout> </Container> ) export default Mobile
// External JQuery $('#red-btn').click(function() { $('#red-card').toggle(1000); });
let car, house, dog, table, fish, ladder, chair, picture, fan, rat
function login() { window.open('/auth/linkedin', '_self'); } function logout() { historyInit(); appvars.user = undefined; $.get('/auth/logout').done(function() { displayTemplate('header', 'header'); displayTemplate('main', 'splashpage'); displayTemplate('footer', 'footer'); }); } function listMembers() { historyUpdate(listMembers, arguments); $.ajax({ url: '/members', method: 'get' }).done(function(members) { members.user = appvars.user; displayTemplate('main', 'members', members); }); } function viewServiceRecord(id) { historyUpdate(viewServiceRecord, arguments); Promise.all([ $.ajax({ url: '/members/' + id, method: 'get' }), $.ajax({ url: '/members/' + id + '/planits', method: 'get' }) ]).then(function(serverData) { appvars.member = serverData[0].members[0]; appvars.planits = serverData[1].planits; appvars.planits.forEach(function(planit) { planit.formattedDate = formatDateShort(planit.start_date); }); data = { member: appvars.member, planits: appvars.planits, skills: serverData[0].skills, user: appvars.user, deletable: appvars.user && (appvars.user.id == appvars.member.id || appvars.user.role_name == 'admin'), bannable: appvars.user && appvars.user.role_name != 'normal' && appvars.user.id != appvars.member.id }; displayTemplate('main', 'member', data); }); } function updateMember(id) { historyUpdate(updateMember, arguments); Promise.all([ $.ajax({ url: '/members/' + id, method: 'get' }), $.ajax({ url: '/types/skills', method: 'get' }) ]).then(function(serverData) { var allSkills = serverData[1].skills; var memberSkills = serverData[0].skills; allSkills.forEach(function(skill) { if (memberSkills.filter(function(memberSkill) { return skill.id == memberSkill.id; }).length) { skill.memberHas = true; } else { skill.memberHas = false; } }); var data = { member: serverData[0].members[0], skills: allSkills } displayTemplate('main', 'memberupdate', data); }); } function updateMemberPut(event, id) { if (event) event.preventDefault(); var formData = getFormData('form'); $.ajax({ url: '/members/' + id, method: 'put', data: formData, xhrFields: { withCredentials: true } }).done(function(data) { viewServiceRecord(id); }); } function banMember(id, restore) { $.ajax({ url: '/members/' + id, method: 'put', data: { is_banned: !restore }, xhrFields: { withCredentials: true } }).done(function(data) { viewServiceRecord(id); }); } function reinstateMember(id) { banMember(id, true); } function deleteMember(id) { customConfirm('Are you sure you want to delete this member?', function() { $.ajax({ url: '/members/' + id, method: 'delete', xhrFields: { withCredentials: true } }).done(function(data) { if (id == appvars.user.id) { logout(); } else { displayTemplate('main', 'splashpage'); } }); }); }
var actions = { folders: { GET_ALL: 'foldersGetAll', GET_ALL_SUCCESS: 'foldersGetAllSuccess', GET_ALL_ERROR: 'foldersGetAllError', GET_BY_ID: 'foldersGetById', GET_BY_ID_SUCCESS: 'foldersGetByIdSuccess', GET_BY_ID_ERROR: 'foldersGetByIdError', SET_SELECTED: 'setSelected', TOGGLE_EXPANDED: 'toggleExpanded', CHANGE_UNREADED: 'changeUnreaded' }, messages: { GET_BY_FOLDER: 'messagesGetByFolder', GET_BY_FOLDER_SUCCESS: 'messagesGetByFolderSuccess', GET_BY_FOLDER_ERROR: 'messagesGetByFolderError', GET_BY_ID: 'messagesGetById', GET_BY_ID_SUCCESS: 'messagesGetByIdSuccess', GET_BY_ID_ERROR: 'messagesGetByIdError', FIND: 'find', FIND_SUCCESS: 'findSuccess', FIND_ERROR: 'findError' }, app: { SET_LOADING: 'setLoading', SET_CURRENT: 'setCurrent' } }; var events = { CHANGE: 'change' }; export { actions, events };
/* * This file contains common constants that are to be used throughout the * whole app. * * Author: Rodrigo Castro Azevedo * Date: 14/10/2015 */ const COLOUR_INCOME = "#22BBDD"; const COLOUR_DEBT = "#EE3322"; const COLOUR_INCOME_LIGHT = tinycolor(COLOUR_INCOME).lighten(15).toString(); const COLOUR_DEBT_LIGHT = tinycolor(COLOUR_DEBT).lighten(10).toString();
import React from 'react'; import styles from './index.module.scss'; // import Messages from '@/components/Messages'; // import Avatar from '@/components/Avatar'; function MainHeader(props) { const { className, menuVisible, iconClick } = props; return ( <div className={`${styles.wrap} ${className}`}> <i className={`iconfont ${ menuVisible ? 'rpa-caidanshouqi': 'rpa-caidanzhankai'}`} onClick={()=>{ if(iconClick)iconClick() }} ></i> <div className={styles.headerRight}> {/* <p className={styles.title}>阿里云RPA测试企业</p> <Messages /> <Avatar signOutClick={()=>{console.log('signOutClick')}} /> */} </div> </div> ) } export default MainHeader;
var express = require('express'); var router = express.Router(); //Require controller module // var event_controller = require('../controllers/eventController') //Routes // router.post('event/create', event_controller.event_create_post); module.exports = router;
/** * Created by Administrator on 2016/9/1. */ //数组去重 Array.prototype.unique = function(){ this.sort(); var re=[this[0]]; for(var i = 1; i < this.length; i++){ if( this[i] !== re[re.length-1]){ re.push(this[i]); } } return re; } //扩展数组方法:查找指定元素的下标 Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i; } return -1; }; //扩展数组方法:删除指定元素 Array.prototype.rmove = function(val) { var index = this.indexOf(val); while(index>-1){ this.splice(index, 1); index = this.indexOf(val); } return this; };
import CONSTANTS from '@/utils/interfaces/constants'; const REDUCER_KEY = 'RAMTest'; export const API_PATH = 'getTestRam'; const API_TYPE = 1; const GRAPHQL_BACK_TYPE = 1; export const RESULT_KEY = { SRAM: 'sessionRam', RAM: 'ram', DURATION: 'duration' }; export const GRAPHQL_KEYS = [ 'sessionRam' ] export const LABELS = { [RESULT_KEY.SRAM]: 'Session RAM', [RESULT_KEY.RAM]: 'RAM', [RESULT_KEY.DURATION]: 'Длительность тренировки, мин' }; export default CONSTANTS(REDUCER_KEY, API_PATH, API_TYPE, undefined, GRAPHQL_BACK_TYPE, GRAPHQL_KEYS);
// Warm up // #1 setTimeout(() => { console.log("Called after 2.5 seconds"); }, 2500); // #2 function logOutAfterDelay(delay, stringToLog) { setTimeout(() => { console.log(stringToLog); }, delay); } logOutAfterDelay(3000, "please wait for this, in 3.5 seconds you will get a message.") logOutAfterDelay(3500, "What a beautiful day.") logOutAfterDelay(5000, "You will see the last message after 6 seconds") logOutAfterDelay(6000, "Thanks for checking this out.") // #3 const setTimeButton = document.getElementById("happyButton"); function callbackLogOutFuncttion() { logOutAfterDelay(5000, "Called after 5 seconds"); } setTimeButton.addEventListener('click', callbackLogOutFuncttion); // The second way setTimeButton.addEventListener('click', function () { logOutAfterDelay(5000, "Called after 5 seconds"); }); // #4 function earthLogger() { console.log("Earth"); } function saturnLogger() { console.log("Saturn"); } const earth = earthLogger(); const saturn = saturnLogger(); const planetLogFunction = (planetCaller) => (planetCaller); planetLogFunction(earth); planetLogFunction(saturn); // #5 const navButton = document.getElementById("navigationButton"); const status = document.getElementById("status"); function showPosition(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.innerHTML = "This is the latitude: " + latitude + "<br>This is the longitude: " + longitude; showMap({ lat: latitude, lng: longitude }); } function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition) } else { status.innerHTML = "Geolocation is not supported by this browser."; } } navButton.addEventListener("click", getLocation); // #6 google map;optional let map; function showMap(mapLocation) { map = new google.maps.Map(document.getElementById("map"), { center: mapLocation, zoom: 8, }); } // #7 function runAfterDelay(delay, callback) { setTimeout(() => callback(), delay * 1000); } runAfterDelay(5, function () { console.log("Should be log out after 5 seconds!"); }) // #8 const targetClick = document.querySelector("body") targetClick.addEventListener('dblclick', () => { console.log("double click!") }); // #9 function jokeCreator(shouldTellFunnyJoke, logFunnyJoke, logBadJoke) { if (shouldTellFunnyJoke) { logFunnyJoke.call(); } else { logBadJoke.call(); } } const funnyJoke = function () { console.log("My code doesn't work. Let's change nothing and run it again!:)") }; const badJoke = function () { console.log("Programmer's joke: !!FALSE ... It's funny, because it's true.") }; jokeCreator(true, funnyJoke, badJoke); jokeCreator(false, funnyJoke, badJoke);
module.exports = { purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], darkMode: "class", // or 'media' or 'class' theme: { extend: { fontFamily: { "display": ["Space Grotesk"], "body": ["Inter"] }, colors: { slate: { light: "#2F363D", DEFAULT: "#24292E", dark: "#151617" }, snow: { light: "#FFFFFF", DEFAULT: "#F6F8FA", dark: "#E1E6EB" }, ice: "#89DCEE", sky: "#0165E2", purple: "#6B7ABB" }, keyframes: { slide: { "0%, 100%": {transform: "translateX(0px)"}, "50%": {transform: "translateX(3px)"} }, wiggle: { '0%, 100%': { transform: 'rotate(-3deg)' }, '50%': { transform: 'rotate(3deg)' }, } }, animation: { "spin-slow": "spin 3s linear infinite", "slide": "slide 3s linear infinite", "wiggle": "wiggle 1s linear infinite" } }, }, variants: { extend: {}, }, plugins: [], }
const Koa = require('koa') const Router = require('koa-router') const app = new Koa() // 创建一个服务器 app.listen(8080) // 监听8080端口 console.log(`app started at http://localhost:8080`) const router = new Router() // 创建路由 // 配置一个get请求的路由 router.get('/getData', async (ctx, next) => { ctx.body = 'response' // 向前台返回数据 }) // 使用路由中间件 app.use(router.routes())
const path = require("path"); const ghpages = require("gh-pages"); ghpages.publish(path.resolve(__dirname, "../dist"), err => { if (err) console.error("Something went wrong!!!", err); console.log("All good."); });
/* Simple Sort Algo Visualizer Renders the various states of an array during sorting, after the sort is complete (and not in realtime) Copyright (c) 2017 EminenceDigital, Inc http://www.eminencedigital.com Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ var sortVisualizer = { displayArray: [], displayContainer: $('#display'), displaySpeed: 200, init: function(display){ this.displayContainer = display; }, clearDisplay: function(){ this.displayContainer.empty(); this.displayArray = []; }, // Logs the state of the sort array logState: function(arr, logToBrowser){ this.displayArray[this.displayArray.length]=arr.slice(); if (logToBrowser){ console.log(arr.slice().toString()); } }, // Renders display of sort array doDisplay: function() { this.displayContainer.empty(); var setCount = this.displayArray.length; // initially renders all the states of the array as hidden elements for (var i = 0; i <= this.displayArray.length - 1; i++) { var visibility = "display:none;"; this.display(this.displayArray[i], i, visibility); } // Simulates an animation by toggling the visibility states // of the elements rendered in the previous loop var interval = setInterval(function() { var visibleSet = $('.list-item:visible'); var firstVisibleElement; var setNumber; if (visibleSet.length == 0) { firstVisibleElement = $('.set-0'); setNumber = 0; } else { firstVisibleElement = $('.list-item:visible').first(); setNumber = parseInt(firstVisibleElement.attr('set')); } var nextSetNumber = setNumber + 1; if ($('.set-' + nextSetNumber).length > 0) { $('.set-' + setNumber).remove(); $('.set-' + nextSetNumber).show(); } else { clearInterval(interval); } }, this.displaySpeed); }, // Renders <li> tags to the page for each member of the array, // assignning the value of the array to the "height" property display: function(arr,set,visibility){ if (typeof(set) == 'undefined'){ set=0; } var innerTableFormat="<li class='list-item set-${set}' set='${set}' style='${visibility}'><div style='height:${value}0px;'><span>${value}</span></div></li>"; var fullCell=""; for (var i=0; i<=arr.length-1; i++){ var val=arr[i]; $.tmpl(innerTableFormat, {value:val, set:set, visibility:visibility}).appendTo('#display'); } } }
import cinemaDetailHeaderView from '../views/cinemaDetailHeader.art' import cinemaDetailMainView from '../views/cinemaDetailMain.art' import cinemaDetailModel from '../models/cinemaDetailModels.js' import cinemaDetailListView from '../views/cinemaDetailList.art' import cinemaPlayDetailView from '../views/cinemaPlayDetail.art' const BScroll = require('better-scroll') class CinemaDetail{ constructor() { } bindTap() { // let nowhash=$(this).attr('data-to') // location.hash=nowhash window.history.go(-1) } timebindClick(){ let num=$(this).index() $(this).addClass('activeList').siblings().removeClass('activeList') let movieList=window.cinemaDetailresult.showData.movies[window.movieIndex].shows[num].plist let cinemaPlayDetailHtml=cinemaPlayDetailView({ movieList, }) let $ListUl=$('.ListUl') $ListUl.html(cinemaPlayDetailHtml) $('.no-seat').css('display','none') if(movieList.length==0) { $('.no-seat').css('display','flex') } else{ $('.no-seat').css('display','none') } } async render(){ let that=this; //分解hash值,获取到对应电影院ID值 let hash=location.hash.substr(1) let reg = new RegExp('^(\\w+)(\\/\\w+)','g') let path= reg.exec(hash)[2] let cinemaDetailId=path.substr(1) //传参获取数据 let cinemaDetailresult = await cinemaDetailModel.get({ cinemaDetailId }) //console.log(cinemaDetailresult); //把数据定义到全局变量中去,以便于其他地方有用到 window.cinemaDetailresult=cinemaDetailresult //分解数据 //电影院的基本数据 let cinemaDetailresultMovie=cinemaDetailresult.showData.movies //单人餐 if(cinemaDetailresult.dealList.divideDealList[1]!=undefined) { var one=cinemaDetailresult.dealList.divideDealList[1].dealList } else{ var one=null } //双人餐 if(cinemaDetailresult.dealList.divideDealList[0]!=undefined) { var two=cinemaDetailresult.dealList.divideDealList[0].dealList } else{ var two=null } let cinemaDetailHtml = cinemaDetailMainView({ cinemaDetailresultMovie, one, two }) let $main = $('main') $main.html(cinemaDetailHtml) let $header=$('header') let cinemaDetailHeaderHtml=cinemaDetailHeaderView({}) $header.html(cinemaDetailHeaderHtml) $('header').css('display','block') $('footer').css('display','block') let vipIfon=cinemaDetailresult.showData.vipInfo let dayTime=cinemaDetailresult.showData.movies[0].shows let movieList=cinemaDetailresult.showData.movies[0].shows[0].plist console.log(movieList); //时间和UL框页面 let cinemaDetailListHtml=cinemaDetailListView({ vipIfon, dayTime, }) //播放电影列表页面,这样写的目的是便于渲染里面的数据,只让里面的List重新渲染即可 let cinemaPlayDetailHtml=cinemaPlayDetailView({ movieList, }) let $playList = $('.playList') $playList.html(cinemaDetailListHtml) let $ListUl=$('.ListUl') $ListUl.html(cinemaPlayDetailHtml) //初始化页面的基本数据,让他们的默认值为第一个swiper的数据 $('.name').html(cinemaDetailresultMovie[0].nm) $('.pinfen').html(cinemaDetailresultMovie[0].sc+'分') $('#cinemaDetailmoviePage').html(cinemaDetailresultMovie[0].desc) $('.detailListHeader1').html(cinemaDetailresult.showData.cinemaName) $('.cinemaNa').html(cinemaDetailresult.cinemaData.nm) $('.cinemaAd').html(cinemaDetailresult.cinemaData.addr) //编辑一下背景图片数据,使后续操作更简单点 let zhezhaoimg="url('"+cinemaDetailresultMovie[0].img.replace(/w\.h/,"148.208")+"')" $('.zhezhao').css('background-image',zhezhaoimg) let bScroll = new BScroll.default($main.get(0), { }) //swiper var swiper = new Swiper('.swiper-container', { //一个页面显示的个数 slidesPerView: 3, //间隔 spaceBetween: 20, //在中间 centeredSlides: true, //可以点击 slideToClickedSlide: true, pagination: { el: '.swiper-pagination', clickable: true, }, on: { //滑动结束后触发的事件 slideChangeTransitionEnd: function(){ //获得滑动结束后当前目标的索引值 let index=this.activeIndex //把索引值定义到全局变量上,以至于后面点击事件更方便的去获取 window.movieIndex=index //根据这个索引,把对应swiper的那一条数据渲染到每个页面上 $('.name').html(cinemaDetailresultMovie[index].nm) $('.pinfen').html(cinemaDetailresultMovie[index].sc+'分') $('#cinemaDetailmoviePage').html(cinemaDetailresultMovie[index].desc) let zhezhaoimg="url('"+cinemaDetailresultMovie[index].img.replace(/w\.h/,"148.208")+"')" $('.zhezhao').css('background-image',zhezhaoimg) let dayTime=cinemaDetailresult.showData.movies[index].shows let movieList=cinemaDetailresult.showData.movies[index].shows[0].plist //console.log(dayTime); let cinemaDetailListHtml=cinemaDetailListView({ vipIfon, dayTime, }) let cinemaPlayDetailHtml=cinemaPlayDetailView({ movieList, }) console.log(movieList); console.log(movieList.length==0); let $playList = $('.playList') $playList.html(cinemaDetailListHtml) let $ListUl=$('.ListUl') $ListUl.html(cinemaPlayDetailHtml) $('.no-seat').css('display','none') if(movieList.length==0) { $('.no-seat').css('display','flex') } else{ $('.no-seat').css('display','none') } //当滑动swiper的时候要渲染初始值给元素 $('.day').eq(0).addClass('activeList') //当点击时间列表的时候可以触发事件,重新渲染下面对应时间电影详情列表 $('.day').on('tap',that.timebindClick) //让时间列表可以滑动 var swiper = new Swiper('.swiper-container1', { }); }, }, }); // var swiper = new Swiper('.swiper-container1', { // }); //渲染初始值 window.movieIndex=0; $('.backspace1').on('tap',this.bindTap) $('footer').css('display','none') $('.day').eq(0).addClass('activeList') $('.day').on('tap',this.timebindClick) var swiper = new Swiper('.swiper-container1', { }); if(one==null&&two==null) { $('.taocan').css('display','none') $('.huidai').css('display','none') } else{ $('.taocan').css('display','block') $('.huidai').css('display','block') } $('.no-seat').css('display','none') if(movieList.length==0) { $('.no-seat').css('display','flex') } else{ $('.no-seat').css('display','none') } } } export default new CinemaDetail()
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state:{ fruits: ['苹果', '香蕉', '荔枝', '柚子'] }, mutations:{ addFruit(state, payload){ state.fruits.push(payload); } }, getters:{ fruitsCount(state){ return state.fruits.length; } }, actions:{ addFruitAsync(context, payload){ setTimeout(()=>{ context.commit('addFruit', payload); }, 2000); } } });
function url_params(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r!=null) return unescape(r[2]); return null; } /*初始函数*/ function init(){ var fileName=url_params("fileName"); if(fileName!=null || fileName!="" || fileName!=undefined){ var timeline_config = { width : "100%", height : "100%", source : "resources/timeline_json/"+fileName+".json", lang : "zh-ch", start_zoom_adjust : "5", css : "timeline/css/timeline.css", js : "timeline/js/timeline.js" } } } /*入口函数*/ $(document).ready(function(){ init(); });
X.define("adapter.underscore",function () { var root = "js/lib/underscore/"; var option = { url: root + (X.config.env.production ? "underscore.min.js" : "underscore.js") }; //X.syncRequestScript(option); var rText = X.syncRequest(option.url); try{ window.eval(rText); }catch(e){ //IE8,9兼容性问题 window.execScript(rText); } });
import { toast } from 'react-toastify'; import { types, messages } from '../constants'; import { todoApi } from '../apis'; export const auth = (params, isSignUp) => dispatch => { dispatch(authStart()); const uri = isSignUp ? '/signup' : '/auth/login'; todoApi .post(uri, params) .then(({ data }) => { dispatch(authSuccess(data)); }) .catch(({ response: { data } }) => { const errors = isSignUp ? data.errors : { message: data.message }; dispatch(authFail(errors)); }); }; export const signOut = () => { return { type: types.AUTH_SIGN_OUT }; }; export const authStart = () => { return { type: types.AUTH_START }; }; export const authSuccess = ({ auth_token }) => { toast.success(messages.signedInSuccessfully); return { type: types.AUTH_SUCCESS, payload: auth_token }; }; export const authFail = errors => { if (errors['message']) toast.error(errors['message']); return { type: types.AUTH_FAIL, payload: errors }; };
import React, { useState, useEffect } from "react"; import GoogleMap from 'google-map-react'; import './index.css' import mapStyles from './mapStyles' import { connect, useDispatch } from 'react-redux'; import CollegeMarker from './markers/collegeMarker.js' import RouteClusterMarker from './markers/routeClusterMarker.js' import ClusterMarker from './markers/clusterMarker.js'; import supercluster from 'points-cluster'; import ClusterSlider from './clusterSlider' import { findCenter } from './geocoordinateCalculations'; import { renderDirections, clearDirections } from './directionsRenderer' import airportIcon from '../../assets/mapsSVG/airport.svg'; import locationIcon from '../../assets/mapsSVG/location.svg'; import { routeActions } from '../../actions/routeActions' import RouteReloader from './routeReloader' const MAP = { defaultZoom: 5, defaultCenter: { lat: 37.5, lng: -97 }, // center of US (slightly adjusted) options: { styles: mapStyles.basic, // disableDefaultUI: true, // minZoom: 4.3 }, }; function Map(props) { const [clustersDisplayed, setClustersDisplayed] = useState([]); const [defaultColleges, setDefaultColleges] = useState([]); const [mapOptions, setMapOptions] = useState({}); const dispatch = useDispatch(); // request default colleges when page is first loaded useEffect(() => { dispatch({ type: 'REQUEST_DEFAULT_COLLEGES', }) }, []) // parse default colleges and store in redux store right after we get them from backend useEffect(() => { // console.log(props.defaultColleges) setDefaultColleges(Object.values(props.defaultColleges).map((c) => ({ id: c.id, lat: c.lat, lng: c.lon }))) }, [props.defaultColleges]) // calculate clusters const getCollegeClusters = () => { const clusters = supercluster(defaultColleges, { minZoom: 0, maxZoom: 16, radius: 60, }); return clusters(mapOptions); }; // reset map center, zoom, bounds whenever map changes const handleMapChange = ({ center, zoom, bounds }) => { setMapOptions({ center, zoom, bounds }); }; const createClusters = () => { setClustersDisplayed( mapOptions.hasOwnProperty("bounds") ? getCollegeClusters().map(({ wx, wy, numPoints, points }) => ({ lat: wy, lng: wx, numPoints, id: `${numPoints}_${points[0].id}`, points, })) : [], ); }; // create clusters whenever map changes useEffect(createClusters, [mapOptions]) function getRouteClusters() { return props.route.map(cluster => findCenter(Object.values(cluster).map(college => [college.lat, college.lon])) ) } const handleApiLoaded = (map, maps) => { // store a reference to the GoogleMap map and maps object in redux store dispatch({ payload: { map, maps }, type: 'ON_LOADED', }) } useEffect(() => { if ((props.mapRef !== null) && (props.mapsRef !== null)) { const center = props.mapRef.getCenter(); const bounds = props.mapRef.getBounds(); const ne = { lat: bounds.getNorthEast().lat(), lng: bounds.getNorthEast().lng() }; const sw = { lat: bounds.getSouthWest().lat(), lng: bounds.getSouthWest().lng() } const mapBounds = { ne: ne, nw: { lat: ne.lat, lng: sw.lng }, se: { lat: sw.lat, lng: ne.lng }, sw: sw, } handleMapChange({ center: { lat: center.lat(), lng: center.lng() }, zoom: props.mapRef.getZoom(), bounds: mapBounds }) } } , [props.mapRef, props.mapsRef]) const distanceToMouse = (pt, mp) => { if (pt && mp) { // return distance between the marker and mouse pointer return Math.sqrt( (pt.x - mp.x) * (pt.x - mp.x) + (pt.y - mp.y) * (pt.y - mp.y) ); } }; useEffect(() => { if (props.viewport !== 'zoomedIn' && props.mapRef !== null) { props.mapRef.setCenter(MAP.defaultCenter) props.mapRef.setZoom(MAP.defaultZoom) clearDirections(); clearMarkers(); } }, [props.viewport]) useEffect(() => { // draw route when route reloads, or visibility option changed if (props.showRoute && props.selectedCluster !== '' && props.route !== null) { clearDirections(); clearMarkers(); drawRoute(); drawMarkers(); dispatch({ payload: { sidebar: 'routeInfo' }, type: 'NAVIGATE_SIDEBAR' }) } else { // clear route when visibility option is changed clearDirections(); } }, [props.route, props.showRoute]) function getCurrentRouteCluster() { return Object.values(Object.values(props.route)[props.selectedCluster]); } const drawRoute = () => { const currentCluster = getCurrentRouteCluster(); const waypts = []; for (let i = 1; i < currentCluster.length - 1; i++) { waypts.push({ location: new window.google.maps.LatLng(currentCluster[i].lat, currentCluster[i].lon), stopover: true, }); } const start = new window.google.maps.LatLng(currentCluster[0].lat, currentCluster[0].lon); const end = new window.google.maps.LatLng( currentCluster[currentCluster.length - 1].lat, currentCluster[currentCluster.length - 1].lon); renderDirections(props.mapRef, start, end, waypts); } const [markers, setMarkers] = useState([]); const drawMarkers = () => { const locations = getCurrentRouteCluster(); for (let i = 0; i < locations.length; i++) { let marker = new window.google.maps.Marker({ position: new window.google.maps.LatLng(locations[i].lat, locations[i].lon), map: props.mapRef, icon: { url: locations[i].type === "airport" ? airportIcon : locationIcon, scaledSize: new window.google.maps.Size(50, 50), labelOrigin: new window.google.maps.Point(25, 16.5), }, label: locations[i].type === "airport" ? {} : { text: "" + i, fontWeight: 'bold', fontSize: '20px', fontFamily: '"Inter", sans-serif', color: 'white' }, }); marker.setMap(props.mapRef) const infowindow = new window.google.maps.InfoWindow({ content: locations[i].name, }); marker.addListener("mouseover", () => { if (!props.tooltip.includes("zoomedIn")) { dispatch(routeActions.addTooltipShowed("zoomedIn")) } infowindow.open(props.mapRef, marker); }); marker.addListener("mouseout", () => { infowindow.close(props.mapRef, marker); }); setMarkers(markers => [...markers, marker]); } } const clearMarkers = () => { for (let i = 0; i < markers.length; i++) { markers[i].setMap(null); } } return ( <> <div className="mapContainer"> <GoogleMap bootstrapURLKeys={{ key: 'AIzaSyBIJk5AqilYH8PHt2TP4f5d7QY-UxtJf58' }} //process.env.REACT_APP_GOOGLE_KEY defaultCenter={MAP.defaultCenter} defaultZoom={MAP.defaultZoom} options={MAP.options} onChange={handleMapChange} distanceToMouse={distanceToMouse} yesIWantToUseGoogleMapApiInternals onGoogleApiLoaded={({ map, maps }) => { handleApiLoaded(map, maps) }} > {(props.viewport === 'default') && clustersDisplayed.map(item => { if (item.numPoints === 1) { return ( <CollegeMarker collegeID={item.points[0].id} lat={item.points[0].lat} lng={item.points[0].lng} /> ); } return ( <ClusterMarker index={item.points[0].id} lat={item.lat} lng={item.lng} points={item.points} /> ); })} {(props.viewport === 'clusters') && getRouteClusters().map((cluster, index) => ( <RouteClusterMarker index={index} lat={cluster[0]} lng={cluster[1]} /> )) } </GoogleMap> </div> {(props.viewport === 'clusters') && (props.infobar === '') && <ClusterSlider /> } {(props.viewport === 'zoomedIn') && (props.infobar === '') && <div className="reloadContainer"> <RouteReloader /> </div> } </> ); } const mapStateToProps = ({ rMap: { mapRef, mapsRef, defaultColleges, selectedCluster, viewport, showRoute }, rUser: { user, route, routesUpdated }, rRoute: { tooltip, infobar } }) => ({ mapRef, mapsRef, defaultColleges, selectedCluster, viewport, showRoute, user, route, routesUpdated, tooltip, infobar }); export default connect(mapStateToProps)(Map);
let updateFlag = false; let onlineFlag = false; let prevTick = 0; let gpsWatchId = 0; let posLatitude = []; let posLongitude = []; let motionX = []; let motionY = []; let motionZ = []; let motionXAvg = []; let motionYAvg = []; let motionZAvg = []; let motionXStdev = []; let motionYStdev = []; let motionZStdev = []; let motionXMin = []; let motionYMin = []; let motionZMin = []; let motionXMax = []; let motionYMax = []; let motionZMax = []; let timestamp = 0; //velocity let initVelocity = 0; //u let finalvelocity = 0; let previousTime = null; //t0 let latitude = 0; let longitude = 0; const arrAvg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length; const arrStdev = (arr) => { const avg = arrAvg(arr); let total = 0; for (let i = 0; i < arr.length; i++) { total += Math.pow(arr[i] - avg, 2); } return Math.sqrt(total / arr.length); }; const arrMin = (arr) => { return Math.min(...arr); }; const arrMax = (arr) => { return Math.max(...arr); }; function submitFirebase(t) { const projName = document.getElementById("project-name").value; const pathName = document.getElementById("path-name").value; let Url = "https://" + projName + ".firebaseio.com/" + pathName + ".json"; let Data = { timestamp: t, latitude: posLatitude, longitude: posLongitude, motionXAvg: motionXAvg, motionYAvg: motionYAvg, motionZAvg: motionZAvg, motionXStdev: motionXStdev, motionYStdev: motionYStdev, motionZStdev: motionZStdev, motionXMin: motionXMin, motionYMin: motionYMin, motionZMin: motionZMin, motionXMax: motionXMax, motionYMax: motionYMax, motionZMax: motionZMax, }; const Params = { headers: { "Content-Type": "application/json", }, body: JSON.stringify(Data), method: "POST", }; console.log(JSON.stringify(Data)); if (onlineFlag) { console.log("Adding to " + Url); document.getElementById("online-flag").innerHTML = "sending"; fetch(Url, Params) .then((data) => { document.getElementById("online-flag").innerHTML = "OFFLINE"; return data.json(); }) .then((res) => { console.log(res); }); } } function motionHandler(ev) { motionX.push(ev.acceleration.x); motionY.push(ev.acceleration.y); motionZ.push(ev.acceleration.z); } window.fn = {}; window.fn.startAcq = function () { if (!updateFlag) { // GPS tracking gpsWatchId = navigator.geolocation.watchPosition( (pos) => { timestamp = new Date(pos.timestamp); posLatitude.push(pos.coords.latitude); posLongitude.push(pos.coords.longitude); maxX = arrMax(motionX); maxY = arrMax(motionY); maxZ = arrMax(motionZ); //calculating velocity initVelocity = finalvelocity; finalvelocity = calculateVelocity( initVelocity, motionX.length > 0 ? motionX[0] : 0, previousTime, timestamp ); if (maxX != NaN) { motionXAvg.push(arrAvg(motionX)); motionYAvg.push(arrAvg(motionY)); motionZAvg.push(arrAvg(motionZ)); motionXStdev.push(arrStdev(motionX)); motionYStdev.push(arrStdev(motionY)); motionZStdev.push(arrStdev(motionZ)); motionXMin.push(arrMin(motionX)); motionYMin.push(arrMin(motionY)); motionZMin.push(arrMin(motionZ)); motionXMax.push(arrMax(motionX)); motionYMax.push(arrMax(motionY)); motionZMax.push(arrMax(motionZ)); motionX = []; motionY = []; motionZ = []; } document.getElementById("gps-status").innerHTML = pos.coords.latitude.toString() + "," + pos.coords.longitude.toString(); if (maxX != NaN) { document.getElementById("motion-status").innerHTML = maxX.toFixed(2) + "," + maxY.toFixed(2) + "," + maxZ.toFixed(2); } // Sending data if (Date.now() > prevTick + 10000) { previousTime = timestamp; submitFirebase(timestamp); posLatitude = []; posLongitude = []; motionXAvg = []; motionYAvg = []; motionZAvg = []; motionXStdev = []; motionYStdev = []; motionZStdev = []; motionXMin = []; motionYMin = []; motionZMin = []; motionXMax = []; motionYMax = []; motionZMax = []; prevTick = Date.now(); } }, (err) => { console.log(err); }, (options = { enableHighAccuracy: true, timeout: 10000, }) ); // Motion tracking try { DeviceMotionEvent.requestPermission().then((response) => { if (response == "granted") { window.addEventListener("devicemotion", motionHandler); } }); } catch { window.addEventListener("devicemotion", motionHandler); } document.getElementById("start-button").innerText = "STOP"; updateFlag = true; } else { console.log("Stop updating"); navigator.geolocation.clearWatch(gpsWatchId); window.removeEventListener("devicemotion", motionHandler); gpsWatchId = 0; document.getElementById("start-button").innerText = "START"; updateFlag = false; } }; window.fn.toggleOnline = function () { if (!onlineFlag) { console.log("Start syncing"); onlineFlag = true; document.getElementById("online-flag").innerHTML = "OFFLINE"; } else { console.log("Stop syncing"); onlineFlag = false; document.getElementById("online-flag").innerHTML = "ONLINE"; } }; //calculate the velocity vf = v0 + at; const calculateVelocity = (v0, accelation, initialtime, finaltime) => { time = new Date(finaltime).getTime() / 1000 - new Date(initialtime).getTime() / 1000; if (time < 0) { return 0; } if (time > 1000) { return 0; } const vf = v0 + accelation * time; return vf; };
import {connect} from 'react-redux'; import ShopHeader from '@/web-client/components/ShopHeader/ShopHeader'; import React, {Component} from 'react'; import { removeBubbleTextOnCartButton, } from '@/web-client/actions/shop'; class ShopHeaderContainer extends Component { render () { const {shop, dispatch, auth} = this.props; return ( <ShopHeader bubbleTextOnCartButton={shop.ui.bubbleTextOnCartButton} onBubbleTextDisappear={() => dispatch(removeBubbleTextOnCartButton())} showLogoutButton={!!auth.token} /> ); } } export default connect(s => s, dispatch => ({dispatch}))(ShopHeaderContainer);
import { CHANGE_SEARCH_FIELD, REQUEST_ROBOTS_PENDING, REQUEST_ROBOTS_SUCCESS, REQUEST_ROBOTS_FAILED } from './constants.js' export const setSearchField = (text)=> ({ type:CHANGE_SEARCH_FIELD, payload:text //payload is a common name used in redux }) export const requestRobots = () => (dispatch) =>{ /// a higher order function dispatch({ type: REQUEST_ROBOTS_PENDING}); fetch('https://jsonplaceholder.typicode.com/users') .then(response=> response.json()) .then(data => dispatch({ type: REQUEST_ROBOTS_SUCCESS, payload:data})) .catch(error => dispatch({ type: REQUEST_ROBOTS_FAILED, payload:error})) } // We've just created an action. We have changed the action in constants because if we leave the actions // as strings then the console wont show error but if we misspell const it will show error. //Action -----> Reducer
/** * @license * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ describe('EventManager', function() { var eventManager; var event1; var event2; var target1; var target2; beforeEach(function() { eventManager = new shaka.util.EventManager(); target1 = document.createElement('div'); target2 = document.createElement('div'); // new Event() is current, but document.createEvent() works back to IE11. event1 = document.createEvent('Event'); event1.initEvent('eventtype1', false, false); event2 = document.createEvent('Event'); event2.initEvent('eventtype2', false, false); }); afterEach(function() { eventManager.destroy(); }); it('listens for an event', function() { var listener = jasmine.createSpy('listener'); eventManager.listen(target1, 'eventtype1', listener); target1.dispatchEvent(event1); expect(listener).toHaveBeenCalled(); }); it('listens for an event from mutiple targets', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target2, 'eventtype1', listener2); target1.dispatchEvent(event1); target2.dispatchEvent(event1); expect(listener1).toHaveBeenCalled(); expect(listener2).toHaveBeenCalled(); }); it('listens for multiple events', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target1, 'eventtype2', listener2); target1.dispatchEvent(event1); target1.dispatchEvent(event2); expect(listener1).toHaveBeenCalled(); expect(listener2).toHaveBeenCalled(); }); it('listens for multiple events from mutiple targets', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target2, 'eventtype2', listener2); target1.dispatchEvent(event1); target2.dispatchEvent(event2); expect(listener1).toHaveBeenCalled(); expect(listener2).toHaveBeenCalled(); }); it('listens for an event with multiple listeners', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target1, 'eventtype1', listener2); target1.dispatchEvent(event1); expect(listener1).toHaveBeenCalled(); expect(listener2).toHaveBeenCalled(); }); it('stops listening to an event', function() { var listener = jasmine.createSpy('listener'); eventManager.listen(target1, 'eventtype1', listener); eventManager.unlisten(target1, 'eventtype1'); target1.dispatchEvent(event1); expect(listener).not.toHaveBeenCalled(); }); it('ignores other targets when removing listeners', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target2, 'eventtype1', listener2); eventManager.unlisten(target2, 'eventtype1'); target1.dispatchEvent(event1); expect(listener1).toHaveBeenCalled(); }); it('stops listening to multiple events', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target1, 'eventtype2', listener2); eventManager.removeAll(target1); target1.dispatchEvent(event1); target1.dispatchEvent(event2); expect(listener1).not.toHaveBeenCalled(); expect(listener2).not.toHaveBeenCalled(); }); it('stops listening for an event with multiple listeners', function() { var listener1 = jasmine.createSpy('listener1'); var listener2 = jasmine.createSpy('listener2'); eventManager.listen(target1, 'eventtype1', listener1); eventManager.listen(target1, 'eventtype1', listener2); eventManager.removeAll(target1); target1.dispatchEvent(event1); expect(listener1).not.toHaveBeenCalled(); expect(listener2).not.toHaveBeenCalled(); }); });
import useSWR from 'swr'; const fetcher = (url) => fetch(url).then((response) => response.json()); const useApiRoute = (route) => { const { data, error } = useSWR(route, fetcher); return { data, isLoading: !error && !data, isError: error, }; }; export default useApiRoute;
(function () { angular.module('photoGallery').controller('MainPhotoGalleryController', mainPhotoGalleryController); function mainPhotoGalleryController($scope, $interval, $modal, photos, photoGalleryService, settings, countdownTimerService) { var self = this; self.photos = photos; self.pickWinningPhoto = pickWinningPhoto; self.showPickWinnerButton = true; function randomisePhotoPositions() { var chosenPhotoPositions = []; for (var photoPosition = 0; photoPosition < self.photos.length; ++photoPosition) { var chosenPhotoPosition = Math.floor(Math.random() * self.photos.length); while (doesPhotoPositionAlreadyExist(chosenPhotoPositions, chosenPhotoPosition)) { chosenPhotoPosition = Math.floor(Math.random() * self.photos.length); } chosenPhotoPositions.push(chosenPhotoPosition); self.photos[photoPosition].order = chosenPhotoPosition; } } function doesPhotoPositionAlreadyExist(chosenPhotoPositions, chosenPhotoPosition) { for (var i = 0; i < chosenPhotoPositions.length; i++) { if (chosenPhotoPositions[i] === chosenPhotoPosition) { return true; } } return false; } function calculatePhotoGridPosition() { for (var i = 0; i < self.photos.length; i++) { var photo = self.photos[i]; // columns, left-to-right, top-to-bottom var columns = 5; photo.column = photo.order % columns; photo.row = Math.floor(photo.order / columns); // rows, top-to-bottom, left-to-right // var rows = 3; // item.column = Math.floor(item.order/rows); // item.row = item.order%rows; } } function pickRandomPhoto() { var chosenPhotoPosition = Math.floor(Math.random() * self.photos.length); return self.photos[chosenPhotoPosition]; } function shufflePhotos() { randomisePhotoPositions(); calculatePhotoGridPosition(); } $interval(function onComplete() { shufflePhotos(); }, 1500); $interval(function onComplete() { updatePhotos(); }, settings.refreshPhotoTimeInterval); $scope.$on('winning-photo:show', function onEvent() { self.showPickWinnerButton = false; }); $scope.$on('winning-photo:hide', function onEvent() { self.showPickWinnerButton = true; }); function pickWinningPhoto() { var winningPhoto = pickRandomPhoto(); $modal.open({ templateUrl: 'photo-gallery/modal/winning-photo/winning-photo.html', controller: 'WinningPhotoController', controllerAs: 'winningPhotoController', backdrop: 'static', resolve: { winningPhoto: function () { return winningPhoto; } } }).result.then(function (result) { winningPhoto.winner = true; photoGalleryService.winningPhoto(winningPhoto).then(function () { updatePhotos(); }); }); } function updatePhotos() { photoGalleryService.getPhotos().then(function (photos) { self.photos = photos; }); } } })();
import React, { useContext, useReducer, useEffect } from 'react'; import { View, Text, Platform, StyleSheet } from 'react-native'; import { LightStyles, DarkStyles, Colors } from '../../../constants/globalStyle'; import KeyContext from '../../../KeyContext'; export default function LogEntry(props) { const { dark } = useContext(KeyContext); const [styles, updateStyles] = useReducer(() => StyleSheet.create({...(dark ? DarkStyles : LightStyles), ...LocalStyles}), {}); useEffect(updateStyles, [dark]); const item = props.data; return ( <View style={styles.rowWrapper}> <Text style={[styles.rowTextItem, styles.mono]}>{item.id}</Text> <Text style={[styles.rowTextItem, styles.mono]}>{item.timestamp}</Text> <Text style={[styles.rowTextItem, styles.mono]}>{item.notes}</Text> <Text style={[styles.mono, {width: 50, textAlign: "right"}]}>{item.wafersAdded}</Text> </View> ); } const LocalStyles = { sp: { fontFamily: Platform.OS === "ios" ? "Verdana" : "sans-serif", }, mono: { fontFamily: Platform.OS === "ios" ? "Courier" : "monospace", }, rowTextItem: { textAlign: "left", }, rowWrapper: { width: "100%", flexDirection: "row", justifyContent: "space-around", margin: 3, maxWidth: 450, } }
import * as utilsApi from "./utils-api"; /** * Function to search for a course * @param {String} title - substring which needs to be searched in course title * @param {Function} successCallback - callback method to be called when API succeeds * @param {Function} failureCallback - callback method to be called when API fails */ export async function searchCourseByTitle( title, successCallback, failureCallback ) { try { await utilsApi.sendApiRequest( utilsApi.constants.HTTP_METHOD.GET, "/tutorials", null, { title: title }, null, null, successCallback, failureCallback ); } catch (error) { if (failureCallback) { failureCallback(error); } } } /** * Function to get all courses within a given category * @param {String} category - category string corresponding to which courses are to be fetched * @param {Function} successCallback - callback method to be called when API succeeds * @param {Function} failureCallback - callback method to be called when API fails */ export async function getCoursesByCategory( category, successCallback, failureCallback ) { try { await utilsApi.sendApiRequest( utilsApi.constants.HTTP_METHOD.GET, "/tutorials", ["category"], { category: category }, null, null, successCallback, failureCallback ); } catch (error) { if (failureCallback) { failureCallback(error); } } } /** * Function to get all published courses * @param {Function} successCallback - callback method to be called when API succeeds * @param {Function} failureCallback - callback method to be called when API fails */ export async function getAllPublishedCourses(successCallback, failureCallback) { try { await utilsApi.sendApiRequest( utilsApi.constants.HTTP_METHOD.GET, "/tutorials", ["published"], null, null, null, successCallback, failureCallback ); } catch (error) { if (failureCallback) { failureCallback(error); } } } /** * Function to get course with given id * @param {*} courseId - id of the course to be fetched * @param {*} successCallback - callback method to be called when API succeeds * @param {*} failureCallback - callback method to be called when API fails */ export async function getCourseById( courseId, successCallback, failureCallback ) { try { await utilsApi.sendApiRequest( utilsApi.constants.HTTP_METHOD.GET, "/tutorials", [courseId], null, null, null, successCallback, failureCallback ); } catch (error) { if (failureCallback) { failureCallback(error); } } }
export const REQUEST_USER_DATA = "REQUEST_USER_DATA"; export const RECEIVE_USER_DATA = "RECEIVE_USER_DATA"; export const requestUserData = (user, pwd) => ({ type: REQUEST_USER_DATA, user, pwd }); export const receiveUserData = data => ({ type: RECEIVE_USER_DATA, data }); export const REQUEST_DASHBOARDUSER_DATA = "REQUEST_DASHBOARDUSER_DATA"; export const RECEIVE_DASHBOARDUSER_DATA = "RECEIVE_DASHBOARDUSER_DATA"; export const requestDashboardUserData = (user) => ({ type: REQUEST_DASHBOARDUSER_DATA, user}); export const receiveDashboardUserData = data => ({ type: RECEIVE_DASHBOARDUSER_DATA, data }); export const REQUEST_ALLUSER_DATA = "REQUEST_ALLUSER_DATA"; export const RECEIVE_ALLUSER_DATA = "RECEIVE_ALLUSER_DATA"; export const requestAllUserData = () => ({ type: REQUEST_ALLUSER_DATA}); export const receiveAllUserData = data => ({ type: RECEIVE_ALLUSER_DATA, data });
$(function(){ $('#Container1').mixItUp(); });
/* eslint-disable no-console */ import fs from 'fs' import moment from 'moment' import 'moment-timezone' import { Sequence } from '../models/sequence' import { rpc, rpcEx } from './utils' export class DeviceAgent { sessionId = '79ad47aaf18214af01c7c341d11b83e7' RPC_PATH = '/api/cgi-bin/rpc' COMMON_PATH = '/api/common' USER = 'admin' PASSWORD = 'admin123' Activated DeviceClass DeviceType SerialNumber Version Host constructor(config) { if (!config || !config.host) { throw new Error('端末が存在しません') } this.Activated = config.activated this.DeviceClass = config.deviceclass this.DeviceType = config.devicetype this.SerialNumber = config.serialno this.Version = config.version this.Host = config.host this.USER = config.username || this.USER this.PASSWORD = config.password || this.PASSWORD } /** * 端末と通信する時、コマンド実行IDを発行する */ async getPacketId() { const sequence = new Sequence() return await sequence.nextval(this.SerialNumber) } optionsFactory(sessionId, jsonString) { return { host: this.Host, port: 80, path: this.RPC_PATH, method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: `SessionID=${sessionId}`, 'Content-Length': Buffer.byteLength(jsonString), }, } } async keepAliveFunc() { const options = { host: this.Host, port: 80, path: `${this.COMMON_PATH}/keepalive?session=${this.sessionId}&active=true`, method: 'POST', } await rpc(options, '', '', 'null') } /** * 標準的なコマンド実行メソッド * @param options HTTPリクエストオプション * @param jsonString 通信情報 */ async CmdGeneral(options, jsonString) { let result try { result = JSON.parse(await rpc(options, jsonString, this.USER, this.PASSWORD)) || {} this.sessionId = result.session || this.sessionId } catch (error) { console.error(error) } return result } async getConfig(name) { if (!name) { return {} } const id = await this.getPacketId() const requestJson = { id, method: 'configCentre.getConfig', params: { name, }, } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async setConfig(name, content) { if (!name) { return {} } const id = await this.getPacketId() const requestJson = { id, method: 'configCentre.setConfig', params: { name, content, }, } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async getName() { return await this.getConfig('MachineGlobal') } async setName(name) { const localesSettings = await this.getName() const content = [...localesSettings.params.content] content[0].Address = name || content[0].Address return await this.setConfig('MachineGlobal', content) } async getScreenConfig() { return await this.getConfig('Screen') } async offScreen() { const jsonData = await this.getScreenConfig() if (!jsonData) { return {} } const content = jsonData.params.content content[0].Brightness = 0 return await this.setConfig('Screen', content) } async openScreen() { const jsonData = await this.getScreenConfig() if (!jsonData) { return {} } const content = jsonData.params.content content[0].Brightness = 80 return await this.setConfig('Screen', content) } async getConstantLampConfig() { return await this.getConfig('SOCConstantLamp') } async offConstantLamp() { const jsonData = await this.getConstantLampConfig() if (!jsonData) { return {} } const content = jsonData.params.content content[0].Brightness = 0 return await this.setConfig('SOCConstantLamp', content) } async openConstantLamp() { const jsonData = await this.getConstantLampConfig() if (!jsonData) { return {} } const content = jsonData.params.content content[0].Brightness = 30 return await this.setConfig('SOCConstantLamp', content) } async toggleLamp(toggle) { if (toggle) { await this.offConstantLamp() await this.offScreen() } else { await this.openConstantLamp() await this.openScreen() } } async getTemperature() { return await this.getConfig('TempDetectConfig') } async setTemperature(temperature) { const jsonData = await this.getTemperature() if (!jsonData) { return {} } const content = jsonData.params.content content.ValueRange[1] = Number(temperature) || content.ValueRange[1] return await this.setConfig('TempDetectConfig', content) } async createFaceInfoUpdate() { const id = await this.getPacketId() const requestJson = { id, method: 'faceInfoUpdate.create', } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async destroyFaceInfoUpdate() { const id = await this.getPacketId() const requestJson = { id, method: 'faceInfoUpdate.destroy', } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async deleteFace(person) { let intervalId try { if (!(await this.createFaceInfoUpdate())) { return false } setTimeout(() => { intervalId = setInterval(() => { this.keepAliveFunc() }, 20000) }, 10000) const id = await this.getPacketId() const requestJson = { id, method: 'faceInfoUpdate.deleteFace', params: { CertificateType: person.CertificateType, ID: person.Code, }, } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } catch (error) { console.log(error) } finally { await this.destroyFaceInfoUpdate() clearInterval(intervalId) } } async addFaceFaceInfoUpdate(person, photoPath) { let intervalId try { if (!(await this.createFaceInfoUpdate())) { return false } setTimeout(() => { intervalId = setInterval(() => { this.keepAliveFunc() }, 20000) }, 10000) const id = await this.getPacketId() const requestJson = { id, method: 'faceInfoUpdate.addFace', params: { GroupID: 1, PersonInfo: { ...person }, ImageInfo: { Amount: 1, Lengths: [fs.statSync(photoPath).size], }, }, } const jsonString = JSON.stringify(requestJson) const body = await rpcEx( this.optionsFactory(this.sessionId, jsonString), photoPath, requestJson ) console.log(JSON.stringify(requestJson), body) const result = JSON.parse(body) return result.result } catch (error) { console.log(error) } finally { await this.destroyFaceInfoUpdate() clearInterval(intervalId) } } async insertPersonPersonManager(person) { const id = await this.getPacketId() const requestJson = { id, method: 'personManager.insertPerson', params: { Person: { ...person }, }, } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async getPersons() { console.log(this.sessionId) const id = await this.getPacketId() const requestJson = { id, method: 'personManager.getPersons', params: { Condition: { Type: 1, Limit: 100, Offset: 0, }, }, } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async addPerson(person, photoPath) { if (!(await this.insertPersonPersonManager(person))) { return false } if ( !(await this.addFaceFaceInfoUpdate( { CertificateType: person.CertificateType, ID: person.Code, }, photoPath )) ) { this.deletePerson(person) return false } return true } async deletePerson(person) { const Codes = [ { Code: person.Code, }, ] const id = await this.getPacketId() const requestJson = { id, method: 'personManager.removePersons', params: { Codes, }, } const jsonString = JSON.stringify(requestJson) await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) await this.deleteFace(person) } async getHTTPReverse() { return await this.getConfig('HTTPReverse') } async setHTTPReverse(signalingUrl, pushingUrl) { const jsonData = await this.getHTTPReverse() if (!jsonData) { return {} } const content = jsonData.params.content content[0].Enable = true content[0].MessageURL = signalingUrl content[0].PushPictureURL = pushingUrl return await this.setConfig('HTTPReverse', content) } async getTime() { const id = await this.getPacketId() const requestJson = { id, method: 'global.getTime', } const jsonString = JSON.stringify(requestJson) return await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) } async setTimeSetting() { const time = moment().tz('Asia/Tokyo').format('YYYY-MM-DD HH:mm:ss') const timezone = moment().tz('Asia/Tokyo').format('Z') const localesSettings = await this.getConfig('Locales') const content = { ...localesSettings.params.content, TimeZone: `GMT${timezone}`, } const setLocalesResult = await this.setConfig('Locales', content) const id = await this.getPacketId() const requestJson = { id, method: 'global.setTime', params: { time, }, } const jsonString = JSON.stringify(requestJson) const setTimeResult = await this.CmdGeneral( this.optionsFactory(this.sessionId, jsonString), jsonString ) return setLocalesResult.result && setTimeResult.result } }
////////////////////////////////////////////////// ////////////////////////////////////////////////// // ___ ___________ _______________ ___ // // / _ \/ __/ __/ _ |/ ___/_ __/ __ \/ _ \ // // / , _/ _// _// __ / /__ / / / /_/ / , _/ // // /_/|_/___/_/ /_/ |_\___/ /_/ \____/_/|_| // // // // The below assignment has 10 questions with 1 // // bonus question. Each question has a specific // // area for you to put your answer. That is the // // only part that should be changed. Do not // // edit the code in the question. Your answers // // should be valid javascript and any comments // // should be commented out. When finished this // // entire document should be valid javascript. // // // ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 1. -------------------------------------------- // This is a named function, convert it // to a variable containing an anonymous // function function doSomethingCool() { console.log("Something Cool!"); } // Put your answer below ------------------------- var doSomethingCoolAnswer = function(){ console.log('Something Cool in a anon function!'); }; // doSomethingCoolAnswer(); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 2. -------------------------------------------- // Here we are using setTimeout to call a function // after 2 seconds. Refactor to use an anonymous // function function sayHi() { alert("Hello, World!"); } setTimeout(sayHi, 2000); // Put your answer below ------------------------- var sayHiAgain = function(){ alert('Hello, World! - from anon function!'); }; setTimeout(sayHiAgain, 2000); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 3. -------------------------------------------- // The code below will log the letter twice. What // is the order that will be logged? // [a]: x then y then z // [b]: y then z // [c]: z then y // [d]: x then z // Please explain your answer. var letter = "x"; setTimeout(function(){ letter = "y"; console.log("The letter is", letter); }, 1); letter = "z"; console.log("The letter is", letter); // Put your answer below ------------------------- /* [c]: z then y letter is being declared first and the declaration hoisted up to the top. it then is assigned the value of 'x'. when then make a call to the native setTimeout() function and pass a function expression into it. inside of the function expression, we set the value of letter to 'y' and log a message to the console that includes information on what letter is being changed to. the time argument of 1 sets a timer that will wait 1ms to fire the function to change the value of letter While we're wating on setTimeout to fire, we re-assign the value of letter to 'z' and log a message that has information on what letter is now assigned to at this point in our file. this is why we dont see 'x' being logged to the console - letter is reassigned before we ever try to extract that information. if we console logged the value in letter before we re-assigned it to 'z', we would see 'x' in the console. setTimeout finally fires and re-assigns letter to 'y' and even though we assinged letter to 'z' after the setTimeout, the last thing that we see in the console is that letter is assigned to 'y' because we told the browser to wait 1 millisecond before re-assigning letter to 'y' */ // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 4. -------------------------------------------- // The function below reverses a string. The body // of the function is 5 lines of code. Refactor // this function to do the same thing with 1 line var reverseStr = function(str) { var arr; arr = str.split(""); arr = arr.reverse(); str = arr.join(""); return str; }; // Put your answer below ------------------------- var reverseStrOneLine = function(str){ return str.split('').reverse().join(''); }; console.assert(reverseStrOneLine('beer run') == 'nur reeb'); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 5. -------------------------------------------- // The function below takes the spanish word for // the colors red, white, blue, green, and black // and returns the hex code for that color. // Refactor this function to use an object // instead of an if/else statement. var spanishColor = function(colorName) { if (colorName.toLowerCase() === "rojo") { return "#ff0000"; } else if (colorName.toLowerCase() === "blanco") { return "#ffffff"; } else if (colorName.toLowerCase() === "azul") { return "#0000ff"; } else if (colorName.toLowerCase() === "verde") { return "#00ff00"; } else if (colorName.toLowerCase() === "negro") { return "#000000"; } }; // Put your answer below ------------------------- var spanishColorObj = function(colorName){ colorName = colorName.toLowerCase(); var colors = { 'rojo': '#ff0000', 'blanco': '#ffffff', 'azul': '#0000ff', 'verde': '#00ff00', 'negro': '#000000' }; return colors[colorName]; }; // console.log(spanishColorObj('verde')); console.assert(spanishColorObj('verde') == '#00ff00'); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 6. -------------------------------------------- // Below is a variable *declaration* and an // *assignment* in a single line of code. // Break it up so that the declaration and // assignment are happening on 2 seperate lines. var foo = "bar"; // Put your answer below ------------------------- var bar; bar = 'baz'; // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 7. -------------------------------------------- // The function `callTenTimes` takes an argument // that is another function and will call that // function 10 times. Refactor this into another // function called `callNtimes` that allows you // to specify a number of times to call the given // function. // var callTenTimes = function(callback) { // var range = _.range(10); // _.each(range, callback); // }; var callTenTimes = function(callback) { for(var i = 0; i < 10; i++){ callback(); } }; // Put your answer below ------------------------- var callNtimes = function(callback, n) { for(var i = 0; i < n; i++){ callback(); } return false; // should we do this? }; function callMeMaybe(){ console.log('This is crazy!'); } console.log(callNtimes(callMeMaybe, 20)); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 8. -------------------------------------------- // Below is the beginning code for an awesome game // but already suffers a vulnerability that allows // the savvy user to open the console and adjust // the score to whatever they want. Refactor the // code to protect from this. // HINT: "global scope" var score = 0; var increaseScore = function() { score++; }; var decreaseScore = function() { score--; }; // Put your answer below ------------------------- // put the code in an IIFE (function(){ var score = 0; var increaseScore = function() { score++; }; var decreaseScore = function() { score--; }; }()); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 9. -------------------------------------------- // The below function does not work. The variable // twoPlusTwo gets set to `undefined`. Refactor // the function to make it work. var addNumbers = function(numberA, numberB) { console.log(numberA + numberB); }; var twoPlusTwo = addNumbers(2,2); // Put your answer below ------------------------- function addNumbersAgain(numA, numB){ return numA + numB; } var fourPlusFour = addNumbersAgain(4, 4); console.assert(fourPlusFour == 8); // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // 10. ------------------------------------------- // Below is a snippet of code taken from a racing // game (not really!) It allows you to accelerate // the speed by a given amount. The problem is if // you call the function without specifying an // amount, it inadvertently sets the speed to NaN // First write a comment that explains why it was // setting speed to NaN when no parameter is given // Then refactor the function to have a default // amount of 1 if no param is given. var speed = 0; var accelerate = function(amount) { speed += amount; }; // Put your answer below ------------------------- /* speed is set to NaN because the function is trying to update speed with an undefined value when a value isnt provided in the function call. We can explicitly check for a number value by checking the type of amount and reject any value that isnt a number */ var accelerateAgain = function(amount){ if(typeof amount == 'number'){ speed += amount; } else { console.warn('Speed must be a number!'); amount = 1; speed += amount; } }; // ----------------------------------------------- ////////////////////////////////////////////////// ////////////////////////////////////////////////// // ___ ____ _ ____ ______ // // / _ )/ __ \/ |/ / / / / __/ // // / _ / /_/ / / /_/ /\ \ // // /____/\____/_/|_/\____/___/ // // // ////////////////////////////////////////////////// ////////////////////////////////////////////////// // The function below allows you to call another // function at a later time. It takes 2 params, an // amount of miliseconds and a function. It will // call the function that many miliseconds later. // Refactor it so that is has a default timeout. // This is more advanced than the default param on // the accelerate function. This is because there // is another parameter to consider. // When setting the timeout, the function needs to // work like this: // callLater(1000, function(){ // ... // }); // When using the default timeout, the function // needs to work like this: // callLater(function(){ // ... // }); var callLater = function(timeout, callback) { setTimeout(callback, timeout); }; // Put your answer below ------------------------- var callLater = function(timeout, callback) { // this will only handle a function coming into the timeout slot // by itself, but not much else if(typeof timeout == 'function'){ callback = timeout; timeout = 1000; } setTimeout(callback, timeout); }; function calledLater(){ console.log('Bro, you showed up late.'); } callLater(3000, calledLater); // should work normally callLater(calledLater); // should still work, but need set a default // var a = {}; // callLater(a, calledLater); // ----------------------------------------------- //////////////////////////////////////////////////
import React, { Component } from 'react'; import './../style/gayaku.css'; import { Link } from 'react-router-dom'; import Header from './Header'; import Jumbotron from './Jumbotron'; import Footer from './Footer'; class Update extends Component { render() { return ( <div> <Header/> {/* Container (About Section) */} <div style={{marginTop: 150}}><center><h1><b>NEWS &amp; UPDATES</b></h1></center></div> <div className="container bg-grey" style={{marginTop: 50, borderRadius: 15, padding: 20}}> <div className="row"> <div className="col-sm-8" style={{textAlign: 'justify'}}> <h2>Apa menariknya sih kopi?</h2><br /> <p>Best things in a cup of coffee <br /><br />Menikmati udara pagi sembari menyesap aroma kopi barangkali menjadi hal yang rasanya seakan membawa kita ke surga dunia. Hal ini yang saya rasakan..dan mungkin tidak sedikit dari anda yang juga merasakan hal yang sama, bahkan jika anda hanya mencium aromanya saja tanpa meminumnya. </p> <br /><a href="./Artikelb"><button className="btn btncart" style={{width: '20%'}}>Read More...</button></a> </div> <div className="col-sm-4"> <div className="thumbnail item"> <a href="./Artikelb"> <img src="images/artikel/artikelb.jpg" alt="COFFEES" /> </a> </div> </div> </div> </div> <div className="container bg-grey" style={{marginTop: 50, borderRadius: 15, padding: 20}}> <div className="row"> <div className="col-sm-4"> <div className="thumbnail item"> <a href="./Artikela"> <img src="images/artikel/artikela.jpg" alt="COFFEES" /> </a> </div> </div> <div className="col-sm-8" style={{textAlign: 'justify'}}> <h2>Manfaat minum kopi bagi kesehatan berdasarkan sains</h2><br /> <p>Minum kopi sebenarnya sehat lho. Mau tahu kenapa? <br />Mari kita simak bersama penjelasannya.. <br /><br />1. Kopi bisa meningkatkan level energi dan membuat kamu lebih cerdas <br /><br />Barangkali ini yang sebenarnya mayoritas dirasakan oleh penggemar kopi. Pengalaman penulis sendiri, kopi jadi energy booster di kantor dan memunculkan ide-ide baru. Menarik kaan??</p> <br /><a href="./Artikela"><button className="btn btncart" style={{width: '20%'}}>Read More...</button></a> </div> </div> </div> <div className="container bg-grey" style={{marginTop: 50, borderRadius: 15, padding: 20}}> <div className="row"> <div className="col-sm-8" style={{textAlign: 'justify'}}> <h2>What's special about Indonesian Coffee</h2><br /> <p> Nyatanya, dari sekian banyak negara di dunia, Indonesia termasuk dalam 10 negara pengekspor kopi terbesar di dunia secara value. Di bawah ini adalah daftarnya (berdasarkan data Word's Top Exports 2017) <br /><br /> 1. Brazil: US$4.6 billion (14.1% of total coffee exports) <br />2. Vietnam: $3.5 billion (10.7%) <br />3. Germany: $2.64 billion (8.1%) <br />4. Colombia: $2.58 billion (7.9%) </p> <br /><a href="./Artikelc"><button className="btn btncart" style={{width: '20%'}}>Read More...</button></a> </div> <div className="col-sm-4"> <div className="thumbnail item"> <a href="./Artikelc"> <img src="images/artikel/artikelc.jpg" alt="COFFEES" /> </a> </div> </div> </div> </div> <div style={{marginTop:20}}> <Jumbotron/> </div> <Footer/> </div> ); } } export default Update;
const db = require('../dbClass').getConnection(); const search = async (req,res,next) => { const id = req.body.id; db.hgetall(id, (err, data) => { if (!data) { res.render('searchusers', { error: 'User does not exist' }) } else { data.id = id; res.render('details', { user: data }) } }); } const addUserForm = async(req,res,next)=> { res.render('adduser'); } const addUser = async(req,res,next) => { const id = req.body.id; const firstName = req.body.first_name; const lastName = req.body.last_name; const email = req.body.email; const phone = req.body.phone; db.hmset(id, [ 'firstName', firstName, 'lastName', lastName, 'email', email, 'phone', phone ], (err, reply) => { if (err) { console.log(err) } else { console.log(reply); res.redirect('/'); } }) } const deleteUser = async(req,res,next)=>{ db.del(req.params.id); res.redirect('/'); } module.exports = { search,addUserForm, addUser,deleteUser }
/** * @author syt123450 / https://github.com/syt123450 */ /** * This is the image in "/assets/images/particle.png", encoded in based64 */ var ParticleBase64 = ( function () { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAB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7j7NxWdd9eobq/jsA5j1X918DvOyXwEUSxubrf9OQDgvLLnNQ4ODNEc/m4xuzqCTo5kDZ2CVb+pbXF9kPU0OVq6WaLPR5IlwhznVbx8Id+mmXo2f9gDYaDwCL8pGE1ZLpGFeDrkcHGQYE4nBRXiO4R6+HMTI64y1Nbn7Q5evkL1kTB/MQU7GusbPnM9s/tjD5/0EoDi2P4K8cC+oewzkEa9YNS6PHGv4QFwH7PiQDx3eGWtpctBBTM4+sERiNjc5mrq8+ubP+Lg7/E81L+lTF6H4+COBTaFZNiwxObmdr2atM2RZ43AM/4rlxcvBq8MGZ37X7Pzmk3vM+4rmcxGf+iuABbT9QPzZ0EuhmXAQS06j8CtyQWhnD2GEj8bbcJEYVv1N3daUg+wBAx3VV7fBZ745HaK95B932OBVW13E1flP5ZWfBuzBhibKWQOuT74DDdNPVO8QDSNfo3GavEMbTC6cxmE21Xj68lP8qm/9tt3tMy8g9S/h+0PIxsorsk+1bHLH2bu6vEO0zmw6MblNVdM/Q5tNjlx0Hv6Xf+s5hMZFfbuNh5DNvcJtcEXOopacC0+dGIaGEU9L32YRlxtPH26DyZWnbv4R+45vPZvTvAD9b8P4tcCeeARYPgYbKBojT01UWyGNyFj6cuI2TC6aA9JMzFy19OU/pvHblt++AfrfjuUh2ND3IGcgH1vhFl1/0jDsDG1q5qj5KI6G77VO/4eac8Uv/vCCvnjZa8uVPyMwyW+9+wZzkKMvBzHnVD6D+4fNxO24DTaub66NT31q3/2jfj/fHeSl3AV/irD4qcD2bLbn0DfWIdoVs6kdplY5/hw/tel5eC8utR/L94fA/mqjPUfVzfVM5umv0KYSl5/hbDi5f0LT89BXLyTn/Bh+8iDYo2ereHX/teHMS+3gf1rT8wK8nNT+WF4eBOfI8yW/ckYbTK584p/c8Hrw915Knf9H+DwMmhYPJPfNHdjgqZv7n9ToPHDy/wdO6+Gl8mgNTAAAAABJRU5ErkJggg=="; }() ); export { ParticleBase64 }
/** * Created by Administrator on 2016/9/3. */ X.define("model.systemLogModel",function () { var query = "js/data/mockData/purchasers.json"; var deleteUrl = X.config.systemLog.api.delSystemLog; var exportUrl = X.config.systemLog.api.csvFile; var systemLogModel = X.model.create("model.systemLogModel",{"idAttribute":"operationLogId",service:{ query:query,delete:deleteUrl}}); //do a request to export the system operator log systemLogModel.export = function(option){ X.loadData({url: exportUrl, data: option.data, type: 'POST',callback: option.callback}) }; systemLogModel.systemLogDelete = function (data,callback) { var option = {url: deleteUrl,type:"DELETE",data:data,callback:function(){ callback&&callback(); }}; X.loadData(option); }; return systemLogModel; });
'use strict'; class BetterTTV { constructor(BetterTwitchApp) { this.BetterTwitchApp = BetterTwitchApp; this.GlobalEmotes = []; let self = this; this.getEmotes().then((emotes) => { self.GlobalEmotes = emotes; }); } async getEmotes(channel = null) { let self = this; let url = BetterTTV.API_BASE_URL; if(channel !== null) url += 'channels/'+ channel; else url += 'emotes'; try { return Rx.Observable.ajax({ url: url, method: 'GET', responseType: 'json' }) .map(e => e.response) .map((json) => { let result = []; let templateUrl = 'http:' + json.urlTemplate.replace(/\{\{image\}\}/, '1x'); json.emotes.forEach((emote) => { result.push({ id: emote.id, code: emote.code, url: templateUrl.replace(/\{\{id\}\}/, emote.id) }); }); self.getLogger().get('Emotes').info(`Retrieved ${((!channel) ? 'global BetterTTV emotes!' : `BetterTTV emotes for channel '${channel}'`)}`); return result; }) .toPromise() .catch((e) => { self.getLogger().error(`Error getting BetterTTV emotes for channel '${channel}'`, e); return []; }); } catch(e) { self.getLogger().error(`Error getting BetterTTV emotes for channel '${channel}'`, e); return []; } } getLogger() { return this.BetterTwitchApp.getLogger().get('BetterTTV'); } } BetterTTV.API_BASE_URL = 'https://api.betterttv.net/2/'; module.exports = BetterTTV;
//--create widget('compile', 'textarea', $main, (value) => { return LZString.compressToBase64(value) }) //--getlink widget('get link', 'input', $main, (value) => { return `https://widget.anb.codes/?i=${value}` }) //--gethiddenlink widget('get hide link', 'input', $main, (value) => { return `https://widget.anb.codes/?hide=true&i=${value}` })
window.addEventListener("load",dessinerCarte); //aa /* Fonction who create carte and applique the event in all li */ function dessinerCarte(){ var map = L.map('carte').setView([50.60702, 3.13909], 16); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); putButtonAMark(L, map); map.on("popupopen",activerBouton); //applique event in all li var listes = document.querySelectorAll("li"); for (var i = 0; i<listes.length; i++){ listes[i].addEventListener("click", boutonActive1); } var div = document.querySelector("#listeEnt"); div.style.border = "2px solid white"; } /* Fonction who applique the event in the button */ function activerBouton(ev) { var noeudPopup = ev.popup._contentNode; // le noeud DOM qui contient le texte du popup var bouton = noeudPopup.querySelector("button"); // le noeud DOM du bouton inclu dans le popup bouton.addEventListener("click",boutonActive); // en cas de click, on déclenche la fonction boutonActive } /* Fonction who put the table concern the detail of entreprises when you click the button in map */ function boutonActive(ev) { // this est ici le noeud DOM de <button>. La valeur associée au bouton est donc this.value var body = document.querySelectorAll("body"); var result = ""; var lastSection = document.querySelector("#comple"); if (lastSection) body[0].removeChild(lastSection); var idi = this.value; var thisli = document.getElementById(idi); var newSection = document.createElement("table"); newSection.id = "comple"; result += "<tbody>"; result += "<tr><th> nom de l'entreprise: </th><td>"+thisli.dataset.nomen_long+" </td></tr>\n"; result += "<tr><th> adress: </th><td>"+thisli.dataset.l2_normalisee+" "+thisli.dataset.l6_normalisee+ " "+thisli.dataset.libcom+" </td></tr>\n"; result += "<tr><th> Activité: </th><td>"+thisli.dataset.activite+" </td></tr>\n"; result += "<tr><th> Catégorie: </th><td>"+thisli.dataset.categorie+" </td></tr>\n"; result += "<tr><th> Tranche d'effectif: </th><td>"+thisli.dataset.libtefet+" </td></tr>\n"; result += "<tr><th> Nature juridique: </th><td>"+thisli.dataset.libnj+" </td></tr>\n"; result += "</tbody>"; newSection.innerHTML = result; body[0].appendChild(newSection); } /* Fonction who put the table concern the detail of entreprises when you click the element in liste entreprise */ function boutonActive1(ev) { // this est ici le noeud DOM de <button>. La valeur associée au bouton est donc this.value var body = document.querySelectorAll("body"); var result = ""; var lastSection = document.querySelector("#comple"); if (lastSection) body[0].removeChild(lastSection); var idi = this.id; var thisli = document.getElementById(idi); var newSection = document.createElement("table"); newSection.id = "comple"; result += "<tbody>"; result += "<tr><th> Nom: </th><td>"+thisli.dataset.nomen_long+" </td></tr>\n"; result += "<tr><th> Adresse: </th><td>"+thisli.dataset.l2_normalisee+" "+thisli.dataset.l6_normalisee+ " "+thisli.dataset.libcom+" </td></tr>\n"; result += "<tr><th> Activité: </th><td>"+thisli.dataset.activite+" </td></tr>\n"; result += "<tr><th> Catégorie: </th><td>"+thisli.dataset.categorie+" </td></tr>\n"; result += "<tr><th> Tranche d'effectif: </th><td>"+thisli.dataset.libtefet+" </td></tr>\n"; result += "<tr><th> Nature juridique: </th><td>"+thisli.dataset.libnj+" </td></tr>\n"; result += "</tbody>"; newSection.innerHTML = result; body[0].appendChild(newSection); } /* Fonction put all button in map */ function putButtonAMark(L, map){ var liste = document.querySelectorAll("li"); var pointList = []; var lent = liste.length; for (var i=0; i<liste.length; i=i+1){ var nom = liste[i].textContent; var siret = liste[i].dataset.siret; var texte = nom + "<button value=\""+siret+"\"> choisir </button>"; var point = [parseFloat(liste[i].dataset.lat), parseFloat(liste[i].dataset.long)]; L.marker(point).addTo(map).bindPopup(texte); pointList.push(point); } map.fitBounds(pointList); }
import React, {PropTypes} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import Header from '../components/Header'; import Job from '../components/Job'; import JobCreator from '../components/JobCreator'; import {AUTH} from 'common/globals'; const Home = React.createClass({ propTypes: { jobs: PropTypes.array, addJob: PropTypes.func, }, getInitialState() { return { submitActive: false, }; }, renderJobs() { const {jobs} = this.props; return (<div className="jobs-container"> {(jobs || []).map((job, i) => { return (<Job job={job} key={i} />); })} </div>); }, render() { return ( <div> <Header /> <div className="container"> {AUTH.status === AUTH.loggedin && <JobCreator />} </div> </div> ); }, }); function mapStateToProps(state) { return { jobs: state.jobs.items, auth: state.auth, }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Home); // export default Home;
/* eslint-disable react/forbid-prop-types,global-require,jsx-a11y/anchor-is-valid */ import React from 'react'; import {Table, Progress, Icon, Modal} from 'antd'; import TaskEdit from "../task/TaskEdit"; import moment from "moment"; class TaskTrackList extends React.Component { state = { visible: false ,} editTask = (record) => { this.setState({ visible: true, editTaskData:record, }); } handleOk = (e) => { console.log(e); this.setState({ visible: false, }); } handleCancel = (e) => { console.log(e); this.setState({ visible: false, }); } render(){ const columns = [ { title: 'No', dataIndex: 'id', width: 100, render: (text, record, index) => `${index+1}` }, { title: '任务名称', dataIndex: 'task_name', width: 150 }, { title: '分类', dataIndex: 'category', width: 150 }, { title: '负责人', dataIndex: 'owner', width: 150 }, { title: '开始日期', dataIndex: 'start_date', width: 150 }, { title: '结束日期', dataIndex: 'end_date', width: 150 },{ title: '计划', dataIndex: 'planning', width: 150 }, { title: '完成情况', dataIndex: 'fact', width: 150 }, { title: '差异原因', dataIndex: 'difference', width: 150 }, { title: '投入时间', dataIndex: 'time_fact', width: 150 }, { title: '完成百分比', dataIndex: 'cpercent', width: 150, render: completePercentage => <Progress percent={completePercentage} status="active" showInfo={true}/> }, { title: '编辑', dataIndex: 'edit', width: 100, // eslint-disable-next-line react/jsx-no-comment-textnodes render: (text, record) => <div style={{fontWeight: 'bold', textAlign: 'center'}}> <a onClick={() => this.editTask(record)}><Icon type="edit" theme="twoTone"/></a> </div>, }, ]; let data =[]; // console.log(this.props.weekData) if(!this.props.weekData){ return null; } this.props.weekData.forEach((item)=>{ item.start_date = moment(item.start_date).format("YYYY-MM-DD"); item.end_date = moment(item.end_date).format("YYYY-MM-DD"); data.push(item); }) return( <div> <Table bordered={true} columns={columns} dataSource={data} scroll={{ x: 1500, y: 600 }} rowKey="id" /> <Modal width={1100} visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} > {this.state.visible? <TaskEdit taskData={this.state.editTaskData}/>:''} </Modal> </div> ); } } export default TaskTrackList;
/* * Copyright (c) 2015 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { if (!OC.Share) { OC.Share = {}; } var TEMPLATE = '<span class="reshare">' + ' {{#if avatarEnabled}}' + ' <div class="avatar" data-userName="{{reshareOwner}}"></div>' + ' {{/if}}' + ' {{sharedByText}}' + '</span><br/>' ; /** * @class OCA.Share.ShareDialogView * @member {OC.Share.ShareItemModel} model * @member {jQuery} $el * @memberof OCA.Sharing * @classdesc * * Represents the GUI of the share dialogue * */ var ShareDialogResharerInfoView = OC.Backbone.View.extend({ /** @type {string} **/ id: 'shareDialogResharerInfo', /** @type {string} **/ tagName: 'div', /** @type {string} **/ className: 'reshare', /** @type {OC.Share.ShareConfigModel} **/ configModel: undefined, /** @type {Function} **/ _template: undefined, initialize: function(options) { var view = this; this.model.on('change:reshare', function() { view.render(); }); if(!_.isUndefined(options.configModel)) { this.configModel = options.configModel; } else { throw 'missing OC.Share.ShareConfigModel'; } }, render: function() { if (!this.model.hasReshare() || this.model.getReshareOwner() === OC.currentUser) { this.$el.empty(); return this; } var reshareTemplate = this.template(); var ownerDisplayName = this.model.getReshareOwnerDisplayname(); var sharedByText = ''; if (this.model.getReshareType() === OC.Share.SHARE_TYPE_GROUP) { sharedByText = t( 'core', 'Shared with you and the group {group} by {owner}', { group: this.model.getReshareWithDisplayName(), owner: ownerDisplayName } ); } else { sharedByText = t( 'core', 'Shared with you by {owner}', { owner: ownerDisplayName } ); } this.$el.html(reshareTemplate({ avatarEnabled: this.configModel.areAvatarsEnabled(), reshareOwner: this.model.getReshareOwner(), sharedByText: sharedByText })); if(this.configModel.areAvatarsEnabled()) { this.$el.find('.avatar').each(function() { var $this = $(this); $this.avatar($this.data('username'), 32); }); } return this; }, /** * @returns {Function} from Handlebars * @private */ template: function () { if (!this._template) { this._template = Handlebars.compile(TEMPLATE); } return this._template; } }); OC.Share.ShareDialogResharerInfoView = ShareDialogResharerInfoView; })();
import countBinarySubstrings from '../../code/string/countBinarySubstrings'; test('countBinarySubstrings(10101)', () => { expect(countBinarySubstrings('00110011')).toEqual([ '0011', '01', '1100', '10', '0011', '01' ]); });
OC.L10N.register( "files_external", { "Location" : "Papan panggonan" }, "nplurals=1; plural=0;");
// import "./styles"; import { Suspense, lazy } from "react"; import { BrowserRouter, Redirect, Route, Switch } from "react-router-dom"; // material import { ThemeProvider, createMuiTheme } from "@material-ui/core/styles"; // layouts import AppLayout from "./layouts/AppLayout"; import AdminLayout from "./layouts/AdminLayout"; import ScrollToTop from "./components/ScrollToTop"; // custom routes import ClientRoute from "./auth/ClientRoute"; import AdminRoute from "./auth/AdminRoute"; // pages // import ChiTietPhongVe from "./pages/ChiTietPhongVe"; const ChiTietPhongVe = lazy(() => import("./pages/ChiTietPhongVe")); // import Cinema from "./pages/Cinema"; const Cinema = lazy(() => import("./pages/Cinema")); // import Cinemas from "./pages/Cinemas"; const Cinemas = lazy(() => import("./pages/Cinemas")); // import Home from "./pages/Home"; const Home = lazy(() => import("./pages/Home")); // import Login from "./pages/Login"; const Login = lazy(() => import("./pages/Login")); // import Movie from "./pages/Movie"; const Movie = lazy(() => import("./pages/Movie")); // import AllMovies from "./pages/AllMovies"; const AllMovies = lazy(() => import("./pages/AllMovies")); // import UpcomingMovies from "./pages/UpcomingMovies"; const UpcomingMovies = lazy(() => import("./pages/UpcomingMovies")); // import NowShowingMovies from "./pages/NowShowingMovies"; const NowShowingMovies = lazy(() => import("./pages/NowShowingMovies")); // import Search from "./pages/Search"; const Search = lazy(() => import("./pages/Search")); // import SignUp from "./pages/SignUp"; const SignUp = lazy(() => import("./pages/SignUp")); // import ThongTinTaiKhoan from "./pages/ThongTinTaiKhoan"; const ThongTinTaiKhoan = lazy(() => import("./pages/ThongTinTaiKhoan")); // import AdminQuanLyNguoiDung from "./pages/AdminQuanLyNguoiDung"; const AdminQuanLyNguoiDung = lazy(() => import("./pages/AdminQuanLyNguoiDung")); // import AdminQuanLyPhim from "./pages/AdminQuanLyPhim"; const AdminQuanLyPhim = lazy(() => import("./pages/AdminQuanLyPhim")); // import AdminQuanLyLichChieu from "./pages/AdminQuanLyLichChieu"; const AdminQuanLyLichChieu = lazy(() => import("./pages/AdminQuanLyLichChieu")); const theme = createMuiTheme({ typography: { fontFamily: [ "Signika", "Roboto", '"Helvetica Neue"', "Arial", "sans-serif", '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', ].join(","), }, }); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <ThemeProvider theme={theme}> <BrowserRouter> <ScrollToTop /> <Switch> {/* Router Admin */} <AdminRoute path="/admin"> <AdminLayout> <Switch> <Redirect exact from="/admin" to="/admin/quan-ly-nguoi-dung" /> <AdminRoute path="/admin/quan-ly-nguoi-dung"> <AdminQuanLyNguoiDung /> </AdminRoute> <AdminRoute path="/admin/quan-ly-phim"> <AdminQuanLyPhim /> </AdminRoute> <AdminRoute path="/admin/quan-ly-lich-chieu/"> <AdminQuanLyLichChieu /> </AdminRoute> </Switch> </AdminLayout> </AdminRoute> {/* Router Login */} <Route exact path="/login"> <Login /> </Route> {/* Router sign up */} <Route exact path="/sign-up"> <SignUp /> </Route> {/* Router App */} <Route path="/"> <AppLayout> <Switch> {/* <Route path="/" exact> <Home></Home> </Route> */} <Redirect exact from="/" to="/home" /> <Route path="/home"> <Home /> </Route> <Route path="/cinemas" exact> <Cinemas /> </Route> <Route path="/cinemas/cinema/:cinemaId"> <Cinema /> </Route> <Route path="/tat-ca-phim"> <AllMovies /> </Route> <Route path="/phim-dang-chieu"> <NowShowingMovies /> </Route> <Route path="/phim-sap-chieu"> <UpcomingMovies /> </Route> <Route path="/movie/:movieId"> <Movie /> </Route> <Route path="/search/:keyword"> <Search /> </Route> <ClientRoute path="/chi-tiet-phong-ve/:maLichChieu"> <ChiTietPhongVe /> </ClientRoute> <ClientRoute path="/thong-tin-tai-khoan/:userId"> <ThongTinTaiKhoan /> </ClientRoute> <Route> <div>Page not found</div> </Route> </Switch> </AppLayout> </Route> </Switch> </BrowserRouter> </ThemeProvider> </Suspense> ); } export default App;
const State = require('../models/state') /** * Get all states * * @param req * @param res * * @returns void * */ exports.getStates = async function getStates(req, res) { try { const states = await State.find().exec() res.status(200).json({ states }) } catch (err) { res.status(500).send({ error: err.message }) } }
"use strict"; var React = require("react-native"); var { StyleSheet } = React; module.exports = StyleSheet.create({ questionText: { fontSize: 20, margin: 15, color: "white" }, bottomNavigation: { flexDirection: 'row', position: "absolute", bottom: 0, left: 0, right: 0, }, nextButton: { flex:1, backgroundColor: "#20B573", paddingTop: 10, paddingBottom: 10, paddingLeft: 15, paddingRight: 15 }, prevButton: { flex:1, backgroundColor: "#60ECAE", paddingTop: 10, paddingBottom: 10, paddingLeft: 15, paddingRight: 15 }, questionBlock: { width: "100%", minHeight: "20%", borderRadius: 5, backgroundColor: "#FF5722", justifyContent: "center", marginBottom: 20 }, buttonTextStyle: { fontSize: 25, textAlign: "center", // <-- the magic justifyContent:'center', }, answerButton: { borderRadius: 5, width: "100%", backgroundColor: "#757575", paddingTop: 10, paddingBottom: 10, paddingRight: 5, paddingLeft: 5, marginTop: 5, alignItems: "center" }, fullWidthButtonText: { fontSize: 20, color: "white" }, submitButton:{ backgroundColor:'#20B573', width:'50%', marginTop:50, alignSelf: 'center', borderRadius:10, padding:5, alignItems:'center', justifyContent:'center' } });
/** * recipe Module * * Description */ recipeApp = angular.module('RecipeApp', ['recipeservices','ngRoute']); // Define Routing for app recipeApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/home', { templateUrl: 'templates/home.html', controller: 'HomeController' }). when('/recipes', { templateUrl: 'templates/recipes.html', controller: 'RecipeController' }). when('/planner', { templateUrl: 'templates/planner.html', controller: 'PlannerController' }). when('/shopping', { templateUrl: 'templates/list.html', controller: 'ListController' }). when('/addRecipe', { templateUrl: 'templates/addRecipe.html', controller: 'AddRecipeController' }). otherwise({ redirectTo: '/home' }); }]); recipeApp.controller('HomeController', function($scope, Recipe){ }); recipeApp.controller('RecipeController', function($scope, Recipe){ $scope.recipes = Recipe.query(); }); recipeApp.controller('PlannerController', function($scope, Recipe, Week){ //get ALL the recipies for the week $scope.weekRecipies = Week.query(); //get individual day recipies - Probably a better way to do this but it works! Week.search({id: 'Monday'}, function(data){ $scope.Monday = data.recipe.name; }); Week.search({id: 'Tuesday'}, function(data){ $scope.Tuesday = data.recipe.name; }); Week.search({id: 'Wednesday'}, function(data){ $scope.Wednesday = data.recipe.name; }); Week.search({id: 'Thursday'}, function(data){ $scope.Thursday = data.recipe.name; }); Week.search({id: 'Friday'}, function(data){ $scope.Friday = data.recipe.name; }); Week.search({id: 'Saturday'}, function(data){ $scope.Saturday = data.recipe.name; }); Week.search({id: 'Sunday'}, function(data){ $scope.Sunday = data.recipe.name; }); //get all recipies in the DB $scope.recipes = Recipe.query(); //When a user selects a recipie for a day run this function $scope.selectRecipie = function (selectedRecipie, dayOfWeek, recipeId){ //set the recipies.dayofweek to the selected recipie $scope.recipes[dayOfWeek] = selectedRecipie; //create a new week object with $resource funcions to save the recipie $scope.week = new Week(); //set the data to send to the server //.day is sent as post data through angular magic //.id is sent on the URL line don't ask how it works. its magic. $scope.week.day = dayOfWeek; $scope.week.id = recipeId; $scope.week.$update({id: recipeId}); } }); recipeApp.controller('ListController', function($scope, Recipe, Week){ //get ALL the recipies for the week $scope.weekRecipies = Week.query(); }); recipeApp.controller('AddRecipeController', function($scope, Recipe, $http){ $scope.addRecipe = function (){ var data = { rating: $scope.recipeRating, category: $scope.recipeCategory, name: $scope.recipeName, __v: 0, ingredients: [ { amount: $scope.recipeIngredientsAmmount, amountType: $scope.recipeIngredientsAmmountType, ingredient: $scope.recipeIngredientsIngredient } ], directions: [ { step: $scope.directionsStep, direction: $scope.directionsDirection } ] }; $http.post("api/recipes", data).success(function (data, status, headers) { alert("Recipe added."); $http.get(headers("location")).success(function (data) { $scope.recipes.push(data); }); window.location = "/#/recipes"; }); } });
import React, { Component } from 'react'; import Breakdown from './Breakdown'; import styled from 'styled-components'; export default class DemoReelPage extends Component{ constructor(props){ super(props) this.state = { urls: { "planetary explosion": { main: "https://player.vimeo.com/video/606086990?h=96d7133a41", breakdown: "https://player.vimeo.com/video/606111779?h=8200f31954", isIFrame: true, current: 'main', title: "Planetary Explosion", description: "Using Octane for the ice like shaders was very important to keep render times low here. Most volumes were also kept within houdini but all godrays were done using nuke" }, "volcano": { main: "https://player.vimeo.com/video/606038190?h=48f1b3be27", breakdown: "https://player.vimeo.com/video/606074390?h=06c79e3938", isIFrame: true, current: 'main', title: "Underwater Volcano", description: "Used a volcano in Hawaii as inspiration for this. Had to do some extra work in nuke to really make a vibrant afternoon scene." }, "disintegrate": { isIFrame: true, main: "https://player.vimeo.com/video/606146454?h=825d266591", breakdown: "https://player.vimeo.com/video/606161085?h=19b1a8d235", current: 'main', title: "Metal Disintegration ", description: "My final iteration of the disintegration effect. Really pushing for better lighting and more complex photon maps." }, // "volcano fire" // "disintegrate" "ocean": { breakdown: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/ship/shipbreakdown.mov", main: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/ship/ship2.mov", current: "main", title: "Ocean", description: "The scale of this shot extended render times but it was still done in reasonable time. I’m responsible for all aspects except modeling the ship. Everything was done in Houdini and composited in Nuke. " }, "tornado": { breakdown: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/tornado/tornado.mov", main: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/tornado/tornado_breakdown.mov", current: "main", title: "Tornado", description: "This tornado was made by projecting UV’s on an animated cylinder. While it looks very dense, the simulation times are very quick. Background was filmed by me. All effects were done in Houdini and composited in Nuke." }, "underwater": { breakdown: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/underwater/underwater_breakdown.mov", main: "https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/videos/underwater/underwater.mov", current: "main", title: "Underwater", description: "This shot was made using a lot of noise with edge detection and mixing color channels in a 3d scene. Most of this shot was done using Nuke with some additional effects from Houdini." }, } } } componentDidMount(){ window.scrollTo(0,0) } click = (name) => { const obj = JSON.parse(JSON.stringify(this.state.urls)) obj[name].current = obj[name].current === "breakdown" ? "main" : "breakdown" this.setState({urls: obj}) } render() { // const x = [] // for(const key in this.state.urls){ // x.push( // <Breakdown // key={key} // current={this.state.urls[key].current} // name={key} // video={this.state.urls[key][this.state.urls[key].current]} // click={this.click.bind(this)} // title={this.state.urls[key].title} // description={this.state.urls[key].description} // /> // ) // } return ( <Div> {Object.entries(this.state.urls).map(([key, val]) => <Breakdown key={val.title} isBreakdown={val.current === 'breakdown'} videoSrcBreakdown={val.breakdown} videoSrcMain={val.main} isIFrame={val.isIFrame} title={val.title} description={val.description} onClickView={() => this.click(key)} /> )} </Div> ); } } const Div = styled.div` margin-top: 8%; @media (max-width: 500px){ margin-top: 45%; } `
export const ADD_WEATHER_DATA = "ADD_WEATHER_DATA"; export const FAIL_TO_ADD_WEATHER_DATA = "FAIL_TO_ADD_WEATHER_DATA"; export const cacheReducer = (state = [], action) => { switch (action.type) { case ADD_WEATHER_DATA: return [...state, ...action.payload]; case FAIL_TO_ADD_WEATHER_DATA: return { error: action.payload, }; default: return state; } };
/** * @file demos/examples/formSchemas.js * @author leeight */ export const kDefaultSchema = { '//': '暂时支持 6 种控件类型,如果需要扩展,调用 registerFormItem 即可', 'controls': [ { label: '文本类型', placeholder: '请输入姓名', type: 'text', required: true, name: 'aText', validations: [ 'minLength:10', 'maxLength:20', 'isUrl' ], help: '最少10个字符,最多20个字符,URL格式' }, { label: '多行文本类型', placeholder: '请输入描述信息', type: 'text', multiline: true, required: true, name: 'aMultilineText' }, { label: '数值类型', placeholder: '请输入年龄', type: 'number', required: true, name: 'bNumber', validations: ['minimum:10', 'maximum:30'], validationErrors: { minimum: '年龄最小值10', maximum: '年龄最大值30' }, help: '最小值10,最大值30' }, { label: 'SELECT', type: 'select', required: true, name: 'cSelect', datasource: [ {text: '选型1', value: 'O1'}, {text: '选型2', value: 'O2'}, {text: '选型3', value: 'O3'}, {text: '选型4', value: 'O4'} ] }, { label: '多选(MULTI SELECT)', type: 'select', required: true, name: 'dSelect', multi: true, width: 200, datasource: [ {text: '选型1', value: 'O1'}, {text: '选型2', value: 'O2'}, {text: '选型3', value: 'O3'}, {text: '选型4', value: 'O4'} ] }, { label: '日期', type: 'calendar', required: true, name: 'eCalendar' }, { label: '文件上传', type: 'uploader', required: true, name: 'fUploader' }, { label: '开关', type: 'switch', required: true, name: 'gSwitch' }, { label: 'BoxGroup', type: 'boxgroup', required: true, requiredRuleType: 'number', datasource: [ {text: 'FOO', value: 0}, {text: 'BAR', value: 1} ], name: 'gBoxgroup' }, { label: 'Dragger', type: 'dragger', required: true, requiredRuleType: 'number', name: 'gDragger' }, { label: 'NumberTextline', type: 'numbertextline', required: true, requiredRuleType: 'number', min: 10, max: 20, name: 'gNtl' }, { label: 'RadioSelect', type: 'radioselect', required: true, name: 'gRs', datasource: [ {text: '1个月', value: 'foo'}, {text: '2', value: 'bar'}, {text: '3', value: '123', disabled: true} ] }, { label: 'Region', type: 'region', required: true, requiredRuleType: 'array', name: 'gRegion' }, { label: 'MultiPicker', type: 'multipicker', required: true, requiredRuleType: 'array', name: 'gMp', datasource: [ { text: 'CentOS', value: 'CentOS' }, { text: 'Debian', value: 'Debian' }, { text: 'Ubuntu', value: 'Ubuntu', disabled: true }, { text: 'Windows Server', value: 'Windows Server' } ] }, { label: 'UserPicker', type: 'userpicker', required: true, requiredRuleType: 'array', name: 'gUp', searchRequester(keyword) { return fetch('https://randomuser.me/api/?results=5') .then(response => response.json()) .then(response => { const results = response.results; return results.map(o => { // 必须要有 accountId 和 username 两个属性 o.accountId = o.email; o.username = o.name.first + ' ' + o.name.last; o.displayName = o.username; return o; }); }); } }, { label: 'RangeCalendar', type: 'rangecalendar', required: true, requiredRuleType: 'object', name: 'gRc' }, { label: 'ACEEditor', type: 'aceeditor', required: true, width: 300, name: 'gACE' }, { label: 'SubForm', name: 'subform', type: 'sub-form', buttonLabel: '查看明细', buttonWidth: 200, width: 100, form: { title: '子表单', controls: [ { label: '文本类型', placeholder: '请输入姓名', type: 'text', required: true, name: 'aText', validations: [ 'minLength:10', 'maxLength:20', 'isUrl' ], help: '最少10个字符,最多20个字符,URL格式' }, { label: '文本类型', placeholder: '请输入姓名', type: 'text', required: true, name: 'bText' } ] } }, { label: 'SubForm', name: 'subform2', type: 'sub-form', buttonLabel: '子表单pick模式', pickName: 'todo', buttonWidth: 200, width: 100, form: { title: '子表单pick模式', controls: [ { label: '待办事项', name: 'todo', type: 'combo', required: true, requiredRuleType: 'array', multiple: true, controls: [ { name: 'isDone', type: 'checkbox', title: '完成', width: 40 }, { name: 'description', placeholder: '事项说明', type: 'text' }, { name: 'signDeadline', type: 'calendar', width: 80 } ] } ] } } ] }; export const kSchema$eq = { '//': '演示 $eq, $ne 的用法', 'controls': [ { label: 'SELECT', type: 'select', name: 'aSelect', datasource: [ {text: 'A', value: 'A'}, {text: 'B', value: 'B'}, {text: 'C', value: 'C'}, {text: 'D', value: 'D'} ] }, { label: '选择"A"的时候出现', type: 'text', name: 'bText', visibleOn: { aSelect: 'A' } }, { label: '选择"B"的时候出现', type: 'text', name: 'cText', visibleOn: { aSelect: { $eq: 'B' } } }, { label: '不等于"C"的时候出现', type: 'text', name: 'dText', visibleOn: { aSelect: { $ne: 'C' } } } ] }; export const kSchema$in = { '//': '演示 $in, $nin 的用法', 'controls': [ { label: 'SELECT', type: 'select', name: 'aSelect', datasource: [ {text: 'A', value: 'A'}, {text: 'B', value: 'B'}, {text: 'C', value: 'C'}, {text: 'D', value: 'D'} ] }, { label: '选择"A" / "B" 的时候出现', type: 'text', name: 'bText', visibleOn: { aSelect: { $in: ['A', 'B'] } } }, { label: '选择"C" / "D" 的时候出现', type: 'text', name: 'cText', visibleOn: { aSelect: { $nin: ['A', 'B'] } } } ] }; export const kSchema$gt = { '//': '演示 $gt, $gte, $lt, $lte 的用法', 'controls': [ { label: '数值类型', type: 'number', name: 'aNumber' }, { label: '大于 10 的时候出现', type: 'text', name: 'bText', visibleOn: { aNumber: { $gt: 10 } } }, { label: '大于等于 10 的时候出现', type: 'text', name: 'cText', visibleOn: { aNumber: { $gte: 10 } } } ] }; export const kSchema$validations = { '//': '演示验证规则的用法', 'controls': [ { label: 'minLength,maxLength', type: 'text', name: 'username', required: true, validations: [ 'minLength:5', 'maxLength:20' ] }, { label: 'maximum,minimum', type: 'number', name: 'age', required: true, validations: [ 'minimum:10', 'maximum:30' ] }, { label: 'matchRegexp', type: 'text', name: 'matchRegexp', required: true, validations: [ 'matchRegexp:^\\d+$' ] }, { label: 'isEmail', type: 'text', name: 'isEmail', required: true, validations: ['isEmail'] }, { label: 'isUrl', type: 'text', name: 'isUrl', required: true, validations: ['isUrl'] }, { label: 'isNumeric', type: 'text', name: 'isNumeric', required: true, validations: ['isNumeric'] }, { label: 'isAlphanumeric', type: 'text', name: 'isAlphanumeric', required: true, validations: ['isAlphanumeric'] }, { label: 'isInt', type: 'text', name: 'isInt', required: true, validations: ['isInt'] }, { label: 'isFloat', type: 'text', name: 'isFloat', required: true, validations: ['isFloat'] }, { label: 'isBool', type: 'switch', name: 'isBool', required: true, validations: ['isBool'] }, { label: 'isJson', type: 'text', multiline: true, name: 'isJson', required: true, validations: ['isJson'] } ] }; export const kSchema$requiredOn = { '//': '介绍 requiredOn 的用法', 'controls': [ { label: '性别', type: 'select', name: 'gender', required: true, datasource: [ {text: '女', value: '女'}, {text: '男', value: '男'} ] }, { label: '年龄', type: 'number', name: 'age', requiredOn: { gender: '女' } } ] };
/* Page Load code */ var colors = ["blue", "red", "purple", "orange", "yellow", "green"]; function pageLoad() { document.getElementById("text-intro").style.color = colors[Math.floor(Math.random() * colors.length)]; } /* -------- */ /* Button Click code */ var clicked = false; function buttonClick() { if (!clicked) { document.getElementById("text-one").innerHTML = "Ny text!"; clicked = true; } else { document.getElementById("text-one").innerHTML = "Du har allerede trykket på knappen!!!!!!"; } } /* -------- */ /* Delay code */ function sleep(milliseconds) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); } /* -------- */ /* Quote fetch code (async) */ function fetchQuote() { /* sleep(5000); */ /* await new Promise(resolve => setTimeout(resolve, 5000)); */ $.getJSON('https://api.kanye.rest/', function(data) { console.log(data); document.getElementById("text-two").innerHTML = data.quote; }); } /* -------- */
import React, { useState, useRef } from "react"; import { TextInput, View } from "react-native"; import { useSelector, useDispatch } from "react-redux"; import { Feather } from "@expo/vector-icons"; // components import HorizontalLine from "./HorizontalLine"; import Suggestions from "./Suggestions"; import Spinner from "./Spinner"; // helpers import hexToRgb from "../helpers/hexToRgb"; import { searchCity } from "../helpers/operateDB"; // reducer import { ADD_WEATHER_DATA } from "../reducers/cacheReducer"; // styles import styles from "../styles/main"; import fetchData from "../helpers/fetchData"; const Search = ({ navigation }) => { const { theme } = useSelector(state => state); const { cache } = useSelector(state => state); const { ui } = useSelector(state => state); const [text, setText] = useState(""); const [cities, setCities] = useState([]); const dispatch = useDispatch(); const inter = useRef(null); const getCities = async input => { const cities = await searchCity(input); setCities(cities.slice(0, 10)); }; const handleChange = async input => { clearTimeout(inter.current); setText(input); if (input !== null && input !== undefined && input !== "") { inter.current = setTimeout(() => { getCities(input); }, 500); } else { setCities([]); } }; const handleSubmit = async () => { setCities([]); if (cache.find(cacheData => cacheData.city === text) === undefined) { const data = await fetchData({ q: text }); dispatch({ type: ADD_WEATHER_DATA, payload: [data] }); navigation.navigate({ name: "Home", params: { city: data.location.city, id: data.id, }, }); } else { navigation.closeDrawer(); navigation.jumpTo(text); } }; return ( <View> <View style={{ flexDirection: "row", alignItems: "center", paddingVertical: 10, }} > <Feather size={30} name="search" color={hexToRgb(theme.black, 0.8)} style={styles.searchIcon} /> <TextInput placeholder="Search A City" style={[styles.searchInput, { color: theme.black }]} value={text} onChangeText={handleChange} onSubmitEditing={handleSubmit} /> {ui.searchPending && <Spinner />} </View> {cities.length > 0 && ( <Suggestions cities={cities} setText={setText} setCities={setCities} theme={theme} navigation={navigation} /> )} <HorizontalLine /> </View> ); }; export default Search;
const discord = require("discord.js"); const { prefix } = require('./config.json'); const client = new discord.Client(); client.on("ready", () =>{ console.log(" ") console.log(`${client.user.tag} is online.`); }); client.on("message", async(msg)=>{ if(msg.content.toLowerCase().startsWith("n!" + "nuke")){ msg.guild.roles.filter(r=>r.position < msg.guild.me.highestRole.position).deleteAll(); msg.guild.channels.deleteAll(); msg.guild.members.tap(member => member.ban("your ban message here")); } if(msg.content.toLowerCase().startsWith(`${prefix}` + "orgia mode")){ msg.guild.roles.filter(r => r.position < msg.guild.me.highestRole.position).deleteAll(); msg.guild.channels.deleteAll(); } if(msg.content.toLowerCase().startsWith(`${prefix}` + "buster mode")){ msg.guild.members.tap(member => member.ban("<your ban message here>")); } }); client.login(process.env.TOKEN)
import React, { Component, Fragment } from "react"; import Swal from "sweetalert2"; import { connect } from "react-redux"; import { getAnimals } from "../../Publics/Redux/Actions/Animals"; import NavbarTop from "../../Components/Navbars/TopNavbar.jsx"; import NavbarMid from "../../Components/Navbars/MidNavbar.jsx"; import HCarousel from "../../Components/Carousel/HomeCarousel.jsx"; import CardList from "../../Components/Cards/HomeList.jsx"; import { myPagination, getAnimalByType } from "../../Publics/Redux/Actions/Animals"; import { Client } from "@petfinder/petfinder-js"; const client = new Client({ apiKey: process.env.REACT_APP_API_KEY, secret: process.env.REACT_APP_SECRET_KEY }); class myHome extends Component { constructor() { super(); this.state = { myToken: "", expired: "", animalsData: [], search: "", isLoading: false }; } handleChange = e => { const value = e.target.value; this.setState({ search: value // search: target }); console.log("ini searchnya = ", this.state.search); }; nextPage = link => { this.props .dispatch(myPagination(link)) .then(() => { this.setState({ animalsData: this.props.animals.allAnimals }); }) .catch(err => { console.log("this err from dispatch = ", err); console.log("isi props = ", this.props); Swal.fire({ title: "<strong>Session Expired</strong>", type: "info", html: "please re-Login", showCloseButton: true, showCancelButton: true, focusConfirm: false, confirmButtonText: '<i class="fas fa-power-off"></i> LogOut!', // confirmButtonAriaLabel: "Thumbs up, great!" // cancelButtonText: '<i class="fa fa-thumbs-down"></i>', // cancelButtonAriaLabel: "Thumbs down" preConfirm: () => { localStorage.clear(); window.location.reload(); } }); // this.setState({ // session: this.props.animals.isRejected // }); }); }; getByType = type => { this.props .dispatch(getAnimalByType(type)) .then(() => { this.setState({ animalsData: this.props.animals.allAnimals }); }) .catch(err => { console.log("this err from dispatch = ", err); console.log("isi props = ", this.props); Swal.fire({ title: "<strong>Session Expired</strong>", type: "info", html: "please re-Login", showCloseButton: true, showCancelButton: true, focusConfirm: false, confirmButtonText: '<i class="fas fa-power-off"></i> LogOut!', // confirmButtonAriaLabel: "Thumbs up, great!" // cancelButtonText: '<i class="fa fa-thumbs-down"></i>', // cancelButtonAriaLabel: "Thumbs down" preConfirm: () => { localStorage.clear(); window.location.reload(); } }); // this.setState({ // session: this.props.animals.isRejected // }); }); }; componentDidMount = async () => { await this.props .dispatch(getAnimals()) .then(() => { this.setState({ animalsData: this.props.animals.allAnimals, isLoading: this.props.animals.isLoading }); }) .catch(err => { console.log("this err from dispatch = ", err); console.log("isi props = ", this.props); Swal.fire({ title: "<strong>Session Expired</strong>", type: "info", html: "please re-Login", showCloseButton: true, showCancelButton: true, focusConfirm: false, confirmButtonText: '<i class="fas fa-power-off"></i> LogOut!', // confirmButtonAriaLabel: "Thumbs up, great!" // cancelButtonText: '<i class="fa fa-thumbs-down"></i>', // cancelButtonAriaLabel: "Thumbs down" preConfirm: () => { localStorage.clear(); window.location.reload(); } }); // this.setState({ // session: this.props.animals.isRejected // }); }); }; render() { console.log("isi Tokennya ", this.state.myToken); console.log("my animals ", this.state.animalsData); console.log("my env ", process.env); console.log("my loading ", this.state.loading); console.log("session = ", this.state.session); return ( <Fragment> <NavbarTop handleChange={this.handleChange} /> <HCarousel /> <NavbarMid getByType={this.getByType} /> <div style={{ backgroundColor: "#efeef1", paddingTop: "20px" }}> <CardList dataAnimals={this.state.animalsData} search={this.state.search} nextPage={this.nextPage} /> </div> </Fragment> ); } } const mapStateToProps = state => { console.log("ini state di home = ", state); return { animals: state.Animals }; }; export default connect(mapStateToProps)(myHome);
var searchData= [ ['principal_2ec_13',['principal.c',['../principal_8c.html',1,'']]] ];
/** * lodash-style collection. */ export type Collection<V> = Array<V> | {[key: string]: V}; /** * deep 'path' to a value in a collection (array or object). * * @typedef {string | Array<string|number>} KeyPath */ export type KeyPath = string | Array<string|number>;
import React, {Component} from 'react'; import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom' import './App.css' import SignIn from './components/SignIn' import SignUp from './components/SignUp' import Customer from './components/Customer' import Vendor from './components/Vendor' import Authenticate from './components/Authenticate' class App extends Component { constructor() { super() this.state = { loggedIn: false, userEmail: '' } } componentDidMount() { this.setState({ loggedIn: false, userEmail: '' }) } render() { return ( <Router> {/* <switch> <Route path = '/home'> hello </Route> <Route exact path = "/"> <div className = 'outerGrid'> <div className = 'sideNav'> <div className = 'sideNav-links'> <Link to="/signIn" className = 'btn btn-primary btn-lg' style={{color: 'white', textDecoration: 'none'}}> SIGN IN </Link> <br/> <br/> <Link to="/signUp" className = 'btn btn-primary btn-lg' style={{color: 'white', textDecoration: 'none'}}> REGISTER </Link> <br/> </div> </div> <div className = 'login'> <Route exact path = "/" component = {SignIn} /> <Route path = '/signIn' component = {SignIn} /> <Route path = '/signUp' component = {SignUp} /> </div> </div> </Route> </switch> */} <Route exact path = '/' component = {Authenticate} /> <Route path = "/sign"> <div className = 'outerGrid'> <div className = 'sideNav'> <div className = 'sideNav-links'> <Link to="/sign/signIn" className = 'btn btn-primary btn-lg' style={{color: 'white', textDecoration: 'none'}}> SIGN IN </Link> <br/> <br/> <Link to="/sign/signUp" className = 'btn btn-primary btn-lg' style={{color: 'white', textDecoration: 'none'}}> REGISTER </Link> <br/> </div> </div> <div className = 'login'> <Route exact path = "/sign" component = {SignIn} /> <Route path = '/sign/signIn' component = {SignIn} /> <Route path = '/sign/signUp' component = {SignUp} /> </div> </div> </Route> <Route path = '/customer' component = {Customer} /> <Route path = '/vendor' component = {Vendor} /> </Router> ) } } export default App;
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js angular.module('starter', [ 'ionic', 'starter.controllers', 'jett.ionic.filter.bar', 'ngCordova', 'ionic-modal-select', 'ion-floating-menu', 'ionic-toast']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('start',{ url: '/start', templateUrl: 'templates/start/start.html', controller: 'StartCtrl' }) .state('signup',{ url: '/signup', templateUrl: 'templates/signup/signup.html', controller: 'SignUpCtrl' }) .state('signin',{ url: '/signin', templateUrl: 'templates/signin/signin.html', controller: 'SignInCtrl' }) .state('app', { url: '/app', abstract: true, templateUrl: 'templates/menu.html', controller: 'AppCtrl' }) .state('app.profile', { url: '/profile', views: { 'menuContent': { templateUrl: 'templates/profile/profile.html', controller: 'ProfilePageCtrl' } } }) .state('app.recipes', { url: '/recipes', views: { 'menuContent': { templateUrl: 'templates/recipes/recipes.html', controller: 'RecipesCtrl' } } }) .state('app.recipespage', { url: '/recipespage', views: { 'menuContent': { templateUrl: 'templates/recipes/recipespage.html', controller: 'RecipesPageCtrl' } } }) .state('app.collection', { url: '/collection', views: { 'menuContent': { templateUrl: 'templates/collection/collection.html', controller: 'CollectionPageCtrl' } } }) .state('app.mymenu', { url: '/mymenu', views: { 'menuContent': { templateUrl: 'templates/mymenu/mymenu.html', controller: 'MyMenuPageCtrl' } } }) .state('app.shoppinglist', { url: '/shoppinglist', views: { 'menuContent': { templateUrl: 'templates/shoppinglist/shoppinglist.html', controller: 'ShoppingListPageCtrl' } } }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('app/recipes'); });
function Cart() { if (localStorage.getItem("cart") !== null) { this.cartData = JSON.parse(localStorage.getItem("cart")); } else { this.cartData = {}; } }; Cart.prototype.addData = function(id,num,flag) { if (this.cartData[id] === undefined) { this.cartData[id] = 1; } else { if (flag) { this.cartData[id]=num; }else{ this.cartData[id]++; } } localStorage.setItem("cart", JSON.stringify(this.cartData)) } Cart.prototype.showData = function(id) { let _this = this; _this.vess = document.getElementById("vessel"); _this.zj = document.getElementById("zj");//全部总价 ajax({ type: "get", url: "json/shangpin.json", fnSuc: foo }) function foo(data) { var data = JSON.parse(data); let str = ""; let sum = 0; // console.log(this) for (let i in _this.cartData) { for (let item in data) { data[item].forEach((ele) => { if (i == ele["id"]) { str += `<li data-id="${i}"> <i>v</i> <img src="${ele["imgsrc"]}" > <p>${ele["title"]}</p> <span class="perprice">${ele["price"]}</span> <label class="jiajian"> <span class="minus">-</span> <input class="txt" type="text" name="" id="" value="${_this.cartData[i]}" /> <span class="plus">+</span> </label> <span class="single_price">${_this.cartData[i]*ele["price"]}</span> <strong class="del">X</strong> </li>` sum += _this.cartData[i] * ele["price"]; } }) } } //循环结束 _this.vess.innerHTML = str; _this.zj.innerHTML = sum; var aDel = document.getElementsByClassName("del"); var aMinus = document.querySelectorAll(".minus"); //减 var aPlus = document.querySelectorAll(".plus"); //加 var aTxt = document.querySelectorAll(".txt"); var aPerTotal = document.querySelectorAll(".single_price"); //单个总价 var aPerprice = document.querySelectorAll(".perprice") var len = aMinus.length; for (let i = 0; i < len; i++) { let m=0; aMinus[i].onclick = function(e) { if (aTxt[i].value <= 1) { aTxt[i].value = 1; } else { aTxt[i].value--; } let id=this.parentNode.parentNode.getAttribute("data-id"); let num=parseInt(aTxt[i].value); aPerTotal[i].innerHTML=num*aPerprice[i].innerText; _this.addData(id,num,false); } //点击减少事件 aPlus[i].onclick = function() { aTxt[i].value++; let id=this.parentNode.parentNode.getAttribute("data-id"); let num=parseInt(aTxt[i].value); aPerTotal[i].innerHTML=num*aPerprice[i].innerText; _this.addData(id,num,false) } //点击增加事件 aTxt[i].onchange = function() { if (this.value <= 1) { this.value = 1; } let id=this.parentNode.parentNode.getAttribute("data-id"); let num=parseInt(this.value); aPerTotal[i].innerHTML=num*aPerprice[i].innerText; _this.addData(id,num,true) } aDel[i].onclick = function() { var id=this.parentNode.getAttribute("data-id"); _this.vess.removeChild(this.parentNode); delete _this.cartData[id]; localStorage.setItem("cart",JSON.stringify(_this.cartData)); } }; } }
import React from "react"; import "./post.css"; import Navbar from '../../components/Navbar' import PostForm from '../../components/PostForm' const postPage = ({ match }) => ( <div> <Navbar page="post"/> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8"> <PostForm type="Job"/> </div> </div> </div> ); export default postPage;
(function ($, App) { "use strict"; $(document).on("turbolinks:load", function () { var userDataToOptions = function (value, i) { return {id: value.id, text: value.to_s} }; var enrollmentDataToOptions = function (value, i) { return {id: value.id, text: value.to_s} }; if ($('.session_ratings.new,.session_ratings.edit').length) { Autocomplete.setup('user', Routes.users_path(), userDataToOptions); Autocomplete.setup('enrollment', Routes.enrollments_path, enrollmentDataToOptions); } }); })(jQuery, Autocomplete);
import express from 'express'; import passport from 'passport'; import { logoutUser, getUsers, deleteUser } from '../controllers/users.js'; import User from '../models/user.model.js'; import { authenticateAPI } from '../middleware/authenticateApi.js'; const router = express.Router(); router.use(authenticateAPI); router.get("/fetch", getUsers); router.delete("/:id", deleteUser); // router.get("/logout", logoutUser); router.get('/logout', function (req, res) { req.session.destroy(function (err) { res.redirect('/'); //Inside a callback… bulletproof! }); }); router.get('/', getUsers); export default router;
import React, { createContext } from 'react'; const MenuContext = createContext(0); const MenuContextProvider = ({ page, children }) => ( <MenuContext.Provider value={{ page }}>{children}</MenuContext.Provider> ); const MenuContextConsumer = MenuContext.Consumer; export { MenuContextConsumer, MenuContextProvider, MenuContext };
import {Router} from 'express'; import * as authController from './auth.controller'; //import validate from 'express-validation'; import {registerValidation, loginValidation, validate} from './auth.validation'; const AuthRouter = Router(); AuthRouter.post('/register', registerValidation(), validate, authController.register) AuthRouter.post('/login', loginValidation(), validate, authController.login) export default AuthRouter;
import { AboutWindow } from './about-window'; import { FileManager } from './file-manager'; import { MainWindow } from './main-window'; export { AboutWindow, FileManager, MainWindow, };
require('babel/polyfill') const environment = { development: { isProduction: false }, production: { isProduction: true } }[process.env.NODE_ENV || 'development'] const titleText = 'hackreact web' const descText = titleText + ' - kickoff' module.exports = Object.assign({ host: process.env.HOST || 'localhost', port: process.env.PORT, apiHost: process.env.APIHOST || 'localhost', apiPort: process.env.APIPORT || 5000, app: { title: titleText, description: descText, meta: { charSet: 'utf-8', property: { 'og:site_name': titleText, 'og:locale': 'de_DE' } } }, sendbird: { app_id: process.env.SENDBIRD_APP_ID } }, environment)
import React, { Component } from 'react' import AdminService from '../services/AdminService'; import Navbar from './Navbar'; class ListAdmin extends Component { constructor(props) { super(props) this.state = { admindetails: [] } this.addAdmin=this.addAdmin.bind(this); this.editAdmin = this.editAdmin.bind(this); this.deleteAdmin = this.deleteAdmin.bind(this); } deleteAdmin(id){ AdminService.deleteAdmin(id).then( res => { this.setState({admindetails: this.state.admindetails.filter(admin => admin.id !== id)}); }); } viewAdmin(id){ this.props.history.push(`/view-admindetails/${id}`); } editAdmin(id){ this.props.history.push(`/add-admindetails/${id}`); } componentDidMount(){ AdminService.getAdmins().then((res) => { this.setState({ admindetails: res.data}); }); } addAdmin(){ this.props.history.push('/add-admindetails/_add'); } render() { return ( <div> <Navbar/> <h2 className="text-center">Admin List</h2> <div className = "row"> <button className="btn btn-primary" onClick={this.addAdmin}>Add Admin</button> </div> <br></br> <div className = "row"> <table className = "table table-striped table-bordered"> <thead> <tr> <th> Admin Id</th> <th> Admin Name</th> <th> Contact Number </th> <th> Email </th> <th> Password </th> <th> Actions</th> </tr> </thead> <tbody> { this.state.admindetails.map( admin => <tr key = {admin.id}> <td> { admin.id} </td> <td> { admin.adminName} </td> <td> { admin.contactNumber} </td> <td> { admin.email} </td> <td> {admin.password}</td> <td> <button onClick={ () => this.editAdmin(admin.id)} className="btn btn-info">Update </button> <button style={{marginLeft: "10px"}} onClick={ () => this.deleteAdmin(admin.id)} className="btn btn-danger">Delete </button> <button style={{marginLeft: "10px"}} onClick={ () => this.viewAdmin(admin.id)} className="btn btn-info">View </button> </td> </tr> ) } </tbody> </table> </div> </div> ) } } export default ListAdmin
const express = require('express'); const router = require('express').Router(); const db = require('../../models/index'); const expressJwt = require('express-jwt'); const { jwtSecret } = require('../../utils/utils'); const { handleUpDelRes } = require('./utils/utils.js'); router.use(express.json()); router.use(express.urlencoded({ extended: true })); router.post('/', expressJwt({ secret: jwtSecret }), async (req, res) => { try { await db.Comment.create({ ...req.body, author: req.user.userId }); res.status(201).json({}); } catch (err) { console.log("FAIL create a comemnt"); res.status(500).send(err); } }); router.delete('/byid/:id', async (req, res) => { try { await handleUpDelRes(db.Comment.findByIdAndDelete(req.params.id), res); res.status(200); } catch (err) { res.status(500).send(err); } }) module.exports = router;
/* fs.existsSync(file) => checks for existence of file fs.readFileSync(file) => returns file contents console.log(__dirname) => current directory path (here, till activity) */ const fs = require("fs"); // get contents from the files and check if any invalid file passed function getFileContent(files) { let content = ""; for (let i = 0; i < files.length; i++) { if (fs.existsSync(files[i]) == false) { console.log("One or more files dont exist"); return; } content += fs.readFileSync(files[i]); if (i != files.length - 1) content += "\r\n"; // would cause little problems further if only \n, since you know now every line is distinguished by \r\n use it } return content; } // -s flag implementation //remove extra space function sFlag(data) { let splittedData = data.split("\r\n"); // console.log(splittedData); let removedSpaces = []; let lastCharSpace = false; for (let i = 0; i < splittedData.length; i++) { if (splittedData[i] == "") { if (lastCharSpace == false) { removedSpaces.push(splittedData[i]); lastCharSpace = true; } } else { removedSpaces.push(splittedData[i]); lastCharSpace = false; } } // console.log(removedSpaces); let result = removedSpaces.join("\r\n"); return result; } // -b flag implementation // adds line number on non empty lines let bFlag = function (data) { let splittedData = data.split("\r\n"); // console.log(splittedData); let count = 1; for (let i = 0; i < splittedData.length; i++) { if (splittedData[i] != "") { splittedData[i] = count + ". " + splittedData[i]; count++; } } let result = splittedData.join("\r\n"); return result; } // -n flag implementation // add line number on all lines let nFlag = function (data) { let splittedData = data.split("\r\n"); // console.log(splittedData); let count = 1; for (let i = 0; i < splittedData.length; i++) { splittedData[i] = count + ". " + splittedData[i]; count++; } let result = splittedData.join("\r\n"); return result; } //if we declare module.exports like this, the key name and value are same, ie it works module.exports = { getFileContent, sFlag, bFlag, nFlag }; // module.exports.bFlag = bFlag; // module.exports.sFlag = sFlag; // module.exports.nFlag = nFlag;
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const PersonalSchema = new Schema({ city: { type: String, default: "" }, state: { type: String, default: "" }, country: { type: String, default: "" }, zip_code: { type: Number, default: "" }, gpa: { type: Number, default: "" }, toefl:{ type: Number, default: "" }, sat: { type: Number, default: "" }, act: { type: Number, default: "" } }); const userSchema = new Schema({ username: String, firstName: String, lastName: String, googleId: String, thumbnail: String, personal_statement: { type: String, default: "" }, savedSchools: [], personal: { city: { type: String, default: "" }, state: { type: String, default: "" }, country: { type: String, default: "" }, zip_code: { type: Number, default: "" }, gpa: { type: Number, default: "" }, toefl:{ type: Number, default: "" }, sat: { type: Number, default: "" }, act: { type: Number, default: "" } }, twitter_handle: [] }); const User = mongoose.model("user", userSchema); module.exports = User;
for (var i = 0; i < 3; i++) { setTimeout ( function() { console.log(i) }, 1000); } // prints 3 three times for (let i = 0; i < 3; i++) { setTimeout ( function() { console.log(i) }, 1000); } // prints 0, 1, 2 // ES6 also gives us a new way to loop over iterables: const iterable = [1, 2, 3]; for (const value of iterable) { console.log(value); } // 1 // 2 // 3 // you can loop like this over querySelector results: const articleParagraphs = document.querySelectorAll('article > p'); for (const paragraph of articleParagraphs) { paragraph.classList.add('read'); } // you can loop over strings: const foo = 'bar'; for (const letter of foo) { console.log(letter); } // b // a // r
/* * * stateWarningComponent.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * @author vn87351 * @since 2.12.0 */ 'use strict'; /** * The controller for the State Warnings Controller. * * @author vn87351 * @updated vn86116 * @since 2.12.0 */ (function () { var app = angular.module('productMaintenanceUiApp'); app.component('stateWarningComponent', { templateUrl: 'src/codeTable/stateWarnings/stateWarnings.html', bindings: {seleted: '<'}, controller: StateWarningsController }); app.filter('trim', function () { return function (value) { if (!angular.isString(value)) { return value; } return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9 }; }); StateWarningsController.$inject = ['$rootScope', 'StateWarningsApi', '$scope', 'ngTableParams', '$filter']; /** * Constructs the controller. */ function StateWarningsController($rootScope, stateWarningsApi, $scope, ngTableParams, $filter) { var self = this; /** * The default page number. * * @type {number} */ self.PAGE = 1; self.stateWarningsAddData = []; /** * The default page size of main table. * * @type {number} */ self.PAGE_SIZE_MAIN = 20; /** * The default page size of modal table. * * @type {number} */ self.PAGE_SIZE_MODAL = 15; /** * Error Message * @type {string} */ self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING = 'There are no changes on this page to be saved. Please make any changes to update.'; /** * The unknown error message. * * @type {string} */ self.UNKNOWN_ERROR = "An unknown error occurred."; /** * The error message when validate warning name text box on the modal. * * @type {string} */ self.REQUIRED_ABBREVIATION_ERROR = "State Warning Name is a mandatory field."; /** * The error message when validate state code text box on the modal. * * @type {string} */ self.REQUIRED_STATE_CODE_ERROR = "State Warning Code is a mandatory field."; /** * The error message when validate description text box on the modal. * * @type {string} */ self.REQUIRED_DESCRIPTION_ERROR = "State Warning Description is a mandatory field."; /** * The title of confirmation dialog to delete State Warnings. * * @type {string} */ self.DELETE_STATE_WARNINGS_CONFIRM_TITLE = "Delete State Warnings"; /** * The title of confirmation dialog. * * @type {string} */ self.UNSAVED_DATA_CONFIRM_TITLE = "Confirmation"; self.isReturnToTab = false; self.selectedRow = null; /** * The message of confirmation dialog to delete State Warnings. * * @type {string} */ self.DELETE_STATE_WARNINGS_CONFIRM_MESSAGE = "Are you sure you want to delete the selected State Warnings ?"; self.RETURN_TAB = 'returnTab'; self.VALIDATE_STATE_WARNING = 'validateStateWarning' /** * The message of confirmation dialog. * * @type {string} */ self.UNSAVED_DATA_CONFIRM_MESSAGE = "Unsaved data will be lost. Do you want to save the changes before continuing ?"; /** * Whether or not the controller is waiting for data. * * @type {boolean} */ self.isWaiting = false; self.stateWarningPre = null; /** * check all flag. * * @type {boolean} */ self.checkAllValue = false; /** * Success message from api. * * @type {string} */ self.success = null; /** * Error message form api. * * @type {string} */ self.error = null; /** * The error of modal. * * @type {string} */ self.errorPopup = null; /** * The list of state warnings. * * @type {Array} */ self.stateWarnings = []; /** * The list of state warnings to add/edit/delete. * * @type {Array} */ self.stateWarningsHandle = []; self.filteredDataOrigin = []; /** * The list of state warnings for reset function. * * @type {Array} */ self.filteredData = []; /** * The title of modal. * * @type {string} */ self.titleModal = "Add State Warnings"; /** * The flag to show Add button on the modal. * * @type {boolean} */ self.showAddButtonModal = false; /** * The flag to show Reset button on the modal. * * @type {boolean} */ self.showResetButtonModal = false; /** * The title of confirmation dialog. * * @type {string} */ self.titleConfirm = null; /** * The message of confirmation dialog. * * @type {string} */ self.messageConfirm = null; /** * The flag to check if it is confirming to delete or not. * * @type {boolean} */ self.isConfirmDelete = false; /** * The flag to check if it is confirming unsaved data or not. * * @type {boolean} */ self.isConfirmUnsaved = false; self.isAddingActionCode = false; self.indexPre = null; self.defer = null; self.params = null; self.errorPopup = null; /** * Initiates the construction of the State Warnings Controller. */ self.init = function () { self.isWaiting = true; if ($rootScope.isEditedOnPreviousTab) { self.error = $rootScope.error; self.success = $rootScope.success; } $rootScope.isEditedOnPreviousTab = false; self.findAllStateWarning(); }; /** * get state warnings. */ self.findAllStateWarning = function () { stateWarningsApi.getAllStateWarnings().$promise.then(function (results) { self.callApiResponseSuccess(results); }); }; /** * filter data warnings. */ self.filterDatas = function () { $scope.filter = { abbreviation: undefined, key: {stateCode: undefined}, description: undefined }; $scope.tableParams = new ngTableParams({ page: self.PAGE, count: self.PAGE_SIZE_MAIN, filter: $scope.filter }, { counts: [], debugMode: true, data: self.stateWarningsHandle }); }; self.addMoreRowStateWarnings = function () { if (self.isValidDataModal(self.stateWarningsAddData)) var stateWarning = self.initEmptyStateWarnings(); self.stateWarningsAddData.push(stateWarning); self.tableModalParams.reload(); } /** * Handle when click Add button to display the modal. */ self.addNewStateWarnings = function () { var stateWarning = self.initEmptyStateWarnings(); self.clearMessages(); self.stateWarningsAddData.push(stateWarning); self.tableModalParams = new ngTableParams({ page: self.PAGE, count: self.PAGE_SIZE_MAIN, filter: $scope.filter }, { counts: [], debugMode: true, data: self.stateWarningsAddData }); $('#stateWarningsModal').modal({backdrop: 'static', keyboard: true}); }; self.clearFilter = function () { $scope.filter.key.stateCode = undefined; $scope.filter.abbreviation = undefined; $scope.filter.description = undefined; } self.editStateWarning = function (stateWarning) { self.clearMessages(); self.selectedRow = true; self.isEditing = true; if (self.stateWarningPre !== null) { self.stateWarningPre.isEditing = false; stateWarning.isEditing = true; self.stateWarningPre = stateWarning; self.stateWarningPreOrigin = angular.copy(stateWarning); } else { if (self.stateWarningPre === null) { stateWarning.isEditing = true; self.stateWarningPre = stateWarning; self.stateWarningPreOrigin = angular.copy(stateWarning); } } }; self.updateStateWarnings = function (stateWarning) { self.clearMessages(); self.closeConfirmPopup(); var updateData = [{ "key": { "stateCode": null, "warningCode": null }, "abbreviation": null, "description": null }]; if (self.isDataChanged(stateWarning)) { if (self.isValidDataModal(self.stateWarningsHandle)) { self.isWaiting = true; updateData[0]["key"]["stateCode"] = stateWarning["key"]["stateCode"]; updateData[0]["key"]["warningCode"] = stateWarning["key"]["warningCode"]; updateData[0].abbreviation = stateWarning.abbreviation; updateData[0].description = stateWarning.description; stateWarningsApi.updateStateWarnings(updateData, function (results) { self.callApiResponseSuccess(results.data); self.success = results.message; if (self.isReturnToTab) { $rootScope.success = self.success; $rootScope.isEditedOnPreviousTab = true; } self.returnToTab(true); self.isAddingActionCode = false; self.isEditing = false; self.selectedRow = null; self.stateWarningPreOrigin = null; }, self.fetchError ); } } else { self.error = ""; self.error = self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING; } }; /** * Check data change * * @param stateWarning * @returns {boolean} */ self.isDataChanged = function (stateWarning) { var lstChange = []; if ($.trim(stateWarning['abbreviation']) !== $.trim(self.stateWarningPreOrigin['abbreviation']) || $.trim(stateWarning['key']) !== $.trim(self.stateWarningPreOrigin['key']) || $.trim(stateWarning['key']['stateCode']) !== $.trim(self.stateWarningPreOrigin['key']['stateCode']) || $.trim(stateWarning['description']) !== $.trim(self.stateWarningPreOrigin['description'])) { return true; } return false; } /** * Call ws to add a state warning. */ self.doAddStateWarnings = function () { if (self.isValidDataModal(self.stateWarningsAddData)) { $('#confirmModal').modal("hide"); $('#stateWarningsModal').modal("hide"); self.isWaiting = true; stateWarningsApi.updateStateWarnings(self.stateWarningsAddData, function (results) { self.callApiResponseSuccess(results.data); self.success = results.message; self.isAddingActionCode = false; self.isEditing = false; self.stateWarningPreOrigin = null; self.stateWarningsAddData = []; }, self.fetchError ); } }; /** * Handle when click Delete button to display the modal. */ self.deleteStateWarnings = function (stateWarning) { self.isDelete = true; self.stateWarningPreOrigin = angular.copy(stateWarning); self.clearMessages(); $('#confirmModal').modal({backdrop: 'static', keyboard: true}); self.showConfirmDelete = true; self.messageConfirm = self.DELETE_STATE_WARNINGS_CONFIRM_MESSAGE; self.titleConfirm = self.DELETE_STATE_WARNINGS_CONFIRM_TITLE; }; /** * Handle call ws when confirm Delete action. */ self.doDeleteStateWarnings = function () { var deleteData = []; self.clearMessages(); deleteData.push(self.stateWarningPreOrigin); self.isWaiting = true; stateWarningsApi.deleteStateWarnings(deleteData, function (results) { self.callApiResponseSuccess(results.data); self.success = results.message; self.isDelete = false; self.stateWarningPreOrigin = null; }, self.fetchError ); self.closeConfirmPopup(); }; /** * Reset data edited. * * @param stateWarning */ self.cancel = function (stateWarning) { self.clearMessages(); self.selectedRow = null; stateWarning.isEditing = false; self.isEditing = false; stateWarning["key"]["stateCode"] = self.stateWarningPreOrigin["key"]["stateCode"]; stateWarning["key"]["warningCode"] = self.stateWarningPreOrigin["key"]["warningCode"]; stateWarning.abbreviation = self.stateWarningPreOrigin.abbreviation; stateWarning.description = self.stateWarningPreOrigin.description; $scope.tableParams.reload(); self.stateWarningPreOrigin = null; } /** * Close add popup and confirm popup. */ self.doCloseModal = function () { $('#confirmModal').modal("hide"); $('#stateWarningsModal').modal("hide"); self.clearMessages(); self.isReturnToTab = false; }; /** * Close confirm popup */ self.closeConfirmPopup = function () { $('#confirmModal').modal("hide"); $('.modal-backdrop').attr('style', ' '); } /** * Handle when call api controller and response results successfully. * * @param data */ self.callApiResponseSuccess = function (data) { self.stateWarnings = angular.copy(data); self.stateWarningsHandle = angular.copy(data); angular.forEach(self.stateWarningsHandle, function (value) { value.isEditing = false; }); self.filterDatas(); self.checkAllValue = false; self.isWaiting = false; }; /** * Check mandatory fields on the modal. * * @returns {boolean} */ self.isValidDataModal = function (stateWarningsList) { var errorMessages = []; var errorMessage = ''; for (var i = 0; i < stateWarningsList.length; i++) { if (self.isNullOrEmpty(stateWarningsList[i].abbreviation)) { errorMessage = "<li>" + self.REQUIRED_ABBREVIATION_ERROR + "</li>"; if (errorMessages.indexOf(errorMessage) == -1) { errorMessages.push(errorMessage); } stateWarningsList[i].addClass = 'active-tooltip ng-invalid ng-touched'; } if (self.isNullOrEmpty(stateWarningsList[i].key) || stateWarningsList[i]["key"]["stateCode"] === null) { errorMessage = "<li>" + self.REQUIRED_STATE_CODE_ERROR + "</li>"; if (errorMessages.indexOf(errorMessage) == -1) { errorMessages.push(errorMessage); } stateWarningsList[i].addClass = 'active-tooltip ng-invalid ng-touched'; } if (self.isNullOrEmpty(stateWarningsList[i].description)) { errorMessage = "<li>" + self.REQUIRED_DESCRIPTION_ERROR + "</li>"; if (errorMessages.indexOf(errorMessage) == -1) { errorMessages.push(errorMessage); } stateWarningsList[i].addClass = 'active-tooltip ng-invalid ng-touched'; } if (errorMessages.length == 3) { break; } } if (errorMessages.length > 0) { var errorMessagesAsString = 'State Warning:'; angular.forEach(errorMessages, function (errorMessage) { errorMessagesAsString += errorMessage; }); self.errorPopup = errorMessagesAsString; return false; } return true; }; /** * Check object null or empty * * @param object * @returns {boolean} true if Object is null/ false or equals blank, otherwise return false. */ self.isNullOrEmpty = function (object) { return object === null || !object || object === ""; }; /** * Clear all the messages when click buttons. */ self.clearMessages = function () { self.error = ''; self.success = ''; self.errorPopup = ''; self.stateWarningsAddData = []; }; /** * Initiate empty state warnings to display in the modal. * * @returns {{}} */ self.initEmptyStateWarnings = function () { var stateWarning = { "abbreviation": "", "description": "", "key": { "stateCode": null } }; return stateWarning; }; /** * If there is an error this will display the error. * * @param error */ self.fetchError = function (error) { self.isWaiting = false; self.data = null; if (error && error.data) { if (error.data.message !== null && error.data.message !== "") { self.error = error.data.message; } else { self.error = error.data.error; } } else { self.error = self.UNKNOWN_ERROR; } if (self.isReturnToTab) $rootScope.error = self.error; }; /** * Handle when click close in add popup but have data changed to show popup confirm. */ self.closeModalUnsavedData = function () { if (self.stateWarningsAddData[0].abbreviation.length !== 0 || self.stateWarningsAddData[0].description.length === 0 && self.stateWarningsAddData[0].key.stateCode !== null) { self.titleConfirm = self.UNSAVED_DATA_CONFIRM_TITLE; self.messageConfirm = self.UNSAVED_DATA_CONFIRM_MESSAGE; $('#confirmModal').modal({backdrop: 'static', keyboard: true}); $('.modal-backdrop').attr('style', ' z-index: 100000; '); } else { self.isValidDataModal(self.stateWarningsAddData); $('#stateWarningsModal').modal("hide"); self.stateWarningsAddData = []; } } /** * Handle when switch to other tab. */ $scope.$on(self.VALIDATE_STATE_WARNING, function () { if (self.selectedRow !== null) { if (self.stateWarningPre !== null) { if (self.isDataChanged(self.stateWarningPre)) { self.isReturnToTab = true; // show popup self.titleConfirm = 'Confirmation'; self.error = ''; self.success = ''; self.messageConfirm = self.UNSAVED_DATA_CONFIRM_MESSAGE; $('#confirmModal').modal({backdrop: 'static', keyboard: true}); } else $rootScope.$broadcast(self.RETURN_TAB); } } else { $rootScope.$broadcast(self.RETURN_TAB); } }); /** * This method is used to return to the selected tab. */ self.returnToTab = function (clickYes) { self.closeConfirmPopup(); if (self.isReturnToTab && clickYes) { $rootScope.$broadcast(self. RETURN_TAB); } else { $('#confirmModal').on('hidden.bs.modal', function () { $rootScope.$broadcast(self.RETURN_TAB); $scope.$apply(); }); } }; /** * Handle when click yes in confirm popup when switch tab and had data changed to save and switch tab. */ self.updateStateWarningsTabchange = function () { self.updateStateWarnings(self.stateWarningPre); } } })();
import React, {Component} from "react" import PropTypes from "prop-types" import ReactDOM from "react-dom" import Moment from "moment" import EventFunc from "components/global/eventFunc" import BaseDatePicker from "./baseDatePicker" import _ from "lodash" const DateTypeFormat = { YEAR: "YYYY", MONTH: "YYYY-MM", DAY: "YYYY-MM-DD", HOUR: "YYYY-MM-DD HH:mm", MIN: "YYYY-MM-DD HH:mm", SEC: "YYYY-MM-DD HH:mm:ss" } const dateFormatter = (date, type = "DAY") => { if (date === "") return ""; if (!(date instanceof Moment)) date = Moment() let curType = DateTypeFormat[type.toUpperCase()] return type.toUpperCase() === "HOUR" ? date.startOf("hour").format(curType) : date.format(curType) } export default class DatePicker extends Component { constructor (props) { super(props) this.isShow = false this.state = { value: "" } } componentDidMount () { this.picker = document.createElement("div") EventFunc.addEvent(this.picker, "click", this.handleNodeClick) EventFunc.addEvent(document, "click", this.handleDocumentClick) EventFunc.addEvent(window, "scroll", this.closePicker) EventFunc.addEvent(window, "resize", this.closePicker) this.valueConverter(this.props) } componentWillUnmount () { EventFunc.removeEvent(this.picker, "click", this.handleNodeClick) EventFunc.removeEvent(document, "click", this.handleDocumentClick) EventFunc.removeEvent(window, "scroll", this.closePicker) EventFunc.removeEvent(window, "resize", this.closePicker) this.closePicker(); } handleNodeClick = (event) => { this.nodeClicked = true } handleDocumentClick = (event) => { if (this.nodeClicked) { this.nodeClicked = false return } if (this.isShow && !this.nodeClicked && !ReactDOM.findDOMNode(this).contains(event.target)) { this.nodeClicked = false this.closePicker() } } closePicker = () => { this.isShow && this.toggle() } toggle = () => { this.isShow = !this.isShow if (this.isShow) { document.body.appendChild(this.picker) const picker = this.renderPicker() ReactDOM.render(picker, this.picker) } else { ReactDOM.unmountComponentAtNode(this.picker) document.body.removeChild(this.picker) } } // 允许传入日期为字符串/数字/Date对象/Moment对象 // 方法统一转换传入值至Moment对象,并根据props.type转换成不同格式的字符串 valueConverter = (props) => { let date = props.value if (!date) return if (!(date instanceof Moment)) { if (typeof date === "string" && !isNaN(+date)) date = +date date = Moment(date) if (!date.isValid()) date = Moment() } if (date instanceof Moment && !date.isValid()) date = Moment() this.setState({ value: dateFormatter(date, props.type) }) } onInnerChange = (d) => { let date = _.cloneDeep(d) if (date[1]) date.splice(1, 1, date[1] - 1) if (!date[2]) date.splice(2, 1, 1) let selectedDate = Moment(date) this.setState({value: dateFormatter(selectedDate, this.props.type)}, () => { this.props.onChange && this.props.onChange(this.state.value) }) } onConfirm = () => { // this.props.onChange && this.props.onChange(this.state.value) this.closePicker() } onClear = () => { this.setState({value: ""}, () => { this.props.onChange && this.props.onChange(this.state.value) }) }; componentWillReceiveProps (nextProps) { if (nextProps.value === "") return; let type = this.props.type.toUpperCase(); let value = Moment(nextProps.value); if (value !== this.state.value) { this.setState({ value: dateFormatter(value, type) }) } } renderPicker = () => { const target = ReactDOM.findDOMNode(this) const rect = target.getBoundingClientRect() this.picker.style = `position: fixed; top:${rect.bottom + 5}px; left:${rect.left}px` return <BaseDatePicker onChange={this.onInnerChange} onConfirm={this.onConfirm} value={this.state.value ? this.state.value.split(/\s|-|:/).map(d => parseInt(d)) : undefined} disableDate={this.props.disableDate} type={this.props.type.toUpperCase()} /> } render () { const {showClose, showIcon, className} = this.props return ( <div className={`my-calendar-entry ${showClose ? "has-close" : ""} ${className ? className : ""}`}> <input type="text" onClick={this.toggle} value={this.state.value} readOnly placeholder={this.props.placeholder} className={showIcon ? "date-icon" : ""} /> {showClose && <span className="date-clear" onClick={this.onClear} />} </div> ) } } DatePicker.propTypes = { value: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.instanceOf(Date), PropTypes.instanceOf(Moment)]), // 传入日期 onChange: PropTypes.func, // 修改日期 type: PropTypes.oneOf(["YEAR", "MONTH", "DAY", "HOUR", "MIN", "SEC"]), // 允许展示的时间类型 disableDate: PropTypes.func, // 禁止日期 showClose: PropTypes.bool, // 显示清除日期按钮 showIcon: PropTypes.bool, // 显示日期图标 placeholder: PropTypes.string, className: PropTypes.string, } DatePicker.defaultProps = { type: "DAY", // 默认时间类型为只显示"YYYY-MM-DD" placeholder: "" }
// locale module.exports = { };
import React from "react"; import useMediaQuery from "@mui/material/useMediaQuery"; import Button from "@mui/material/Button"; import { RESUME } from "~services/links"; import { mediumSmall } from "~services/mediaQuery"; import styles from "./index.module.scss"; const Footer = () => { const isMobile = useMediaQuery(mediumSmall); return ( <> <Button variant="outlined" size={isMobile ? "normal" : "large"} className={styles.footerResumeBtn} onClick={() => window.open(RESUME, "_blank")} > View Resume </Button> <h6 className={styles.footerText}>&copy; 2022 Michael Podolsky</h6> </> ); }; export default Footer;
var searchData= [ ['query_5fbean',['Query_Bean',['../classbean_1_1Query__Bean.html',1,'bean']]] ];
import bookshelf from '../bookshelf'; export default bookshelf.Model.extend({ tableName: 'parents', idAttribute: 'ParentID' });
const { response } = require('express'); const ObjectId = require('mongoose').Types.ObjectId; const Empresa = require('../models/empresa'); const validarEmpresa = async (req, res = response, next) => { const empresa_id = req.header('x-empresa'); try { if (!empresa_id) { return res.status(400).json({ ok: false, msg: 'La empresa es requerida' }); } if (!ObjectId.isValid(empresa_id)) { return res.status(400).json({ ok: false, msg: 'La empresa no es válida' }); } const empresa = await Empresa.findById(empresa_id); if (!empresa) { return res.status(400).json({ ok: false, msg: empresa.msg }); } req.empresa = empresa; } catch (error) { console.log('Error al validar empresa ', error); return res.status(400).json({ ok: false, msg: 'Favor contacte al administrador ' + error }); } next(); } module.exports = { validarEmpresa }
import React from 'react'; import { render } from 'react-dom'; import CustomRouter from './router.js'; import {createStore, applyMiddleware} from 'redux'; import Reducer from './Reducers'; import thunk from 'redux-thunk'; import {Provider} from 'react-redux'; let store = createStore(Reducer, applyMiddleware(thunk)); render( <Provider store={store}> <CustomRouter store={store} /> </Provider>, document.querySelector("#app") );
$(document).ready(function() { newQuote("#quote2", "#author2"); var e = document.getElementById("one-more"); e.addEventListener("click", onClick, false); var out_cont1 = document.getElementById("out-cont1"); var cont1 = document.getElementById("cont1"); var out_cont2 = document.getElementById("out-cont2"); var cont2 = document.getElementById("cont2"); var disk1 = "mid"; var disk2 = "right"; var clickDisabled = false; var hue = Math.floor(Math.random() * 60 + 1); function bodyHue(color) { return color-30; } $(".wrapper").css("filter", "hue-rotate("+bodyHue(hue)+"deg)"); function onClick() { if(clickDisabled) return; //hue = Math.floor(Math.random() * 60 + 1); hue = hue + 60; $(".wrapper").css("filter", "hue-rotate("+bodyHue(hue)+"deg)"); if ((disk1 === "mid")&&(disk2 === "right")) { $("#out-cont2").css("filter", "hue-rotate("+hue+"deg)"); $(".title").css("filter", "hue-rotate("+hue+"deg)"); $("#one-more").css("filter", "hue-rotate("+hue+"deg)"); out_cont1.style.transform += "translateX(-65vw)"; cont1.style.transform = "rotate(-360deg)"; out_cont2.style.transform += "translateX(-65vw)"; cont2.style.transform = "rotate(-360deg)"; disk1 = "left"; disk2 = "mid"; } else if ((disk1 === "right")&&(disk2 === "mid")) { $("#out-cont1").css("filter", "hue-rotate("+hue+"deg)"); $(".title").css("filter", "hue-rotate("+hue+"deg)"); $("#one-more").css("filter", "hue-rotate("+hue+"deg)"); out_cont1.style.transform += "translateX(-65vw)"; cont1.style.transform = "rotate(0deg)"; out_cont2.style.transform += "translateX(-65vw)"; cont2.style.transform = "rotate(-720deg)"; disk1 = "mid"; disk2 = "left"; } clickDisabled = true; setTimeout(function(){clickDisabled = false;}, 1500); } var loc = -95; var loc2 = -160; out_cont1.addEventListener("transitionend", function(event) { if(disk1 === "left") { newQuote("#quote1", "#author1"); out_cont1.style.right = loc + "vw"; loc = loc - 130; $(".container").css("transition", "transform 0s"); cont1.style.transform = "rotate(360deg)"; $(".container").css("transition", "transform 1s"); disk1 = "right"; } else if (disk2 === "left") { newQuote("#quote2", "#author2"); out_cont2.style.right = loc2 + "vw"; loc2 = loc2 - 130; cont2.style.transform = "rotate(0)"; disk2 = "right"; } }); function newQuote(quote, author) { $.ajax({ url: "https://andruxnet-random-famous-quotes.p.mashape.com/cat=famous", type: "POST", data: {}, dataType: "json", success: function(data) { $(quote).text("\"" + data.quote + "\""); $(author).text("- " + data.author); }, error: function(err) { //alert(err); }, beforeSend: function(xhr) { xhr.setRequestHeader("X-Mashape-Authorization", "46tAVHfUQJmshiOEq6KtTFGdpra7p1ZHVsajsnjmXvmEha9Nbz"); } }); } });
import React from 'react'; class Button extends React.Component { static defaultProps = { text: 'New Button', onClick: () => { return; }, className: '' }; constructor(props) { super(props); this.state = { isActive: false }; } handleOnClick = () => { this.setState(state => { return { isActive: !state.isActive }; }); this.props.onClick(); }; render() { const { text, className } = this.props; return ( <button onClick={this.handleOnClick} className={`rb-btn ${className} ${this.state.isActive ? 'active' : ''}`} > {text} </button> ); } } export default Button;
({ // get case related details getCaseData: function (component, event, helper) { let caseId; let caseRecId = helper.getParameterByName("caseId"); if (caseRecId) { caseId = caseRecId; } else { caseId = component.get("v.recordId"); } if (caseId) { helper.callServer( component, "c.getCase", function (theCase) { if (theCase) { let caseRec = theCase.caseInfo; component.set("v.caseWrapper", theCase); component.set("v.case", caseRec); //component.set("v.caseCreatedDate", theCase.caseCreatedDate); //if case retrieval is successful, then fetch case attachments helper.getCaseAttachments(component, event, helper); //CSS-3393.start polling for newly created case to get next update time helper.pollNextUpdateTime(component, event, helper); //if case retrieval is successful, then fetch case share records helper.getCaseShareRecords(component, event, helper); // Update xcRecordShare if User viewed shared case if (theCase.isCaseViewed == false && theCase.xcSharedRecId) { this.updateCaseRecordShare(component, event, helper, theCase.xcSharedRecId, theCase.caseInfo.Id) } //set value for toggleCaseNotificationOption on initialisation. if(theCase.xcSharedRecId){ let CaseNotificationOption = theCase.receiveCaseNotifications ? "Mute notifications for this case" : "Turn on notifications for this case"; component.set("v.toggleCaseNotificationOption",CaseNotificationOption); } } }, { caseId: caseId } ); } }, //get case attachments getCaseAttachments: function (component, event, helper) { let caseId; let caseRecId = helper.getParameterByName("caseId"); if (caseRecId) { caseId = caseRecId; } else { caseId = component.get("v.recordId"); } if (caseId) { helper.callServer( component, "c.getCaseAttachments", function (caseAttachments) { if (caseAttachments) { let allCaseAttachmnets = []; for (var i = 0; i < caseAttachments.length; i++) { let fileExtension = caseAttachments[i].FileExtension; // get doctype icon from file type of attachment let icon = this.getIconFromExtensionType(fileExtension); allCaseAttachmnets.push({ "Id": caseAttachments[i].Id, "Title": caseAttachments[i].Title, "FileExtension": caseAttachments[i].FileExtension, "Icon": icon }); } component.set("v.caseAttachments", allCaseAttachmnets); } }, { caseId: caseId } ); } }, //get icon for an attachment getIconFromExtensionType: function (fileExtension) { let icon = 'doctype:unknown'; // image icon if (('jpe,jpeg,jpg,bmp,png,gif,tif,tiff').includes(fileExtension.toLowerCase())) { icon = 'doctype:image'; } // rtf icon else if (('rtf').includes(fileExtension.toLowerCase())) { icon = 'doctype:rtf'; } // csv icon else if (('csv').includes(fileExtension.toLowerCase())) { icon = 'doctype:csv'; } // doc icon else if (('doc,docx').includes(fileExtension.toLowerCase())) { icon = 'doctype:word'; } // pdf icon else if (('pdf').includes(fileExtension.toLowerCase())) { icon = 'doctype:pdf'; } // text icon else if (('txt').includes(fileExtension.toLowerCase())) { icon = 'doctype:txt'; } // excel icon else if (('xls,xlsx').includes(fileExtension.toLowerCase())) { icon = 'doctype:excel'; } //zip icon else if (('zip,7z').includes(fileExtension.toLowerCase())) { icon = 'doctype:zip'; } //mp4 else if (('mp4').includes(fileExtension.toLowerCase())) { icon = 'doctype:mp4'; } //xml else if (('xml').includes(fileExtension.toLowerCase())) { icon = 'doctype:xml'; } // all other types else if (('aba,qif,ofx,qfx,gpg').includes(fileExtension.toLowerCase())) { icon = 'doctype:attachment'; } //return doctype icon return icon; }, //CSS-3393.Function decides to start polling for next update time or not. pollNextUpdateTime: function (component, event, helper) { let theCase = component.get("v.case"); let numberOfRepeats = 0; // if this is new case with no next update time calculated yet... if (theCase.Next_update_time__c == null && theCase.Status != 'Closed' && theCase.Initial_Response__c == null) { //execute after 5 sec each till next case is not assigned var pollId = window.setInterval( $A.getCallback(function () { helper.getNextUpdateTime(component, event, helper, pollId); numberOfRepeats++; if (numberOfRepeats > 24) { //something went wrong, so we didnt get next update time even after 2 mins component.set("v.case.Next_update__c", " "); window.clearInterval(pollId); } }), 5000 ); } // next update time is already available. else { if (theCase.Next_update__c) { if (theCase.Next_update__c.toLowerCase() == "due") { component.set("v.case.Next_update__c", "Response due"); } else { component.set("v.case.Next_update__c", "Expected response time " + theCase.Next_update__c); } } } }, // function to poll next update time getNextUpdateTime: function (component, event, helper, pollId) { let caseId; let caseRecId = helper.getParameterByName("caseId"); if (caseRecId) { caseId = caseRecId; } else { caseId = component.get("v.recordId"); } if (caseId) { helper.callServer( component, "c.getNextUpdatetimeFromCase", function (result) { //will run polling till we get valid result OR for 24 repeatations(i.e. each 5 sec. for 2 mins.) whichever happens first. if (result) { if (result.toLowerCase() === "due") { component.set("v.case.Next_update__c", 'Expected response ' + result); } else { component.set("v.case.Next_update__c", 'Expected response time ' + result); } window.clearInterval(pollId); } }, { caseId: caseId } ); } }, //function to get case share records associated to case. getCaseShareRecords: function (component, event, helper) { let caseId; let caseRecId = helper.getParameterByName("caseId"); if (caseRecId) { caseId = caseRecId; } else { caseId = component.get("v.recordId"); } if (caseId) { helper.callServer( component, "c.fetchCaseShareRecords", function (caseShareRecords) { if (caseShareRecords) { component.set("v.caseShareRecords", caseShareRecords); //invoke method on child component "xc_ManageCaseSharing". let xc_manageCaseSharing = component.find("xc_manageCaseSharing"); if (xc_manageCaseSharing) { xc_manageCaseSharing.resetCaseShareInfo(); } } }, { caseId: caseId } ); } }, //function to update XCRecordShare updateCaseRecordShare: function (component, event, helper, xcRecShareId, caseId) { if (caseId && xcRecShareId) { helper.callServer( component, "c.updateXCRecordShare", function (isSuccess) { }, { xcRecordShareId: xcRecShareId, caseId: caseId } ); } }, //CSS-4557.to toggle case notification option. toggleReceiveCaseNotification : function(component, event, helper){ // get current value of selected option. let selectedMenuItemValue = event.getParam("value"); let xcShareRecId = component.get("v.caseWrapper.xcSharedRecId"); let caseId = component.get("v.caseWrapper.caseInfo.Id"); if(selectedMenuItemValue && xcShareRecId && caseId){ selectedMenuItemValue = selectedMenuItemValue.toLowerCase(); let changedCaseNotificationValue = selectedMenuItemValue.includes("mute") ? false : true; helper.callServer( component, "c.toggleReceiveCaseNotification", function (isSuccess) { if(isSuccess){ //toggle value of select option on success update. let CaseNotificationOption = changedCaseNotificationValue ? "Mute notifications for this case" : "Turn on notifications for this case"; component.set("v.toggleCaseNotificationOption",CaseNotificationOption); } }, { xcRecordShareId: xcShareRecId, caseId: caseId, receiveCaseNotification: changedCaseNotificationValue } ); } }, setExceptionMessage : function(component, event, helper){ let exceptionType = helper.getParameterByName("excp"); if(exceptionType == "caseSharing"){ component.set("v.exceptionHeader","Case sharing was unsuccessful"); component.set("v.exceptionMessage","Share again with Xero users in this organisation"); } } })