text
stringlengths
7
3.69M
// REQUIRED MODULES const path = require("path"); require("dotenv").config({ path: "./.env", }); const web3 = require("web3"); const Tx = require("ethereumjs-tx").Transaction; const cron = require("node-cron"); // ABIs const testContract = require("./abis/test-contract"); // Infura HttpProvider Endpoint web3js = new web3( new web3.providers.HttpProvider( "https://ropsten.infura.io/v3/dedac6824bfa4dd5833903d6efa48af8" ) ); let counter = 1; const runTransaction = () => { var myAddress = process.env.MY_PUBLIC_ADDRESS; var privateKey = Buffer.from(process.env.MY_PRIVATE_KEY, "hex"); //contract abi is the array that you can get from the ethereum wallet or etherscan var contractABI = testContract.abi; var contractAddress = "0xB7B1200C5a343CaF399CF59a064223F2b9AfEE7f"; //creating contract object var contract = new web3js.eth.Contract(contractABI, contractAddress); var count; // get transaction count, later will used as nonce web3js.eth.getTransactionCount(myAddress).then(function (v) { console.log("Count: " + v); count = v; //creating raw tranaction var rawTransaction = { from: myAddress, gasPrice: web3js.utils.toHex(20 * 1e9), gasLimit: web3js.utils.toHex(210000), to: contractAddress, value: "0x0", data: contract.methods.setName("FROM NODE - " + counter).encodeABI(), nonce: web3js.utils.toHex(count), }; console.log(rawTransaction); //creating tranaction via ethereumjs-tx var transaction = new Tx(rawTransaction, { chain: "ropsten", hardfork: "petersburg", }); //signing transaction with private key transaction.sign(privateKey); // sending transacton via web3js module web3js.eth .sendSignedTransaction("0x" + transaction.serialize().toString("hex")) .on("transactionHash", (res) => { console.log(res); counter++; }); }); }; cron.schedule("*/15 * * * *", function () { console.log("Transaction Started - " + counter); runTransaction(); });
Polymer.PaperInkyFocusBehaviorImpl = { observers: ["_focusedChanged(receivedFocusFromKeyboard)"], _focusedChanged: function(e) { e && this.ensureRipple(), this.hasRipple() && (this._ripple.holdDown = e) }, _createRipple: function() { var e = Polymer.PaperRippleBehavior._createRipple(); return e.id = "ink", e.setAttribute("center", ""), e.classList.add("circle"), e } }, Polymer.PaperInkyFocusBehavior = [Polymer.IronButtonState, Polymer.IronControlState, Polymer.PaperRippleBehavior, Polymer.PaperInkyFocusBehaviorImpl];
const express = require('express') const app = express() const expresslayout = require('express-ejs-layouts') const mongoose = require('mongoose') const env = require('dotenv').config const indexRouter = require('./routes/home') const oncologicoRouter = require('./routes/oncologico') const path = require('path') app.set('view engine', 'ejs') app.set('views',__dirname + '/views') app.set('layout', 'layout/layout') app.use(expresslayout) app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter) app.use('/oncologico', oncologicoRouter) app.listen(process.env.PORT || 3000)
import React from 'react'; const SimpleButton = (props) => { const { clickEvent, btnLabel } = props; return ( <> <button onClick={clickEvent} className=" mdl-cell mdl-cell--12-col mdl-color--teal-300 mdl-button mdl-button--raised mdl-button--colored mdl-js-button mdl-js-ripple-effect mdl-color-text--white "> {btnLabel} </button> </> ); }; export default SimpleButton;
const Generator = require('yeoman-generator'); const { kebabCase } = require('lodash'); const whoami = require('whoami'); const shell = require('shelljs'); module.exports = class extends Generator { constructor(args, opts) { // Calling the super constructor is important so our generator is correctly set up super(args, opts); this.Licenses = ['MIT', 'ISC', 'Apache-2.0']; this.writingMonoRepo = (answers) => { const LernaFileTree = [ { origin: 'package.json', destination: 'package.json', variables: { author: answers.author, name: kebabCase(answers.name), license: answers.license, }, }, { origin: 'README.md', destination: 'README.md', variables: { name: answers.name } }, { origin: '.gitignore', destination: '.gitignore', variables: {} }, { origin: 'lerna.json', destination: 'lerna.json', variables: { packages: answers.packages }}, { origin: '.editorconfig', destination: '.editorconfig', variables: {} }, { origin: '.eslintrc', destination: '.eslintrc', variables: {} }, { origin: 'commitlint.config.js', destination: 'commitlint.config.js', variables: {} }, ]; return LernaFileTree; }; } prompting() { return this.prompt([{ type: 'input', name: 'name', message: 'The name of your monorepo', default: this.appname, // Default to current folder name }, { type: 'input', name: 'packages', message: 'Name of the package folder', default: 'packages', }, { type: 'input', name: 'author', message: 'Who is the author of this awesome bot?', default: whoami, }, { type: 'list', name: 'license', message: 'Which license do you want to use?', choices: this.Licenses, }, ]) .then((answers) => { this.answers = answers; }); } writing() { return this.writingMonoRepo(this.answers).map((file) => { return this.fs.copyTpl( this.templatePath(file.origin), this.destinationPath(file.destination), file.variables, ); }); } install() { this.installDependencies({ npm: true, bower: false, yarn: false }); shell.exec('npx lerna init'); } };
../../next.config.js
import React from 'react' export default class Empty extends React.Component { componentDidMount(){ if (this.props.history.action.toLowerCase()==='pop'){ this.props.history.goBack(); } } render() { return ( <div></div> ); } }
function add(a,b){ var sum = a + b; return sum; } var num1 = parseInt(prompt()); var num2 = parseInt(prompt()); var result = add(num1,num2); document.write(result);
arr = [15, 2, 30, 4, 50]; y = 10 function countGreaterY(arr, y) { let count = 0; for(let i = 0; i < arr.length; i++) { if(arr[i] > y) { count++ console.log(arr[i]) } } console.log("total greater than y is " + count) } countGreaterY(arr, y);
import React, { createRef, Component } from "react"; export default class FocusCompont extends Component { refInput = createRef(); async componentDidMount() { this.refInput.current.style.color = "red"; await this.refInput; } render() { return (<div ref={this.refInput}>Hello</div>) } }
import React from 'react' import './background.css' class BackgroundImage extends React.Component{ state={ x:0, y:0, } componentWillMount(){ var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight|| e.clientHeight|| g.clientHeight; this.setState({x:x,y:y}); } render(){ return (<div><img className='bg' src={'./images/main.png'} /></div>) } } export default BackgroundImage;
var user = require("../../api/users/user.model"); var designation = require("../../api/designation/designation.model"); async function func() { const number = await user.countDocuments(); if (number < 1) { const des = await designation.findOne({ name: "Admin" }); const hrDes = await designation.findOne({ name: "Human Resource" }); if (des) { const des_id = await des._id; const obj = { name: "CEO", email: "admin@gmail.com", designation_id: des_id, gender: "Male" }; const e = new user(obj); e.save(); const hrDes_id = await hrDes._id; const hrObj = { name: "HR", email: "mernhr@gmail.com", designation_id: hrDes_id, gender: "Male" }; const elem = new user(hrObj); elem.save(); } else { func(); } } } func(); module.exports = func;
import main from '../index'; test('parse default ', async () => { expect(await main()).toBe('6\n7\n13\n7'); });
const TYPE = { SET_CONFIG: 'SET_CONFIG', CHANGE_LANGUAGE: 'CHANGE_LANGUAGE' }; export default TYPE;
const utils1 = require("../../modules/IMPmodules/util") const util = new utils1() function collisions2(entities, i, j) { entity_1 = entities[i] entity_2 = entities[j] if (entity_1 && entity_2) { if (entity_1.type != 2 && entity_1.isloaded && entity_1.class != "Biome") { if (entity_2.type == 40) { if (!entity_1.isbiome) { if (entity_1.isloaded) { if (entity_1.y + entity_1.radius > entity_2.y - entity_2.height / 2 && entity_2.x - entity_2.width / 2 < entity_1.x + entity_1.radius && entity_1.y - entity_1.radius < entity_2.y + entity_2.height / 2 && entity_2.x + entity_2.width / 2 > entity_1.x - entity_1.radius) { if (entity_1.biome != 1) { if (entity_1.type != 3) { entity_1.biome = 1 } } if (entity_1.movable) { if (entity_2.specType == 0) { if (!entity_1.isflying) { if (entity_1.whichbiome != 5 && entity_1.whichbiome != 6) { entity_1.x -= 1.5 } } } else { if (!entity_1.isflying) { if (entity_1.whichbiome != 5 && entity_1.whichbiome != 6) { entity_1.x += 1.5 } } } } } } } } if (entity_1.biome != 1) { if (entity_2.type == 12) { if (entity_1.y > entity_2.y - entity_2.height / 2 && entity_2.x - entity_2.width / 2 < entity_1.x && entity_1.y < entity_2.y + entity_2.height / 2 && entity_2.x + entity_2.width / 2 > entity_1.x) { entity_1.biome = 1 } } if (entity_1.type != 3) { if (entity_2.type == 4 || entity_2.type == 10 || entity_2.type == 34) { if (entity_1.type != 10) { let distance = util.getDistance2D(entity_1.x, entity_1.y, entity_2.x, entity_2.y) if (distance <= entity_2.radius) { entity_1.biome = 1 } } } } } if (entity_1.biome != 0) { if (entity_2.type == 1) { if (entity_1.y > entity_2.y - entity_2.height / 2 && entity_2.x - entity_2.width / 2 < entity_1.x && entity_1.y < entity_2.y + entity_2.height / 2 && entity_2.x + entity_2.width / 2 > entity_1.x) { entity_1.biome = 0 } } } if (entity_1.biome != 2) { if (entity_2.type == 16) { if (entity_1.y > entity_2.y - entity_2.height / 2 && entity_2.x - entity_2.width / 2 < entity_1.x && entity_1.y < entity_2.y + entity_2.height / 2 && entity_2.x + entity_2.width / 2 > entity_1.x) { entity_1.biome = 2 } } } } } } collisions2.prototype = {} module.exports = collisions2
(function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.Boa = factory(); } }(this, function() { /* global document:false, MutationObserver:false, window:false */ 'use strict'; var Boa = { VERSION: '0.2.0', _bindings: [], _properties: {}, _sources: {}, _style: null, init: function() { var _this = this; this._style = document.createElement('style'); document.head.appendChild(this._style); document.addEventListener('DOMContentLoaded', function() { new MutationObserver(function(mutations) { mutations.forEach(_this._handleMutation.bind(_this)); }).observe(document.body, { attributes: true, childList: true, characterData: true, subtree: true, attributeFilter: ['class', 'style'] }); }); }, _handleMutation: function(mutation) { var changedEl = mutation.target; this._bindings.forEach(function(binding) { /* istanbul ignore else */ if (Boa._matches(changedEl, binding.source.selector)) { binding._apply(binding, changedEl); } }.bind(this)); }, _matches: function(el, selector) { if (!el) { return false; } var matcherFunc = el.matches || /* istanbul ignore next */ el.msMatchesSelector || /* istanbul ignore next */ el.mozMatchesSelector || /* istanbul ignore next */ el.webkitMatchesSelector; /* istanbul ignore if */ if (!matcherFunc) { throw new Error('Boa is unsupported on this browser.'); } return matcherFunc.call(el, selector); }, /** * Finds all sources which could match a selector. * For example, say you have three sources: * - #nav > li : color * - ul li : color * - .widget : color * Boa.findSources('li', 'color') will return the first two sources. * * @param {string} selector * @param {string} property */ findSources: function(selector, property) { var sources = []; var key; for (key in Boa._sources) { var source = Boa._sources[key]; if (source.property !== property) { continue; } if (Boa._matches(document.querySelector(source.selector), selector)) { sources.push(source); } } return sources; }, setProperty: function(selector, property, value) { var pseudoSource = { value: function() { return value; } }; new Boa.Binding(pseudoSource, selector, property); }, source: function(selector, property) { var combined = selector + '.' + property; if (!this._sources.hasOwnProperty(combined)) { this._sources[combined] = new this.Source(selector, property); } return this._sources[combined]; }, defineProperty: function(property, func) { if (arguments.length !== 2) { throw new Error('Incorrect number of arguments to defineProperty'); } if (this._properties.hasOwnProperty(property)) { throw new Error('Property already exists'); } this._properties[property] = func; }, defineTransform: function(name, func) { if (typeof name !== 'string') { throw new Error('name must be a string'); } if (typeof func !== 'function') { throw new Error('func must be a function'); } if (Boa.Source.prototype.hasOwnProperty(name)) { throw new Error('transform already exists'); } Boa.Source.prototype[name] = function() { var transformedSource = new Boa.Source(this.selector, this.property); transformedSource._parentSource = this; transformedSource._transformArgs = arguments; transformedSource.value = function() { var parentValue = [this._parentSource.value()]; var args = Array.prototype.concat.apply( parentValue, this._transformArgs ); return func.apply(this, args); }; return transformedSource; }; } }; Boa.Source = function(selector, property) { this._bindings = []; var pattern = /((\w+):)?([\w-]+)/i; var parsed = pattern.exec(property); if (parsed) { this._custom = parsed[2]; this.property = parsed[3]; } else { throw new Error('unable to parse property'); } this.selector = selector; }; Boa.Source.prototype._applyAllBindings = function() { this._bindings.forEach(function(binding) { binding._apply(); }); }; Boa.Source.prototype.bindTo = function(selector, property) { var binding = new Boa.Binding(this, selector, property); Boa._bindings.push(binding); this._bindings.push(binding); return binding; }; Boa.Source.prototype.value = function() { var element = document.querySelector(this.selector); if (this._custom) { return Boa._properties[this.property](element); } return window.getComputedStyle(element).getPropertyValue(this.property); }; Boa.Binding = function(source, selector, property) { this.source = source; this.selector = selector; this.property = property; this._apply(); }; Boa.Binding.prototype._apply = function() { var value = this.source.value(); if (this.cssRule) { this.cssRule.style[this.property] = value; } else { var rule = this.selector + '{' + this.property + ':' + value + ';}'; var sheet = Boa._style.sheet; var ruleIdx = sheet.insertRule(rule, sheet.cssRules.length); this.cssRule = sheet.cssRules[ruleIdx]; } Boa.findSources(this.selector, this.property).forEach(function(source) { source._applyAllBindings(); }); }; Boa.defineProperty('clientLeft', function(e) { return e.getBoundingClientRect().left; }); Boa.defineProperty('clientTop', function(e) { return e.getBoundingClientRect().top; }); var splitValueUnit = function(val) { var value = parseFloat(val, 10); var unit = val.replace(value.toString(), ''); return { value: value, unit: unit }; }; var deunitify = function(f) { return function(v, a) { v = splitValueUnit(v); if (a instanceof Boa.Source) { a = splitValueUnit(a.value()); // not sure if this is actually necessary, seems like it outputs // everything in pixels anyway //if (v.unit !== a.unit) { //throw new Error('Source units do not match: ' + v.unit + ', ' + a.unit); //} return f(v.value, a.value) + v.unit; } return f(v.value, a) + v.unit; }; }; Boa.defineTransform('plus', deunitify(function(v, a) { return v + a; })); Boa.defineTransform('minus', deunitify(function(v, a) { return v - a; })); Boa.defineTransform('times', deunitify(function(v, a) { return v * a; })); Boa.defineTransform('dividedBy', deunitify(function(v, a) { return v / a; })); Boa.defineTransform('mod', deunitify(function(v, a) { return v % a; })); Boa.init(); return Boa; }));
/** * Created by Ingunn on 27.09.2016. * Login and reg javascript */ $(document).ready(function() { function login(userName, password1) { var ok = false; var test = $.ajax ({ type: "GET", url: "Login/Login.json", dataType: 'json', success: function (data) { for(var i = 0; i < data.length; i++) { if(data[i].username.valueOf() === userName && data[i].password.valueOf() === password1) { ok = true; window.location = '/index2.html'; } } /*if(Boolean(ok) == false) { alert("Feil brukernavn eller passord test"); }*/ }, error: function() { alert("Error"); } }); } function reg(username, password, password2) { var okbruk = false; var okpass = false; var ok = false; var sjekkbnogpass = $.ajax({ type: "GET", url: "Login/Login.json", dataType: 'json', success: function (data) { if(password === password2) { okpass = true; for(var i = 0; i < data.length; i++) { if(data[i].username.valueOf() != username) { okbruk = true; var lagre = $.ajax({ type: "POST", url: "rest/User", data: '{"userName": "' + username + '", "password" : "' + password + '"}', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (data) { ok = true; alert("det gikk"); } }); } } } }, error: function() { alert("Dette er feil"); } }); } $("#TESTTEST").click(function() { var username = $("#username").val(); var password = $("#password").val(); login(username, password); }); $("#regknapp").click(function() { var username = $("#username1").val(); var password = $("#password1").val(); var password2 = $("#password2").val(); reg(username, password, password2); }); $("#registrer").click(function() { $("#login-overlay").fadeOut(); $("#reg-overlay").fadeIn(); }); });
import { useState, useEffect } from 'react' import useKeyPress from "./useKeyPress" import {useMoveViewerStore} from "./useMoveViewerStore" import useSound from 'use-sound'; import { useForceUpdate } from "./useForceUpdate" import { Chess } from 'chess.js'; import { useParams, useHitory, useHistory } from "react-router-dom"; // TODO: currentVariation . // TODO: Save variations to course collection // TODO: userSuccessRatio, XP points // TODO: MODE OF show, then you do for each variation(!!!!!!!!! ) const useChessGameView = ({ lesson, currentOpening , lessonMode:paramsLesson}) => { const history = useHistory() const params = useParams() const [playSound ] = useSound ("/sounds/move.mp3", {volume:0.5}) const setCurrentVariation = useMoveViewerStore(state => state.setCurrentVariation) const updateShapes = useMoveViewerStore(state => state.updateShapes) const isPractice = useMoveViewerStore(state => state.isPractice) const setUserTurn = useMoveViewerStore(state => state.setUserTurn) const setSelectedMove = useMoveViewerStore(state => state.setSelectedMove) const selectedMove = useMoveViewerStore(state => state.selectedMove) const setParentMove = useMoveViewerStore(state => state.setParentMove) const shadowChessGame = useMoveViewerStore(state => state.shadowChessGame) const setShadowChessGame = useMoveViewerStore(state => state.setShadowChessGame) const setPracticeMoveFens = useMoveViewerStore(state => state.setPracticeMoveFens) const practiceMoveFens = useMoveViewerStore(state => state.practiceMoveFens) const currentVariation = useMoveViewerStore(state => state.currentVariation) const setFirstMove = useMoveViewerStore(state => state.setFirstMove) const setCurrentLesson = useMoveViewerStore(state => state.setCurrentLesson) const setIsPractice = useMoveViewerStore(state => state.setIsPractice) const setVariations = useMoveViewerStore(state => state.setVariations) const currentLesson = useMoveViewerStore(state => state.currentLesson) const setCurrentOpening = useMoveViewerStore(state => state.setCurrentOpening) const setDisplayMoves = useMoveViewerStore(state => state.setDisplayMoves) const next = useMoveViewerStore(state => state.next) const nextResponse = useMoveViewerStore(state => state.nextResponse) const back = useMoveViewerStore(state => state.back) const setMoves = useMoveViewerStore(state => state.setMoves) const moves = useMoveViewerStore(state => state.moves) const setBasePgn = useMoveViewerStore(state => state.setBasePgn) const setPGNIntro = useMoveViewerStore(state => state.setPGNIntro) const setInitialState = useMoveViewerStore(state => state.setInitialState) const setLessonMode = useMoveViewerStore(state => state.setLessonMode) const [firstLoad, setFirstLoad] = useState(true) const isLeftPressed = useKeyPress('ArrowLeft') const isRightPressed = useKeyPress('ArrowRight') const forceUpdate = useForceUpdate(); useEffect(() => { initialiseChessGameView() }, []) useEffect(() => { return history.listen((location) => { console.log(`You changed the page to: ${location.pathname}`, {lesson}) // initialiseChessGameView() loadLesson() }) },[history]) // useEffect(() => { // let newVariation // if (params && params.variationId && lesson && lesson.variations){ // newVariation= lesson.variations.find((variation)=>variation.variationId===params.variationId) // } // setCurrentVariation(newVariation) // }, [params.variationId]) const initialiseChessGameView = ()=>{ setInitialState() let chess = new Chess() setShadowChessGame(chess) } const loadMoves = ()=>{ console.log ("loading moves mate ", ) setMoves(currentVariation.moves) setSelectedMove(currentVariation.moves[0]) setShadowChessGame(new Chess(currentVariation.moves[0].fen)) setFirstMove(true) updateShapes(currentVariation.moves[0].commentDiag) } useEffect(() => { if (params){ useMoveViewerStore.setState({params:params}) } }, [params]) useEffect(() => { if (params && params.lessonMode ){ setLessonMode(params.lessonMode) setIsPractice(params.lessonMode==="show"?false:true) } }, [params]) useEffect(() => { if (isLeftPressed) { back(playSound) } if (isRightPressed) { next(playSound) } }, [isLeftPressed, isRightPressed]) useEffect (()=>{ if (selectedMove){ if (isPractice && params.lessonMode ==="practice" && currentOpening && currentOpening.length>0 && currentOpening[0].orientation.substring(0,1) !== selectedMove.turn){ setUserTurn(true) } else{ setUserTurn(false) } } },[selectedMove]) useEffect(() => { if (selectedMove && shadowChessGame) { // IF NEW VARIATION, FOLLOW UP FROM 1 MOVE TO CURRENT. OTHERWISE, MOVE shadowChessGame.move({ from: selectedMove.from, to: selectedMove.to }) } }, [selectedMove]) // Change in variation of lesson. LOADING MOVES useEffect(() => { if (currentVariation && currentVariation.moves && currentVariation.moves.length>0){ loadMoves() } }, [currentVariation]) useEffect(() => { if (lesson && (currentLesson===undefined || JSON.stringify(currentLesson)!== JSON.stringify(lesson)) ){ loadLesson() } }, [ JSON.stringify(lesson)]) // Effect to manage the "parent" move (when displaying the comments of a move) useEffect(() => { if (selectedMove && selectedMove.variationLevel === 0) { setParentMove(selectedMove) } }, [selectedMove]) useEffect(() => { if (lesson ){ if (firstLoad){ setFirstLoad(false) loadLesson() } } }, [ lesson]) const loadLesson = ()=>{ if (lesson){ setCurrentLesson(lesson) setBasePgn(lesson.basePgn) loadPGNIntro (lesson.pgn) let newVariation if (lesson.variations ){ if (params.variationId){ newVariation= lesson.variations.find((variation)=>variation.variationId===params.variationId) } else{ // TODO: TEMPORAL FIX, TAKE OUT newVariation= lesson.variations[0] } setCurrentVariation(newVariation) setMoves(newVariation.moves) } setVariations ( lesson.variations) } if (currentOpening){ setCurrentOpening (currentOpening) } } // load intro comment of a PGN const loadPGNIntro = (pgn)=>{ var intro = pgn.substring( pgn.indexOf("{") + 1, pgn.indexOf("}") ); if (intro){ setPGNIntro (intro) } } // this processing could be in the backend useEffect(() => { console.log ("MOVES PROCESSING ", moves) let dualMod = [] let displayMov = [] let currentIndex = 0 let displayIndex = 0 if (moves) { let initialVariationLevel = moves[0].variationLevel //1. extract main line into an array moves.forEach((move) => { if (move.variationLevel === initialVariationLevel) { dualMod[currentIndex] = { ...move } currentIndex++ } }) console.log ({dualMod}) // 2 group moves in pairs (helps to plot) dualMod.forEach((mov, i ) => { if (i<(dualMod.length-1)){ if (mov.turn === "w") { displayMov[displayIndex] = displayMov[displayIndex] ? [displayMov[displayIndex], mov] : mov } if (mov.turn === "b") { displayMov[displayIndex] = displayMov[displayIndex] ? [displayMov[displayIndex], mov] : mov displayIndex++ } } else{ displayMov[displayIndex] = [mov] } }) } console.log({movesDisplay: displayMov}) setDisplayMoves(displayMov) }, [moves]) // onMove in practice mode! const onMove = (from, to) => { if (params.lessonMode === "practice") { playSound() shadowChessGame.move({ from, to }) const possibleMoves = shadowChessGame.moves({ verbose: true }) for (let i = 0, len = possibleMoves.length; i < len; i++) { /* eslint-disable-line */ if (possibleMoves[i].flags.indexOf("p") !== -1 && possibleMoves[i].from === from) { console.log({ from, to }) return } } if (moves) { let nextMove = moves.find((move) => move.index === selectedMove.next) let indexOfProgress = moves.indexOf((nextMove)) console.log({indexOfProgress, length: moves.length, moves}) { if (nextMove && nextMove.from === from && nextMove.to === to) { setSelectedMove(nextMove) useMoveViewerStore.setState({currentProgress:( (indexOfProgress>0?(indexOfProgress+1): indexOfProgress)/ moves.length) *100 }) // Update the list of fens that have been used (used to determine whether o not we can move back and next in practice mode) setPracticeMoveFens([...practiceMoveFens, nextMove.fen]) updateShapes(nextMove.commentDiag) shadowChessGame.move({ from, to, promotion: "x" }) setTimeout(function () { nextResponse(playSound) }, 500); } else { shadowChessGame.move({ from, to, promotion: "x" }) undo() } } } } } // Called when user does wrong move // TODO: Add red arrow // TODO: Add sound of wrong move const undo = () => { setTimeout(function () { shadowChessGame.undo() console.log({ fen: selectedMove.fen }) // setSelectedFen(selectedMove.fen) forceUpdate() } , 500); } return ({ onMove }) // return ({ moves, onMove }) } export default useChessGameView
const express=require("express"); const pool=require("../pool.js"); const router=express.Router(); router.get("/reg_phone",(req,res)=>{ var $reg_phone=req.query.user_phone; if(!$reg_phone){ res.send("手机号不能为空"); return; } pool.query("SELECT * FROM store_user WHERE user_phone=?",[$reg_phone],(err,result)=>{ if(err) throw err; if(result.length>0){ res.send({"code":"1"}); }else{ res.send({"code":"0"}); } }); }); router.get("/reg_upwd",(req,res)=>{ var $user_upwd=req.query.user_upwd; if(!$user_upwd){ res.send("密码不能为空"); return; } pool.query('SELECT * FROM store_user WHERE user_upwd="?"',[$user_upwd],(err,result)=>{ if(err) throw err; if(result.length>0){ res.send({"code":"1"}); }else{ res.send({"code":"0"}); } }); }); router.post("/Reg",(req,res)=>{ var $reg_phone=req.body.user_phone; var $reg_upwd=req.body.user_upwd; if(!$reg_phone){ res.send("手机号不能为空"); return; } if(!$reg_upwd){ res.send("密码不能为空"); return; } pool.query("INSERT INTO store_user VALUES('NULL',?,?)",[$reg_phone,$reg_upwd],(err,result)=>{ if(err) throw err; if(result.affectedRows>0){ res.send({"code":"1"}); }else{ res.send({"code":"0"}); } }); }); module.exports=router;
/* * UpdateAuthPage Messages * * This contains all the text for the UpdateAuthPage component. */ import { defineMessages } from 'react-intl' export default defineMessages({ CheckPrivateKeyMessage: { id: 'UpdateAuthPage CheckPrivateKeyMessage', defaultMessage: '校验私钥' }, CheckPrivateKeyPlaceholder: { id: 'UpdateAuthPage CheckPrivateKeyPlaceholder', defaultMessage: '请输入需要校验的私钥' }, GetPrivateKeyButtonMessage: { id: 'UpdateAuthPage GetPrivateKeyButtonMessage', defaultMessage: '生成公私钥' }, ModifyPrivateKeyTitle: { id: 'UpdateAuthPage ModifyPrivateKeyTitle', defaultMessage: '修改私钥' }, UpdateAuthAccountNamePlaceholder: { id: 'UpdateAuthPage UpdateAuthAccountNamePlaceholder', defaultMessage: '请输入私钥对应的账户名' }, UpdateAuthActiveKeyPlaceholder: { id: 'UpdateAuthPage UpdateAuthActiveKeyPlaceholder', defaultMessage: '请输入您想要的公钥activeKey' }, UpdateAuthOwnerKeyPlaceholder: { id: 'UpdateAuthPage UpdateAuthOwnerKeyPlaceholder', defaultMessage: '请输入您想要的公钥ownerKey' }, PrivateKeyLabel: { id: 'UpdateAuthPage PrivateKeyLabel', defaultMessage: '私钥' }, AccountLabel: { id: 'UpdateAuthPage AccountLabel', defaultMessage: '账户名' } })
blue_10_interval_name = ["佳里","番子寮","漚汪","苓子寮","將軍","山子腳","馬沙溝","將軍漁港"]; blue_10_interval_stop = [ ["佳里站","北門高中","潭墘"], // 佳里 ["番子寮"], // 番子寮 ["竹子腳","漚汪","將軍區衛生所","中社","忠興里","過港仔","忠嘉里"], // 漚汪 ["苓子寮","巷口"], // 苓子寮 ["北埔","將軍","將軍國小","將富"], // 將軍 ["玉山里口","玉山里","玉山玉天宮","公館","山子腳","廣山里"], // 山子腳 ["長平國小","馬沙溝"], // 馬沙溝 ["將軍漁港"] // 將軍漁港 ]; blue_10_fare = [ [26], [26,26], [26,26,26], [26,26,26,26], [32,26,26,26,26], [42,33,27,26,26,26], [51,42,36,28,26,26,26], [56,47,42,34,26,26,26,26] ]; // format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] blue_10_main_stop_name = ["佳里站","番子寮","漚汪","苓子寮","將軍","山子腳","馬沙溝","將軍漁港"]; blue_10_main_stop_time_consume = [0, 6, 9, 14, 17, 22, 25, 30]; blue_10_important_stop = [0, 2, 6, 7]; // 佳里站, 漚汪, 馬沙溝, 將軍漁港 var Jiali = 0; // 佳里站 var Mashagou = 6; // 馬沙溝 blue_10_time_go = [["05:20",Jiali,Mashagou],["06:00"],["07:20"],["08:50"],["09:30"],["10:50"],["12:30"],["13:40"],["15:10"],["16:10"],["17:00",["繞"]],["17:40",Jiali,Mashagou],["19:00"],["20:00"],["20:20"],["21:10"],["22:00"]]; blue_10_time_return = [["05:45",Mashagou,Jiali],["06:30",["繞"]],["08:00"],["09:30"],["10:10"],["11:30"],["13:10"],["14:20"],["15:50"],["16:50"],["17:40"],["18:15",Mashagou,Jiali],["19:40"],["20:40"],["21:00"],["21:40"],["22:30"]];
var XRay = require('aws-xray-sdk'); // Initialize X-ray SDK var AWS = XRay.captureAWS(require('aws-sdk')); // Capture all AWS SDK calls var http = XRay.captureHTTPs(require('http')); // Capture all HTTP/HTTPS calls const express = require('express'); var bodyParser = require('body-parser'); var queryString = require('querystring'); // Constants const PORT = 8080; const apiCNAME = process.env.API_CNAME || 'localhost'; // App const app = express(); XRay.config([XRay.plugins.EC2Plugin, XRay.plugins.ECSPlugin]); XRay.middleware.enableDynamicNaming(); app.use(bodyParser.urlencoded({extended: false})); // Start capturing the calls in the application app.use(XRay.express.openSegment('service-a')); app.get('/health', function(req, res) { res.status(200).send("Healthy"); }); app.get('/', function(req, res) { var seg = XRay.getSegment(); seg.addAnnotation('service', 'service-b-request'); var reqData = queryString.stringify(req.body); var options = { host: apiCNAME, port: '80', path: '/create', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(reqData) } }; // Set up the request var remoteReq = http.request(options, function(remoteRes) { var body = ''; remoteRes.setEncoding('utf8'); remoteRes.on('data', function(chunk) { body += chunk; }); remoteRes.on('end', function() { res.status(200).send(body); }); }); remoteReq.on('error', function() { console.log('service-b request failed'); }); // post the data remoteReq.write(reqData); remoteReq.end(); }); // Stop capturing the calls in the application app.use(XRay.express.closeSegment()); app.listen(PORT); console.log('Running on http://0.0.0.0:' + PORT);
function createObserver(elemento, classe) { const observer = new IntersectionObserver((entradas) => { entradas.forEach((entrada) => { if (entrada.intersectionRatio > 0) { entrada.target.classList.add(classe); observer.unobserve(entrada.target); } }) }) observer.observe(elemento); } const tipos = document.querySelectorAll('.tipos li'); tipos.forEach((tipo) => { createObserver(tipo, 'item-ativo'); })
//Created by VIMRIO helper //Please rename XXX. //For example. If current final stage is 013, this function's name is "initStage014" and save "stage014.js". function initStage014(stage){ var item; // Percent of one unit. if you want to change unit size, change this. var u=8; /////Animation Parameter///// // //dsp :display (true/false) startIndex.... display or hide //x : position x (percent) //y : position y (percent) //w : width (percent) //h : height (percent) //bgc : background-color //bdc : border-color //img : background-image (filename) //opc : opacity (0.0....1.0) default=1.0 //z : z-index (default=2) //wd : character of word //Answer String //helper original string=kke"It"e" is"e" funny"k stage.setAnsStr("kkeeek"); item=stage.createNewItem(); //class name item.setName("vimrio"); //frame offset. default startindex=0 item.setFrameStartIndex(0); stage.addItem(item); //first frame //1 start item.addAnimation({"dsp":true,"x":0*u,"y":6*u,"w":u,"h":u,"bgc":"transparent","bdc":"blue","img":"vimrio01.png","z":5,"opc":1.0,"wd":""}); //following next frames //2 k item.addAnimation({"y":5*u}); //3 k item.addAnimation({"y":4*u}); //4 e item.addAnimation({"x":1*u}); //5 e item.addAnimation({"x":4*u}); //6 e item.addAnimation({"x":10*u}); //7 k item.addAnimation({"y":3*u}); //1 goal item=stage.createNewItem(); item.setName("goal"); item.addAnimation({"dsp":true,"x":10*u,"y":3*u,"w":u,"h":u,"img":"goal01.png","bgc":"yellow","bdc":"yellow"}); stage.addItem(item); //word "It" [I] 1 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":0*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"I"}); stage.addItem(item); //word "It" [t] 2 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":1*u,"y":4*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"t"}); stage.addItem(item); //word " is" [ ] 1 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":2*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "}); stage.addItem(item); //word " is" [i] 2 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":3*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"i"}); stage.addItem(item); //word " is" [s] 3 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":4*u,"y":4*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"s"}); stage.addItem(item); //word " funny" [ ] 1 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":5*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "}); stage.addItem(item); //word " funny" [f] 2 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":6*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"f"}); stage.addItem(item); //word " funny" [u] 3 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":7*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"u"}); stage.addItem(item); //word " funny" [n] 4 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":8*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"n"}); stage.addItem(item); //word " funny" [n] 5 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":9*u,"y":4*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"n"}); stage.addItem(item); //word " funny" [y] 6 item=stage.createNewItem(); item.setName("word"); item.addAnimation({"dsp":true,"x":10*u,"y":4*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"y"}); stage.addItem(item); //wall 1 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":9*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 2 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":10*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 3 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":11*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 4 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":0*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 5 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":1*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 6 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":2*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 7 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":3*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 8 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":4*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 9 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":5*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 10 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":6*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 11 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":7*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 12 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":8*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 13 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":9*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 14 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":11*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 15 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":11*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 16 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":1*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 17 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":2*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 18 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":3*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 19 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":4*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 20 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":5*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 21 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":6*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 22 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":7*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 23 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":8*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 24 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":9*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 25 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":10*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 26 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":11*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 27 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":1*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 28 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":0*u,"y":7*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); //wall 29 item=stage.createNewItem(); item.setName("wall"); item.addAnimation({"dsp":true,"x":1*u,"y":7*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"}); stage.addItem(item); }
"use strict"; const express = require("express"); const ptv = require("ptv-api"); const async = require('async'); const app = express(); const port = process.env.PORT || 3000; const devId = "1000649"; const apiKey = "47235180-b369-11e5-a65e-029db85e733b"; const ptvClient = ptv(devId, apiKey); app.get("*", (req, res, next) => { if (!req.query.hasOwnProperty("stop_id")) { return res.sendStatus(404); } // Hit PTV for departures, collect ids ptvClient .then(apis => { return apis.Departures.Departures_GetForStop({ route_type: 0, stop_id: req.query.stop_id }); }) .then(ptvRes => { let stopRoutes = []; try { ptvRes.body.departures.forEach(departure => { stopRoutes.push(departure.route_id); }); } catch(err) { return next(err) } const uniqueStopRoutesSet = new Set(stopRoutes); const uniqueStopRoutes = Array.from(uniqueStopRoutesSet); // Hit PTV for route names, match against route ids async.map(uniqueStopRoutes, getDirections, (err, directionsRes) => { if (err) { return next(err); } // Flatten array of arrays into a 2d array const directionsData = [].concat.apply([], directionsRes); const directions = directionsData.filter((x, i, self) => // Item is a duplicate if findIndex returns a different index // to the current item index // Retrieved from https://stackoverflow.com/a/36744732/5891072 self.findIndex(item => item.direction_id === x.direction_id ) === i ); res.send(directions); }); }) .catch(err => { return next(err); }); }); function getDirections(routeId, callback) { ptvClient .then(apis => { return apis.Directions.Directions_ForRoute({ route_id: routeId }); }) .then(res => { const directions = res.body.directions.map(x => { return { direction_id: x.direction_id, direction_name: x.direction_name } }) return callback(undefined, directions); }) .catch(err => { return callback(err); }); } app.listen(port, () => console.log(`Listening on port ${port}`));
//////////////////////////////////////////////////////////////////// // brinnathomsen.js // // basic brinnathomsen tool: draws a thin, solid line // author: Justin Bakse //////////////////////////////////////////////////////////////////// // create and install brush var brinnathomsen = new Brush("p", "./brushes/brinnathomsen/brinnathomsen.svg"); brushes.push(brinnathomsen); //////////////////////////////////////////////////////////////////// // define brush behavior var centerX = 0; var centerY = 0; var drawColor = forecolor; brinnathomsen.draw = function() { // black hole brush // brinnathomsen.draw = function() { var colorF = random(0, 200); stroke(red(forecolor) + random(0, 150), green(forecolor) + random(0, 150), blue(forecolor) + random(0, 150)); strokeWeight(2); fill(255); tint(forecolor); if (mouseIsPressed) { bezier(mouseX, mouseY, mouseX + 10, mouseY + 10, mouseX, mouseY, centerX, centerY); } }; function mousePressed() { centerX = mouseX; centerY = mouseY; } // netting brush //brinnathomsen.draw = function() { // colorMode(HSB, 100); // stroke(random(0, 100), 100, 50, 10); // strokeWeight(5); // if (mouseIsPressed) { // line(random(200, 500), 0, mouseX, mouseY); // line(random(200, 500), 1000, mouseX, mouseY + 10); // } //}; // curtain brush? //brinnathomsen.draw = function() { // colorMode(HSB, 100); // stroke(random(0, 100), 100, 50, 10); // strokeWeight(5); // if (mouseIsPressed) { // line(mouseX + random(10, 50), 0, mouseX, mouseY); // line(mouseX - random(10, 50), 0, mouseX, mouseY); // } // tube brush? //brinnathomsen.draw = function() { //colorMode(HSB, 100); //stroke(random(0, 100), random(0, 100), 50, 10); //strokeWeight(50); //if (mouseIsPressed) { // line(pmouseX, pmouseY, mouseX, mouseY); // } //};
function highestProductOf3(arrayOfInts) { if (arrayOfInts.length < 3) throw 'Not enough integers'; arrayOfInts.sort(function(a, b){return a - b;}); if(arrayOfInts[0] * arrayOfInts[1] > //if negative product higher than positive arrayOfInts[arrayOfInts.length - 1] * arrayOfInts[arrayOfInts.length - 2] && arrayOfInts[arrayOfInts.length - 1] > 0){ //and top number is positive return arrayOfInts[0] * arrayOfInts[1] * arrayOfInts[arrayOfInts.length- 1]; } return arrayOfInts[arrayOfInts.length - 1] * arrayOfInts[arrayOfInts.length - 2] * arrayOfInts[arrayOfInts.length - 3]; //top three numbers }
import React,{useContext, useEffect,useState} from 'react'; import LocationCard from '../components/LocationCard'; import ThemeContext from '../context/ThemeContext'; import '../assets/pages/Locations.css' import '../assets/Theme/darkTheme.css' const Locations = () => { const [locations,getLocations] = useState([]) var theme = useContext(ThemeContext) useEffect(()=>{ fetch(`https://rickandmortyapi.com/api/location`) .then(res => res.json()) .then(data =>{ console.log(data.results) getLocations(data.results) }) },[]) return ( <div> <div className={theme ? "LocationContainer dark": "LocationContainer"}> {locations.map((location)=> <LocationCard key={location.id} imgSrc={location.image} name={location.name}/> )} </div> </div> ); } export default Locations;
import React, { useEffect, useRef, useState } from 'react'; import * as d3 from 'd3'; import companyData from '../../../data/companies_yearly_data.json'; import * as _ from 'lodash' const RELEVANT_YEARS = ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018"]; const stack_company_data = _.mapValues(_.groupBy(companyData, "primary_code_in_NIC"), business_segment => { let result = RELEVANT_YEARS.map(x => 0); for (let company of business_segment) { for (let i = 0; i < RELEVANT_YEARS.length; i++) { if (company["revenue_" + RELEVANT_YEARS[i]] != null) { result[i] += company["revenue_" + RELEVANT_YEARS[i]] } } } return result }); // omitting companies without sni for now delete stack_company_data['null']; const SNI_codes = Object.keys(stack_company_data); const result = RELEVANT_YEARS.map(year => { let obj = { year: year, }; for (let SNI of SNI_codes) { obj[SNI] = stack_company_data[SNI][RELEVANT_YEARS.indexOf(year)] } return obj }); const Sunburst = ({ onYearClicked }) => { const year_choice = onYearClicked; const margin = { top: 10, right: 10, bottom: 10, left: 10 }; const width = 400 - margin.left - margin.right; const height = 400 - margin.top - margin.bottom; const outerRadius = ((width + height) / 4) - margin.top; const innerRadius = outerRadius / 3; // state and ref to svg const svgRef = useRef(); const [data, setData] = useState([]); useEffect(() => { setData(result); }, []); // code runs only if data has been fetched useEffect(() => { const dataHasFetched = data !== undefined && data.length !== 0; const svg = d3.select(svgRef.current); svg.selectAll("*").remove(); if (dataHasFetched) { var pie = d3.pie().value((d) => { return d.value }); if (!RELEVANT_YEARS.includes(year_choice.toString())) { var emptyData = [{ name: "", value: 1 }]; svg .attr("width", width) .attr("height", height) .append('g') .attr('transform', 'translate(' + height / 2 + ' ' + width / 2 + ')') .selectAll() .data(pie(emptyData)) .enter() .append('path') .attr('d', d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) ) .attr('fill', 'white') .attr('stroke', "black") .append('title') .text("no data available"); svg .append('text') .attr("x", width / 2) .attr("y", height / 2 + 5) .text(year_choice.toString()) .style("text-anchor", "middle"); return; } var yearData = data[year_choice - 2010]; delete yearData['year']; var data_ready = pie(d3.entries(yearData)); //const colorScale = d3.scaleOrdinal(d3.schemeCategory10).domain(d3.range(20)); var colorScale2 = d3.interpolateRainbow; const numCategories = 200; //use change colorscale2 to colorscale and change numCategories to 77 to use same color scheme as balls svg .attr("width", width) .attr("height", height) .selectAll() .data(data_ready) .enter() .append('path') .attr('class', 'piece') .attr('d', d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) ) .attr('fill', function (d) { return colorScale2(d.data.key / numCategories); }) .attr("stroke", "white") .attr('transform', 'translate(' + height / 2 + ' ' + width / 2 + ')') .append('title') .text(function (d) { return d.data.key; }); svg .append('text') .attr('x', width / 2) .attr('y', height / 2 + 5) .attr('class', 'circletext') .style("text-anchor", "middle") .text(year_choice); //INTERACTION svg.selectAll('path') .on('mouseover', function (d) { d3.selectAll(".circletext").text(d.data.key); d3.selectAll(".piece").style("opacity", .2); d3.select(this).style("opacity", 1); }) .on('mouseout', function (d) { d3.selectAll(".circletext").text(year_choice.toString()); d3.selectAll(".piece").style("opacity", 1); }); } return () => { svg.selectAll("svg").exit().remove(); } }, [data]); return <React.Fragment> <svg height={height} width={width} ref={svgRef} /> </React.Fragment>; }; export default Sunburst;
import React from "react"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { ArrowBack } from "@styled-icons/evaicons-solid/ArrowBack"; import { ArrowForward } from "@styled-icons/evaicons-solid/ArrowForward"; const PaginationTable = styled.ul` display: flex; `; const ArrowContainer = styled.li` width: 30px; height: auto; `; // Te quedó muy bien este componente! Vas por un buen camino para hacerlo funcional. // No dejes de escribirme si queres seguirlo // Por otro lado, podes chusmear algunas librerias que simplifcan este tipo de componentes // Por ejemplo, Material UI: https://material-ui.com/components/pagination/ const Pagination = ({ pageNumbers, paginate }) => { const pageNumbersArray = []; for (let i = 1; i <= pageNumbers; i++) { pageNumbersArray.push(i); } return ( <PaginationTable> <Link> <ArrowContainer> <ArrowBack /> </ArrowContainer> </Link> {pageNumbersArray.map( (number) => number <= 5 && ( <li key={number}> <Link onClick={() => paginate(number)}>{number}</Link> </li> ) )} <span> <Link to="#">...</Link> </span> <span> <Link>{pageNumbers}</Link> </span> <Link> <ArrowContainer> <ArrowForward /> </ArrowContainer> </Link> </PaginationTable> ); }; export default Pagination;
export default [ {value: '中国', label: '中国', children: [ {value: '北京市', label: '北京市'}, {value: '天津市', label: '天津市'}, {value: '河北省', label: '河北省'}, {value: '山西省', label: '山西省'}, {value: '内蒙古自治区', label: '内蒙古自治区'}, {value: '辽宁省', label: '辽宁省'}, {value: '吉林省', label: '吉林省'}, {value: '黑龙江省', label: '黑龙江省'}, {value: '上海市', label: '上海市'}, {value: '江苏省', label: '江苏省'}, {value: '浙江省', label: '浙江省'}, {value: '安徽省', label: '安徽省'}, {value: '福建省', label: '福建省'}, {value: '江西省', label: '江西省'}, {value: '山东省', label: '山东省'}, {value: '河南省', label: '河南省'}, {value: '湖北省', label: '湖北省'}, {value: '湖南省', label: '湖南省'}, {value: '广东省', label: '广东省'}, {value: '广西壮族自治区', label: '广西壮族自治区'}, {value: '海南省', label: '海南省'}, {value: '重庆市', label: '重庆市'}, {value: '四川省', label: '四川省'}, {value: '贵州省', label: '贵州省'}, {value: '云南省', label: '云南省'}, {value: '西藏自治区', label: '西藏自治区'}, {value: '陕西省', label: '陕西省'}, {value: '甘肃省', label: '甘肃省'}, {value: '青海省', label: '青海省'}, {value: '宁夏回族自治区', label: '宁夏回族自治区'}, {value: '新疆维吾尔自治区', label: '新疆维吾尔自治区'}, {value: '台湾省', label: '台湾省'}, {value: '香港特别行政区', label: '香港特别行政区'}, {value: '澳门特别行政区', label: '澳门特别行政区'} ] } ]
// custom-ul.js Component({ relations: { './custom-li': { type: 'child', //关联的目标节点为子节点 linked: function(target) { }, linkChanged: function(target) {}, unlinked: function(target) {} } }, /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { }, /** * 组件的方法列表 */ methods: { _getAllLi: function() { var nodes = this.getRelationNodes('./custom-li') }, }, ready: function() { this._getAllLi() } })
const baseVertexShaderSrc = require('./shaders/shader-vert.glsl'); const baseFragmentShaderSrc = require('./shaders/shader-frag.glsl'); import { Program, ArrayBuffer, IndexArrayBuffer } from 'tubugl-core'; import { mat4 } from 'gl-matrix'; import { TRIANGLES, UNSIGNED_SHORT, CULL_FACE, DEPTH_TEST, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, BLEND } from 'tubugl-constants'; export class ModelObject { constructor(gl, params = {}, data) { this._gl = gl; this.modelMatrix = mat4.create(); mat4.scale(this.modelMatrix, this.modelMatrix, [20, 20, 20]); mat4.translate(this.modelMatrix, this.modelMatrix, [0, 7.75, 0]); this.normalMatrix = mat4.create(); mat4.invert(this.normalMatrix, this.modelMatrix); mat4.transpose(this.normalMatrix, this.normalMatrix); console.log(this.normalMatrix); let vertexShaderSrc = params.vertexShaderSrc ? params.vertexShaderSrc : baseVertexShaderSrc; let fragmentShaderSrc = params.fragmentShaderSrc ? params.fragmentShaderSrc : baseFragmentShaderSrc; this._makeProgram(vertexShaderSrc, fragmentShaderSrc); this._makeBuffers(data.data); } _makeProgram(vertexShaderSrc, fragmentShaderSrc) { this._program = new Program(this._gl, vertexShaderSrc, fragmentShaderSrc); } _makeBuffers(data) { this._positionBuffer = new ArrayBuffer( this._gl, new Float32Array(data.attributes.position.array) ); this._positionBuffer.setAttribs('position', 3); this._uvBuffer = new ArrayBuffer(this._gl, new Float32Array(data.attributes.uv.array)); this._uvBuffer.setAttribs('uv', 2); this._normalBuffer = new ArrayBuffer( this._gl, new Float32Array(data.attributes.normal.array) ); this._normalBuffer.setAttribs('normal', 3); this._indexBuffer = new IndexArrayBuffer(this._gl, new Uint16Array(data.index.array)); this._cnt = data.index.array.length; } render(camera) { this.update(camera).draw(); } update(camera) { this._program.use(); this._positionBuffer.bind().attribPointer(this._program); this._uvBuffer.bind().attribPointer(this._program); this._normalBuffer.bind().attribPointer(this._program); this._indexBuffer.bind(); this._gl.uniformMatrix4fv( this._program.getUniforms('modelMatrix').location, false, this.modelMatrix ); this._gl.uniformMatrix4fv( this._program.getUniforms('viewMatrix').location, false, camera.viewMatrix ); this._gl.uniformMatrix4fv( this._program.getUniforms('projectionMatrix').location, false, camera.projectionMatrix ); this._gl.uniformMatrix4fv( this._program.getUniforms('normalMatrix').location, false, this.normalMatrix ); return this; } draw() { // if (this._side === 'double') { this._gl.disable(CULL_FACE); // } else if (this._side === 'front') { // this._gl.enable(CULL_FACE); // this._gl.cullFace(BACK); // } else { // this._gl.enable(CULL_FACE); // this._gl.cullFace(FRONT); // } this._gl.enable(DEPTH_TEST); this._gl.blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA); this._gl.enable(BLEND); this._gl.drawElements(TRIANGLES, this._cnt, UNSIGNED_SHORT, 0); } }
import React, { Component } from 'react' const DatePicker = ({ date, m, d, y, isToday, nextDate, prevDate }) => { return ( <div className="form" style={{ padding: '10px' }}> <div className="form-item"> <button className="button inverted" onClick={ () => { prevDate(date) } }>{ '<' }</button> <button className="button inverted">{ `${m} ${d}, ${y}` }</button> <button className="button inverted" onClick={ () => { nextDate(date) } } disabled={ isToday }>{ '>' }</button> </div> </div> ) } export default DatePicker
import React from 'react' import PropTypes from 'prop-types' import './style.scss' import profile from '../../images/profile.png'; import firebase from 'firebase'; import { store } from "../../store"; import {followed} from "../../actions/index"; export const Profile = (props) => { return ( <div className="tsProfile"> <div> <div className="profileImg"> <img src={props.profileInfo.profileImage} alt="profile"/> </div> <h4>{props.profileInfo.username}</h4> <div className="follow"> <a onClick={() => { let currentUser = {uid: store.getState().auth.uid}; if(currentUser.uid != ''){ const id = store.getState().user.id; if(store.getState().user.following){ firebase.database().ref(`users/${currentUser.uid}/following/${id}`).remove(); firebase.database().ref(`users/${id}/followers/${currentUser.uid}`).remove(); store.dispatch(followed(!store.getState().user.following)); } else{ firebase.database().ref(`users/${currentUser.uid}/following`).child(id).push(id); firebase.database().ref(`users/${id}/followers/`).child(currentUser.uid).push(currentUser.uid); firebase.database().ref(`users/${currentUser.uid}/activity`).push({action: 'follow', id: id, user: currentUser.uid, time: firebase.database.ServerValue.TIMESTAMP}); store.dispatch(followed(!store.getState().user.following)); } } }}> {store.getState().user.following ? 'UNFOLLOW' : 'FOLLOW'} </a> </div> <div className="specialisation">{props.profileInfo.bio}</div> </div> <div className="info-wrap"> <div> Following <span>{props.userFollowing.length}</span> </div> <div> Followers <span>{props.userFollowers.length}</span> </div> <div> Tracking <span>{props.userTrackingList.length}</span> </div> </div> </div> ) } Profile.propTypes = {}
import { observable, action } from 'mobx' import axios from 'axios' class Job { id @observable name @observable options @observable result @observable status @observable thinking = true constructor (id) { axios.get(`/api/jobs/${id}`).then(({ data: { success, job }}) => { if (success && job) { this.options = job.options this.result = job.result this.name = job.name this.status = job.status } this.thinking = false }) } } export default Job
// Browse is the component which appears under the Maintenance/Find tab. Since // it allows you to look at the list of records in the database, as well as an // individual record, the top level component here just creates a stack navigator // to wrap the list/filter and creation functionalities. // Imports import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import GrowthCalendar from './GrowthCalendar'; import SampleDetails from '../../Growths/SampleDetails'; import GrowthDetails from '../../Growths/GrowthDetails'; // Create the stack navigator const Stack = createStackNavigator(); export default function GrowthCal(props) { return ( <Stack.Navigator> <Stack.Screen name="Calendar" component={GrowthCalendar} options={{headerShown: false}}/> <Stack.Screen name="Sample Details" component={SampleDetails}/> <Stack.Screen name="Growth Details" component={GrowthDetails}/> </Stack.Navigator> ) }
var searchData= [ ['validate_5ffunction_5fname_59',['validate_function_name',['../classclasses_1_1nag_1_1_nag.html#ae0e4bee92353fd428abb37f4ecf0b016',1,'classes::nag::Nag']]] ];
AutoForm = Celestial.AutoForm = React.createClass({ getInitialState: function () { return { modifiedFields: {} }; }, handleChange(e) { let modFields = {} modFields[e.target.name] = e.target.value; this.setState({ modifiedFields: modFields }) }, //let docPath = this.props.topKey ? this.props.item[this.props.topKey] : this.props.item; //docPath = this.props.topKey || ''; //docPath = this.props.subKey ? `${docPath}.${this.props.subKey}` : docPath; //console.log('AutoForm change: ' + docPath + ", " + e.target.name + ", " + e.target.value); //var obj = {} ////obj[this.props.section + "." + e.target.name] = e.target.value //obj[docPath + '.' + e.target.name] = e.target.value //console.log('obj: ' + JSON.stringify(obj)); //this.props.collection.update(this.props.item._id, {"$set": obj}) save() { const keys = Object.keys(this.state.modifiedFields) keys.map( field => { let value = this.state.modifiedFields[field]; //const dotKey = `${this.props.dotKey}.${field}`; //console.log(`save: ${dotKey},${value},${this.props._id}`); //let obj = {}; //obj[dotKey] = value; //this.props.collection.update(this.props._id, {"$set": obj}) Celestial.updateItem(this.props, field, value); }) }, render() { //var sectionArr = this.props.item[this.props.section] || []; //let item = eval(`(() => { return this.props.item${this.props.docPath}})()`) //let doc = this.props.topKey ? this.props.item[this.props.topKey] : this.props.item; //let item = (this.props.subKey ? doc[this.props.subKey] : doc) || {}; //console.log('AutoForm item: ' + Object.keys(item)); var rows = this.props.fields.map((field) => { let value = this.props.item[field] || ''; return <tr key={field}> <td className="meta-head">{field}</td> <td><textarea name={field} onChange={this.handleChange} defaultValue={value} rows="10" cols="50" /> </td> </tr>; }); var rows2 = this.props.checkboxFields && this.props.checkboxFields.map((field) => { let value = this.props.item[field] || ''; return <tr key={field}> <td className="meta-head">{field}</td> <td> <LinkedCheckbox {...this.props} property={field} /> </td> </tr>; }); return <div> <table id="meta"> <tbody> {rows} {rows2} </tbody> </table> <button onClick={this.save}>Save</button> </div>; } }) LinkedCheckbox = React.createClass({ //doesn't work yet //setChecked(e) { // const dotKey = `${this.props.dotKey}.${this.props.property}`; // this.props.updateItem('$set', dotKey, e.target.checked) //}, setChecked(e) { let obj = {} const dotKey = `${this.props.dotKey}.${this.props.property}`; console.log(`setChecked: ${dotKey},${e.target.value},${e.target.checked},${this.props._id}`); obj[dotKey] = e.target.checked this.props.collection.update(this.props._id, {"$set": obj}) }, render() { return <input type='checkbox' onChange={this.setChecked} checked={this.props.item[this.props.property]}/> } });
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const DisplayComments = (props) => { const [displayComments, setDisplayComments] = useState ([]); useEffect(() => { axios.get('http://localhost:5000/api/comments/46h4by4r74') .then(response => setDisplayComments(response.data)) }, []); return ( <div> { displayComments && displayComments.map(comment =>{ return ( <li> {comment.text} <br/> {comment.timeStamp} {comment.replies.map(reply => [ reply.text, reply.timeStamp ])} </li> ); }) } </div> ); } export default DisplayComments;
import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import CustomInput from './CustomInput'; describe('When everything is OK', () => { test('should call the onChange callback handler when using the fireEvent function', () => { const onChange = jest.fn(); render( <CustomInput value="" onChange={onChange}> Input: </CustomInput> ); fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Paula' } }); expect(onChange).toHaveBeenCalledTimes(1); }); test('should call the onChange handler when using the userEvent API', async () => { const onChange = jest.fn(); render( <CustomInput value="" onChange={onChange}> Input: </CustomInput> ); await userEvent.type(screen.getByRole('textbox'), 'Paula'); expect(onChange).toHaveBeenCalledTimes(5); }) });
import React, { useEffect, useState } from 'react'; import { Text, StatusBar, View, Image, Dimensions, StyleSheet, ImageBackground } from 'react-native'; import { connect } from 'react-redux'; import { getAllCategories } from '../store/actions/category'; import { Header, Body, Container, Left, Right, Card, CardItem } from 'native-base'; import { PRIMARY_COLOR, SECONDARY_COLOR, BASE_URL } from '../utils/constants'; import { SafeAreaView } from 'react-navigation'; import { FlatGrid } from 'react-native-super-grid'; import { heightInPercentage, widthInPercentage } from '../utils/helpers'; const BrowseScreen = (props) => { useEffect(() => { // Update the document title using the browser API props.getAllCategories(); }, []); const CategoryListComponent = () => { return ( <FlatGrid data={props.categories} itemDimension={widthInPercentage(90)} renderItem={({ item }) => { return <CategoriesItem key={item._id} category={item} />; }} /> ); }; return ( <SafeAreaView style={styles.container}> <CategoryListComponent /> </SafeAreaView> ); }; const CategoriesItem = ({ category }) => { return category ? ( <View style={styles.container}> <View style={{ backgroundColor: '#fff', height: heightInPercentage(30) }} > <ImageBackground source={{ uri: `${BASE_URL}/category/images/${category._id}` }} style={{ width: '100%', height: heightInPercentage(30) }} imageStyle={{ height: heightInPercentage(30), resizeMode: 'contain' }} > <View style={styles.overlay}> <Text style={styles.title}>{category.name.toUpperCase()}</Text> </View> </ImageBackground> </View> </View> ) : ( <Card key={'noitem'}> <Body> <Text>NO ITEMS FOUND</Text> </Body> </Card> ); }; const mapStateToProps = (state) => ({ categories: state.categories.categories }); const styles = StyleSheet.create({ container: { flex: 1, shadowColor: 'rgba(1,1,1,0.5)', shadowOffset: { width: 0, height: 2 }, shadowRadius: 5, shadowOpacity: 1.0, height: heightInPercentage(30), backgroundColor: '#fff' }, item: { backgroundColor: '#f9c2ff', padding: 20, marginVertical: 8, marginHorizontal: 16 }, title: { fontSize: 32, color: '#fff', fontWeight: 'bold', letterSpacing: 8, alignSelf: 'center', padding: 5, borderRadius: 5, backgroundColor: 'rgba(1,1,1,0.5)' }, overlay: { backgroundColor: 'rgba(0,0,0,0.3)', height: '100%', justifyContent: 'center' } }); export default connect(mapStateToProps, { getAllCategories })(BrowseScreen);
var net = require('net'); // var HOST = '127.0.0.1'; // var PORT = 6967; // 为客户端添加“data”事件处理函数 // data是服务器发回的数据 // // 为客户端添加“close”事件处理函数 // client.on('close', function() { // console.log('Connection closed'); // }); module.exports = function() { var client = new net.Socket(); var buffer = ""; var fn = new Function(); return { display: function() { console.log(123); }, connect: function(PORT, HOST) { client.connect(PORT, HOST, function() { client.write(buffer); }); return this; }, write: function(str) { buffer = str; return this; }, then: function(f) { fn = f; client.on('data', function(data) { fn(data); // 完全关闭连接 client.destroy(); }); return this; } } }
export default (error) => { const errors = []; if (!error.errors) { return [{ path: 'user', message: 'Unauthorized' }]; } const pathName = Object.keys(error.errors); for (let i = 0; i < pathName.length; i += 1) { const newPathName = pathName[i]; const { path, message } = error.errors[newPathName].properties; errors.push({ path, message }); } return errors; };
//Jobs global.loadJobs = function(player) { adv.mysql.handle.query("SELECT * FROM `jobs`", [], function(err, res) { let fancurier = res[0]; player.setVariable("fan_curier", fancurier); global.fanCurierInfo = fancurier; let drugDealer = res[1]; player.setVariable("drug_dealer", drugDealer); global.drugDealer = drugDealer; }); } global.jobs = [{ ID: 1, Name: "Fan Courier", GetJobPosition: new mp.Vector3(775.7708129882812, -2475.1005859375, 20.5), WorkPoint: new mp.Vector3(797.9589233398438, -2491.508056640625, 21.108142852783203), FirstCheckpoint: new mp.Vector3(1016.9273071289062, -2515.9750976562, 28.303483963012695), SpawnCar: new mp.Vector3(809.2395629882812, -2492.60498046875, 22.86774444580078) }, { ID: 2, Name: "Drug Dealer", GetJobPosition: new mp.Vector3(710.8890991210938, -909.504638671875, 22.5), WorkPoint: new mp.Vector3(731.89453125, -876.4656372070312, 25), } ]; global.FanCourierCheckPoints = [ [838.407470703125, -2253.494873046875, 29], [907.7179565429688, -2201.599365234375, 30], [787.4412841796875, -1770.443115234375, 27], [770.088623046875, -1914.8140869140625, 27], [457.20220947265625, -2058.638671875, 22], [331.3427429199219, -2000.2864990234375, 21], [1369.1063232421875, -1734.953857421875, 64.5], [1382.427490234375, -1544.612060546875, 56.5], ]; //End Jobs global.ADMIN_COLOR = '#f3cb8f'; global.DARK_COLOR = '#dc3545'; global.SUCCESS_COLOR = '#28a745'; global.WARNING_COLOR = '#ffc107'; global.WHITE_COLOR = '#ffffff'; global.PURPLE_COLOR = '#C2A2DA'; global.COLOR_ADMIN = '#f3cb8f'; global.COLOR_DARKRED = '#dc3545'; global.COLOR_SUCCESS = '#28a745'; global.COLOR_WARNING = '#ffc107'; global.COLOR_WHITE = '#ffffff'; global.COLOR_PURPLE = '#C2A2DA'; global.COLOR_GOLD = "#FFB95E"; global.COLOR_MONEY = "#4dad2b"; global.COLOR_DARKYELLOW = "#FFA500"; global.getRandomInt = function(max) { return Math.floor(Math.random() * Math.floor(max)); } global.distance = function(pointA, pointB) { var dx = pointB.x - pointA.x; var dy = pointB.y - pointA.y; var dz = pointB.z - pointA.z; var dist = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2) + Math.pow(dz, 2)); return dist; } //global vars global.inExamPlayers = new Array(); global.ExamCoords = [ [233, -348, 43], [210, -294, 45], [257, -160, 59.5], [284, -111, 68], [339, -115, 66], [433, -149, 62.5], [479, -160, 55.5], [509, -200, 50.5], [495, -275, 45.5], [447, -341, 47], [369, -392, 44.5], [283, -358, 43.5] ]; global.vehColors = [ [8, 8, 8], [15, 15, 15], [28, 30, 33], [41, 44, 46], [90, 94, 102], [119, 124, 135], [81, 84, 89], [50, 59, 71], [51, 51, 51], [31, 34, 38], [35, 41, 46], [18, 17, 16], [5, 5, 5], [18, 18, 18], [47, 50, 51], [8, 8, 8], [18, 18, 18], [32, 34, 36], [87, 89, 97], [35, 41, 46], [50, 59, 71], [15, 16, 18], [33, 33, 33], [91, 93, 94], [136, 138, 153], [105, 113, 135], [59, 70, 84], [105, 0, 0], [138, 11, 0], [107, 0, 0], [97, 16, 9], [74, 10, 10], [71, 14, 14], [56, 12, 0], [38, 3, 11], [99, 0, 18], [128, 40, 0], [110, 79, 45], [189, 72, 0], [120, 0, 0], [54, 0, 0], [171, 63, 0], [222, 126, 0], [82, 0, 0], [140, 4, 4], [74, 16, 0], [89, 37, 37], [117, 66, 49], [33, 8, 4], [0, 18, 7], [0, 26, 11], [0, 33, 30], [31, 38, 30], [0, 56, 5], [11, 65, 69], [65, 133, 3], [15, 31, 21], [2, 54, 19], [22, 36, 25], [42, 54, 37], [69, 92, 86], [0, 13, 20], [0, 16, 41], [28, 47, 79], [0, 27, 87], [59, 78, 120], [39, 45, 59], [149, 178, 219], [62, 98, 122], [28, 49, 64], [0, 85, 196], [26, 24, 46], [22, 22, 41], [14, 49, 109], [57, 90, 131], [9, 20, 46], [15, 16, 33], [21, 42, 82], [50, 70, 84], [21, 37, 99], [34, 59, 161], [31, 31, 161], [3, 14, 46], [15, 30, 115], [0, 28, 50], [42, 55, 84], [48, 60, 94], [59, 103, 150], [245, 137, 15], [217, 166, 0], [74, 52, 27], [162, 168, 39], [86, 143, 0], [87, 81, 75], [41, 27, 6], [38, 33, 23], [18, 13, 7], [51, 33, 17], [61, 48, 35], [94, 83, 67], [55, 56, 43], [34, 25, 24], [87, 80, 54], [36, 19, 9], [59, 23, 0], [110, 98, 70], [153, 141, 115], [207, 192, 165], [31, 23, 9], [61, 49, 29], [102, 88, 71], [240, 240, 240], [179, 185, 201], [97, 95, 85], [36, 30, 26], [23, 20, 19], [59, 55, 47], [59, 64, 69], [26, 30, 33], [94, 100, 107], [0, 0, 0], [176, 176, 176], [153, 153, 153], [181, 101, 25], [196, 92, 51], [71, 120, 60], [186, 132, 37], [42, 119, 161], [36, 48, 34], [107, 95, 84], [201, 110, 52], [217, 217, 217], [240, 240, 240], [63, 66, 40], [255, 255, 255], [176, 18, 89], [246, 151, 153], [143, 47, 85], [194, 102, 16], [105, 189, 69], [0, 174, 239], [0, 1, 8], [5, 0, 8], [8, 0, 0], [86, 87, 81], [50, 6, 66], [5, 0, 8], [8, 8, 8], [50, 6, 66], [5, 0, 8], [107, 11, 0], [18, 23, 16], [50, 51, 37], [59, 53, 45], [112, 102, 86], [43, 48, 43], [65, 67, 71], [102, 144, 181], [71, 57, 27], [71, 57, 27], [255, 216, 89] ]; global.Skins = [ "ig_abigail", "csb_abigail", "u_m_y_abner", "a_m_m_acult_01", "a_m_o_acult_01", "a_m_y_acult_01", "a_m_o_acult_02", "a_m_y_acult_02", "a_m_m_afriamer_01", "ig_mp_agent14", "csb_mp_agent14", "csb_agent", "s_f_y_airhostess_01", "s_m_y_airworker", "u_m_m_aldinapoli", "ig_amandatownley", "cs_amandatownley", "s_m_y_ammucity_01", "s_m_m_ammucountry", "ig_andreas", "cs_andreas", "csb_anita", "u_m_y_antonb", "csb_anton", "g_m_m_armboss_01", "g_m_m_armgoon_01", "g_m_y_armgoon_02", "g_m_m_armlieut_01", "mp_s_m_armoured_01", "s_m_m_armoured_01", "s_m_m_armoured_02", "s_m_y_armymech_01", "ig_ashley", "cs_ashley", "s_m_y_autopsy_01", "s_m_m_autoshop_01", "s_m_m_autoshop_02", "ig_money", "csb_money", "g_m_y_azteca_01", "u_m_y_babyd", "g_m_y_ballaeast_01", "g_m_y_ballaorig_01", "g_f_y_ballas_01", "ig_ballasog", "csb_ballasog", "g_m_y_ballasout_01", "u_m_m_bankman", "ig_bankman", "cs_bankman", "s_m_y_barman_01", "ig_barry", "cs_barry", "s_f_y_bartender_01", "u_m_y_baygor", "s_f_y_baywatch_01", "s_m_y_baywatch_01", "a_f_m_beach_01", "a_f_y_beach_01", "a_m_m_beach_01", "a_m_o_beach_01", "a_m_y_beach_01", "a_m_m_beach_02", "a_m_y_beach_02", "a_m_y_beach_03", "a_m_y_beachvesp_01", "a_m_y_beachvesp_02", "ig_benny", "ig_bestmen", "ig_beverly", "cs_beverly", "a_f_m_bevhills_01", "a_f_y_bevhills_01", "a_m_m_bevhills_01", "a_m_y_bevhills_01", "a_f_m_bevhills_02", "a_f_y_bevhills_02", "a_m_m_bevhills_02", "a_m_y_bevhills_02", "a_f_y_bevhills_03", "a_f_y_bevhills_04", "u_m_m_bikehire_01", "u_f_y_bikerchic", "s_m_y_blackops_01", "s_m_y_blackops_02", "s_m_y_blackops_03", "a_c_boar", "mp_f_boatstaff_01", "mp_m_boatstaff_01", "a_f_m_bodybuild_01", "s_m_m_bouncer_01", "ig_brad", "cs_bradcadaver", "cs_brad", "a_m_y_breakdance_01", "ig_bride", "csb_bride", "u_m_y_burgerdrug_01", "csb_burgerdrug", "s_m_y_busboy_01", "a_m_y_busicas_01", "a_f_y_business_01", "a_m_m_business_01", "a_m_y_business_01", "a_f_m_business_02", "a_f_y_business_02", "a_m_y_business_02", "a_f_y_business_03", "a_m_y_business_03", "a_f_y_business_04", "s_m_o_busker_01", "ig_car3guy1", "csb_car3guy1", "ig_car3guy2", "csb_car3guy2", "cs_carbuyer", "ig_casey", "cs_casey", "a_c_cat_01", "s_m_m_ccrew_01", "s_m_y_chef_01", "ig_chef2", "csb_chef2", "ig_chef", "csb_chef", "s_m_m_chemsec_01", "g_m_m_chemwork_01", "g_m_m_chiboss_01", "a_c_chickenhawk", "g_m_m_chicold_01", "g_m_m_chigoon_01", "g_m_m_chigoon_02", "a_c_chimp", "csb_chin_goon", "u_m_y_chip", "a_c_chop", "s_m_m_ciasec_01", "mp_m_claude_01", "ig_clay", "cs_clay", "ig_claypain", "ig_cletus", "csb_cletus", "s_m_y_clown_01", "s_m_m_cntrybar_01", "u_f_y_comjane", "s_m_y_construct_01", "s_m_y_construct_02", "s_f_y_cop_01", "s_m_y_cop_01", "csb_cop", "a_c_cormorant", "u_f_m_corpse_01", "u_f_y_corpse_02", "a_c_cow", "a_c_coyote", "ig_chrisformage", "cs_chrisformage", "a_c_crow", "csb_customer", "u_m_y_cyclist_01", "a_m_y_cyclist_01", "ig_dale", "cs_dale", "ig_davenorton", "cs_davenorton", "s_m_y_dealer_01", "cs_debra", "a_c_deer", "ig_denise", "cs_denise", "csb_denise_friend", "ig_devin", "cs_devin", "s_m_y_devinsec_01", "a_m_y_dhill_01", "u_m_m_doa_01", "s_m_m_dockwork_01", "s_m_y_dockwork_01", "s_m_m_doctor_01", "ig_dom", "cs_dom", "s_m_y_doorman_01", "a_f_m_downtown_01", "a_m_y_downtown_01", "ig_dreyfuss", "cs_dreyfuss", "ig_drfriedlander", "cs_drfriedlander", "mp_f_deadhooker", "s_m_y_dwservice_01", "s_m_y_dwservice_02", "a_f_m_eastsa_01", "a_f_y_eastsa_01", "a_m_m_eastsa_01", "a_m_y_eastsa_01", "a_f_m_eastsa_02", "a_f_y_eastsa_02", "a_m_m_eastsa_02", "a_m_y_eastsa_02", "a_f_y_eastsa_03", "u_m_m_edtoh", "a_f_y_epsilon_01", "a_m_y_epsilon_01", "a_m_y_epsilon_02", "mp_m_exarmy_01", "ig_fabien", "cs_fabien", "s_f_y_factory_01", "s_m_y_factory_01", "g_m_y_famca_01", "mp_m_famdd_01", "g_m_y_famdnf_01", "g_m_y_famfor_01", "g_f_y_families_01", "a_m_m_farmer_01", "a_f_m_fatbla_01", "a_f_m_fatcult_01", "a_m_m_fatlatin_01", "a_f_m_fatwhite_01", "ig_fbisuit_01", "cs_fbisuit_01", "s_f_m_fembarber", "u_m_m_fibarchitect", "u_m_y_fibmugger_01", "s_m_m_fiboffice_01", "s_m_m_fiboffice_02", "mp_m_fibsec_01", "s_m_m_fibsec_01", "u_m_m_filmdirector", "u_m_o_filmnoir", "u_m_o_finguru_01", "s_m_y_fireman_01", "a_f_y_fitness_01", "a_f_y_fitness_02", "ig_floyd", "cs_floyd", "csb_fos_rep", "player_one", "mp_f_freemode_01", "mp_m_freemode_01", "ig_g", "s_m_m_gaffer_01", "s_m_y_garbage", "s_m_m_gardener_01", "a_m_y_gay_01", "a_m_y_gay_02", "csb_g", "a_m_m_genfat_01", "a_m_m_genfat_02", "a_f_y_genhot_01", "a_f_o_genstreet_01", "a_m_o_genstreet_01", "a_m_y_genstreet_01", "a_m_y_genstreet_02", "s_m_m_gentransport", "u_m_m_glenstank_01", "a_f_y_golfer_01", "a_m_m_golfer_01", "a_m_y_golfer_01", "u_m_m_griff_01", "s_m_y_grip_01", "ig_groom", "csb_groom", "csb_grove_str_dlr", "cs_guadalope", "u_m_y_guido_01", "u_m_y_gunvend_01", "cs_gurk", "hc_hacker", "s_m_m_hairdress_01", "ig_hao", "csb_hao", "a_m_m_hasjew_01", "a_m_y_hasjew_01", "a_c_hen", "s_m_m_highsec_01", "s_m_m_highsec_02", "a_f_y_hiker_01", "a_m_y_hiker_01", "a_m_m_hillbilly_01", "a_m_m_hillbilly_02", "u_m_y_hippie_01", "a_f_y_hippie_01", "a_m_y_hippy_01", "a_f_y_hipster_01", "a_m_y_hipster_01", "a_f_y_hipster_02", "a_m_y_hipster_02", "a_f_y_hipster_03", "a_m_y_hipster_03", "a_f_y_hipster_04", "s_f_y_hooker_01", "s_f_y_hooker_02", "s_f_y_hooker_03", "u_f_y_hotposh_01", "csb_hugh", "ig_hunter", "cs_hunter", "a_c_husky", "s_m_y_hwaycop_01", "u_m_y_imporage", "csb_imran", "a_f_o_indian_01", "a_f_y_indian_01", "a_m_m_indian_01", "a_m_y_indian_01", "csb_jackhowitzer", "ig_janet", "cs_janet", "csb_janitor", "s_m_m_janitor", "ig_jay_norris", "u_m_m_jesus_01", "a_m_y_jetski_01", "u_f_y_jewelass_01", "ig_jewelass", "cs_jewelass", "u_m_m_jewelsec_01", "u_m_m_jewelthief", "ig_jimmyboston", "cs_jimmyboston", "ig_jimmydisanto", "cs_jimmydisanto", "ig_joeminuteman", "cs_joeminuteman", "ig_johnnyklebitz", "cs_johnnyklebitz", "ig_josef", "cs_josef", "ig_josh", "cs_josh", "a_f_y_juggalo_01", "a_m_y_juggalo_01", "u_m_y_justin", "ig_karen_daniels", "cs_karen_daniels", "ig_kerrymcintosh", "g_m_m_korboss_01", "g_m_y_korean_01", "g_m_y_korean_02", "g_m_y_korlieut_01", "a_f_m_ktown_01", "a_f_o_ktown_01", "a_m_m_ktown_01", "a_m_o_ktown_01", "a_m_y_ktown_01", "a_f_m_ktown_02", "a_m_y_ktown_02", "ig_lamardavis", "cs_lamardavis", "s_m_m_lathandy_01", "a_m_y_latino_01", "ig_lazlow", "cs_lazlow", "ig_lestercrest", "cs_lestercrest", "ig_lifeinvad_01", "cs_lifeinvad_01", "s_m_m_lifeinvad_01", "ig_lifeinvad_02", "s_m_m_linecook", "g_f_y_lost_01", "g_m_y_lost_01", "g_m_y_lost_02", "g_m_y_lost_03", "s_m_m_lsmetro_01", "ig_magenta", "cs_magenta", "s_f_m_maid_01", "a_m_m_malibu_01", "u_m_y_mani", "ig_manuel", "cs_manuel", "s_m_m_mariachi_01", "s_m_m_marine_01", "s_m_y_marine_01", "s_m_m_marine_02", "s_m_y_marine_02", "s_m_y_marine_03", "u_m_m_markfost", "ig_marnie", "cs_marnie", "mp_m_marston_01", "cs_martinmadrazo", "ig_maryann", "cs_maryann", "ig_maude", "csb_maude", "csb_mweather", "a_m_y_methhead_01", "g_m_m_mexboss_01", "g_m_m_mexboss_02", "a_m_m_mexcntry_01", "g_m_y_mexgang_01", "g_m_y_mexgoon_01", "g_m_y_mexgoon_02", "g_m_y_mexgoon_03", "a_m_m_mexlabor_01", "a_m_y_mexthug_01", "player_zero", "ig_michelle", "cs_michelle", "s_f_y_migrant_01", "s_m_m_migrant_01", "u_m_y_militarybum", "ig_milton", "cs_milton", "s_m_y_mime", "u_f_m_miranda", "u_f_y_mistress", "mp_f_misty_01", "ig_molly", "cs_molly", "a_m_y_motox_01", "a_m_y_motox_02", "a_c_mtlion", "s_m_m_movalien_01", "cs_movpremf_01", "cs_movpremmale", "u_f_o_moviestar", "s_f_y_movprem_01", "s_m_m_movprem_01", "s_m_m_movspace_01", "mp_g_m_pros_01", "ig_mrk", "cs_mrk", "ig_mrsphillips", "cs_mrsphillips", "ig_mrs_thornhill", "cs_mrs_thornhill", "a_m_y_musclbeac_01", "a_m_y_musclbeac_02", "ig_natalia", "cs_natalia", "ig_nervousron", "cs_nervousron", "ig_nigel", "cs_nigel", "mp_m_niko_01", "a_m_m_og_boss_01", "ig_old_man1a", "cs_old_man1a", "ig_old_man2", "cs_old_man2", "ig_omega", "cs_omega", "ig_oneil", "ig_orleans", "cs_orleans", "ig_ortega", "csb_ortega", "csb_oscar", "ig_paige", "csb_paige", "a_m_m_paparazzi_01", "u_m_y_paparazzi", "ig_paper", "cs_paper", "s_m_m_paramedic_01", "u_m_y_party_01", "u_m_m_partytarget", "ig_patricia", "cs_patricia", "s_m_y_pestcont_01", "hc_driver", "hc_gunman", "a_c_pig", "a_c_pigeon", "s_m_m_pilot_01", "s_m_y_pilot_01", "s_m_m_pilot_02", "u_m_y_pogo_01", "g_m_y_pologoon_01", "g_m_y_pologoon_02", "a_m_m_polynesian_01", "a_m_y_polynesian_01", "a_c_poodle", "ig_popov", "csb_popov", "u_f_y_poppymich", "csb_porndudes", "s_m_m_postal_01", "s_m_m_postal_02", "ig_priest", "cs_priest", "u_f_y_princess", "s_m_m_prisguard_01", "s_m_y_prismuscl_01", "u_m_y_prisoner_01", "s_m_y_prisoner_01", "u_m_y_proldriver_01", "csb_prologuedriver", "u_f_o_prolhost_01", "a_f_m_prolhost_01", "a_m_m_prolhost_01", "u_f_m_promourn_01", "u_m_m_promourn_01", "u_m_m_prolsec_01", "csb_prolsec", "ig_prolsec_02", "cs_prolsec_02", "a_c_pug", "a_c_rabbit_01", "ig_ramp_gang", "csb_ramp_gang", "ig_ramp_hic", "csb_ramp_hic", "ig_ramp_hipster", "csb_ramp_hipster", "csb_ramp_marine", "ig_ramp_mex", "csb_ramp_mex", "s_f_y_ranger_01", "s_m_y_ranger_01", "ig_rashcosvki", "csb_rashcosvki", "a_c_rat", "csb_reporter", "a_c_retriever", "a_c_rhesus", "u_m_m_rivalpap", "a_m_y_roadcyc_01", "s_m_y_robber_01", "ig_roccopelosi", "csb_roccopelosi", "a_c_rottweiler", "u_m_y_rsranger_01", "a_f_y_runner_01", "a_m_y_runner_01", "a_m_y_runner_02", "a_f_y_rurmeth_01", "a_m_m_rurmeth_01", "ig_russiandrunk", "cs_russiandrunk", "a_f_m_salton_01", "a_f_o_salton_01", "a_m_m_salton_01", "a_m_o_salton_01", "a_m_y_salton_01", "a_m_m_salton_02", "a_m_m_salton_03", "a_m_m_salton_04", "g_m_y_salvaboss_01", "g_m_y_salvagoon_01", "g_m_y_salvagoon_02", "g_m_y_salvagoon_03", "u_m_y_sbike", "a_f_y_scdressy_01", "s_m_m_scientist_01", "ig_screen_writer", "csb_screen_writer", "s_f_y_scrubs_01", "a_c_seagull", "s_m_m_security_01", "a_c_shepherd", "s_f_y_sheriff_01", "s_m_y_sheriff_01", "s_f_m_shop_high", "mp_m_shopkeep_01", "s_f_y_shop_low", "s_m_y_shop_mask", "s_f_y_shop_mid", "ig_siemonyetarian", "cs_siemonyetarian", "a_f_y_skater_01", "a_m_m_skater_01", "a_m_y_skater_01", "a_m_y_skater_02", "a_f_m_skidrow_01", "a_m_m_skidrow_01", "s_m_m_snowcop_01", "a_m_m_socenlat_01", "ig_solomon", "cs_solomon", "a_f_m_soucent_01", "a_f_o_soucent_01", "a_f_y_soucent_01", "a_m_m_soucent_01", "a_m_o_soucent_01", "a_m_y_soucent_01", "a_f_m_soucent_02", "a_f_o_soucent_02", "a_f_y_soucent_02", "a_m_m_soucent_02", "a_m_o_soucent_02", "a_m_y_soucent_02", "a_f_y_soucent_03", "a_m_m_soucent_03", "a_m_o_soucent_03", "a_m_y_soucent_03", "a_m_m_soucent_04", "a_m_y_soucent_04", "a_f_m_soucentmc_01", "u_m_m_spyactor", "u_f_y_spyactress", "u_m_y_staggrm_01", "a_m_y_stbla_01", "a_m_y_stbla_02", "ig_stevehains", "cs_stevehains", "a_m_y_stlat_01", "a_m_m_stlat_02", "ig_stretch", "cs_stretch", "csb_stripper_01", "s_f_y_stripper_01", "csb_stripper_02", "s_f_y_stripper_02", "mp_f_stripperlite", "s_f_y_stripperlite", "s_m_m_strperf_01", "s_m_m_strpreach_01", "g_m_y_strpunk_01", "g_m_y_strpunk_02", "s_m_m_strvend_01", "s_m_y_strvend_01", "a_m_y_stwhi_01", "a_m_y_stwhi_02", "a_m_y_sunbathe_01", "a_m_y_surfer_01", "s_m_y_swat_01", "s_f_m_sweatshop_01", "s_f_y_sweatshop_01", "ig_talina", "ig_tanisha", "cs_tanisha", "ig_taocheng", "cs_taocheng", "ig_taostranslator", "cs_taostranslator", "u_m_o_taphillbilly", "u_m_y_tattoo_01", "a_f_y_tennis_01", "a_m_m_tennis_01", "ig_tenniscoach", "cs_tenniscoach", "ig_terry", "cs_terry", "cs_tom", "ig_tomepsilon", "cs_tomepsilon", "ig_tonya", "csb_tonya", "a_f_y_topless_01", "a_f_m_tourist_01", "a_f_y_tourist_01", "a_m_m_tourist_01", "a_f_y_tourist_02", "ig_tracydisanto", "cs_tracydisanto", "ig_trafficwarden", "csb_trafficwarden", "u_m_o_tramp_01", "a_f_m_tramp_01", "a_m_m_tramp_01", "a_m_o_tramp_01", "a_f_m_trampbeac_01", "a_m_m_trampbeac_01", "a_m_m_tranvest_01", "a_m_m_tranvest_02", "player_two", "s_m_m_trucker_01", "ig_tylerdix", "csb_undercover", "s_m_m_ups_01", "s_m_m_ups_02", "s_m_y_uscg_01", "g_f_y_vagos_01", "mp_m_g_vagfun_01", "ig_vagspeak", "csb_vagspeak", "s_m_y_valet_01", "a_m_y_vindouche_01", "a_f_y_vinewood_01", "a_m_y_vinewood_01", "a_f_y_vinewood_02", "a_m_y_vinewood_02", "a_f_y_vinewood_03", "a_m_y_vinewood_03", "a_f_y_vinewood_04", "a_m_y_vinewood_04", "ig_wade", "cs_wade", "s_m_y_waiter_01", "ig_chengsr", "cs_chengsr", "a_c_westy", "u_m_m_willyfist", "s_m_y_winclean_01", "s_m_y_xmech_01", "s_m_y_xmech_02", "a_f_y_yoga_01", "a_m_y_yoga_01", "ig_zimbor", "cs_zimbor", "u_m_y_zombie_01", "a_f_y_femaleagent", "g_f_importexport_01", "g_m_importexport_01", "ig_agent", "ig_malc", "mp_f_cardesign_01", "mp_f_chbar_01", "mp_f_cocaine_01", "mp_f_counterfeit_01", "mp_f_execpa_01", "mp_f_execpa_02", "mp_f_forgery_01", "mp_f_helistaff_01", "mp_f_meth_01", "mp_f_weed_01", "mp_m_cocaine_01", "mp_m_counterfeit_01", "mp_m_execpa_01", "mp_m_forgery_01", "mp_m_meth_01", "mp_m_securoguard_01", "mp_m_waremech_01", "mp_m_weapexp_01", "mp_m_weapwork_01", "mp_m_weed_01", "s_m_y_xmech_02_mp", "u_f_m_drowned_01", "u_f_y_corpse_01", "u_m_m_streetart_01", "ig_lestercrest_2", "ig_avon", "u_m_y_juggernaut_01", "mp_m_avongoon", "mp_m_bogdangoon", "u_m_y_corpse_01" ] console.log(" Global Variables Loaded ");
module.exports = { 'Open Home Page': function(browser) { const page = browser.page.webPostulationPJ(); page .navigate() .maximizeWindow() browser .assert.title('postulacion-pj-2') .saveScreenshot('tests/nuevosSocios/img/TC01.png') .pause(3 * 1000) .end() } }
import React from 'react'; import {Signer} from '@waves/signer'; import {ProviderWeb} from '@waves.exchange/provider-web'; const signer = new Signer({ NODE_URL: 'https://nodes-testnet.wavesnodes.com' }); signer.setProvider(new ProviderWeb('https://testnet.waves.exchange/signer/')) let address = 'not authorized' async function auth() { try { const user = await signer.login(); address = user.address; } catch (e) { console.error('login rejected') } finally { document.querySelector(".address").innerHTML = "Your address is: " + address } } export function SignerBlock() { return ( <section className="signer_buttons"> <br/> <input className="btn btn-primary" type="submit" value="Auth with WavesSigner" onClick={auth}/> <p class="address"></p> </section> ); }
'use strict'; app.controller('AuthCtrl', function($scope, $location, authService, authorizedUser){ if(authorizedUser){ redirectToHome(); } $scope.register = function () { authService.register($scope.user).then(function(newUser) { return authService.login($scope.user).then(function() { newUser.username = $scope.user.username; return authService.createProfile(newUser); }).then(function() { $location.path('/'); }); }, function(error) { $scope.error = error.toString(); }); }; $scope.login = function(){ authService.login($scope.user).then(function(){ redirectToHome(); }, function(error){ $scope.error = error.toString(); }) }; function redirectToHome() { $location.path('/') } });
(function(){ 'use strict'; angular .module('App.Book', [ 'App.Book.Contact' ]) .config(bookConfig) .service('BookList', BookList) .run(function(){ console.log('BOOK RUN'); }) .controller('bookCtrl', bookCtrl) .directive('bookItem', bookItem); //************************************************************************************************** bookConfig.$inject = [ '$stateProvider', '$urlRouterProvider' ]; function bookConfig ( $stateProvider, $urlRouterProvider ) { $urlRouterProvider.otherwise('/'); $stateProvider .state('search', { url: '/', templateUrl: 'app/Book/book.tpl.html', controller: 'bookCtrl', controllerAs: 'bookView' }) .state('search.new', { url: 'new', templateUrl: 'app/Book/Contact/contact.tpl.html', controller: 'newContactCtrl', controllerAs: 'vm' }) .state('search.details', { url: '{id:[A-Z]{10,}}', templateUrl: 'app/Book/Details/details.tpl.html', controller: 'detailsCtrl' }) .state('search.edit', { url: '{id:[A-Z]{10,}}/edit', templateUrl: 'app/Book/Contact/contact.tpl.html', controller: 'editContactCtrl', controllerAs: 'vm' }); console.log('BOOK CONFIG'); } //************************************************************************************************** BookList.$inject = ['DataBase']; function BookList (DataBase) { this.db = DataBase.getData(); this.markItem = function(n) { // Add "active" only on this item }; this.demarkAllItems = function() { // Clear "active" from all items }; } //************************************************************************************************** bookCtrl.$inject = [ 'DataBase', '$scope', '$state', 'BookList', 'Stage' ]; function bookCtrl ( DataBase, $scope, $state, BookList, Stage ) { var bookView = this; bookView.db = DataBase.getData(); bookView.openDetails = function() { Stage.detailsOpen = true; }; bookView.isDetailsOpen = function() { return !!Stage.detailsOpen; }; bookView.activeId = ''; bookView.open = function(nn){ BookList.demarkAllItems(); BookList.markItem(nn.id); $state.go('search.details', {id:nn.id}); }; $scope.$on('$stateChangeSuccess', function() { var id = $state.params.id; if(id) { bookView.activeId = id; BookList.markItem(id); } else { bookView.activeId = ''; BookList.demarkAllItems(); } Stage.detailsOpen = !$state.is('search'); }); console.log('BOOK CTRL'); } //************************************************************************************************** bookItem.$inject = [ ]; function bookItem () { return { scope:{ itemData:'=', toOpen:'=' }, replace:true, restrict:'C', templateUrl:'bookItem.tpl.html', link:function(scope) { var d = scope.itemData, names = [], contacts = []; d.firstName ? names.push(d.firstName) : 0; d.middleName ? names.push(d.middleName) : 0; d.lastName ? names.push(d.lastName) : 0; d.nick ? names.push(d.nick) : 0; d.phones ? contacts.push(d.phones.join(' ')) : 0; d.emails ? contacts.push(d.emails.join(' ')) : 0; scope.names = names.join(' '); scope.contacts = contacts.join(' '); // TODO: This is need to optimised! Put this logic intro Book module and create alternative db list as {id, names, contacts} } } } })();
$(function(){ $.each($("input"),function(){ var obj = $(this); obj.mouseover(function(){obj.addClass('onFocus')}).mouseout(function(){obj.removeClass('onFocus')}); }); var checkObj = $("#checkImage"); checkObj.mouseover(function(){checkObj.addClass('onFocus')}).mouseout(function(){checkObj.removeClass('onFocus')}); });
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ /** * @ngdoc directive * @name ngMango.directive:maSwitchImg * @restrict E * @description * `<ma-switch-img></ma-switch-img>` * - `<ma-switch-img>` displays an image who's image source will be switched based on a point's value. * - Use default-src to set the default image that will display if no match is found or the point is disabled. * - <a ui-sref="ui.examples.singleValueDisplays.switchImage">View Demo</a> * * @param {object=} point A data point object from a watch list, point query, point drop-down, `maPoint` service, or `<ma-get-point-value>` component. * @param {string=} point-xid Instead of supplying a data point object, you can supply it's XID. * @param {string=} default-src Set the default image path that will display if no match is found or the point is disabled. * @param {object=} src-map Use an object to map any data point value to an image path: (`{'value1': 'img/image1.png', * 'value2': 'img/image2.png'}`) * @param {string=} src-### The part of attribute after `src-` (the `###`) is used to compare against the point value. For strings with spaces replace the spaces in the point value with dashes in attribute name. *Not to be used with `src-map` attribute. * @param {*=} value Alternatively to passing in a point you can use the `value` attribute to pass in a raw value. * @param {boolean=} toggle-on-click Set to true to enable click to toggle. *Only works with binary data points. * @param {string} label Displays a label next to the point value. Three special options are available: * NAME, DEVICE_AND_NAME, and DEVICE_AND_NAME_WITH_TAGS * @param {expression=} label-expression Expression that is evaluated to set the label. Gives more control for formatting the label. * Takes precedence over the label attribute. Available locals are $point (Data point object). * * @usage <ma-point-list limit="200" ng-model="myPoint"></ma-point-list> <ma-point-value point="myPoint"></ma-point-value> <ma-switch-img point="myPoint" src-false="img/ligthbulb_off.png" src-true="img/ligthbulb_on.png" default-src="img/close.png" toggle-on-click="true"></ma-switch-img> * */ switchImg.$inject = ['maPointValueController', 'maUtil']; function switchImg(PointValueController, maUtil) { const replaceAll = function replaceAll(target, search, replacement) { return target.replace(new RegExp(search, 'g'), replacement); }; class SwitchImgController extends PointValueController { $onChanges(changes) { super.$onChanges(...arguments); if (changes.srcMap && !changes.srcMap.isFirstChange() || changes.defaultSrc && !changes.defaultSrc.isFirstChange()) { this.updateImage(); } if (changes.toggleOnClick) { if (this.toggleOnClick) { this.$element.on('click.maIndicator', this.clickHandler.bind(this)); this.$element.attr('role', 'button'); } else { this.$element.off('click.maIndicator'); this.$element.removeAttr('role'); } } } valueChangeHandler() { super.valueChangeHandler(...arguments); this.updateImage(); if (this.point && this.point.pointLocator && !this.point.pointLocator.settable) { this.$element.attr('disabled', 'disabled'); } else { this.$element.removeAttr('disabled'); } } updateImage() { const value = this.getValue(); if (value == null) { delete this.src; } else { // TODO better conversion to attr name for symbols etc const valueString = typeof value === 'string' ? replaceAll(value, ' ', '-').toLowerCase() : value.toString(); const attrName = maUtil.camelCase('src-' + valueString); this.src = this.$attrs[attrName]; if (!this.src && this.srcMap) { this.src = this.srcMap[value]; } } if (!this.src) { this.src = this.defaultSrc || 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; } } clickHandler() { if (this.point && !this.$element.attr('disabled')) { this.point.toggleValue(); } } } return { restrict: 'E', template: `<img ng-src="{{$ctrl.src}}"> <div ng-if="$ctrl.label" ng-bind="$ctrl.label" class="ma-point-value-label"></div>`, scope: {}, controller: SwitchImgController, controllerAs: '$ctrl', bindToController: { point: '<?', pointXid: '@?', srcFalse: '@?', srcTrue: '@?', defaultSrc: '@?', srcMap: '<?', src0: '@?', src1: '@?', src2: '@?', src3: '@?', value: '<?', renderValue: '&?', toggleOnClick: '<?', labelAttr: '@?label', labelExpression: '&?' }, designerInfo: { translation: 'ui.components.switchImg', icon: 'image', category: 'pointValue', attributes: { point: {nameTr: 'ui.app.dataPoint', type: 'datapoint'}, pointXid: {nameTr: 'ui.components.dataPointXid', type: 'datapoint-xid'}, toggleOnClick: {nameTr: 'ui.components.toggleOnClick', type: 'boolean'}, srcTrue: {type: 'choosefile', optional: true}, srcFalse: {type: 'choosefile', optional: true}, defaultSrc: {type: 'choosefile'}, srcMap: {type: 'string'}, src0: {type: 'choosefile', optional: true}, src1: {type: 'choosefile', optional: true}, src2: {type: 'choosefile', optional: true}, src3: {type: 'choosefile', optional: true}, value: {type: 'string'}, label: {options: ['NAME', 'DEVICE_AND_NAME', 'DEVICE_AND_NAME_WITH_TAGS']} } } }; } export default switchImg;
(function () { 'use strict'; angular .module('busfeedback.home.controllers') .controller('IndexController', IndexController); IndexController.$inject = ['$location', 'Authentication', 'Snackbar', 'Home']; function IndexController($location, Authentication, Snackbar, Home) { var vm = this; activate(); function activate() { vm.isAuthenticated = Authentication.isAuthenticated(); var authenticatedAccount = Authentication.getAuthenticatedAccount(); // Redirect if not logged in if (!authenticatedAccount) { $location.url('/login'); Snackbar.error('You are not authorized to view this page.'); return; } // Get ride statistics for the past 30 days var now = new Date(); var thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate()-30)); var rideStatisticsQueryParameters = { created_at_lte: thirtyDaysAgo, created_at_gt: now }; Home.getRideStatistics(rideStatisticsQueryParameters).then(statisticsSuccessful, statisticsError); Home.getTimelineStatistics().then(timelineStatisticsSuccessful, timelineStatisticsError); function statisticsSuccessful(data, status, headers, config){ // Seat Pie vm.seatPieLabels = ["Yes", "No"]; var seatData = []; seatData.push(data.data.seat_positives); seatData.push(data.data.seat_negatives); vm.seatPieData = seatData; vm.seatPieType = 'Pie'; // Greet Pie vm.greetPieLabels = ["Yes", "No"]; var greetData = []; greetData.push(data.data.greet_positives); greetData.push(data.data.greet_negatives); vm.greetPieData = greetData; vm.greetPieType = 'Pie'; // General vm.averageDistance = data.data.average_distance; vm.averagePeopleBoarding = data.data.average_people_boarding; vm.averagePeopleWaiting = data.data.average_people_waiting; vm.averageTravelDuration = data.data.average_travel_duration; vm.averageWaitingDuration = data.data.average_waiting_duration; vm.numberOfJourneys = data.data.number_of_journeys; vm.numberOfRides = data.data.number_of_rides; vm.tripsPerJourney = data.data.trips_per_journey; vm.averageRating = data.data.average_rating; } function statisticsError(data, status, headers, config) { Snackbar.error('Statistics could not be retrieved.'); } function timelineStatisticsSuccessful(data, status, headers, config){ var timelineLabels = []; var timelineData = []; data.data.forEach(function(entry) { timelineLabels.push(entry['day']); timelineData.push(entry['available']); }); vm.timelineLabels = timelineLabels; vm.timelineSeries = ['Number of Rides']; vm.timelineData = [timelineData]; } function timelineStatisticsError(data, status, headers, config) { Snackbar.error('Timeline statistics could not be retrieved.'); } } } })();
import React, { useState} from 'react'; function Todo({id, todo, removeTodo}) { const[doneState, setDoneState] = useState(todo.isDone); function toggleState(){ setDoneState(!doneState); } return ( <div className="todo"> <li style={{ textDecoration: doneState ? "line-through" : "" }}> {id}, {todo.description} </li> <div> <input type="checkbox" checked={doneState?'checked':''} onChange={() => toggleState()}></input> <button onClick={() => removeTodo(id)}>Delete</button>{' '} </div> </div> ); } export default Todo;
import React, { useEffect, useState, useContext } from "react"; import { makeStyles } from "@material-ui/core/styles"; import SideBar from "./SideBar.jsx"; import Head from "./Head.jsx"; import PDFViewer from "./PDFViewer.jsx"; import PDFJSBackend from "./PDFJs.jsx"; import { Typography } from "@material-ui/core"; import DocumentsContext from "../../context/document/documentsContext" const useStyles = makeStyles(() => ({ root: { display: "grid", gridTemplateColumns: "1% 16% 1%", gridTemplateRows: "8% 8% 8% 5% 14% 6%", width: "100vw", minHeight: "100vh", background: "#FFFFFF", }, head: { gridColumnStart: "1", gridColumnEnd: "5", gridRowStart: "1", gridRowEnd: "3", }, sideBar: { gridColumnStart: "1", gridColumnEnd: "3", gridRowStart: "2", gridRowEnd: "8", }, pdf: { gridColumnStart: "4", gridColumnEnd: "5", gridRowStart: "2", gridRowEnd: "8", }, arrow: { marginLeft:"0.2rem", gridColumnState: "3", gridColumnEnd: "4", gridRowStart: "2", gridRowEnd: "8", } })); const DocumentPreview = () => { const classes = useStyles(); const documentsContext = useContext(DocumentsContext); const [sideBarEnd, setSideBarEnd] = useState("3"); const [pdfStart, setPDFStart] = useState("4"); const [arrowStart, setArrowStart] = useState("3"); const [arrowEnd, setArrowEnd] = useState("4"); const [arrow, setArrow] = useState("<"); useEffect(() => { console.log("watttup") }, [documentsContext.currentURL]); const handleSideBar = () => { if(sideBarEnd === "3" && arrowStart === "3" && pdfStart === "4") { setSideBarEnd("1"); setArrowStart("1"); setArrowEnd("2"); setPDFStart("2"); setArrow(">"); } else if(sideBarEnd === "1" && arrowStart === "1" && pdfStart === "2") { setSideBarEnd("3"); setArrowStart("3"); setArrowEnd("4"); setPDFStart("4"); setArrow("<"); } }; const renderSideBar = () => { if(sideBarEnd === "3" && arrowStart === "3" && pdfStart === "4") return(<SideBar />) }; return ( <div className={classes.root}> <div className={classes.head}> <Head /> </div> <div className={classes.sideBar} style={{gridColumnEnd:sideBarEnd}}> {renderSideBar()} </div> <div className={classes.arrow} style={{gridColumnStart:arrowStart, gridColumnEnd:arrowEnd}} onClick={e => handleSideBar()}> {arrow} </div> <div className={classes.pdf} style={{gridColumnStart:pdfStart}}> <iframe width="100%" height="100%" src={documentsContext.currentURL} /> </div> </div> ); }; export default DocumentPreview; /*<div className={classes.pdf} style={{ gridColumnStart: pdfColumn }}> <Typography className={classes.collapseExtend} onClick={(event) => setColumn(event)} > {arrow} </Typography> </div>*/
const express = require('express'); const app = express(); var cors = require('cors') app.use(cors()); app.listen(666); const mongoose = require('mongoose'); const Todo = mongoose.model('Todo',{ title: String, completed: Boolean, userId: Number }) mongoose.connect("mongodb://localhost/newbase"); // traitement de toutes les réponses pour supprimer _v et renommer _id en id const mung = require('express-mung') app.use(mung.json(entity=>{ if (entity.length) { return entity.map(e=>transform(e)) } else return transform(entity); })); function transform(entity){ if (!entity.toObject) return; entity = entity.toObject(); delete entity.__v; entity.id = entity._id; delete entity._id; return entity; } // le module body-parser nous permet de récupérer le body des requêtes en json const bodyParser = require('body-parser'); // app.use permet d'ajouter un middleware, cad une fonction qui sera executé sur la requete avant l'appel de la route // ici le middleware bodyParser transforme la requete en ajoutant le body en json dans reqla propriété body app.use(bodyParser.json()) app.route('/todos').get((req, res)=>{ Todo.find({},(err, todos)=>{ res.json(todos); }) }) app.route('/todos').post((req, res)=>{ let entity = req.body; Todo.create(entity, (err, todo)=>{ res.json(todo); }) })
//Doing $("btnUploadFile").fade("out"); oSetListFetchRequest.send(); oBlanksRequest.send(); oSetFetchRequest.send({data:{file:getDefaultSetName()}}); oSongListFetchRequest.send(); oVideoListFetchRequest.send(); oPresentationListFetchRequest.send(); oBibleDataRequest.send();
import VueMoment from 'vue-moment' import VueEcho from 'vue-echo' import Toasted from 'vue-toasted' import 'croud-style-guide/src/components/shared/forms/toast/themes/croudToastTheme.scss' import universal from './store/modules/universal' import notifications from './store/modules/notifications' import croudLayout from './App' window.io = require('socket.io-client') export default { install(Vue, options) { Vue.component('croud-layout', croudLayout) Vue.use(VueMoment, { moment: options.moment || false, }) Vue.use(VueEcho, { broadcaster: 'socket.io', host: `${node_gateway_url.includes('https://') ? '' : '//'}${node_gateway_url}`, auth: { headers: { Authorization: `Bearer ${localStorage.getItem('jwt')}`, }, }, }) Vue.use(Toasted, { fullWidth: true, theme: 'croud', duration: 2500, position: 'top-center', }) options.store.registerModule('universal', universal) options.store.registerModule('notifications', notifications) /* eslint-disable no-underscore-dangle */ Object.keys(options.store._actions).filter(a => a.includes('$init')).forEach(a => options.store.dispatch(a, a)) if (options.noLegacyAuth) { options.store.commit('universal/STOP_LEGACY_AUTH') } if (options.globalPermission) { options.store.commit('universal/SET_GLOBAL_PERMISSION_KEY', options.globalPermission) } Vue.nextTick(() => { /* eslint-disable */ (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-NLBX2QT'); /* eslint-disable */ }) }, }
var express = require('express'); var router = express.Router(); var fs = require('fs'); var dal = require('../../common/dalData'); // var db = require('mongoose'); // db.Promise = global.Promise; // db.connect('mongodb://localhost/blog_db'); // var Blog = db.model('blog',{ // name:String, // nickName:String, // detail:String, // id:String, // create_time:String, // view_times:Number // }); //发表页面 router.get('/add',function(req,res){ var postUrl = '/users/create'; res.render('admin/add',{data:{},postUrl:postUrl}); }) //列表页面 router.get('/list',function(req,res){ var data = dal.getData(); res.render('admin/list',{list:data}); }); //修改页面 router.get('/edit/:id',(req,res) =>{ var data = dal.getDataByID(req.params.id); var postUrl = '/users/update/'+req.params.id; res.render('admin/add',{data:data,postUrl:postUrl}); }) router.post('/create',function(req,res){ var arr = dal.getData(); var blog = {}; blog = req.body; var now = new Date(); blog.id = now.getTime(); blog.create_time = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate()+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds(); blog.view_times = 0; arr.push(req.body); fs.writeFile('./data/users.json', JSON.stringify(arr)); res.redirect('/users/list'); // var blog = new Blog(); // blog.name = req.body.name; // blog.nickName = req.body.nickName; // blog.detail = req.body.detail; // blog.id = req.body.id; // blog.create_time = req.body.create_time; // blog.view_times = req.body.view_times; // // blog.save(function(err){ // if (err) { // console.log(err); // }else{ // console.log('博客信息保存完毕'); // } // }) // console.log(req.body); }); //删除数据 router.post('/delete',(req,res) =>{ dal.getDelDataByID(req.body.id); res.redirect('/users/list'); }); //修改表单数据 router.post('/update/:id',(req,res) =>{ dal.update(req.params.id,req.body); res.redirect('/users/list'); }); module.exports = router;
import React, { useState, useEffect } from "react" import { connect } from "react-redux" import { withRouter } from "react-router-dom" import { reverseValue, redirectIfFalse, emailNewTeamMember, getNumberOfTeamMembers, checkNewMemberIsAdmin } from "./../../christianLogic/christianLogic" import Employee from "./Employee" import axios from "axios" const TeamMembers = (props) => { // -- STATE -- // const [teamMembers, setTeamMembers] = useState([]) const [addNewMember, setAddNewMember] = useState(false) const [form, setValues] = useState({ newFirstname: "", newLastname: "", newEmail: "", newIsadmin: false, newImg: "https://www.aber.ac.uk/staff-profile-assets/img/noimg.png" }) // -- LIFECYCLE EVENTS -- // useEffect(() => { const checkIsAdmin = redirectIfFalse(props.admin) if (!checkIsAdmin) { props.history.push("/") } }, []) const getTeamMembers = async () => { const { company_id } = props const numberOfTeamMembers = await getNumberOfTeamMembers(company_id) if (numberOfTeamMembers.length !== teamMembers.length) { setTeamMembers(numberOfTeamMembers) return teamMembers } } useEffect(() => { getTeamMembers() }, [teamMembers]) useEffect(() => { getTeamMembers() }) // -- METHODS -- // // Add Team Member const handleAddNewMember = () => { setAddNewMember(reverseValue(addNewMember)) } const handleCancelAddNewMember = event => { event.preventDefault() setAddNewMember(reverseValue(addNewMember)) } const updateField = event => { setValues({ ...form, [event.target.name]: event.target.value }) } const handleNewTeamMemberCheckIsAdmin = () => { const checkIsAdmin = document.getElementById("newTeamMemberCheckIsAdmin") checkIsAdmin.value = checkIsAdmin.checked const value = () => { return checkNewMemberIsAdmin(checkIsAdmin.value) } setValues({ ...form, newIsadmin: value() }) } const handleAddNewUserFormSubmit = async (event) => { event.preventDefault() const { newFirstname: firstname, newLastname: lastname, newEmail: email, newIsadmin: isadmin, newImg: img } = form const { company_id } = props await axios.post("/team-member", { firstname, lastname, email, isadmin, company_id, img }) .then(results => { const { team_member_id, firstname, email } = results.data[0] emailNewTeamMember(team_member_id, firstname, email) // axios.post("/email-team-member", { team_member_id, firstname, email }) }) .then(getTeamMembers) .then(() => { setValues({ ...form, newFirstname: "", newLastname: "", newEmail: "", newIsadmin: false }) }) .then(() => { setAddNewMember(!addNewMember) }) .catch(console.log) } // ----- ----- // -- JSX -- // const teamMember = teamMembers && teamMembers.map((member) => { return <Employee member={member} getTeamMembers={getTeamMembers} key={member.team_member_id} teamMembers={teamMembers} setTeamMembers={setTeamMembers} /> }) return ( <div className="team-members" > <h1>Team Members</h1> <hr /> <div className="team-members-hero"> {teamMember} </div> <hr /> <div className="add-team-member"> { !addNewMember ? <div> <button className="add-new-team-member-btn" onClick={handleAddNewMember}>Add New Team Member</button> </div> : <div> <form className="add-new-team-member" onSubmit={handleAddNewUserFormSubmit}> <label> First Name: <input value={form.newFirstname} type="text" name="newFirstname" onChange={updateField} className="new-firstname" /> </label> <label> Last Name: <input value={form.newLastname} type="text" name="newLastname" onChange={updateField} className="new-lastname" /> </label> <label> Email: <input value={form.newEmail} type="text" name="newEmail" onChange={updateField} className="new-email" /> </label> <label htmlFor="newIsadmin"> Admin <input value={true} id="newTeamMemberCheckIsAdmin" type="checkbox" name="isadmin" onClick={handleNewTeamMemberCheckIsAdmin} /> </label> <div className="add-new-team-member-btns"> <button>Submit</button> <button onClick={handleCancelAddNewMember}>Cancel</button> </div> </form> </div> } </div> </div> ) } function mapStateToProps(state) { return state } export default connect(mapStateToProps)(withRouter(TeamMembers))
import React, { Component } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import "./App.css"; import { BrowserRouter, Route } from "react-router-dom"; import { getData } from "./components/quiz"; import Header from "./components/Header"; import Modal1 from "./components/Modal1"; import About from "./components/About"; class App extends Component { state = { quiz: getData(), evaluate: "", userAnswers: [], id: [], modalOpen: false }; ///check the Answer....... handleAnswer = (q, e) => { console.log(q.id); this.setState({ userAnswers: e.concat({ id: q.id }) }); if (q.correct !== e) { this.setState({ modalOpen: true, evaluate: <h4>{q.explanation}</h4> }); } else { this.setState({ modalOpen: true, evaluate: "correct" }); } }; toggleModal = () => { this.setState({ modalOpen: !this.state.modalOpen }); }; getColor1 = () => { return this.props.modalContent === "correct" ? "badge badge-pill bg-primary" : "badge badge-pill bg-danger"; }; render() { return ( <BrowserRouter> <div className="App"> <Header /> <switch> <Route exact path="/" render={props => ( <form> <hr /> {this.state.quiz.map(q => ( <div key={q.id}> <h3 className="text-secondary">{q.question}</h3> <img src={q.image} /> <hr /> {q.choices.map(a => ( <label key={a} className="text-secondary"> <input type="checkbox" onClick={() => this.handleAnswer(q, a)} ref="check_me" />{" "} {a} </label> ))} <br /> <form /> <hr /> </div> ))} <form> <button className=" btn btn-secondary btn-sm"> Result </button> </form> <Modal1 toggleModalHandler={this.toggleModal} modalOpen={this.state.modalOpen} modalContent={this.state.evaluate} /> </form> )} /> <hr /> <Route path="/about" component={About} /> </switch> </div> </BrowserRouter> ); } } export default App;
const PERIODS = { "IB":"Italo-Byzantine", "15":"15 Cen North Renaissance", "16":"16 Cen North Renaissance", "ER":"Early Renaissance", "HR":"High Renaissance", "VR":"Venetian Renaissance", "MAN":"Mannerism", "NB":"Northern Baroque", "SB":"Southern Baroque", "Arch_R":"Renaissance Architecture", "Arch_B":"Baroque Architecture" }; var galleryData = [ { "name":"Foundling Hospital", "artist":"Filippo Bruneslleschi", "year":1425, "loc":"south", "pos":95, "img":"https://o.quizlet.com/GxyZM1cvo6d91ByVnGBuAA.png", "period":PERIODS.Arch_R, "id":0}, { "name":"Villa Rotunda", "artist":"Palladio", "year":1560, "loc":"south", "pos":50, "img":"https://o.quizlet.com/i/WtybKZuN-YWIa9yCmkZuuA.jpg", "period":PERIODS.Arch_R, "id":1}, { "name":"Virgin and Child Before a Fire Screen (Merode Altarpiece)", "artist":"Robert Campim", "year":1425, "loc":"north", "pos":40, "img":"https://farm8.staticflickr.com/7166/6408027119_34c1e88a3b.jpg", "period":"15 Cen North Renaissance", "id":2}, { "name":"Madonna del Bordone", "artist":"Coppo di Marcolvado", "year":1265, "loc":"south", "pos":50, "img":"https://kids.kiddle.co/images/thumb/5/5f/Coppo_di_Marcovaldo_Mad.1.jpg/300px-Coppo_di_Marcovaldo_Mad.1.jpg", "period":"Italo-Byzantine", "id":3}, { "name":"Hunters in the Snow", "artist":"Pieter Breugel", "year":1565, "loc":"north", "pos":50, "img":"https://farm4.staticflickr.com/3009/3037876791_c7923ea5bb.jpg", "period":"16 Cen North Renaissance", "id":4}, { "name":"Tribute Money", "artist":"Masaccio", "year":1427, "loc":"south", "pos":60, "img":"https://farm9.staticflickr.com/8050/8087572248_1c0757895f.jpg", "period":"Early Renaissance", "id":5}, { "name":"Madonna of the Meadows", "artist":"Raphael", "year":1505, "loc":"south", "pos":68, "img":"https://o.quizlet.com/i/CidRZxg4EZgiobQOion02w.jpg", "period":"Early Renaissance", "id":6}, { "name":"Judith Slaying Holofernes", "artist":"Artemisia Gentileschi", "year":1620, "loc":"south", "pos":60, "img":"https://o.quizlet.com/xEWhB4QMrFUGWl6lErHCCg.jpg", "period":"Southern Baroque", "id":7}, { "name":"Woman Holding a Balance", "artist":"Johannes Vermeer", "year":1663, "loc":"north", "pos":75, "img":"https://o.quizlet.com/eJFvlxX-IV-UcFTxmR6sYA.jpg", "period":"Northern Baroque", "id":8}, { "name":"Portinari Alterpiece", "artist":"Hugo Van der Goes", "year":1475, "loc":"north", "pos":95, "img":"https://o.quizlet.com/Bc0cqFf5MCEsvx5-eS5bbQ.png", "period":"15 Cen North Renaissance", "id":9}, { "name":"Les Tres Riches Hueres du Duc de Berry [May]", "artist":"Limbourg Brothers", "year":1413, "loc":"north", "pos":80, "img":"https://upload.wikimedia.org/wikipedia/commons/4/4c/Limbourg_brothers_-_Les_tr%C3%A8s_riches_heures_du_Duc_de_Berry_-_Mai_%28May%29_-_WGA13022.jpg", "period":"15 Cen North Renaissance", "id":10}, { "name":"Les Tres Riches Hueres du Duc de Berry [Jan]", "artist":"Limbourg Brothers", "year":1413, "loc":"north", "pos":70, "img":"https://o.quizlet.com/z43Hr-XPM3yNgIJ8yNraSg.jpg", "period":"15 Cen North Renaissance", "id":11}, { "name":"The Baptism of Jesus Christ", "artist":"Verrocchio and da Vinci", "year":1475, "loc":"south", "pos":60, "img":"https://o.quizlet.com/i/dtVWn169RbFfOPKP4h1T_Q.jpg", "period":"Early Renaissance", "id":12}, { "name":"The Immaculate Cenception", "artist":"Murillo", "year":1665, "loc":"south", "pos":70, "img":"https://o.quizlet.com/8d1emjyeFQYpSenqEmyvPQ.jpg", "period":"Southern Baroque", "id":13}, { "name":"Madonna Enthroned with Angels and Prophets", "artist":"Cimbue", "year":1290, "loc":"south", "pos":50, "img":"https://o.quizlet.com/p9jbo7f0JKs3I4P5scSRJQ.jpg", "period":"Italo-Byzantine", "id":14}, { "name":"Madonna Enthroned", "artist":"Giotto de Bondone", "year":1310, "loc":"south", "pos":50, "img":"https://o.quizlet.com/i/iymBQsQKyyRs9y_krApk_A.jpg", "period":"Italo-Byzantine", "id":15}, { "name":"The Conversion of St Paul", "artist":"Caravaggio", "year":1601, "loc":"south", "pos":63, "img":"https://o.quizlet.com/7kzUEK.RMDQBvgOOm9Focw.jpg", "period":"Southern Baroque", "id":16}, { "name":"Las Meninas", "artist":"Diego Velazquez", "year":1656, "loc":"south", "pos":40, "img":"https://o.quizlet.com/i/ZvHes2stWj3cnqTpIPb39w.jpg", "period":"Southern Baroque", "id":17}, { "name":"Well of Moses", "artist":"Claus Sluter", "year":1395, "loc":"north", "pos":40, "img":"https://o.quizlet.com/uQxbJr0ucUiOaLlWeLMvXA.jpg", "period":"15 Cen North Renaissance", "id":18}, { "name":"The Last Supper", "artist":"Dirk Bouts", "year":1465, "loc":"north", "pos":40, "img":"https://o.quizlet.com/APR5k6DBlYKz6PSbDOz5UA.jpg", "period":"15 Cen North Renaissance", "id":19}, { "name":"The Last Supper", "artist":"Leonardo da Vinci", "year":1495, "loc":"south", "pos":35, "img":"https://o.quizlet.com/THc-D2ivMF5yjxx-cyKyNQ.jpg", "period":"High Renaissance", "id":20}, { "name":"Isenheim Alterpiece", "artist":"Matthias Grunewald", "year":1510, "loc":"north", "pos":35, "img":"https://o.quizlet.com/WYdkP2npkONJNPLWUZr.lg.jpg", "period":"16 Cen North Renaissance", "id":21}, { "name":"Adam and Eve", "artist":"Albrecht Durer", "year":1504, "loc":"north", "pos":65, "img":"https://o.quizlet.com/aooDE5yHF2N.gzTRGkLy8w.jpg", "period":"16 Cen North Renaissance", "id":22}, { "name":"A Goldsmith in his Shop", "artist":"Petrus Christus", "year":1449, "loc":"north", "pos":80, "img":"https://o.quizlet.com/X96RdXpT2itiY.jnz9s-kg.png", "period":"15 Cen North Renaissance", "id":23}, { "name":"A Money Changer and his Wife", "artist":"Quentin Massys", "year":1514, "loc":"north", "pos":63, "img":"https://o.quizlet.com/cAV2KI4utRNA-nyw3l4D.w.jpg", "period":"16 Cen North Renaissance", "id":24}, { "name":"Lamentation", "artist":"Giotto de Bondone", "year":1305, "loc":"south", "pos":90, "img":"https://o.quizlet.com/i/XVRPWs4IM_FdriXKEJuNzg.jpg", "period":"Italo-Byzantine", "id":25}, { "name":"Annunciation", "artist":"Simone Martini", "year":1333, "loc":"south", "pos":50, "img":"https://o.quizlet.com/ZptLZEjf7iBmBT1WFbirdg.jpg", "period":"Italo-Byzantine", "id":26}, { "name":"The Sacrifice of Isaac", "artist":"Filippo Brunneleschi", "year":1402, "loc":"south", "pos":40, "img":"https://o.quizlet.com/Vi67mQpAs2B3i3WPu2VzgA.jpg", "period":"Early Renaissance", "id":27}, { "name":"The Sacrifice of Isaac", "artist":"Lorenzo Ghiberti", "year":1402, "loc":"south", "pos":55, "img":"https://o.quizlet.com/i/37hZP7512MP-0jnjgyxuhA.jpg", "period":"Early Renaissance", "id":28}, { "name":"David", "artist":"Donatello", "year":1428, "loc":"south", "pos":30, "img":"https://o.quizlet.com/i/TDZE1k7h5j86aVU5Fs1tiA.jpg", "period":"Early Renaissance", "id":29}, { "name":"David", "artist":"Michelangelo", "year":1501, "loc":"south", "pos":60, "img":"https://o.quizlet.com/i/IRBUdw0bBpYMNuSTChaP3w.jpg", "period":"High Renaissance", "id":30}, { "name":"David", "artist":"Bernini", "year":1623, "loc":"south", "pos":95, "img":"https://o.quizlet.com/yFu3vE56TP9JMVOzPv-AdA.jpg", "period":"Southern Baroque", "id":31}, { "name":"Palazzo Rucella", "artist":"Alberti", "year":1452, "loc":"south", "pos":30, "img":"https://o.quizlet.com/UZNEPSmUVlQwNChaImWO9Q.png", "period":"Renaissance Architecture", "id":32}, { "name":"San Carlo alle Quattro Fontane", "artist":"Borromini", "year":1675, "loc":"south", "pos":40, "img":"https://o.quizlet.com/C3MZOMnjvJcAu7gMHDogPg.jpg", "period":"Southern Baroque", "id":33}, { "name":"Christ Delivering the Keys of the Kingdon to St Peter", "artist":"Perugino", "year":1481, "loc":"south", "pos":30, "img":"https://o.quizlet.com/kdCXvUm-o8Z6XzlLeTpD1w.jpg", "period":"Early Renaissance", "id":34}, { "name":"The Expulsion of Adam and eve", "artist":"Masaccio", "year":1427, "loc":"south", "pos":65, "img":"https://farm3.staticflickr.com/2313/2236991826_01eecb571e.jpg", "period":"Early Renaissance", "id":35}, { "name":"Ghent Alterpiece (Adam and Eve)", "artist":"Jan van Eyck", "year":1432, "loc":"north", "pos":80, "img":"https://o.quizlet.com/i/IyIToh26EEHz4MQj0hVn1A.jpg", "period":"15 Cen North Renaissance", "id":36}, { "name":"Pesaro Madonna", "artist":"Titian", "year":1520, "loc":"south", "pos":95, "img":"https://o.quizlet.com/e41UokIDjj2Qn76jSLS5YA.jpg", "period":"Venetian Renaissance", "id":37}, { "name":"Deposition", "artist":"Pontormo", "year":1525, "loc":"south", "pos":60, "img":"https://o.quizlet.com/RpQwBI0Dp6vyARgZs24Mww.jpg", "period":"Mannerism", "id":38}, { "name":"The Tempest", "artist":"Giorgione", "year":1506, "loc":"south", "pos":92, "img":"https://o.quizlet.com/uVZR2.kZDm0Y-BTnMnzbQA.jpg", "period":"Venetian Renaissance", "id":39}, { "name":"View of Haarlem from the Dunes at Overveen", "artist":"Ruisdael", "year":1670, "loc":"north", "pos":60, "img":"https://o.quizlet.com/i/TH_CEIZwCTw3wCAvMExOBA.jpg", "period":"Northern Baroque", "id":40}, { "name":"Giovanni Arnolfini and his Bride", "artist":"Jan van Eyck", "year":1434, "loc":"north", "pos":73, "img":"https://o.quizlet.com/7zJsAHpJX7KGMgPuj-e9jQ.jpg", "period":"15 Cen North Renaissance", "id":41}, { "name":"Holy Trinity", "artist":"Masaccio", "year":1428, "loc":"south", "pos":70, "img":"https://farm9.staticflickr.com/8048/8087573267_111816b7f2.jpg", "period":"Early Renaissance", "id":42}, { "name":"Bacchus", "artist":"Caravaggio", "year":1595, "loc":"south", "pos":60, "img":"https://o.quizlet.com/i/9CZ-Lk7AtpjvslJ6j29hYg.jpg", "period":"Southern Baroque", "id":43}, { "name":"Triumph of Bacchus", "artist":"Caracci", "year":1600, "loc":"south", "pos":30, "img":"https://o.quizlet.com/3Vfcw.0i8az4RHdH6dKqPQ.jpg", "period":"Southern Baroque", "id":44}, { "name":"Saint Serapion", "artist":"Zurbaran", "year":1628, "loc":"south", "pos":63, "img":"https://o.quizlet.com/i/TmFJGMblQvFZAGIglIzJ8w.jpg", "period":"Southern Baroque", "id":45}, { "name":"Elevation of the Cross", "artist":"Rubens", "year":1610, "loc":"north", "pos":50, "img":"https://o.quizlet.com/i/sgB7SKqS15aXFivmVHuUzg.jpg", "period":"Northern Baroque", "id":46}, { "name":"Return of the Prodigal Son", "artist":"Rembrant van Rijn", "year":1665, "loc":"north", "pos":40, "img":"https://o.quizlet.com/LURL4OsfWKMd0GL9iv2CkQ.jpg", "period":"Northern Baroque", "id":47}]
import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; export default class ReadStoryScreen extends React.Component { render() { return ( <View> <Text style={styles.head}>STORY HUB</Text> <Text style={styles.displayText}>Read Story</Text> </View> ); } } const styles = StyleSheet.create({ head: { marginTop: 0, textAlign: 'center', backgroundColor: 'rgb(63, 86, 154)', color: 'white', fontSize: 30, height: 40, fontWeight: 'bold', }, displayText:{ alignSelf:'center', marginTop:100, fontSize:20 } });
class Refund { constructor(instance, data) { Object.assign(this, data, { _instance: instance }); } reload() { return this._instance.getRefund(this.id) .then(data => { Object.assign(this, data); return true; }); } } module.exports = Refund;
$(document).ready(async () => { let csrfToken = $('#csrf_token').val() let myMessageTemplate = await $.get('TemplatesHbs/myMessage.hbs') let yourMessageTemplate = await $.get('TemplatesHbs/yourMessage.hbs') let friendTemplate = await $.get('TemplatesHbs/friendTemplate.hbs') // sendMessage(csrfToken, myMessageTemplate) changeCurrentFriends(csrfToken, myMessageTemplate, yourMessageTemplate) // getMessages(csrfToken, myMessageTemplate, yourMessageTemplate, friendTemplate) searchInFriends(friendTemplate, csrfToken, myMessageTemplate, yourMessageTemplate) }) // function sendMessage(csrfToken, myMessage) { // $('.send_message_button').on('click', function () { // let acceptUser = $('.message_text').attr('acceptUser') // let content = $('.send_message').val() // // if ( content !== '' ) { // let data = { // 'csrfToken': csrfToken, // 'acceptUser': acceptUser, // 'content': content // } // // $.ajax({ // url: 'api/sendMessage', // type: 'POST', // data: JSON.stringify(data), // headers: { // 'Content-Type': 'application/json' // } // }).then(() => { // $('.be_first_to_message').empty() // // let obj = { // 'content': content // } // let template = Handlebars.compile(myMessage) // let html = template(obj) // $('.message_text .real_text_message_container').append(html) // // let scrollHeight = $('.message_container .message_text')[0].scrollHeight // $('.message_text').animate({scrollTop: scrollHeight}) // $('.send_message').val('') // // }).catch((err) => { // // }) // } // }) // } function changeCurrentFriends(csrfToken, myMessage, yourMessage) { let xhr = new XMLHttpRequest() $('.friend_id').on('click', function () { $('.spinner').css('display', 'none') sessionStorage.setItem('haveMore', 'false') let currentUser = $('.current_user').attr('acceptUser') let id = $(this).attr('id') let data = null if (currentUser === id) { return } $('.message_container .message_text .real_text_message_container').empty() let img = $(this).children('img').attr('src') let names = $(this).children('.full_name').text() $('.message_container .current_user img').attr('src', img) $('.message_container .current_user h3').text(names) $('.message_container .current_user').attr('acceptUser', id) $('.message_container .message_text').attr('acceptUser', id) $('.message_container .message_text .sk-circle').css('display', 'block') $('aside #' + id + ' .current_user_count_message span').text('0') $('aside #' + id + ' .current_user_count_message').css('display', 'none') $('aside #' + id + ' .search_friends_container .current_user_count_message').css('display', 'none') xhr.open('GET', 'api/getMessagesBetweenUsers/' + id + '/' + csrfToken) xhr.send() xhr.onload = function () { if ( xhr.status === 200 ) { data = JSON.parse(xhr.responseText) renderMessagesWithUser(data, csrfToken, myMessage, yourMessage) } } }) } function renderMessagesWithUser(res, csrfToken, myMessage, yourMessage) { let realData = JSON.parse(res) let myId = realData['userId'] let data = realData['responce'] if (data === 'none') { $('.message_container .message_text .real_text_message_container').empty() $('.message_container .message_text .sk-circle').css('display', 'none') $('.message_container .message_text .real_text_message_container').append("<p class='be_first_to_message'>Be first to write something!!!</p>") $('.message_container .div_send_message').css('display', 'block') return } for (let i = 0; i < data.length; i++) { $('.message_container .message_text .sk-circle').css('display', 'none') $('.message_container .div_send_message').css('display', 'block') if (i < 20) { if (data[i]['sendUserId'] === myId) { let template = Handlebars.compile(myMessage) let html = template(data[i]) $('.message_container .message_text .real_text_message_container').prepend(html) } else { let template = Handlebars.compile(yourMessage) let html = template(data[i]) $('.message_container .message_text .real_text_message_container').prepend(html) } } else { onScrollTop(csrfToken, myMessage, yourMessage) } } let scrollHeight = $('.message_container .message_text')[0].scrollHeight $('.message_text').animate({scrollTop: scrollHeight}) } function onScrollTop(csrfToken, myMessage, yourMessage) { sessionStorage.setItem('list', '1') sessionStorage.setItem('haveMore', 'true') let scrollHeight = $('.message_container .message_text')[0].scrollHeight let xhr = new XMLHttpRequest() if (scrollHeight > 430) { $('.message_container .message_text').scroll(function () { if ( sessionStorage.getItem('haveMore') === 'true' ) { let currentUser = $('.current_user').attr('acceptUser') let scrollTop = $(this).scrollTop() if (scrollTop === 0) { sessionStorage.setItem('haveMore', 'false') $('.spinner').css('display', 'block') xhr.open('GET', 'api/getMoreMessages/' + csrfToken + '/' + currentUser + '/' + Number(sessionStorage.getItem('list'))) xhr.send() xhr.onload = function () { if (xhr.status === 200) { showMoreOnScroll(JSON.parse(xhr.responseText), myMessage, yourMessage) } } } } }) } } function showMoreOnScroll(res, myMessage, yourMessage) { let realData = JSON.parse(res) if ( $('.current_user').attr('acceptUser') === realData['otherUser'] ) { let data = realData['messages'] let currentId = realData['currentId'] sessionStorage.setItem('list', Number(sessionStorage.getItem('list')) + 1) $('.spinner').css('display', 'none') sessionStorage.setItem('haveMore', 'false') for (let i = 0; i < data.length; i++) { if (i < 20) { if (data[i]['sendUserId'] === currentId) { let template = Handlebars.compile(myMessage) let html = template(data[i]) $('.message_container .message_text .real_text_message_container').prepend(html) } else { let template = Handlebars.compile(yourMessage) let html = template(data[i]) $('.message_container .message_text .real_text_message_container').prepend(html) } } else { sessionStorage.setItem('haveMore', 'true') } } } } // function getMessages(csrfToken, myMessage, yourMessage, friendTemplate) { // let audio = new Audio('sounds/musical_keyboard_key_flick_spring_up.mp3') // setInterval(function () { // let currentUser = $('.current_user').attr('acceptUser') // // if ( currentUser === undefined ) { // currentUser = 'undefined' // } // // $.ajax({ // url: 'api/getMessageData/' + csrfToken + '/' + currentUser, // type: 'GET', // }).then((res) => { // let realData = JSON.parse(res) // let currentUser = $('.current_user').attr('acceptUser') // let data = realData['data'] // // if ( data.length > 0 ) { // audio.play() // for (let msg of data) { // if ( msg['sendUserId'] == currentUser ) { // let template = Handlebars.compile(yourMessage) // let html = template(msg) // $('.message_container .message_text .real_text_message_container').append(html) // let scrollHeight = $('.message_container .message_text')[0].scrollHeight // $('.message_text').animate({scrollTop: scrollHeight}) // }else { // let id = msg['sendUserId'] // $('aside #' + id + ' .current_user_count_message').css('display', 'block') // let currentMsg = $('aside .friends_container #' + id + ' .current_user_count_message span').text() // if ( currentMsg !== '' ) { // let obj = { // 'id': id, // 'image': $('aside .friends_container #' + id + ' img').attr('src'), // 'fullName': $('aside .friends_container #' + id + ' .full_name').text(), // 'countMsg': Number(currentMsg) + 1 // } // $('aside #' + id).remove() // // let template = Handlebars.compile(friendTemplate) // let html = template(obj) // $('aside .friends_container').prepend(html) // }else { // let obj = { // 'id': id, // 'image': $('aside .friends_container #' + id + ' img').attr('src'), // 'fullName': $('aside .friends_container #' + id + ' .full_name').text(), // 'countMsg': 1 // } // $('aside #' + id).remove() // // let template = Handlebars.compile(friendTemplate) // let html = template(obj) // $('aside .friends_container').prepend(html) // } // } // } // } // changeCurrentFriends(csrfToken, myMessage, yourMessage) // }) // }, 5000) // } function searchInFriends(friendTemplate, csrfToken, myMessage, yourMessage) { $('aside .search_friends .search_friends_input').on('input', function () { let arr = [] let val = $(this).val() for (let text of $('.friends_container .friend_id').toArray()) { let obj = {} let id = $(text).attr('id') let image = $(text).children('img').attr('src') let fullName = $(text).children('.full_name').text() let countMsg = null if ( $(text).children('.current_user_count_message').text() !== '' ) { countMsg = $(text).children('.current_user_count_message').text() }else { countMsg = '' } obj['id'] = id obj['fullName'] = fullName obj['image'] = image obj['countMsg'] = countMsg arr.push(obj) } if ( val !== '' ) { $('.search_friends_container').css('display', 'block') $('.friends_container').css('display', 'none') $('.search_friends_container').empty() for ( let obj of arr ) { if ( obj['fullName'].includes(val) ) { let template = Handlebars.compile(friendTemplate) let html = template(obj) $('.search_friends_container').append(html) } } }else { $('.friends_container').css('display', 'block') $('.search_friends_container').css('display', 'none') } changeCurrentFriends(csrfToken, myMessage, yourMessage) }) }
var searchData= [ ['children',['children',['../classTrieNode.html#a69ae75c32241f3f6b49f3aad6e6fb6f2',1,'TrieNode']]] ];
import { makeStyles } from '@material-ui/core' const useStyles = makeStyles({ profilePicture: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }, avatar: { backgroundColor: 'white', borderRadius: '30%', marginBottom: '10px', marginTop: '15px', padding: 5, width: 60, height: 60 }, media: { width: 110, height: 110, position: 'absolute', top: '-40px', left: '50%', transform: 'translate(-50%)' }, delivery: { width: '60%', display: 'flex', margin: '0 auto', paddingTop: 50, marginTop: 40, borderRadius: 25, color: '#30334E', position: 'relative', overflow: 'visible', boxShadow: 'none' } }) export default useStyles
import { combineReducers } from 'redux' import { reducer as formReducer } from 'redux-form' import authReducer from './AuthReducer' import invoicesReducer from './InvoicesReducer' import customersReducer from './CustomersReducer' import notificationsReducer from './NotificationsReducer' import settingsReducer from './settingsReducer' const rootReducer = combineReducers({ auth: authReducer, invoicing: invoicesReducer, customers: customersReducer, form: formReducer, notifications: notificationsReducer, settings: settingsReducer }) export default rootReducer
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withGoogleMap, GoogleMap, Marker, Polyline } from 'react-google-maps'; import '../styles/homeContainer.css'; import { Icon } from 'semantic-ui-react'; import busIcon from '../images/map/bus.png'; import trainIcon from '../images/map/train.png'; import walkIcon from '../images/map/walk.png' const google = window.google; const lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 }; const busSymbol ={ path: 'M -2,0 0,-2 2,0 0,2 z', strokeColor: '#F00', fillColor: '#F00', fillOpacity: 1 } class MapContainer extends Component { constructor(props) { super(props); this.state = { map: null, bounds: null, } // this.handleBoundsChanged = this.handleBoundsChanged.bind(this); } // handleBoundsChanged() { // this.setState({ // bounds: this.state.map.getBounds(), // // center: this.state.map.getCenter(), // }); // } // componentDidMount() { // console.log("zoomMarets",) // this.setState({ // zoomToMarkers: map => { // const bounds = new window.google.maps.LatLngBounds(); // map.props.children.forEach((child) => { // if (child.type === Marker) { // bounds.extend(new window.google.maps.LatLng(child.props.position.lat, child.props.position.lng)); // } // }) // map.fitBounds(bounds); // } // }) // } // componentDidUpdate() { // console.log("aaaaaaaa",this.refs.resultMap) // const bounds = new window.google.maps.LatLngBounds() // this.props.startAndEndAddressPoint.map((result) => { // bounds.extend(new window.google.maps.LatLng( // result.lat, // result.lng // )); // }); // this.refs.resultMap.fitBounds(bounds) // } showWalkingLine(array, index) { // console.log("walking line", array) if (array) { let source; let destination; let srcDestArray =[]; if(this.props.pathLocations.nodes.length>0){ for(let i = 0; i < this.props.pathLocations.nodes.length; i++) { if(array.source===this.props.pathLocations.nodes[i]["id"]){ // source = this.props.pathLocations.nodes[i]["pos"]; source = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(source) } if(array.target===this.props.pathLocations.nodes[i]["id"]){ destination = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(destination) } } } return ( <div> <Polyline key={225+index} options={{// strokeOpacity: 0, icons: [{ icon: lineSymbol, offset: '0', repeat: '20px' }], }} path={srcDestArray}> </Polyline> </div> ) } else { return null } } showTaxiLine(array, index) { if (array) { let source; let destination; let srcDestArray =[]; if(this.props.pathLocations.nodes.length>0){ for(let i = 0; i < this.props.pathLocations.nodes.length; i++) { if(array.source===this.props.pathLocations.nodes[i]["id"]){ // source = this.props.pathLocations.nodes[i]["pos"]; source = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(source) } if(array.target===this.props.pathLocations.nodes[i]["id"]){ destination = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(destination) } } } return ( <Polyline key={221+index} options={{// strokeOpacity: 1.0, strokeWeight: 5, visible: true, strokeColor: 'red' }} path={srcDestArray}> </Polyline> ) } else return null; } showBusLine(array, index) { if (array) { let source; let destination; let srcDestArray =[]; if(this.props.pathLocations.nodes.length>0){ for(let i = 0; i < this.props.pathLocations.nodes.length; i++) { if(array.source===this.props.pathLocations.nodes[i]["id"]){ // source = this.props.pathLocations.nodes[i]["pos"]; source = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(source) } if(array.target===this.props.pathLocations.nodes[i]["id"]){ destination = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(destination) } } } return ( <Polyline key={220+index} options={{// strokeOpacity: 1.0, strokeWeight: 5, visible: true, strokeColor: 'green' }} path={srcDestArray}> </Polyline> ) } else return null; } showAutoLine(array, index) { if (array) { let source; let destination; let srcDestArray =[]; if(this.props.pathLocations.nodes.length>0){ for(let i = 0; i < this.props.pathLocations.nodes.length; i++) { if(array.source===this.props.pathLocations.nodes[i]["id"]){ // source = this.props.pathLocations.nodes[i]["pos"]; source = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(source) } if(array.target===this.props.pathLocations.nodes[i]["id"]){ destination = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(destination) } } } return ( <Polyline key={227+index} options={{// strokeOpacity: 1.0, strokeWeight: 5, visible: true, strokeColor: 'yellow' }} path={srcDestArray}> </Polyline> ) } else return null; } showMetroLine(array, index) { if (array) { let source; let destination; let srcDestArray =[]; if(this.props.pathLocations.nodes.length>0){ for(let i = 0; i < this.props.pathLocations.nodes.length; i++) { if(array.source===this.props.pathLocations.nodes[i]["id"]){ // source = this.props.pathLocations.nodes[i]["pos"]; source = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(source) } if(array.target===this.props.pathLocations.nodes[i]["id"]){ destination = { lat: parseFloat(this.props.pathLocations.nodes[i]["pos"][1]), lng: parseFloat(this.props.pathLocations.nodes[i]["pos"][0]) } srcDestArray.push(destination) } } } return ( <Polyline key={226+index} options={{// strokeOpacity: 1.0, strokeWeight: 5, visible: true, strokeColor: 'blue' }} path={srcDestArray}> </Polyline> ) } else return null; } showTotalPathPolyline(){ if( this.props.pathLocations.links){ if(this.props.pathLocations.links.length > 0) { return this.props.pathLocations.links.map((path, singleIndex) => { // console.log(path, singleIndex); return Object.keys(path).map((key,index1)=>{ if (path[key] === "feet") { // console.log("feet", index1) return this.showWalkingLine(path, index1); } if (path[key] === "taxi") { // console.log("taxi",path[key], index1) return this.showTaxiLine(path, index1); } if (path[key]=== "auto") { return this.showAutoLine(path, index1); } if (path[key] === "bus") { return this.showBusLine(path, index1); } if (path[key] === "metro") { return this.showMetroLine(path, index1); } }) }) // return this.props.pathLocations.map((singlePathArray, index) => { // console.log(singlePathArray, index); // return singlePathArray.map((path, singleIndex) => { // console.log(path, singleIndex); // return Object.keys(path).map((key,index1)=>{ // if (key === "walk") { // console.log(path[key], index1) // return this.showWalkingLine(path[key], index1); // } // if (key === "taxi") { // console.log("taxi",path[key], index1) // return this.showTaxiLine(path[key], index1); // } // if (key === "auto") { // return this.showAutoLine(path[key], index1); // } // if (key === "bus") { // return this.showBusLine(path[key], index1); // } // if (key === "metro") { // return this.showMetroLine(path[key], index1); // } // }) // }) // }) } } } getAllMarkers(){ if( this.props.pathLocations.nodes){ if( this.props.pathLocations.nodes.length > 0){ let icon = ''; return this.props.pathLocations.nodes.map((place, index) => { if(this.props.pathLocations.links){ if(this.props.pathLocations.links.length > 0){ for(let i=0; i<this.props.pathLocations.links.length;i++ ) { if(place.id===this.props.pathLocations.links[i].source ) { icon = ''; if(this.props.pathLocations.links[i].type==="bus") { icon = busIcon; } if(this.props.pathLocations.links[i].type==="feet") { icon = walkIcon; } if(this.props.pathLocations.links[i].type==="metro") { icon = trainIcon } } } } } return ( <Marker position={{ lat: parseFloat(place["pos"][1]), lng: parseFloat(place["pos"][0]) }} animation={google.maps.Animation.DROP} title={place["id"]} key={1+index} icon={icon} //onClick={this.markerClicked.bind(this, place)} /> ) } )} } } showStartEndMarkers() { if (this.props.startPointAddress.lat) { // this.state.bounds.extend({lat:18, lng:75}) // this.state.map.fitBounds( this.state.bounds); return ( <div> <Marker position={{ lat: this.props.startPointAddress.lat, lng: this.props.startPointAddress.lng }} animation={google.maps.Animation.DROP} title={"Start Point"} key={1} icon={{ url: "https://maps.google.com/mapfiles/ms/icons/red-dot.png", strokeColor: "red", scale: 3 }} //onClick={this.markerClicked.bind(this, location.deviceID)} /> <Marker position={{ lat: this.props.endPointAddress.lat, lng: this.props.endPointAddress.lng }} animation={google.maps.Animation.DROP} title={"End Point"} key={2} icon={{ url: "https://maps.google.com/mapfiles/ms/icons/yellow-dot.png", strokeColor: "yellow", scale: 3 }} //onClick={this.markerClicked.bind(this, location.deviceID)} /> </div> ) } else { return null } } mapLoaded(map) { if (this.state.map != null) { return } this.setState({ map: map, }) } render() { return ( <div> <GoogleMap ref={this.mapLoaded(this)} defaultZoom={10} center={this.props.mapCenter} // onBoundsChanged={this.handleBoundsChanged} bounds={this.state.bounds} > {this.showStartEndMarkers()} {this.getAllMarkers()} {/* <Polyline key={225} options={{// strokeOpacity: 1.0, strokeWeight: 5, visible: true, strokeColor: 'green' }} path={this.props.pathLocations.walk}> </Polyline> */} {this.showTotalPathPolyline()} {/* {this.showWalkingLine()} {this.showTaxiLine()} */} </GoogleMap> </div> ); } } function mapStatesToProps(globalData) { // console.log( globalData.homeData); return { homeData: globalData.homeData, mapData: globalData.mapData, pathLocations: globalData.mapData.pathLocations, startPointAddress: globalData.homeData.startPointAddress, endPointAddress: globalData.homeData.endPointAddress, startAndEndAddressPoint: globalData.homeData.startAndEndAddressPoint, mapCenter: globalData.homeData.mapCenter }; } const myConnector = connect(mapStatesToProps); export default myConnector(withGoogleMap(MapContainer));
const ul = document.querySelector(".items"); //REMOVING LIST --------------------------- //ul.remove(); ----REMOVE list //ul.lastElementChild.remove(); ---- REMOVE last child //ul.firstElementChild.remove(); --- REMOVE first child //ul.children[1].remove(); --------- REMOVE your desired item. //CHANGE VALUE OF ITEMS //ul.firstElementChild.textContent ="Hello"; //ul.children[1].innerText = "makeiteasy"; //ul.lastElementChild.textContent ="world";
const requelize = require('sequelize'); const models = require('./models'); models.sequelize.sync().then(() => { console.log('connected to database'); // eslint-disable-line no-console }).catch((err) => { console.log(err); // eslint-disable-line no-console });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Pagination from 'General/Pagination'; import Card from '../../Card'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' class SearchPage extends Component { constructor(props) { super(props); this.state = { pageOfItems: [] } this.onPageChange = this.onPageChange.bind(this); } onPageChange(pageOfItems) { // update state with new page of items this.setState({ pageOfItems: pageOfItems }); } render() { const { books } = this.props return ( <div> <div className="container"> <div className="text-center"> <h1>Search results</h1> { this.state.pageOfItems.map(item => <MuiThemeProvider> <Card book = { item }/> </MuiThemeProvider> )} <Pagination items={ books } onPageChange={this.onPageChange} /> </div> </div> <hr /> <div className="credits text-center"> <p> {`${books.length >= 1 ? books.length : 'No'} books found`} </p> </div> </div> ); } } const mapStateToProps = (state) => ({ books: state.books['books'] }); export { SearchPage } export default connect(mapStateToProps)(SearchPage)
const express = require('express') const router = express.Router() const wrap = require('co-express') router.use('/test', require('./api_test')) router.use('/jobs', require('./api_jobs')) router.use('/sunspots', require('./api_sunspots')) router.get('/status', wrap(function *(req, res) { return res.json({ success: true }) })) module.exports = router
/** * @fileoverview default-export-name = default-import-name = filename * @author minseoksuh */ 'use strict'; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const defaultExportMatchFilename = require('./rules/default-export-match-filename'); const defaultImportMatchFilename = require('./rules/default-import-match-filename'); module.exports = { configs: { fixed: { plugins: ['consistent-default-export-name'], env: { browser: true, es6: true, node: true, }, rules: { 'consistent-default-export-name/default-export-match-filename': 'error', 'consistent-default-export-name/default-import-match-filename': 'error', }, }, }, rules: { 'default-export-match-filename': defaultExportMatchFilename, 'default-import-match-filename': defaultImportMatchFilename, }, };
import localforage from 'localforage' import dayjs from 'dayjs' import { removeTrnToAddLaterLocal, saveTrnToAddLaterLocal, saveTrnIDforDeleteWhenClientOnline, removeTrnToDeleteLaterLocal } from './helpers' import useCalculator from '~/components/trnForm/calculator/useCalculator' import { db } from '~/services/firebaseConfig' export default { /** * Create new trn * and save it to local storage when Client offline * * @param {object} * @param {string} {}.id * @param {object} {}.values * @param {string} {}.values.amount * @param {string} {}.values.category */ addTrn ({ commit, rootState }, { id, values }) { const uid = rootState.user.user.uid const trns = rootState.trns.items const valuesWithEditDate = { ...values, edited: dayjs().valueOf() } let isTrnSavedOnline = false localforage.setItem('finapp.trns', { ...trns, [id]: valuesWithEditDate }) commit('setTrns', Object.freeze({ ...trns, [id]: valuesWithEditDate })) db.ref(`users/${uid}/trns/${id}`) .set(valuesWithEditDate) .then(() => { isTrnSavedOnline = true removeTrnToAddLaterLocal(id) }) setTimeout(() => { if (!isTrnSavedOnline) saveTrnToAddLaterLocal({ id, values }) }, 1000) const { clearExpression } = useCalculator() clearExpression() commit('trnForm/setTrnFormValues', { trnId: null, amount: '0', description: null }, { root: true }) return true }, // delete deleteTrn ({ commit, rootState }, id) { const uid = rootState.user.user.uid const trns = { ...rootState.trns.items } delete trns[id] commit('setTrns', Object.freeze(trns)) localforage.setItem('finapp.trns', trns) saveTrnIDforDeleteWhenClientOnline(id) db.ref(`users/${uid}/trns/${id}`) .remove() .then(() => removeTrnToDeleteLaterLocal(id)) }, async deleteTrnsByIds ({ rootState }, trnsIds) { const uid = rootState.user.user.uid const trnsForDelete = {} for (const trnId of trnsIds) trnsForDelete[trnId] = null await db.ref(`users/${uid}/trns`) .update(trnsForDelete) // .then(() => console.log('trns deleted')) }, // init async initTrns ({ rootState, dispatch, commit }) { const uid = rootState.user.user.uid await db.ref(`users/${uid}/trns`).on('value', (snapshot) => { const items = Object.freeze(snapshot.val()) if (items) { for (const trnId of Object.keys(items)) { if (!items[trnId].walletId || items[trnId].accountId) { commit('app/setAppStatus', 'loading', { root: true }) const trn = items[trnId] db.ref(`users/${uid}/trns/${trnId}`) .set({ amount: trn.amount, categoryId: trn.categoryId, date: Number(trn.date), description: trn.description || null, edited: dayjs().valueOf(), groups: trn.groups || null, type: Number(trn.type), walletId: trn.accountId || trn.walletId }) } } } dispatch('setTrns', items) }, e => console.error(e)) }, setTrns ({ commit }, items) { commit('setTrns', items) localforage.setItem('finapp.trns', items) }, unsubcribeTrns ({ rootState }) { const uid = rootState.user.user.uid db.ref(`users/${uid}/trns`).off() }, /** * Add and delete trns with had been created in offline mode * * When user online * get trns from local storage * and add them to database */ uploadOfflineTrns ({ dispatch, rootState }) { db.ref('.info/connected').on('value', async (snap) => { const isConnected = snap.val() if (isConnected) { const trnsArrayForDelete = await localforage.getItem('finapp.trns.offline.delete') || [] const trnsItemsForUpdate = await localforage.getItem('finapp.trns.offline.update') || {} // delete trns for (const trnId of trnsArrayForDelete) { dispatch('deleteTrn', trnId) delete trnsItemsForUpdate[trnId] } await localforage.setItem('finapp.trns.offline.update', trnsItemsForUpdate) // add trns for (const trnId in trnsItemsForUpdate) { const wallet = rootState.wallets.items[trnsItemsForUpdate[trnId].walletId] const category = rootState.categories.items[trnsItemsForUpdate[trnId].categoryId] // delete trn from local storage if no wallet or category if (!wallet || !category) { delete trnsItemsForUpdate[trnId] await localforage.setItem('finapp.trns.offline.update', trnsItemsForUpdate) } // add else if (trnsItemsForUpdate[trnId] && trnsItemsForUpdate[trnId].amount) { console.log('update', trnId, trnsItemsForUpdate[trnId]) dispatch('addTrn', { id: trnId, values: trnsItemsForUpdate[trnId] }) } } } }) } }
/** * @requires javelin-install * javelin-dom * javelin-vector * javelin-request * javelin-uri * @provides phui-hovercard * @javelin */ JX.install('Hovercard', { statics : { _node : null, _activeRoot : null, _visiblePHID : null, _alignment: null, fetchUrl : '/search/hovercard/', /** * Hovercard storage. {"PHID-XXXX-YYYY":"<...>", ...} */ _cards : {}, getAnchor : function() { return this._activeRoot; }, getCard : function() { var self = JX.Hovercard; return self._node; }, getAlignment: function() { var self = JX.Hovercard; return self._alignment; }, show : function(root, phid) { var self = JX.Hovercard; if (root === this._activeRoot) { return; } self.hide(); self._visiblePHID = phid; self._activeRoot = root; if (!(phid in self._cards)) { self._load([phid]); } else { self._drawCard(phid); } }, _drawCard : function(phid) { var self = JX.Hovercard; // card is loading... if (self._cards[phid] === true) { return; } // Not the current requested card if (phid != self._visiblePHID) { return; } // Not loaded if (!(phid in self._cards)) { return; } var root = self._activeRoot; var node = JX.$N('div', { className: 'jx-hovercard-container' }, JX.$H(self._cards[phid])); self._node = node; // Append the card to the document, but offscreen, so we can measure it. node.style.left = '-10000px'; document.body.appendChild(node); // Retrieve size from child (wrapper), since node gives wrong dimensions? var child = node.firstChild; var p = JX.$V(root); var d = JX.Vector.getDim(root); var n = JX.Vector.getDim(child); var v = JX.Vector.getViewport(); var s = JX.Vector.getScroll(); // Move the tip so it's nicely aligned. var margin = 20; // Try to align the card directly above the link, with left borders // touching. var x = p.x; // If this would push us off the right side of the viewport, push things // back to the left. if ((x + n.x + margin) > (s.x + v.x)) { x = (s.x + v.x) - n.x - margin; } // Try to put the card above the link. var y = p.y - n.y - margin; self._alignment = 'north'; // If the card is near the top of the window, show it beneath the // link we're hovering over instead. if ((y - margin) < s.y) { y = p.y + d.y + margin; self._alignment = 'south'; } node.style.left = x + 'px'; node.style.top = y + 'px'; }, hide : function() { var self = JX.Hovercard; self._visiblePHID = null; self._activeRoot = null; if (self._node) { JX.DOM.remove(self._node); self._node = null; } }, /** * Pass it an array of phids to load them into storage * * @param list phids */ _load : function(phids) { var self = JX.Hovercard; var uri = JX.$U(self.fetchUrl); var send = false; for (var ii = 0; ii < phids.length; ii++) { var phid = phids[ii]; if (phid in self._cards) { continue; } self._cards[phid] = true; // means "loading" uri.setQueryParam('phids['+ii+']', phids[ii]); send = true; } if (!send) { // already loaded / loading everything! return; } new JX.Request(uri, function(r) { for (var phid in r.cards) { self._cards[phid] = r.cards[phid]; // Don't draw if the user is faster than the browser // Only draw if the user is still requesting the original card if (self.getCard() && phid != self._visiblePHID) { continue; } self._drawCard(phid); } }).send(); } } });
import React from 'react'; import {connect} from "react-redux"; import * as actionCreators from "../actions/index.js"; import axios from 'axios'; import socketIOClient from 'socket.io-client'; import './main-page.css'; import User from '../components/users-box/user.js'; import ChatApp from './chat-app/chat-app.js'; class MainPage extends React.Component{ constructor(props) { super(props); this.state = { users: [], messages: '', socket: socketIOClient("https://mysterious-sands-35555.herokuapp.com/"), currentUser: '' } this.state.socket.on('server-user', user => { console.log('user added'); let users = this.state.users; users.push(user); this.setState({users: users}); }); } changeFreindMessages = (frientId) => { this.props.fetchMessages(frientId); } componentDidMount(){ let url = "https://mysterious-sands-35555.herokuapp.com/users"; axios.get(url) .then((res)=>{ let users = res.data; this.setState({users: res.data}); }) .catch(err => console.log(err)); } render(){ let users = this.state.users; console.log(users); let user = <User />; if(users && users!==''){ if(users){ user = users.map( user => ( <User key={user.userId} userName={user.idName} friendId={user.userId} pictureUrl = {user.pictureUrl} onclick={this.changeFreindMessages} /> ) ) } } let friendId = this.state.users[0]; if(friendId){ console.log(friendId.userId); this.props.fetchMessages(friendId.userId); } return( <div id="line-chat-page"> <div id="users-list"> <div> <div id="users-header"> <h2 style={{border:'1px solid black'}}> Friends List </h2> </div> <div id="list"> {user} </div> </div> <div id="qrcode"> <div style={{"margin-left": "10px"}}> <img src="https://qr-official.line.me/M/VsOqSRhAuH.png" /> </div> <div style={{"margin-left": "10px"}}> <small> Scan this QR code for Friendship </small></div> </div> </div> <div id="chat-app"> <ChatApp socket={this.state.socket} /> </div> </div> ) } } export default connect( null , actionCreators )(MainPage);
const formatter = require('../../tools') const classgradeRepository = require('../repositories/classgradeRepository') exports.listClassgrade = function(req, res) { classgradeRepository.listClassgrade(result=>{ var resdata = {} if (result.length != 0) { resdata.code = 200 resdata.success = true resdata.data = result res.json(resdata) } }) } exports.readClassgrade = function(req, res) { classgradeRepository.readClassgrade(req.params.classID,result=>{ var resdata = {} if (result.length != 0) { resdata.code = 200 resdata.success = true resdata.data = result res.json(resdata) } }) }
(function () { 'use strict'; var controllerId = 'boostersim'; angular.module('app').controller(controllerId, ['common', 'datacontext', 'localStorageService', boostersim]); function boostersim(common, datacontext, localStorageService) { var getLogFn = common.logger.getLogFn; var log = getLogFn(controllerId); var logError = common.logger.getLogFn(controllerId, 'error'); var vm = this; vm.title = 'Booster Simulator'; vm.column1Title = "Image"; vm.column2Title = "Name"; vm.column3Title = "Rarity"; vm.boosters_to_open_ktk = localStorageService.getBoosterSim_numBoosters_setOne() || 0; vm.boosters_to_open_frf = localStorageService.getBoosterSim_numBoosters_setTwo() || 3; vm.boosters_to_open_dtk = localStorageService.getBoosterSim_numBoosters_setThree() || 0; vm.boosters_to_open_core = localStorageService.getBoosterSim_numBoosters_setZero() || 0; vm.boosters_to_open_ths = 0; vm.boosters_to_open_bng = 0; vm.boosters_to_open_jou = 0; vm.cards = []; function storeValues() { localStorageService.setBoosterSim_numBoosters_setZero(vm.boosters_to_open_core); localStorageService.setBoosterSim_numBoosters_setOne(vm.boosters_to_open_ktk); localStorageService.setBoosterSim_numBoosters_setTwo(vm.boosters_to_open_frf); localStorageService.setBoosterSim_numBoosters_setThree(vm.boosters_to_open_dtk); } function validateEntries() { if (vm.boosters_to_open_core == null || vm.boosters_to_open_ths == null || vm.boosters_to_open_bng == null || vm.boosters_to_open_jou == null || vm.boosters_to_open_ktk == null || vm.boosters_to_open_frf == null || vm.boosters_to_open_dtk == null) { logError("Please use a number for the amount of boosters."); return false; } return true; } vm.openBoosters = function() { if (!validateEntries()) { return false; } storeValues(); return datacontext.openMixtureOfSortedBoosters( parseInt(vm.boosters_to_open_ths), parseInt(vm.boosters_to_open_bng), parseInt(vm.boosters_to_open_jou), parseInt(vm.boosters_to_open_core), parseInt(vm.boosters_to_open_ktk), parseInt(vm.boosters_to_open_frf), parseInt(vm.boosters_to_open_dtk) ).then(function (data) { vm.cards = []; log("Opening booster packs..."); vm.cards.push.apply(vm.cards, data.mythicCards); vm.cards.push.apply(vm.cards, data.rareCards); vm.cards.push.apply(vm.cards, data.uncommonCards); vm.cards.push.apply(vm.cards, data.commonCards); return vm.cards; }); } activate(); function activate() { common.activateController([], controllerId) .then(function () { }); } } })();
(function($){ /* ================================================== Lock Screen ================================================== */ // 記事編集画面かつステータスが公開のときに限定する if (mtappVars.screen_id == 'edit-entry' && mtappVars.status == 2) { // ロックスクリーン用のアイコンを挿入 $('body').append('<div id="mtapp-lock-screen"><i id="mtapp-lock-icon" class="fa fa-lock fa-5x"></i></div>'); // ロックアイコンに関する動作 $('#mtapp-lock-icon').on({ // マウスを乗せたら鍵が開いたアイコンにする mouseenter: function(){ $(this).toggleClass('fa-lock').toggleClass('fa-unlock'); }, // マウスを離したら鍵が開じたアイコンに戻す mouseleave: function(){ $(this).toggleClass('fa-lock').toggleClass('fa-unlock'); }, // クリックしたときの動作 click: function(){ // 簡易パスワードは「admin」 var password = 'admin'; // プロンプトに入力された値を変数に保存 var input = prompt('Type the password.'); // 入力された値によって動作を切り替える switch (input) { // パスワードと一致するとき、ロックスクリーンを非表示 case password: this.parentNode.style.display = 'none'; break; // キャンセルされたとき、何もしない case null: break; // 間違った値が入力されたとき、アラートを表示 default: this.parentNode.style.backgroundColor = '#F6BFBC'; alert('Invalid password.'); this.parentNode.removeAttribute('style'); } } }); } /* Lock Screen */ })(jQuery);
// // NOTES // !(function(){ // let counter = 0; // if(document.title === "Etalon - Notes"){ // function xhrRequest () { // const xhr = new XMLHttpRequest(); // xhr.open('POST', '/notes'); // xhr.send(); // xhr.onreadystatechange = ()=>{ // if(xhr.readyState === 4 && xhr.status === 200) { // if(!JSON.parse(xhr.response)[0]){ // xhrRequest(); // } // if(JSON.parse(xhr.response)[0].length >= 1) { // let body = JSON.parse(xhr.response)[0]; // console.log(JSON.parse(xhr.response)[0]) // for(let i = 0; i < body.length; i++ ) { // makeFigure(body[i]); // } // } else { // counter += 1; // xhrRequest(); // if(counter === 10) { // document.write('We failed to fetch the articles, please refresh the page') // } // } // } // } // } // xhrRequest(); // function makeFigure (obj) { // const parent = document.getElementById('articles'); // const figure = document.createElement('figure'); // const articleContainerOuter = document.createElement('article'); // const articleContainer = document.createElement('article'); // const h3 = document.createElement('h3'); // const h5 = document.createElement('h5'); // const h4 = document.createElement('h4'); // const a = document.createElement('a'); // const img = document.createElement('img'); // figure.className = 'notesFigure'; // articleContainerOuter.className = 'articleContainerOuter'; // articleContainer.className = 'container'; // h3.className = 'notesFigureH3'; // h5.className = 'notesFigureH5'; // h4.className = 'notesFigureH4'; // a.className = 'notesA'; // img.className = 'notesFigureImg'; // h3.textContent = obj.title; // // h5.textContent = obj.date; // h4.textContent = obj.body.substr(0, 100) + "...."; // a.href = '/article'; // a.textContent = 'Read more...'; // img.src = "img/susan-yin-647448-unsplash.jpg"; // img.alt = 'Image alt'; // articleContainerOuter.appendChild(articleContainer); // articleContainer.appendChild(h3); // articleContainer.appendChild(h5); // articleContainer.appendChild(h4); // articleContainer.appendChild(a); // articleContainerOuter.appendChild(img); // figure.appendChild(articleContainerOuter); // parent.appendChild(figure); // } // } // })();
'use strict'; const eventData = require('../../data/events/cobranza-citas'); const cobranza = async (req, res, next) => { try { const data = req.body; const eventlist = await eventData.cobranza(data); res.send(eventlist); } catch (error) { res.status(400).send(error.message); } } module.exports = { cobranza }
import React, { useEffect } from "react"; import { StripeProvider, Elements } from "react-stripe-elements"; import CheckoutForm from "./checkoutForm"; // import { products } from "./datas/products"; let product = { name: "Rubber Duck", desc: `Rubber ducks can lay as many eggs as the best chicken layers, and they are fun to watch with their antics in your backyard, your barnyard, or your pond.`, price: 9.99, img: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSqkN8wkHiAuT2FQ14AsJFgihZDzKmS6OHQ6eMiC63rW8CRDcbK", id: 100, }; const Checkout = ({ selectedProduct, history }) => { console.log(selectedProduct); useEffect(() => { window.scrollTo(0, 0); }); return ( <StripeProvider apiKey="pk_test_51HD8tWJN8jdrIll5wm8SHAwvqBYQiFq3coQmibqX9ILJANJWQAFFWUOU50gDVJNbI1n2ogjSJX1ZnRxvm3vRZRkt00zKH8RShf"> <Elements> <CheckoutForm product={product} history={history} /> </Elements> </StripeProvider> ); }; export default Checkout;
export const updateList = (list, item, idx) => { if (item === "remove") { return [...list.slice(0, idx), ...list.slice(idx + 1)]; } if (typeof idx === "number") { return [...list.slice(0, idx), item, ...list.slice(idx + 1)]; } return [...list, item]; };
import * as Victor from 'victor'; import { Random } from 'random-js' const rng = new Random(Random.browserCrypto); const getRandomPosition = (width, height) => { const PAD = 50; return new Victor( rng.integer(PAD, width - PAD), rng.integer(PAD, height - PAD) ); }; export const createRandomFood = ( worldWidth, worldHeight, radius ) => ({ id: rng.uuid4(), position: getRandomPosition(worldWidth, worldHeight), radius: radius, isEaten: false, });
 //=================================================== function LuuThongTinXe() { $('#KeyHangSanXuatXe').val($('#HangSanXuatXeKey').val()); $('#KeyLoaiXe').val($('#LoaiXeKey').val()); //Save //_______________________________________________ $.ajax({ type: "POST", datatype: "JSON", url: '/QuanLyXe/LuuThongTinXe', data: $('#formThongTinXe').serialize(), //---------------------------------- success: function (response) { if (response != null) { //XoaDuLieuForm(); $('#tableThongTinXe').DataTable().ajax.reload(); ShowMessage(response); }//End If else { $('#output').text(msg); } }, //---------------------------------- //complete: function () { //}, //---------------------------------- failure: function (message) { ShowMessageFailure(message); //$('#output').text(msg); }, //---------------------------------- //error: function (jqXhr, exception) { // ShowMessage(response); // //if (jqXhr.status != 0) ShowMessage(response); //alert('Thực hiện không thành công'); //} });//End ajax }//EndFunction //=================================================== function KhoiTaoCheckBoxThietBiTheoXe() { //--------------------------------------------------- var coWifi = true; if (String("@(Model.CoWifi)") == "False") { coWifi = false }; var coTivi = true; if (String("@(Model.CoTivi)") == "False") { coTivi = false }; var coCameraHanhTrinh = true; if (String("@(Model.CoCameraHanhTrinh)") == "False") { coCameraHanhTrinh = false }; $('#CoWifi').attr("checked", coWifi); $('#CoTivi').attr("checked", coTivi); $('#CoCameraHanhTrinh').attr("checked", coCameraHanhTrinh); $('#hdCoWifi').val(coWifi); $('#hdCoTivi').val(coTivi); $('#hdCoCameraHanhTrinh').val(coCameraHanhTrinh); //--------------------------------------------------- $('#CoWifi').change(function () { if (this.checked) { $(this).attr("checked", true); $('#hdCoWifi').attr("value", true); } else { $(this).attr("checked", false); $('#hdCoWifi').attr("value", false); } }); $('#CoTivi').change(function () { if (this.checked) { $(this).attr("checked", true); $('#hdCoTivi').attr("value", true); } else { $(this).attr("checked", false); $('#hdCoTivi').attr("value", false); } }); $('#CoCameraHanhTrinh').change(function () { if (this.checked) { $(this).attr("checked", true); $('#hdCoCameraHanhTrinh').attr("value", true); } else { $(this).attr("checked", false); $('#hdCoCameraHanhTrinh').attr("value", false); } }); }//EndFunction //=================================================== function KhoiTaoDuLieuComboBox() { //Load dữ liệu Danh Mục Hãng sảng xuất xe //_______________________________________________ $.ajax({ url: '/QuanLyXe/LayHangSanXuatXeChoSelect', dataType: "JSON", success: function (response) { $("#HangSanXuatXeKey").select2({ data: response , placeholder: "Chọn hãng sản xuất xe" , allowClear: true }); $("#HangSanXuatXeKey").val(null).trigger("change"); }, failure: function (msg) { } });//EndLoadDataForLoaiGheSelector //_______________________________________________ $("#LoaiXeKey").select2({ placeholder: "Chọn loại xe" }); //_______________________________________________ $('#HangSanXuatXeKey').change(function () { var id = $(this).val(); //Load dữ liệu Danh mục loai xe if (id != null) { var url = '/QuanLyXe/LayLoaiXeChoSelect'; $.getJSON(url, { hangSanXuatXeKey: id }, function (data) { $('#LoaiXeKey').empty(); $("#LoaiXeKey").select2({ data: data , placeholder: "Chọn loại xe" , allowClear: true }); $("#LoaiXeKey").val(null).trigger("change"); $('#LoaiXeKey').val($('#KeyLoaiXe').val()).change(); }); } }); }//EndFunction //=================================================== function CauHinhBangDuLieu() { var tableName = '#tableThongTinXe'; //_______________________________________________ var table = $(tableName).DataTable({ ajax: { url: '/QuanLyXe/LayThongTinXe', dataSrc: '' } , columns: [ { //Index Column. data: null, searchable: false , orderable: false , targets: 0 } , { className: 'details-control', orderable: false, data: null, defaultContent: '' //defaultContent: '<button class="btn btn-tini btn-primary btn-circle" type="button"><i class="glyphicon glyphicon-plus-sign"></i></button>' } , { data: 'XeKey', visible: false } , { data: 'HangSanXuatXeKey', visible: false } , { data: 'LoaiXeKey', visible: false } , { data: 'BangSoXe' } , { data: 'SoSan' } , { data: 'LoaiXe' } , { data: 'HangSanXuatXe' } , { data: 'NgayCapPhep' , render: function (data, type, full, meta) { if (full != null && full.NgayCapPhep != null) { return formatDateToString(full.NgayCapPhep, 'DD/MM/YYYY'); } return ''; }//EndRender } , { data: 'Mau' } , { data: 'GiaMua', render: $.fn.dataTable.render.number(',', '.', 0, '', ' VNĐ') } , { data: 'CoWifi' , render: function (data, type, full, meta) { if (full != null && full.CoWifi != null) { if (full.CoWifi) return "Có"; return "Không"; } return 'Không'; }//EndRender } , { data: 'CoTivi' , render: function (data, type, full, meta) { if (full != null && full.CoTivi != null) { if (full.CoTivi) return "Có"; return "Không"; } return 'Không'; }//EndRender } , { data: 'CoCameraHanhTrinh' , render: function (data, type, full, meta) { if (full != null && full.CoCameraHanhTrinh != null) { if (full.CoCameraHanhTrinh) return "Có"; return "Không"; } return 'Không'; }//EndRender } , { data: 'GhiChuThongTinXe' } , { //Button Edit data: null, defaultContent: '<a class="edit"><center><i class="glyphicon glyphicon-pencil" aria-hidden="true"></i></center></a>', orderable: false } , { //Button Delete data: null, defaultContent: '<a class="delete"><center><i class="glyphicon glyphicon-trash" aria-hidden="true"></i></center></a>', orderable: false } ]//EndColumns , order: [5, 'asc'] , language: { lengthMenu: 'Hiển thị _MENU_ dòng mỗi trang' , info: 'Hiển thị dòng _START_ đến dòng _END_ trên tổng số _TOTAL_ dòng' , infoEmpty: 'Hiển thị dòng _START_ đến dòng _END_ trên tổng số _TOTAL_ dòng' , zeroRecords: "Xin lỗi không có dữ liệu hiển thị" , search: 'Tìm kiếm' , decimal: "," , thousands: "." , paginate: { first: "Trang đầu", last: "Trang cuối", next: "Sau", previous: "Trước" } } }); //Index columns. //_______________________________________________ table.on('order.dt search.dt', function () { table.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) { cell.innerHTML = i + 1; }); }).draw(); //_______________________________________________ $(tableName+' tbody').on('click', 'tr', function () { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } }); //_______________________________________________ $(tableName).on('click', 'a.edit', function (e) { e.preventDefault(); var row = $(tableName).DataTable().data()[$(tableName).DataTable().row('.selected')[0][0]]; if (row != null) { $('#XeKey').val(row.XeKey); $(tableName).val(row.HangSanXuatXeKey).change(); //$('#LoaiXeKey').val(row.LoaiXeKey).change(); $('#KeyLoaiXe').val(row.LoaiXeKey); $('#BangSoXe').val(row.BangSoXe); $('#SoSan').val(row.SoSan); $('#Mau').val(row.Mau); var ngayCapPhep = eval(("new " + row.NgayCapPhep).replace(/\//g, "")); $('#NgayCapPhep').val(ngayCapPhep.getDate() + "/" + (ngayCapPhep.getMonth() + 1) + "/" + ngayCapPhep.getFullYear()); $('#CoWifi').prop('checked', row.CoWifi); $('#CoTivi').prop('checked', row.CoTivi); $('#CoCameraHanhTrinh').prop('CoCameraHanhTrinh', row.CoCameraHanhTrinh); $('#hdCoWifi').attr("value", row.CoWifi); $('#hdCoTivi').attr("value", row.CoTivi); $('#hdCoCameraHanhTrinh').attr("value", row.CoCameraHanhTrinh); $('#GhiChuThongTinXe').val(row.GhiChuThongTinXe); $('#GiaMua').val(row.GiaMua); $('#TongTienKhauHao').val(row.TongTienKhauHao); $('#SoThangKhauHao').val(row.SoThangKhauHao); $('#TienKhauHaoHangThang').val(row.TienKhauHaoHangThang); var ngayBatDauKhauHao = eval(("new " + row.NgayBatDauKhauHao).replace(/\//g, "")); $('#NgayBatDauKhauHao').val(ngayBatDauKhauHao.getDate() + "/" + (ngayBatDauKhauHao.getMonth() + 1) + "/" + ngayBatDauKhauHao.getFullYear()); var ngayKetThucKhauHao = eval(("new " + row.NgayKetThucKhauHao).replace(/\//g, "")); $('#NgayKetThucKhauHao').val(ngayKetThucKhauHao.getDate() + "/" + (ngayKetThucKhauHao.getMonth() + 1) + "/" + ngayKetThucKhauHao.getFullYear()); $('#GhiChuKhauHaoXe').val(row.GhiChuKhauHaoXe); } });//EndFunction //_______________________________________________ $(tableName).on('click', 'a.delete', function (e) { e.preventDefault(); var row = $(tableName).DataTable().data()[$(tableName).DataTable().row('.selected')[0][0]]; if (row != null) { $('#XeKey').val(row.XeKey); $.ajax({ type: "POST", dataType: "JSON", contentType: "application/json; charset=utf-8", url: '/QuanLyXe/XoaThongTinXeVaKhauHao', data: { xeKey: $('#XeKey').val() }, success: function (response) { $(tableName).DataTable().ajax.reload(); onNewClick(); ShowMessage(response); }, failure: function (msg) { $('#output').text(msg); } }); } });//EndFunction //_______________________________________________ //$(tableName).on('click', 'button i', function (e) { // e.preventDefault(); // var buttonCircle = $(this).closest('button'); // var addSign = 'glyphicon glyphicon-plus-sign'; // var minusSign = 'glyphicon glyphicon-minus-sign'; // var buttonAdd = 'btn btn-tini btn-primary btn-circle'; // var buttonMinus = 'btn btn-tini btn-danger btn-circle'; // if ($(this).hasClass(minusSign)) // { // $(this).removeClass(minusSign); // $(this).addClass(addSign); // buttonCircle.removeClass(buttonMinus); // buttonCircle.addClass(buttonAdd); // } // else if ($(this).hasClass(addSign)) { // $(this).removeClass(addSign); // $(this).addClass(minusSign); // buttonCircle.removeClass(buttonAdd); // buttonCircle.addClass(buttonMinus) // } //});//EndFunction //Add Child Table. //_______________________________________________ function format(d) { // `d` is the original data object for the row return '<table class="table table-striped table-bordered" cellpadding="5" cellspacing="0" border="0" style="padding-left:80px;" width="100%">' + '<tr>' + '<td width="30%" height="15px">Tổng tiền khấu hao:</td>' + '<td width="70%" height="15px">' + d.TongTienKhauHao + '</td>' + '</tr>' + '<tr>' + '<td width="30%" height="15px">Số tháng khấu hao:</td>' + '<td width="70%" height="15px">' + d.SoThangKhauHao + '</td>' + '</tr>' + '<tr>' + '<td width="30%" height="15px">Tiền khấu hao hàng tháng:</td>' + '<td width="70%" height="15px">' + d.TienKhauHaoHangThang + '</td>' + '</tr>' + '<tr>' + '<td width="30%" height="15px">Ngày bắt đầu khấu hao:</td>' + '<td width="70%" height="15px">' + formatDateToString(d.NgayBatDauKhauHao, 'DD/MM/YYYY') + '</td>' + '</tr>' + '<tr>' + '<td width="30%" height="15px">Ngày kết thúc khấu hao:</td>' + '<td width="70%" height="15px">' + formatDateToString(d.NgayKetThucKhauHao, 'DD/MM/YYYY') + '</td>' + '</tr>' + '<tr>' + '<td width="30%" height="15px">Ghi chú khấu hao:</td>' + '<td width="70%" height="15px">' + d.GhiChuKhauHaoXe + '</td>' + '</tr>' + '</table>'; }; // Add event listener for opening and closing details //_______________________________________________ $(tableName + ' tbody').on('click', 'td.details-control', function () { var tr = $(this).closest('tr'); var row = table.row(tr); if (row.child.isShown()) { // This row is already open - close it row.child.hide(); //if (!tr.hasClass('selected')) tr.removeClass('selected'); tr.removeClass('shown'); } else { // Open this row row.child(format(row.data())).show(); //if (!tr.hasClass('selected')) tr.addClass('selected'); tr.addClass('shown'); } }); }//EndFunction //=================================================== function SuKienThayDoiGiaMua_TienChietKhau_SoThangKhauHao() { //Sự kiện thay đổi giá mua xe. //_______________________________________________ $('#GiaMua').change(function () { var stringGiaMua = $('#GiaMua').val(); var giaMua = convertStringWithCommasToNumber(stringGiaMua,true); stringGiaMua = addThousandSeperator(giaMua,false); $('#GiaMua').val(stringGiaMua); $('#TongTienKhauHao').val(stringGiaMua); var soThangKhauHao = $('#SoThangKhauHao').val(); if (soThangKhauHao > 0) { var tienKhauHaoHangThang = (giaMua / soThangKhauHao); $('#TienKhauHaoHangThang').val(addThousandSeperator(tienKhauHaoHangThang)); } }); //Sự kiện thay đổi số tháng khấu hao. //_______________________________________________ $('#SoThangKhauHao').change(function () { var soThangKhauHao = $('#SoThangKhauHao').val(); var tongTienKhauHao = convertStringWithCommasToNumber($('#TongTienKhauHao').val(),true); if (soThangKhauHao > 0) { //$('#TienKhauHaoHangThang').val((tongTienKhauHao / soThangKhauHao).toFixed(2)); var tienKhauHaoHangThang = (tongTienKhauHao / soThangKhauHao); $('#TienKhauHaoHangThang').val(addThousandSeperator(tienKhauHaoHangThang)); var ngayBatDauKhauHao = new Date($('#NgayBatDauKhauHao').val()); SetDateForDatepicker('NgayKetThucKhauHao', new Date(ngayBatDauKhauHao.setMonth(soThangKhauHao))); } }); }//EndFunction. //=================================================== function CauHinhSmartWizard() { var idForm = "#formThongTinXe"; // Smart Wizard //=================================================== $('#smartwizard').smartWizard({ selected: 0, //Specify the selected step on the first load, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled). enableAllSteps: false, // Enable/Disable all steps on first load autoAdjustHeight: false, //Automatically adjust content height. contentURL: null, //Content url, Enables Ajax content loading. can set as data data-content-url on anchor. contentURLData: null, // override ajax query parameters useURLhash: true, // Enable selection of the step based on url hash showStepURLhash: true, // Show url hash based on step contentCache: true, // cache step contents, if false content is fetched always from ajax url enableFinishButton: false, // makes finish button enabled always cycleSteps: false, //Allows to cycle the navigation of steps. hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead backButtonSupport: false, //Enable the back button support. errorSteps: [], // array of step numbers to highlighting as error steps hiddenSteps: [], // Hidden steps disableSteps: [], //Array Steps disable. theme: 'arrows', // theme for the wizard, related css need to include for other than default theme transitionEffect: 'slide', // Effect on navigation, none/fade/slide transitionSpeed: 400, //noForwardJumping: false, ajaxType: 'POST', toolbarSettings: { toolbarPosition: 'bottom',//none/top/bottom/both toolbarPosition: 'right', //left/right showNextButton: true, showPreviousButton: true, toolbarExtraButtons: [ { label: 'Lưu', css: 'btn-info disabled btn-finish', onClick: function () { //alert('Finish Clicked'); if (!$(this).hasClass('disabled')) { ////--------------------------------------- ////var elmForm = $("#form-step-" + stepNumber); //var elmForm = $(idForm); //if (elmForm) { ////// //elmForm.validator('validate'); // elmForm.validate({ // rules: { // HangSanXuatXeKey: "required" // , LoaiXeKey: "required" // , BangSoXe: "required" // //, confirm_password: { // // required: true, // // minlength: 5, // // equalTo: "#password" // //} // }, // messages: { // HangSanXuatXeKey: "Vui lòng chọn một hãng sản xuất." // , LoaiXeKey: "Vui lòng chọn một loại xe." // , BangSoXe: "Vui lòng nhập bảng số xe." // //,confirm_password: { // // required: "Please provide a password", // // minlength: "Your password must be at least 5 characters long", // // equalTo: "Please enter the same password as above" // //}, // } // }); //}//EndelmForm //if ($(idForm).validator('check') < 1) { // alert('Hurray, your information will be saved!'); //} //Save //================================== LuuThongTinXe(); } } }, { label: 'Tạo mới', css: 'btn-danger', onClick: function () { var today = new Date(); var soThangKhauHao = 12; $('#XeKey').val(''); $('#HangSanXuatXeKey').change(); $('#LoaiXeKey').change(); $('#KeyLoaiXe').val(''); $('#BangSoXe').val(''); $('#SoSan').val(''); $('#Mau').val(''); $('#NgayCapPhep').val(convertDateToString(today)); $('#CoWifi').prop('checked', true); $('#CoTivi').prop('checked', true); $('#CoCameraHanhTrinh').prop('CoCameraHanhTrinh', true); $('#hdCoWifi').attr("value", true); $('#hdCoTivi').attr("value", true); $('#hdCoCameraHanhTrinh').attr("value", true); $('#GhiChuThongTinXe').val(''); $('#GiaMua').val(0); $('#TongTienKhauHao').val(0); $('#SoThangKhauHao').val(soThangKhauHao); $('#TienKhauHaoHangThang').val(0); $('#NgayBatDauKhauHao').val(convertDateToString(today)); $('#NgayKetThucKhauHao').val(convertDateToString(new Date(today.setMonth(soThangKhauHao)))); $('#GhiChuKhauHaoXe').val(''); } } ] },//End-toolbarSettings anchorSettings: { anchorClickable: false, //Enable/Disable the click option on the step header anchors. enableAllAnchors: false, // Activates all anchors clickable all times markDoneStepp: true, //Make already visited steps as done. enableAnchorOnDoneStep: true, //Enable/Disable the done steps navigation. markAllPreviousStepsAsDone: true, // When a step selected by url hash, all previous steps are marked done removeDoneStepOnNavigateBack: false // While navigate back done step after active step will be cleared },//End-anchorSettings lang: { // Language variables for button next: 'Tiếp theo', previous: 'Quay lại' } }); //=================================================== $("#smartwizard").on("showStep", function (e, anchorObject, stepNumber, stepDirection) { // Enable finish button only on last step if (stepNumber == 1) { $('.btn-finish').removeClass('disabled'); } else { $('.btn-finish').addClass('disabled'); } }); //=================================================== //var currentStep = $('#smartwizard').smartWizard('currentStep'); //$('#smartwizard').smartWizard('enableStep', 0); //$('#smartwizard').smartWizard('goToStep', 0); //$('#smartwizard').smartWizard('disableStep', 1); //=================================================== $("#smartwizard").on("leaveStep", function (e, anchorObject, stepNumber, stepDirection) { //var elmform = $("#form-step-" + stepNumber); //// stepdirection === 'forward' :- this condition allows to do the form validation //// only on forward navigation, that makes easy navigation on backwards still do the validation when going next //if (stepDirection === 'forward' && elmform) { // elmform.validator('validate'); // var elmerr = elmform.children('.has-error'); // if (elmerr && elmerr.length > 0) { // // form validation failed // return false; // } //} //return true; //--------------------------------------- //var elmForm = $("#form-step-" + stepNumber); ////var elmForm = $(idForm); //if (stepDirection === 'forward' && elmForm) { //// //elmForm.validator('validate'); // elmForm.validate({ // rules: { // HangSanXuatXeKey: "required" // , LoaiXeKey: "required" // , BangSoXe: "required" // //, confirm_password: { // // required: true, // // minlength: 5, // // equalTo: "#password" // //} // }, // messages: { // HangSanXuatXeKey: "Vui lòng chọn một hãng sản xuất." // , LoaiXeKey: "Vui lòng chọn một loại xe." // , BangSoXe: "Vui lòng nhập bảng số xe." // //,confirm_password: { // // required: "Please provide a password", // // minlength: "Your password must be at least 5 characters long", // // equalTo: "Please enter the same password as above" // //}, // } // }); //}//EndelmForm //--------------------------------------- //$(idForm).validate(); ValidateForm(); }); }//EndFunction //=================================================== function ValidateForm() { var result = true; $('#formThongTinXe').bootstrapValidator({ framework: 'bootstrap', err: { container: 'tooltip' }, icon: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { HangSanXuatXeKey: { // Show the message in a tooltip //err: 'tooltip', validators: { notEmpty: { message: 'Vui lòng chọn một hãng sản xuất.' } } } , LoaiXeKey: { // Show the message in a tooltip //err: 'tooltip', validators: { notEmpty: { message: 'Vui lòng chọn một loại xe.' } } } , BangSoXe: { // Show the message in a tooltip //err: 'tooltip', validators: { notEmpty: { message: 'Vui lòng nhập bảng số xe.' } } } //email: { // validators: { // notEmpty: { // message: 'The email address is required and cannot be empty' // }, // emailAddress: { // message: 'The email address is not valid' // } // } //}, //title: { // validators: { // notEmpty: { // message: 'The title is required and cannot be empty' // }, // stringLength: { // max: 100, // message: 'The title must be less than 100 characters long' // } // } //}, } }); return result; } //=================================================== jQuery(function ($) { //_______________________________________________ $('[data-toggle="tooltip"]').tooltip(); //_______________________________________________ KhoiTaoDuLieuComboBox(); KhoiTaoCheckBoxThietBiTheoXe(); CauHinhBangDuLieu(); //_______________________________________________ SettingDatepicker('divFrmGrpNgayCapPhep'); SetDateForDatepicker('NgayCapPhep', new Date()); SettingDatepicker('divFrmGrpNgayBatDauKhauHao'); SetDateForDatepicker('NgayBatDauKhauHao', new Date()); SettingDatepicker('divFrmGrpNgayKetThucKhauHao'); SetDateForDatepicker('NgayKetThucKhauHao', new Date((new Date).setMonth(12))); $(".touchspin3").TouchSpin({ verticalbuttons: true, verticalupclass: 'glyphicon glyphicon-plus', verticaldownclass: 'glyphicon glyphicon-minus', min:0, max: 100, initval: 0 }); //_______________________________________________ CauHinhSmartWizard(); //_______________________________________________ validateValueControlsOnForm(); //_______________________________________________ SuKienThayDoiGiaMua_TienChietKhau_SoThangKhauHao(); });//EndFunction$
'use strict' module.exports = { 'amqp10': require('../../../datadog-plugin-amqp10/src'), 'amqplib': require('../../../datadog-plugin-amqplib/src'), 'aws-sdk': require('../../../datadog-plugin-aws-sdk/src'), 'bluebird': require('../../../datadog-plugin-bluebird/src'), 'bunyan': require('../../../datadog-plugin-bunyan/src'), 'cassandra-driver': require('../../../datadog-plugin-cassandra-driver/src'), 'connect': require('../../../datadog-plugin-connect/src'), 'couchbase': require('../../../datadog-plugin-couchbase/src'), 'dns': require('../../../datadog-plugin-dns/src'), 'elasticsearch': require('../../../datadog-plugin-elasticsearch/src'), 'express': require('../../../datadog-plugin-express/src'), 'fastify': require('../../../datadog-plugin-fastify/src'), 'fs': require('../../../datadog-plugin-fs/src'), 'generic-pool': require('../../../datadog-plugin-generic-pool/src'), 'google-cloud-pubsub': require('../../../datadog-plugin-google-cloud-pubsub/src'), 'graphql': require('../../../datadog-plugin-graphql/src'), 'grpc': require('../../../datadog-plugin-grpc/src'), 'hapi': require('../../../datadog-plugin-hapi/src'), 'http': require('../../../datadog-plugin-http/src'), 'http2': require('../../../datadog-plugin-http2/src'), 'ioredis': require('../../../datadog-plugin-ioredis/src'), 'knex': require('../../../datadog-plugin-knex/src'), 'koa': require('../../../datadog-plugin-koa/src'), 'limitd-client': require('../../../datadog-plugin-limitd-client/src'), 'memcached': require('../../../datadog-plugin-memcached/src'), 'microgateway-core': require('../../../datadog-plugin-microgateway-core/src'), 'mongodb-core': require('../../../datadog-plugin-mongodb-core/src'), 'mysql': require('../../../datadog-plugin-mysql/src'), 'mysql2': require('../../../datadog-plugin-mysql2/src'), 'net': require('../../../datadog-plugin-net/src'), 'paperplane': require('../../../datadog-plugin-paperplane/src'), 'pg': require('../../../datadog-plugin-pg/src'), 'pino': require('../../../datadog-plugin-pino/src'), 'promise': require('../../../datadog-plugin-promise/src'), 'promise-js': require('../../../datadog-plugin-promise-js/src'), 'q': require('../../../datadog-plugin-q/src'), 'redis': require('../../../datadog-plugin-redis/src'), 'restify': require('../../../datadog-plugin-restify/src'), 'rhea': require('../../../datadog-plugin-rhea/src'), 'router': require('../../../datadog-plugin-router/src'), 'tedious': require('../../../datadog-plugin-tedious/src'), 'when': require('../../../datadog-plugin-when/src'), 'winston': require('../../../datadog-plugin-winston/src') }
import React, { useState, useEffect } from "react"; const LoginForm = ({ handleSubmit, handleUsernameChange, username }) => { return ( <div> <h2>Kirjaudu</h2> <form onSubmit={handleSubmit}> <div> username <input value={username} onChange={handleUsernameChange} /> </div> <button type="submit">Kirjaudu</button> </form> </div> ); }; export default LoginForm;
// Use a request to grab the json data needed for all charts d3.json('/movie', function(sampleData) { array=sampleData[4]; var myMap = L.map("map", { center: [sampleData[4][0].lat, sampleData[4][0].lng], zoom: 13 }); // Add a tile layer (the background map image) to our map // We use the addTo method to add objects to our map L.tileLayer( "https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/tiles/256/{z}/{x}/{y}?" + "access_token=pk.eyJ1Ijoia2pnMzEwIiwiYSI6ImNpdGRjbWhxdjAwNG0yb3A5b21jOXluZTUifQ." + "T6YbdDixkOBWH_k9GbS8JQ" ).addTo(myMap); // Create a new marker // Pass in some initial options, and then add it to the map using the addTo method for(i=0;i<sampleData[4].length;i++){ var marker = L.marker([sampleData[4][i].lat, sampleData[4][i].lng], { draggable: true, title: "My First Marker" }).addTo(myMap); // Binding a pop-up to our marker marker.bindPopup("Movie Name:"+sampleData[0]+"<img src='"+sampleData[6]+"'>" +"release Year:"+sampleData[3]+"\ngenres:"+sampleData[5] ); } });
let menuIsOpen = false; // Bind menus let menuItems = document.querySelectorAll('.menus--items--item'); let submenus = document.querySelectorAll('.menus--items--item--submenu'); function closeAllMenus() { for (let i=0; i < submenus.length; i++) { submenus[i].style.display = 'none'; } } for (let i=0; i < menuItems.length; i++) { let menuItem = menuItems[i]; menuItem.addEventListener('click', function(e) { e.stopPropagation(); if (this.querySelector('.menus--items--item--submenu').style.display === 'block') { this.querySelector('.menus--items--item--submenu').style.display = 'none'; menuIsOpen = false; } else { closeAllMenus(); this.querySelector('.menus--items--item--submenu').style.display = 'block'; menuIsOpen = true; } }); menuItem.addEventListener('mouseenter', function() { if (!menuIsOpen) return; if (this.querySelector('.menus--items--item--submenu').style.display !== 'block') { closeAllMenus(); this.querySelector('.menus--items--item--submenu').style.display = 'block'; } }); } document.addEventListener('click', function () { closeAllMenus(); menuIsOpen = false; }); // Open document.getElementById('menu-open').addEventListener('touchend', function () { document.querySelector('.menus').classList.add('menus_is-active'); }); // Close document.getElementById('menu-close').addEventListener('touchend', function (e) { e.preventDefault(); document.querySelector('.menus').classList.remove('menus_is-active'); }); // -- File // -- -- Open document.getElementById('menu--file--open').addEventListener('click', function () { closeAllMenus(); document.getElementById('canvas-file-input').click(); }); // -- -- Save as document.getElementById('menu--file--save').addEventListener('click', function () { if (this.classList.contains('menus--items--item--submenu--item_disabled')) { return; } closeAllMenus(); let $download = document.createElement('a'); $download.setAttribute('href', $canvas.toDataURL('image/jpeg', .8)); $download.setAttribute('target', '_blank'); $download.setAttribute('download', 'anonymous-image.jpg'); $download.click(); });
import React, { Component } from "react" import axios from "../../axios-orders" import Router from 'next/router' import SocialLogin from "../SocialLogin/Index" import {withRouter} from 'next/router'; import Link from "next/link" import Translate from "../../components/Translate/Index" const { BroadcastChannel } = require('broadcast-channel'); import PhoneInput,{ isValidPhoneNumber } from 'react-phone-number-input' import 'react-phone-number-input/style.css' import OtpInput from 'react-otp-input'; import { GoogleReCaptchaProvider,GoogleReCaptcha } from 'react-google-recaptcha-v3'; import GoogleRecaptchaIndex from '../GoogleCaptcha/Index'; class Form extends Component{ constructor(props){ super(props) this.state = { email:"", password:"", passwordError:null, emailError:null, isSubmit:false, previousUrl:typeof window != "undefined" ? Router.asPath : "", verifyAgain:false, verifyEmail:"", otpEnable:props.pageData.appSettings['twillio_enable'] == 1, type:"email", phone_number:"", disableButtonSubmit:false, otpTimer:0, getCaptchaToken:true, firstToken:true, keyCaptcha:1 } } componentWillUnmount(){ if($('.modal-backdrop').length) $(".modal-backdrop").remove() if(this.state.orgCode){ //remove code const querystring = new FormData(); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; querystring.append("phone",this.state.phone_number); querystring.append("type",'login'); querystring.append("code",this.state.orgCode); axios.post("/auth/remove-otp", querystring, config) .then(response => { }).catch(err => { }); } } onChange = (type,e) => { (type == "email" ? this.setState({"email":e.target.value}) : this.setState({"password":e.target.value})) } componentDidMount(){ $("#signupbtn").click(function(e){ setTimeout(() => { $("body").addClass("modal-open") }, 1000); }) $("#forgot-btn").click(function(e){ $("body").removeClass("modal-open") }) $(document).on('click','.verificationLink',function(e){ e.preventDefault(); Router.push(`/verify-account`,`/verify-account`) }) this.props.socket.on('otpCode',data => { let email = data.email let code = data.code let phone = data.phone let error = data.error if(phone == this.state.phone_number && !error){ this.setState({orgCode:code,otpTimer:0,disableButtonSubmit:false},() => { if(this.resendInterval){ clearInterval(this.resendInterval) } this.resendInterval = setInterval( () => this.updateResendTimer(), 1000 ); }) //set timer to resend code }else if(error){ if(this.resendInterval){ clearInterval(this.resendInterval) } this.setState({ emailError: Translate(this.props, error), otpValidate: false, otpVerificationValidate:false, otpValue:"", otpError:false }); } }); } updateResendTimer() { if(this.state.otpTimer >= 60){ this.setState({disableButtonSubmit:true,otpTimer:0}) clearInterval(this.resendInterval) }else{ this.setState({otpTimer:this.state.otpTimer+1}) } } onSubmit = (e) => { e.preventDefault(); if(this.state.isSubmit){ return false; } let valid = true let emailError = null if(!this.state.otpEnable){ if(!this.state.email){ //email error emailError = Translate(this.props,"Please enter valid Email ID or Username/Password.") valid = false }else if(this.state.email){ // const pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // if(!pattern.test( this.state.email )){ // //invalid email // emailError = Translate(this.props,"Please enter valid Email ID or Username/Password.") // valid = false // } } if(!this.state.password){ //email error emailError = Translate(this.props,"Please enter valid Email ID or Username/Password.") valid = false } }else{ if(this.state.type == "email"){ if(!this.state.email){ //email error emailError = Translate(this.props,"Please enter valid Email ID or Username/Password.") valid = false } if(!this.state.password){ //email error emailError = Translate(this.props,"Please enter valid Email ID or Username/Password.") valid = false } }else{ if(!this.state.phone_number){ //email error emailError = Translate(this.props,"Enter valid Phone Number.") valid = false }else{ let checkError = isValidPhoneNumber(this.state.phone_number) ? undefined : 'Invalid phone number'; if(checkError){ valid = false emailError = Translate(this.props, "Enter valid Phone Number.") } } } } this.setState({emailError:emailError,verifyEmail:this.state.email,verifyAgain:false}) if(valid){ if(this.props.pageData.appSettings["recaptcha_enable"] == 1 && this.props.pageData.appSettings["recaptcha_login_enable"] == 1){ let isSubmit = true; if(this.state.type != "email"){ //validate phone number this.validatePhoneNumber() isSubmit = false; } this.setState({getCaptchaToken:true,isSubmit:isSubmit,keyCaptcha:this.state.keyCaptcha + 1}); }else if(this.state.type != "email"){ //validate phone number this.validatePhoneNumber() }else{ this.loginUser(); } } return false } loginUser = () => { if(this.resendInterval){ clearInterval(this.resendInterval) } this.setState({isSubmit:true,otpValidate: false,otpValue:"",otpError:false}) //SEND FORM REQUEST const querystring = new FormData(); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; if(this.state.type == "email"){ querystring.append("email",this.state.email); querystring.append("password",this.state.password); } else { querystring.append("phone_number",this.state.phone_number) querystring.append("code",this.state.orgCode) } if(this.state.captchaToken){ querystring.append("captchaToken",this.state.captchaToken); } axios.post("/login", querystring,config) .then(response => { this.setState({isSubmit:false}) if(response.data.error){ //error try{ this.setState({emailError:Translate(this.props,response.data.error[0].message),verifyAgain:response.data.verifyAgain}) }catch(err){ this.setState({emailError:Translate(this.props,"Please enter valid Email ID or Username/Password.")}) } }else{ const currentPath = Router.pathname; const userChannel = new BroadcastChannel('user'); userChannel.postMessage({ payload: { type: "LOGIN" } }); //success $("body").removeClass("modal-open"); $("body").removeAttr("style"); $('.loginRgtrBoxPopupForm').find('button').eq(0).trigger('click') if(currentPath == "/" || currentPath == "/login") Router.push('/') else{ Router.push( this.state.previousUrl ? this.state.previousUrl : Router.pathname) } } }) .catch(err => { this.setState({emailError:Translate(this.props,"Please enter valid Email ID or Username/Password.")}) //error }); } validatePhoneNumber = async () => { this.resendOTP() this.setState({otpValidate:true}); } closePopup = (e) => { this.setState({ otpValidate: false,otpValue:"",otpError:false,otpTimer:0}) } resendOTP = () => { if(this.state.otpTimer != 0){ return; } //SEND FORM REQUEST const querystring = new FormData(); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; querystring.append("phone",this.state.phone_number); querystring.append("type",'login'); axios.post("/users/otp", querystring, config) .then(response => { }).catch(err => { }); } codeValidate = () => { if(this.state.otpValue && this.state.orgCode && this.state.otpValue == this.state.orgCode){ this.loginUser() } } handleOTPChange = (value) => { this.setState({otpValue:value,otpError:false}) } verification = (e) => { e.preventDefault(); if(this.state.type != "email"){ this.verificationPhoneNumber(); }else{ this.sendVerification(); } } sendVerification = () => { if(this.state.verificationResend){ return } this.setState({verificationResend:true}) //SEND FORM REQUEST const querystring = new FormData(); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; if(this.state.type == "email") querystring.append("email",this.state.verifyEmail); else querystring.append("phone",this.state.phone_number); axios.post("/resendVerification", querystring,config) .then(response => { this.setState({verificationResend:false}) if(response.data.success){ //error try{ this.setState({verifyAgain:false,emailError:null}) if(response.data.code){ Router.push(`/verify-account?code=${response.data.code}`, `/verify-account/${response.data.code}`) } }catch(err){ } }else{ } }) .catch(err => { //error }); } verificationPhoneNumber = async () => { this.resendVerificationOTP() this.setState({otpVerificationValidate:true}); } closeVerificationPopup = (e) => { this.setState({ otpVerificationValidate: false,otpValue:"",otpError:false,otpTimer:0}) } resendVerificationOTP = () => { //SEND FORM REQUEST const querystring = new FormData(); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; querystring.append("phone",this.state.phone_number); querystring.append("type",'verification'); axios.post("/users/otp", querystring, config) .then(response => { }).catch(err => { }); } codeVerificationValidate = () => { if(this.state.otpValue && this.state.orgCode && this.state.otpValue == this.state.orgCode){ this.sendVerification() } } setToken = (token) => { if(this.state.firstToken){ this.setState({captchaToken:token,getCaptchaToken:false,firstToken:false}); }else{ this.setState({captchaToken:token,getCaptchaToken:false},() => { if(this.state.type == "email"){ this.loginUser(); } }); } } render(){ let otpHMTL = null if(this.state.otpValidate){ otpHMTL = <div className="popup_wrapper_cnt"> <div className="popup_cnt otp-cnt"> <div className="comments"> <div className="VideoDetails-commentWrap phone-otp"> <div className="popup_wrapper_cnt_header"> <h2>{Translate(this.props,"Enter Verification Code")}</h2> <a onClick={this.closePopup} className="_close"><i></i></a> </div> <p>{this.props.t("Verification code is valid for {{expiration_time}}.",{expiration_time:`${60 - this.state.otpTimer} seconds`})}</p> <OtpInput value={this.state.otpValue} onChange={this.handleOTPChange} numInputs={4} placeholder="0000" inputStyle="form-control" hasErrored={this.state.otpError ? true : false} isInputNum={true} separator={<span>-</span>} /> <div className="form-group"> <label htmlFor="name" className="control-label"></label> <button type="submit" onClick={this.codeValidate}>{Translate(this.props,"Validate Code")}</button> <button type="submit" onClick={this.resendOTP} disabled={!this.state.disableButtonSubmit} >{Translate(this.props,"Resend Code")}</button> </div> </div> </div> </div> </div> } let otpHVerificationMTL = null if(this.state.otpVerificationValidate){ otpHVerificationMTL = <div className="popup_wrapper_cnt"> <div className="popup_cnt otp-cnt"> <div className="comments"> <div className="VideoDetails-commentWrap phone-otp"> <div className="popup_wrapper_cnt_header"> <h2>{Translate(this.props,"Enter Verification Code")}</h2> <a onClick={this.closeVerificationPopup} className="_close"><i></i></a> </div> <p>{this.props.t("Verification code is valid for {{expiration_time}}.",{expiration_time:`${60 - this.state.otpTimer} seconds`})}</p> <OtpInput value={this.state.otpValue} onChange={this.handleOTPChange} numInputs={4} placeholder="0000" inputStyle="form-control" hasErrored={this.state.otpError ? true : false} isInputNum={true} separator={<span>-</span>} /> <div className="form-group"> <label htmlFor="name" className="control-label"></label> <button type="submit" onClick={this.codeVerificationValidate}>{Translate(this.props,"Validate Code")}</button> <button type="submit" onClick={this.resendVerificationOTP} disabled={!this.state.disableButtonSubmit} >{Translate(this.props,"Resend Code")}</button> </div> </div> </div> </div> </div> } return ( <React.Fragment> { otpHVerificationMTL } { otpHMTL } { this.props.pageData.appSettings['member_registeration'] == 1 ? <SocialLogin {...this.props} /> : null } <div className="form loginBox"> { this.state.successVerification ? <p className="form_error" style={{color: "green",margin: "0px",fontSize: "16px"}}>{this.state.successVerification}</p> : null } { this.state.emailError ? <p className="form_error" style={{color: "red",margin: "0px",fontSize: "16px"}}>{this.state.emailError}</p> : null } { this.state.verifyAgain ? <p className="form_error" style={{color: "green",margin: "0px",fontSize: "16px"}}> { <a href="#" onClick={this.verification}> { this.props.t("Click here") } </a> } { this.props.t(" to resend verification email.") } </p> : null } <form onSubmit={this.onSubmit.bind(this)}> { !this.state.otpEnable ? <React.Fragment> <div className="input-group"> <input className="form-control" type="text" onChange={this.onChange.bind(this,'email')} value={this.state.email} placeholder={Translate(this.props,"Email / Username")} name="email" /> </div> <div className="input-group"> <input className="form-control" autoComplete="off" type="password" onChange={this.onChange.bind(this,'password')} value={this.state.password} placeholder={Translate(this.props,"Password")} name="password" /> </div> { this.props.pageData.appSettings["recaptcha_enable"] == 1 && this.props.pageData.appSettings["recaptcha_login_enable"] == 1 ? <GoogleReCaptchaProvider useRecaptchaNet={false} language={this.props.i18n.language} useEnterprise={this.props.pageData.appSettings["recaptcha_enterprise"] == 1 ? true : false} reCaptchaKey={this.props.pageData.appSettings["recaptcha_key"]} scriptProps={{ async: true, defer: true, appendTo: 'body' }} > <GoogleRecaptchaIndex keyCaptcha={this.state.keyCaptcha} GoogleReCaptcha={GoogleReCaptcha} token={this.setToken} type="login" /> </GoogleReCaptchaProvider> : null } <div className="input-group"> <button className="btn btn-default btn-login" type="submit"> { this.state.isSubmit ? Translate(this.props,"Login ...") : Translate(this.props,"Login") } </button> </div> </React.Fragment> : <React.Fragment> { !this.state.passwordEnable ? this.state.type == "email" ? <div className="input-group"> <input className="form-control" type="text" onChange={this.onChange.bind(this,'email')} value={this.state.email} placeholder={Translate(this.props,"Email / Username")} name="email" /> </div> : <div className="input-group"> <PhoneInput countryCallingCodeEditable={false} countrySelectProps={{ unicodeFlags: true }} placeholder={Translate(this.props,"Phone Number")} value={this.state.phone_number} onChange={ (value) => this.setState({"phone_number":value})} /> </div> : null } { this.state.type == "email" ? <div className="input-group"> <input className="form-control" autoComplete="off" type="password" onChange={this.onChange.bind(this,'password')} value={this.state.password} placeholder={Translate(this.props,"Password")} name="password" /> </div> : null } { this.state.type == "email" ? <div className="input-group" onClick={() => this.setState({email:"",type:"phone",emailError:null,verifyAgain:false })}><p className="choose-option">{Translate(this.props,'Use Phone Number')}</p></div> : <div className="input-group" onClick={() => this.setState({phone_number:"",type:"email",emailError:null,verifyAgain:false})}><p className="choose-option">{Translate(this.props,'Use Email Address')}</p></div> } { this.props.pageData.appSettings["recaptcha_enable"] == 1 && this.props.pageData.appSettings["recaptcha_login_enable"] == 1 ? <GoogleReCaptchaProvider useRecaptchaNet={false} language={this.props.i18n.language} useEnterprise={this.props.pageData.appSettings["recaptcha_enterprise"] == 1 ? true : false} reCaptchaKey={this.props.pageData.appSettings["recaptcha_key"]} scriptProps={{ async: true, defer: true, appendTo: 'body' }} > <GoogleRecaptchaIndex keyCaptcha={this.state.keyCaptcha} GoogleReCaptcha={GoogleReCaptcha} token={this.setToken} type="login" /> </GoogleReCaptchaProvider> : null } <div className="input-group"> <button className="btn btn-default btn-login" type="submit"> { this.state.type == "email" ? this.state.isSubmit ? Translate(this.props,"Login ...") : Translate(this.props,"Login") : Translate(this.props,"Continue") } </button> </div> </React.Fragment> } </form> </div> <div className="forgot"> { this.props.pageData.appSettings['member_registeration'] == 1 ? this.props.router.pathname == "/login" || this.props.router.pathname == "/signup" || this.props.user_login == 1 ? <Link href="/signup"> <a>{Translate(this.props,"create an account?")}</a> </Link> : <a href="/signup" data-bs-dismiss="modal" data-bs-target="#registerpop" data-bs-toggle="modal" id="signupbtn">{Translate(this.props,"create an account?")}</a> : null } <Link href="/forgot"> <a className="forgot-btn">{Translate(this.props,"forgot password?")}</a> </Link> </div> </React.Fragment> ) } } export default withRouter(Form)
import React from 'react'; import "./Ribbons.css"; export const PitchRibbon = ({ endTone, setCenterTone: setCenterToneAction, startTone, }) => { const prib = React.useRef(); let pitchStarted = false, centerTone; const [pitchRibbonOffset, setPitchRibbonOffset] = React.useState(0); const [pitchRibbonScale, setPitchRibbonScale] = React.useState(0); const setRibbon = () => { setPitchRibbonScale(1000 / prib.current.getBoundingClientRect().width); setPitchRibbonOffset(prib.current.getBoundingClientRect().left); } React.useEffect(() => { setRibbon(); }, []) const startNote = event => { event.preventDefault(); pitchStarted = true; if (event.touches) { centerTone = (event.changedTouches[0].clientX - pitchRibbonOffset) * pitchRibbonScale; } else { centerTone = (event.clientX - pitchRibbonOffset) * pitchRibbonScale; startTone(centerTone); } } const checkRibbonBoundaries = evt => { var xpos = evt.clientX, ypos = evt.clientY, bound = evt.target.getBoundingClientRect(); if (xpos < bound.left || xpos > bound.right || ypos < bound.top || ypos > bound.bottom) { return true; } else return false; } const setCenterTone = event => { if (pitchStarted) { if (event.touches) { if (checkRibbonBoundaries(event.changedTouches[0])) { pitchStarted = false; endTone(); return; } centerTone = (event.changedTouches[0].clientX - pitchRibbonOffset) * pitchRibbonScale; } else { centerTone = (event.clientX - pitchRibbonOffset) * pitchRibbonScale; } setCenterToneAction(centerTone); } } const endNote = () => { pitchStarted = false; endTone(); } return ( <div className="ctl-ribbon" id="pitch-ribbon" ref={prib} onMouseDown={startNote} onMouseMove={setCenterTone} onTouchStart={startNote} onTouchMove={setCenterTone} onMouseUp={endNote} onMouseOut={endNote} onTouchEnd={endNote} ></div> ) }
const toHttpRequest = (data) => ({ name_farm: data.nameFarm, }); const loadFarmQuery = ({ payload }) => { const { producerId } = payload; return { method: "POST", url: `/producers/${producerId}/farms`, data: toHttpRequest(payload), }; }; export default loadFarmQuery;
import { Badge} from '@material-ui/core'; import { ShoppingCartOutlined} from '@material-ui/icons'; import classes from './HeaderCartButton.module.css'; import {useContext} from 'react'; import CartContext from '../../Context/cart-context'; const HeaderCartButton = (props) => { const Cartctx = useContext(CartContext); const numberOfCartItems = Cartctx.items.reduce((curNumber, item) => { return curNumber + item.amount; }, 0); return ( <button className={classes.button} onClick={props.onShowCart}> <span>Your Cart</span> <span className={classes.badge}> <Badge color="secondary" badgeContent={numberOfCartItems} showZero> <ShoppingCartOutlined /> </Badge> </span> </button> ); }; export default HeaderCartButton;
FinVue = function() { this.afficher = function(nomJoueur, nomAdversaire, etat, vitesse) { var nouveauHTML = ""; //{MESSAGE} est seulement une chaine à remplacer par une vraie valeur. if(etat=="gagne") nouveauHTML = FinVue.html.replace("{MESSAGE}","Vous avez battu " + nomAdversaire); else nouveauHTML = FinVue.html.replace("{MESSAGE}","Vous avez perdu contre " + nomAdversaire); //{NOM} est seulement une chaine à remplacer par une vraie valeur. nouveauHTML = nouveauHTML.replace("{NOM}",nomJoueur); nouveauHTML = nouveauHTML.replace("{RECORD}",'Vous avez atteint une vitesse de ' + vitesse + ' années lumieres!'); document.getElementsByTagName("body")[0].innerHTML = nouveauHTML; } } FinVue.html = document.getElementById("page-fin").innerHTML;
import { Tooltip } from "shared"; import { FormattedMessage as T } from "react-intl"; import { LoaderBarBottom } from "indicators"; import { InvisibleButton } from "buttons"; export default ({ onHideReleaseNotes, onShowSettings, onShowLogs, getCurrentBlockCount, getNeededBlocks, getEstimatedTimeLeft }) => ( <div className="page-body getstarted"> <div className="getstarted loader logs"> <div className="content-title"> <div className="loader-settings-logs"> <InvisibleButton onClick={onShowSettings}> <T id="getStarted.btnSettings" m="Settings" /> </InvisibleButton> <InvisibleButton onClick={onShowLogs}> <T id="getStarted.btnLogs" m="Logs" /> </InvisibleButton> </div> <Tooltip text={ <T id="logs.goBack" m="Go back" /> }><div className="go-back-screen-button" onClick={onHideReleaseNotes}/></Tooltip> <T id="getStarted.logsTitle" m="Decrediton v1.1.2 Released" /> </div> <div className="release-notes"> <div className="release-notes-text"> <p> This release marks a major turning point in our overall look and feel of Decrediton. We have introduced consistent header areas with a new subpage/tab interface. React-motion has been added to give a better feel for transitions from page to page and expanded area reveals. All information modals and passphrase modals have been consolidated to have a consistent feel whenever they are used. </p> <p> As part of the design overhaul, the Tickets page has begun its transformation to provide a much better user experience. My Tickets subpage is the first step into giving users a clearer picture into their current staking situation. In the upcoming release, we will be adding extensive statistics and graphing to further help visualize a given users' balance and staking history. Overall, we aim to continue to add more tools that will help users' staking experience be much more enjoyable and carefree. </p> <p> We have also added advanced daemon setup abilities for users that want to use remote daemons or use a different location for their blockchain data. In the next release, we plan on also adding the ability to handle advanced back-end wallet setups: easily switch between different wallet files on the same machine, connecting to a remote wallet and other possible situations. But these advanced options will also be completely transparent for users that choose to run with the default settings. </p> <p> We have added a Security Center page that will be a catch-all place to store tools that we feel have utility, but aren't needed for everyday normal wallet operation. The first 2 tools that have been added are for Signing and Verifying messages using addresses and private keys to prove ownership of a given address. Here is a typical use case: User A wants to prove to User B that they control a given address. With the Sign Message tool, User A enters the address, a message and their wallet's private passphrase. The tool produces a hash that was created based on that address' private key and the given message. With the Verify Message tool, User B can use the address in question, the hash and the message from User A to verify that it was signed using that address' private key. </p> <p> We are also happy to announce the introduction of internationalization. Brazilian Portuguese has been added for the first pass and we will be slowly adding more languages on every new release. </p> Things to expect in the next release: <ul> <li>New overview page design</li> <li>Rich historical Statistics/Graphs</li> <li>New staking account user experience</li> <li>Advanced wallet settings</li> <li>More languages translated</li> </ul> Bug fixes <ul> <li>Fix issue on Windows caused by using "Aux" as a filename. Aux is a restricted filename with Windows and a simple filename change fixed it.</li> <li>Fix shutdown issue with macOS. When cmd-Q or quitting Decrediton from the dock caused dcrd and dcrwallet to not be shutdown in the background. By adding a final closeClis() in app.on("before-quit",...) it ensures that everything is closed on any shutdown.</li> <li>Removed Skip Sync button due to the new slip44 change in dcrwallet. With the new coin type change, dcrwallet needs to check if there has been any address usage up to that point in the chain for a given wallet.</li> <li>Shorten account names in various areas to avoid obnoxious overflow.</li> <li>Fix issue that was occuring when clearing out stakepool configurations. This would cause users to possibly have incorrect stakepool setups.</li> <li>Change functionality of the space key during seed entry. Previously, when the user would enter the space key they would end up not "selecting" a word and then just type the whole seed. Now the space "selects" the word just as pressing tab does.</li> </ul> </div> <div className="release-notes-image" /> </div> <LoaderBarBottom {...{ getCurrentBlockCount, getNeededBlocks, getEstimatedTimeLeft }} /> </div> </div> );
'use strict'; import * as chai from 'chai'; import { respond } from './action'; import * as sinon from 'sinon'; import * as sinonAsPromised from 'sinon-as-promised'; import { SentEmail } from 'moonmail-models'; import * as event from './event.json'; const expect = chai.expect; describe('saveSentEmails', () => { describe('#respond()', () => { beforeEach(() => { sinon.stub(SentEmail, 'saveAll').resolves('ok'); }); it('saves all the sent emails', (done) => { respond(event, (err, result) => { const sentEmails = SentEmail.saveAll.firstCall.args[0]; for (let sentEmail of sentEmails) { expect(sentEmail).to.have.property('messageId'); expect(sentEmail).to.have.property('listId'); expect(sentEmail).to.have.property('recipientId'); expect(sentEmail).to.have.property('campaignId'); expect(err).to.not.exist; expect(result).to.exist; } done(); }); }); afterEach(() => { SentEmail.saveAll.restore(); }); }); });
//API //openweather api key const key = "b9e8ddc20a672bf8cdcffd0193b2aa0a"; //mapquest api key const key2 = "Y9QVmRGWZUavjlpNda6CreXSUXVwDGZ5"; //Elements const searchKey = document.querySelector("#searchKey"); const searchBtn = document.querySelector("#searchBtn"); const locationIcon = document.getElementById("locationIcon"); const currentCity = document.querySelector("#city"); const currentCountry = document.querySelector("#country"); const currentDate = document.querySelector("#date"); const currentDesc = document.querySelector("#currentDescription"); const currentTemp = document.querySelector("#currentTemp"); const currentWind = document.querySelector("#currentWind"); const currentWindDegree = document.querySelector("#currentWindDegree"); const currentHumidity = document.querySelector("#currentHumidity"); const currentRainProb = document.querySelector("#currentRainProb"); const forecastTable = document.querySelector("#forecast"); /*const notification = document.querySelector("#notification");*/ //app data const date = new Date(); const weather = {}; var forecast; //const arrays const months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']; const days = ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi']; /*notification.style.display = "none";*/ //event listener searchBtn.addEventListener('click', eventHandler); function eventHandler(e) { e.preventDefault(); let citySearched = searchKey.value.trim(); getWeatherCityName(citySearched); fetchCoordsCityName(citySearched); } //location services if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition(setPosition, showError); } else { /*notification.style.display = "block"; notification.innerHTML = "<p>Konum servisi kullanılamıyor.</p>";*/ } function setPosition(position) { //locationIcon göster let lat = position.coords.latitude; let lon = position.coords.longitude; getWeatherCoords(lat, lon); locationIcon.classList.toggle('d-none'); getForecastLocation(lat, lon); } function showError(error) { /*notification.style.display = "block"; notification.innerHTML = "<p>Konum servisi kullanılamıyor.</p>";*/ } //fetch location function fetchCoordsCityName(cityName) { if (cityName == "") { alert("Şehir giriniz!"); } else { let api = `http://www.mapquestapi.com/geocoding/v1/address?key=${key2}&thumbMaps=false&maxResults=1&location=${cityName}`; fetch(api) .then( function (response) { let data = response.json(); return data; }).then(function (data) { let lat = data.results[0].locations[0].latLng.lat; let lon = data.results[0].locations[0].latLng.lng; getForecastLocation(lat, lon); }); } } //fetch current function fetchCurrent(api) { fetch(api) .then(function (response) { let data = response.json(); return data; }).then(function (data) { weather.date = data.dt; weather.temp = Math.round(data.main.temp); weather.description = data.weather[0].description; weather.humidty = data.main.humidity; weather.wind = data.wind; weather.city = data.name; weather.country = data.sys.country; }).then(function () { displayCurrent(); }); } //fetch forecast function fetchForecast(api) { fetch(api) .then(function (response) { let data = response.json(); console.log(data); return data; }).then(function (data) { forecast = data.daily; currentRainProb.textContent = Math.round(forecast[0].pop * 100) + " %"; }).then(function () { displayForecast(); }) } //get by user location function getWeatherCoords(lat, lon) { let api = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&lang=tr&units=metric&appid=${key}`; fetchCurrent(api); } //get by city name function getWeatherCityName(cityName) { if (cityName == "") { alert("Şehir giriniz!"); } else { let api = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&lang=tr&units=metric&appid=${key}`; fetchCurrent(api); } } function getForecastLocation(lat, lon) { let api = `http://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&lang=tr&units=metric&appid=${key}`; fetchForecast(api); } function getForecastCityName(cityName) { if (cityName == "") { alert("Şehir giriniz!"); } else { let api = `http://api.openweathermap.org/data/2.5/onecall?q=${cityName}&lang=tr&units=metric&appid=${key}`; console.log("--getForecastCityName func--"); fetchForecast(api); } } //display current function displayCurrent() { currentCity.textContent = weather.city; currentCountry.textContent = weather.country; currentDate.textContent = timeConverter(weather.date); currentDesc.textContent = weather.description; currentTemp.textContent = weather.temp + " °C"; currentHumidity.textContent = weather.humidty + " %"; currentWind.textContent = weather.wind.speed.toFixed(1) + " m/s " + degToDir(weather.wind.deg); } //display forecast function displayForecast() { console.log("^^ begin query - display forecast ^^"); console.log(forecastTable.children); console.log(forecastTable.children.length) for (let i = 0; i < forecastTable.children.length; i++) { //date forecastTable.children[i] .firstElementChild .firstElementChild .textContent = timeConverterDate(forecast[i + 1].dt); //date-day forecastTable.children[i] .firstElementChild .lastElementChild .textContent = timeConverterDay(forecast[i + 1].dt); //temperature forecastTable.children[i] .lastElementChild .firstElementChild .children[1] .textContent = Math.round(forecast[i + 1].temp.day) + " °C"; //rain probability forecastTable.children[i] .lastElementChild .firstElementChild .children[3] .textContent = Math.round(forecast[i + 1].pop * 100) + "%"; // STLYING // //temperature margin forecastTable.children[i] .lastElementChild .firstElementChild .children[1].style.marginBottom = "1.5rem"; //temperature font size forecastTable.children[i] .lastElementChild .firstElementChild .children[1].style.fontSize = "1.5rem"; //rain probability font-size forecastTable.children[i] .lastElementChild .firstElementChild .children[3].style.fontSize = "1.5rem"; //temperature icon font size forecastTable.children[i] .lastElementChild .firstElementChild .children[0].style.fontSize = '1.2rem'; //rain probability icon font size forecastTable.children[i] .lastElementChild .firstElementChild .children[2].style.fontSize = '1.2rem'; } console.log("^^ end query - display forecast ^^"); } //unix time converter function timeConverter(dt) { var a = new Date(dt * 1000); var year = a.getFullYear(); var month = months[a.getMonth()]; var day = days[a.getDay()]; var date = a.getDate(); var time = date + ' ' + month + ' ' + year + ' ' + day; return time; } function timeConverterDate(dt) { var a = new Date(dt * 1000); var year = a.getFullYear(); var month = months[a.getMonth()]; var date = a.getDate(); var time = date + ' ' + month + ' ' + year return time; } function timeConverterDay(dt) { var a = new Date(dt * 1000); var day = days[a.getDay()]; return day; } //wind degree to wind direction var degToDir = function (deg) { var directions = ['Kuzey', 'Kuzey Batı', 'Batı', 'Güney Batı', 'Güney', 'Güney Doğu', 'Doğu', 'Kuzey Doğu']; return directions[Math.round(((deg %= 360) < 0 ? deg + 360 : deg) / 45) % 8]; }
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const jokeTypes = [ 'Programming', 'Miscellaneous', 'Dark', 'Pun', 'Spooky', 'Christmas', ] export default new Vuex.Store({ state: { isMobile: false, error: null, isFetching: true, userIdSelected: 0, users: [], messagesArray: [], }, getters: { getIsMobile(state) {return state.isMobile}, getUserIdSelected(state) {return state.userIdSelected}, getAllMessagesForSelectedPersonId(state, getters) { return state.messagesArray.filter(msg => msg.userId === getters.getUserIdSelected) }, getUsers(state) {return state.users}, getSelectedUsers(state, getters) { let data = state.users.filter(user => user.id === getters.getUserIdSelected) return data[0] }, getSelectedUserJokeType(_, getters) { let data = getters.getSelectedUsers.jokeType return data }, getIsSent: (state) => (id) => { let messages = state.messagesArray.filter(msg => msg.userId == id) if (messages.length > 1) {return messages[0].isSent} return null }, getIsRead: (state) => (id) => { let messages = state.messagesArray.filter(msg => msg.userId == id) if (messages.length > 1) {return messages[0].isRead} return null }, getLastUpdated: (state) => (id) => { let messages = state.messagesArray.filter(msg => msg.userId === id) if (messages.length > 1) {return messages[0].time} return null }, getLastMessage: (state) => (id) => { let messages = state.messagesArray.filter(msg => msg.userId == id) if (messages.length > 1) {return messages[0].msg} return null }, isSystemTyping: (state) => (id) => { let user = state.users.filter((user) => user.id == id) if (user) {return user[0].isTyping} return null }, }, actions: { fetchUsers({state, commit}) { fetch('https://reqres.in/api/users') .then((response) => { if (response.ok) {return response.json();} }).then((input) => { const users = input.data const results = []; for (const id in users) { results.push({ id: users[id].id - 1, firstName: users[id].first_name, avatar: users[id].avatar, isTyping: false, jokeType: jokeTypes[id], }); } commit('fetchUsers', { results: results }); state.isFetching = false; return results; }).catch((err) => { console.error(err); state.error = err; }); }, startConversation({state, getters, commit}, payload) { state.error = null; let userId = getters.getUserIdSelected if (payload.userId != null) {userId = payload.userId} state.isFetching = true; state.users[userId].isTyping = true fetch(`https://v2.jokeapi.dev/joke/${payload.jokeType}?blacklistFlags=nsfw,religious,political,racist,sexist,explicit`, { "method": "GET", }) .then(response => {return response.json()}) .then(body => { if (!body.error) commit('addMessage', { ...body, id: userId, isSystem: true }) state.isFetching = false; state.users[userId].isTyping = false; }) .catch(err => { console.error(err); state.error = err; }); }, userReply({getters, dispatch, commit}, payload) { commit('addMessage', { ...payload, id: getters.getUserIdSelected, isSystem: false }) dispatch('startConversation', { jokeType: getters.getSelectedUserJokeType, userId: null }) }, }, mutations: { setIsMobile(state, payload) {Object.assign(state, {isMobile: payload.isMobile})}, fetchUsers(state, payload) {Object.assign(state, {users: payload.results})}, selectUser(state, payload) {Object.assign(state, {userIdSelected: payload.id})}, addMessage(state, payload) { let newArray = Object.assign([], state.messagesArray) addMessage(newArray, payload, payload.isSystem) Object.assign(state, {messagesArray: newArray}) } }, }) function addMessage(array, payload) { const obj = { userId: payload.id, time: Date.now(), isSystemInput: payload.isSystem, isSent: true, isRead: true, msg: payload.isSystem ? " --- Wanna listen to a joke? ---" : payload.msg, } array.unshift(Object.assign({}, obj)) if (payload.joke && payload.isSystem) { obj.msg = payload.joke array.unshift(Object.assign({}, obj)) } else if (payload.isSystem) { obj.msg = payload.setup array.unshift(Object.assign({}, obj)) obj.msg = payload.delivery array.unshift(Object.assign({}, obj)) } }
function draw_passenger_sm(passenger, wrapper) { var cad=''; var pay='PAGADO'; var classpagado='paid'; var color='style="color:green; padding-top: 2px; padding: 0px; text-align: center;"'; if(passenger.paid==0){ cad = 'background-color:#f8bfbf;'; pay = 'NO PAGADO'; classpagado="notpaid"; color='style="color:red; padding-top: 2px; padding: 0px; text-align: center;"';} if(passenger.validated==0){ cad = cad + 'text-decoration: line-through;';} /*var item = $('<div></div>').attr({'class':cad, 'data-id':passenger.id}); sm3.append(item); var title = $('<div></div>').attr({'class':'title','style':'max-height: 20px; overflow: hidden;'}).text(passenger.name+' '+passenger.surname); item.append(title); var text = $('<div></div>').attr({'class':'text','style':'max-height: 20px; overflow: hidden;'}).text(passenger.email); item.append(text); var text = $('<div></div>').attr({'class':'text', 'style':'max-height: 20px; overflow: hidden;'}).text(passenger.phone); item.append(text); item.click(function(){ modal_passenger_details(passenger.id); })*/ $('#tableweybody2').append('<tr style="cursor:pointer; '+cad+'" data-id="'+passenger.id+'">'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.name+'</td>'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.surname+'</td>'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.credit_wod+'/'+passenger.credit_wod_tarifa+'</td>'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.credit_box+'/'+passenger.credit_box_tarifa+'</td>'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.credit_bono+'/'+passenger.credit_bono_tarifa+'</td>'+'<td onclick="modal_passenger_details('+passenger.id+');">'+passenger.tarifa_vigente+' ('+passenger.tarifa_vigente_precio+'€)'+'</td>'+'<td '+color+' class="pagador '+classpagado+'">'+pay+'</td>'+'</tr>'); $(".pagador").hover(function(){ if($(this).hasClass('paid')){ $(this).html('<button onclick="revertirPago(this);" style="color:red; margin-top:0px; margin-bottom: 0px; margin-left:auto; margin-right: auto;">REVERTIR</button>'); }else{ if($(this).hasClass('notpaid')){ $(this).html('<button onclick="pagar(this);" style="color:green; margin-top:0px; margin-bottom: 0px; margin-left:auto; margin-right: auto;">PAGAR</button>'); } } }, function(){ if($(this).hasClass('paid')){ $(this).html('PAGADO'); }else{ if($(this).hasClass('notpaid')){ $(this).html('NO PAGADO'); } } }); } function draw_passenger_md(passenger, wrapper) { var sm3 = $('<div></div>').attr({'class':'col-sm-12'}); wrapper.append(sm3); var item = $('<div></div>').attr({'class':'item linkable', 'data-id':passenger.id}); sm3.append(item); var title = $('<div></div>').attr({'class':'title','style':'max-height: 20px; overflow: hidden;'}).text(passenger.name); item.append(title); var text = $('<div></div>').attr({'class':'text', 'style':'max-height: 20px; overflow: hidden;'}).text(passenger.email); item.append(text); var text = $('<div></div>').attr({'class':'text', 'style':'max-height: 20px; overflow: hidden;'}).text(passenger.phone); item.append(text); item.click(function(){ modal_passenger_details(passenger.id); }) } function draw_not_auth_md(passenger, wrapper) { var sm3 = $('<div></div>').attr({'class':'col-sm-12'}); wrapper.append(sm3); var item = $('<div></div>').attr({'class':'item linkable', 'data-id':passenger.email}); sm3.append(item); var title = $('<div></div>').attr({'class':'title'}).text(passenger.email); item.append(title); }
import { combineReducers } from 'redux'; import searchUserReducer from './searchUser'; import userData from './userDetail'; export const rootReducer = combineReducers({ searchUser: searchUserReducer, userData: userData, });