text
stringlengths
7
3.69M
import { config } from '../config/config' export class PlayScene extends Phaser.Scene { constructor() { super({ key: config.scenes.play }) this.ui = {} this.cards = [] this.initialize() } initialize() { this.points = 0 this.currentCard = null this.remainingCards = 0 this.flippedCardCount = 0 this.triesCount = 0 this.remainingCards = this.cards.length / 2 } drawUI() { this.add .image(0, 0, config.images.bg) .setOrigin(0) .setAlpha(0.6) .setDepth(0) .setScale(0.4) this.ui.score = this.add.text(25, 25, `Pontos: ${this.points}`, { style: { font: '20px monospace', fill: '#ffffff' } }) } setCardData(card, frame) { const frameKey = `${frame.key}-${this.cards.length}` card.setDataEnabled() card.data.set('name', frame.frame) card.data.set('selected', 0) card.data.set('key', frameKey) card.data.set('flipped', 1) card.setTexture('items', 'map.png') } generateCardDeck() { const frameNames = this.anims.generateFrameNames('items', { frames: ['armor', 'axe', 'axeDouble', 'backpack', 'bow', 'coin', 'dagger', 'envelope'], suffix: '.png' }) this.cardGroup = this.add.group({}) frameNames.map(frame => { const card = this.make.sprite(frame.key, frame.frame) this.setCardData(card, frame) this.cardGroup.add(card) this.cards.push(card) }) frameNames.map(frame => { const card = this.make.sprite(frame.key, frame.frame) this.setCardData(card, frame) this.cardGroup.add(card) this.cards.push(card) }) this.remainingCards = this.cards.length / 2 } selectCard(card) { if (!this.currentCard) { this.currentCard = card return } if (this.currentCard.data.get('key') === card.data.get('key')) { return } const curCardName = this.currentCard.data.get('name') const selCardName = card.data.get('name') if (curCardName === selCardName) { this.time.delayedCall(800, () => { this.currentCard.setVisible(false) card.setVisible(false) this.currentCard = null this.remainingCards-- this.flippedCardCount = 0 this.sound.play(config.audio.flipSuccess) this.finishGame() }) this.points += 50 return } this.currentCard = null this.time.delayedCall(800, () => { this.triesCount++ this.sound.play(config.audio.flipFail) this.flipAll() }) } flipAll() { this.cards.map(card => { const unflipped = !card.data.get('flipped') if (unflipped) { this.flip(card) } }) this.flippedCardCount = 0 } flip(card) { const timeline = this.tweens.createTimeline() timeline.add({ targets: card, scaleX: 0, scaleY: 1, ease: 'Linear', duration: 100, repeat: 0, yoyo: false, onComplete: () => { card.data.set('flipped', 1) card.setTexture('items', 'map.png') } }) timeline.add({ targets: card, scaleX: 1, scaleY: 1, ease: 'Linear', duration: 100, repeat: 0, yoyo: false }) timeline.play() } unflip(card) { const timeline = this.tweens.createTimeline() timeline.add({ targets: card, scaleX: 0, scaleY: 1, ease: 'Linear', duration: 100, repeat: 0, yoyo: false, onComplete: () => { const name = card.data.get('name') card.data.set('flipped', 0) this.selectCard(card) card.setTexture('items', name) this.flippedCardCount++ } }) timeline.add({ targets: card, scaleX: 1, scaleY: 1, ease: 'Linear', duration: 100, repeat: 0, yoyo: false }) timeline.play() } flipCard(card) { const flipped = card.data.get('flipped') if (flipped) { this.sound.play(config.audio.flip) this.unflip(card) return } // this.flip(card) } attachCardEvents() { this.cards.map(card => { card.setInteractive() card.on('pointerup', () => { if (this.flippedCardCount >= 2) { return } const selected = card.data.get('selected') card.data.set('selected', !selected) this.flipCard(card) }) }) } drawCards() { Phaser.Actions.GridAlign(this.cardGroup.getChildren(), { width: 4, height: 4, cellWidth: 100, cellHeight: 120, x: 250, y: 150 }) } shuffleCards() { Phaser.Actions.Shuffle(this.cardGroup.getChildren()) } create() { this.drawUI() this.generateCardDeck() this.attachCardEvents() this.shuffleCards() this.drawCards() } resetGame() { this.initialize() this.shuffleCards() this.flipAll() this.cards.map(card => { card.setVisible(true) }) this.time.delayedCall(500, () => { this.drawCards() }) } finishGame() { if (this.remainingCards !== 0) { return } this.sound.play(config.audio.levelCompleted) this.resetGame() } update() { this.ui.score.setText([ `Pontos: ${this.points}\nFalta: ${this.remainingCards}\nTentativas: ${this.triesCount}` ]) } }
// Exercice 4 /** Créer un timer. Toute les secondes, incrémenter un chiffre pour le faire afficher dans le span#timer/ Un bouton doit permettre de recommencer et un autre bouton pour faire pause/play */ console.log('exercice 4') const timerElm = document.getElementById('timer') const replayElm = document.getElementById('replay') const pauseElm = document.getElementById('toggle-timer') let status = 'IS_PLAYING' let currentInterval = null let currentTime = null let number = 0 function playTimer() { currentInterval = setInterval(() => { if(number === 5) { stopAndReset() }else { number = number + 1 timerElm.textContent = number } }, 1000) pauseElm.textContent = 'Pause' status = 'IS_PLAYING' } function clearTimer() { clearInterval(currentInterval) currentInterval = null pauseElm.textContent = 'Play' status = 'IS_PAUSED' } function stopAndReset() { number = 0 timerElm.textContent = number clearTimer() } playTimer(number) pauseElm.addEventListener('click', function() { if (status === 'IS_PLAYING') { clearTimer() } else { playTimer() } }) replayElm.addEventListener('click', function(){ stopAndReset() playTimer() })
import React, {createContext, useEffect, useContext, useReducer, useState} from 'react'; import {mainReducer} from "../reducers"; import Cookie from "js-cookie"; import dispatchMiddleware from "../reducers/fetchMiddleware"; import {useStream} from "./useStream"; // TODO move state data structure and initialization function to another file function init(initialState) { if (Object.keys(initialState).length === 0) { return { user: { isLoading: true, name: undefined }, agent: { appCodeName: navigator.appCodeName, appName: navigator.appName, appVersion: navigator.appVersion, cookieEnabled: navigator.cookieEnabled, language: navigator.language, onLine: navigator.onLine, platform: navigator.platform, userAgent: navigator.userAgent }, listening: false, theme: { primary: 'blue' }, prodDevProjects: [{ id: "", name: "", startDate: "" }] } } return initialState; } const StateContext = createContext(); // useReducer accepts reducer function of type (state, action) => newState, // and returns the current state paired with a dispatch method. export const StateProvider = ({initialState, children}) => { const [state, dispatch] = useReducer(mainReducer, initialState, init); // TODO do this after syncing user and auth useStream(state.listening, dispatch); return ( <StateContext.Provider value={[state, dispatchMiddleware(dispatch)]}> {children} </StateContext.Provider> ) }; export const useStateValue = () => useContext(StateContext); // returns the current context value for StateContext
import wepy from 'wepy' import api from '../api/index' /*** * 注意: * 1. 默认式混合:对于组件data数据,components组件,events事件以及其它自定义方法采用默认式混合,即如果组件未声明该数据,组件,事件,自定义方法等,那么将混合对象中的选项将注入组件这中。对于组件已声明的选项将不受影响。 * 2. 兼容式混合:对于组件methods响应事件,以及小程序页面事件将采用兼容式混合,即先响应组件本身响应事件,然后再响应混合对象中响应事件。 */ export default class LoginMixin extends wepy.mixin { data = { } methods = { } computed = { } watch = { } onShow() { } async getLogin() { const self = this let toRoute = '' if (this.$parent.__route__) { const goRoute = this.$parent.__route__ const index = goRoute.indexOf('/') toRoute = goRoute.slice(index + 1) } wx.showModal({ title: '授权提示', content: '检测到您没打开鲜盒子的登录权限,是否去设置打开?', success(res) { if (res.confirm) { wx.openSetting({ success(res) { const { authSetting } = res if (authSetting['scope.userInfo']) { console.log('0000') wepy.setStorageSync('isAgree', true) self.login() } self.$apply() } }) } else if (res.cancel) { // console.log('用户取消授权') } } }) } toIndex() { this.$switch({ url: './index' }) } async onLoad() { } }
import {createStore, applyMiddleware, compose} from 'redux' import rootReducer from '../reducer/index'; import thunk from 'redux-thunk'; export function configureStore() { const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; return createStore(rootReducer, composeEnhancers(applyMiddleware(thunk))) }
import React from 'react'; import { BackGround } from './elements/BackGround/BackGround'; import { Header } from './elements/Header'; import { Icon } from './elements/Icon'; import { Information } from './elements/Information/Information'; import { SearchingPanel } from './elements/SearchingPanel/SearchingPanel'; import style from './style.module.css'; export const Widget = () => ( <div className={style.widget}> <Header /> <Icon /> <BackGround /> <Information /> <SearchingPanel /> </div> );
courier.config({ paths: { "courier/*" : "../*.js", "@traceur": "traceur/traceur.js" } });
import React from "react"; import styles from "./Loader.css"; export default class Loader extends React.Component { render() { console.log("LOADER"); return ( <div> <div className={styles.background}></div> <div className={styles.loader}></div> </div> ); } }
const childProcess = require('child_process'); const fs = require('fs-extra'); const path = require('path'); const utility = require('../utility'); const startTime = Date.now(); const timestamp = utility.getTimestamp(startTime); const baseDpath = path.resolve(process.cwd(), 'testwork/size'); const resourceFpaths = [ '1_1.bmp:dir2/dir1/1_1.bmp', '1_1.gif:dir2/1_1.gif', '1_10.jpg:dir1/1_10.jpg', '10_1.png:10_1.png', '2_10.bmp:dir2/dir2/2_10.bmp', '10_2.gif:dir2/dir1/10_2.gif', '10_10.jpg:dir2/10_10.jpg', '10_10.png:dir1/10_10.png', 'file0:99_76543210987654321-file0', 'file1:dir1/file1', 'file2:dir2/98_76543210987654321-file2', 'file3:dir2/dir1/file3', 'file4:dir2/dir2/97_76543210987654321-file4', 'file5:file5', 'file6:dir1/96_76543210987654321-file6', 'file7:dir2/file7', 'file8:dir2/dir1/95_76543210987654321-file8', 'file9:dir2/dir2/file9' ]; const resourceSlpaths = [ 'file0:dir2/dir2/syml0' ]; const expectRecordList = [ '1_1/0_12345678901234567-1_1.bmp:dir2/dir1/1_1.bmp', '1_1/1_12345678901234567-1_1.gif:dir2/1_1.gif', '10_1/0_12345678901234567-1_10.jpg:dir1/1_10.jpg', '10_1/1_12345678901234567-10_1.png:10_1.png', '10_2/0_12345678901234567-2_10.bmp:dir2/dir2/2_10.bmp', '10_2/1_12345678901234567-10_2.gif:dir2/dir1/10_2.gif', '10_10/0_12345678901234567-10_10.jpg:dir2/10_10.jpg', '10_10/1_12345678901234567-10_10.png:dir1/10_10.png', 'other.d/0_12345678901234567-file0:99_76543210987654321-file0', 'other.d/1_12345678901234567-file1:dir1/file1', 'other.d/2_12345678901234567-file2:dir2/98_76543210987654321-file2', 'other.d/3_12345678901234567-file3:dir2/dir1/file3', 'other.d/4_12345678901234567-file4:dir2/dir2/97_76543210987654321-file4', 'other.d/5_12345678901234567-file5:file5', 'other.d/6_12345678901234567-file6:dir1/96_76543210987654321-file6', 'other.d/7_12345678901234567-file7:dir2/file7', 'other.d/8_12345678901234567-file8:dir2/dir1/95_76543210987654321-file8', 'other.d/9_12345678901234567-file9:dir2/dir2/file9' ]; const recordRegExp = /^(?<size>other\.d|\d+_\d+)\/(?<no>\d+)_\d{17}\-(?<newName>.+)\:(?<oldPath>.+)$/; const expectBeforeTargetFpathList = [ 'dir2/dir1/1_1.bmp', 'dir2/1_1.gif', 'dir1/1_10.jpg', '10_1.png', 'dir2/dir2/2_10.bmp', 'dir2/dir1/10_2.gif', 'dir2/10_10.jpg', 'dir1/10_10.png', '99_76543210987654321-file0', 'dir1/file1', 'dir2/98_76543210987654321-file2', 'dir2/dir1/file3', 'dir2/dir2/97_76543210987654321-file4', 'file5', 'dir1/96_76543210987654321-file6', 'dir2/file7', 'dir2/dir1/95_76543210987654321-file8', 'dir2/dir2/file9' ].map(testPath => path.resolve(baseDpath, testPath)).sort(); const expectBeforeTargetSLpathList = [ 'dir2/dir2/syml0' ].map(testPath => path.resolve(baseDpath, testPath)).sort(); const expectExtraPathList = [ 'extra.d', 'extra.d/dir1', 'extra.d/dir2', 'extra.d/dir2/dir1', 'extra.d/dir2/dir2', 'extra.d/dir2/dir2/syml0' ].sort(); // test log // test target directory // test extra directory const test_not_forced = async () => { childProcess.execSync(`node size ./testwork/size -s TEST_NOT_FORCED`); // test log const info = require(utility.getLatestFpath('./logs', timestamp, 'size_TEST_NOT_FORCED.json')); if (info['Target directory'] !== baseDpath) { throw new Error(`Target directory: ${info['Target directory']}`); } if (info['Target file count'] !== expectBeforeTargetFpathList.length) { throw new Error(``); } if (info['Target symbolic link count'] !== expectBeforeTargetSLpathList.length) { throw new Error(``); } if (info['Forced'] !== false) { throw new Error(`Forced: ${info['Forced']}`); } if (info['Extra directory'] !== null) { throw new Error(`Extra directory: ${info['Extra directory']}`); } if (info['Records'].length !== expectRecordList.length) { throw new Error(`${expectRecordList.length} !== ${info['Records'].length}`); } const records = info['Records'].map(record => record.replaceAll(path.sep, '/')); for (let i = 0; i < records.length; i++) { const record = records[i]; if (!recordRegExp.test(record)) { throw new Error(``); } } const actualRecord_size_no = records.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.no}`; }).sort(); const expectRecord_size_no = expectRecordList.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.no}`; }).sort(); for (let i = 0; i < actualRecord_size_no.length; i++) { const actual = actualRecord_size_no[i]; const expect = expectRecord_size_no[i]; if (actual !== expect) { throw new Error(``); } } const actualRecord_size_newName_oldPath = records.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.newName}:${groups.oldPath}`; }).sort(); const expectRecord_size_newName_oldPath = expectRecordList.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.newName}:${groups.oldPath}`; }).sort(); for (let i = 0; i < actualRecord_size_newName_oldPath.length; i++) { const actual = actualRecord_size_newName_oldPath[i]; const expect = expectRecord_size_newName_oldPath[i]; if (actual !== expect) { throw new Error(``); } } if (!(-1 < info['Time'])) { throw new Error(`Time: ${info['Time']}`); } // test target directory const targetFpaths = utility.getFilePaths('./testwork/size').sort(); if (targetFpaths.length !== expectBeforeTargetFpathList.length) { throw new Error(``); } for (let i = 0; i < targetFpaths.length; i++) { if (targetFpaths[i] !== expectBeforeTargetFpathList[i]) { throw new Error(``); } } const targetSlpaths = utility.getSymbolicLinkPaths('./testwork/size').sort(); if (targetSlpaths.length !== expectBeforeTargetSLpathList.length) { throw new Error(``); } for (let i = 0; i < targetSlpaths.length; i++) { if (targetSlpaths[i] !== expectBeforeTargetSLpathList[i]) { throw new Error(``); } } // test extra directory const execIdDpath = utility.getLatestDpath('./extra', timestamp, 'size_TEST_NOT_FORCED'); if (execIdDpath !== null) { throw new Error(`${execIdDpath}`); } }; // test log // test target directory // test extra directory const test_forced = async () => { childProcess.execSync(`node size ./testwork/size -s TEST_FORCED -F`); // test log const info = require(utility.getLatestFpath('./logs', timestamp, 'size_TEST_FORCED.json')); if (info['Target directory'] !== baseDpath) { throw new Error(`Target directory: ${info['Target directory']}`); } if (info['Target file count'] !== expectBeforeTargetFpathList.length) { throw new Error(``); } if (info['Target symbolic link count'] !== expectBeforeTargetSLpathList.length) { throw new Error(``); } if (info['Forced'] !== true) { throw new Error(`Forced: ${info['Forced']}`); } const execIdDpath = utility.getLatestDpath('./extra', timestamp, 'size_TEST_FORCED'); if (info['Extra directory'] !== execIdDpath) { throw new Error(`Extra directory: ${info['Extra directory']}`); } if (info['Records'].length !== expectRecordList.length) { throw new Error(`${expectRecordList.length} !== ${info['Records'].length}`); } const records = info['Records'].map(record => record.replaceAll(path.sep, '/')); for (let i = 0; i < records.length; i++) { const record = records[i]; if (!recordRegExp.test(record)) { throw new Error(``); } } const actualRecord_size_no = records.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.no}`; }).sort(); const expectRecord_size_no = expectRecordList.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.no}`; }).sort(); for (let i = 0; i < actualRecord_size_no.length; i++) { const actual = actualRecord_size_no[i]; const expect = expectRecord_size_no[i]; if (actual !== expect) { throw new Error(``); } } const actualRecord_size_newName_oldPath = records.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.newName}:${groups.oldPath}`; }).sort(); const expectRecord_size_newName_oldPath = expectRecordList.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.newName}:${groups.oldPath}`; }).sort(); for (let i = 0; i < actualRecord_size_newName_oldPath.length; i++) { const actual = actualRecord_size_newName_oldPath[i]; const expect = expectRecord_size_newName_oldPath[i]; if (actual !== expect) { throw new Error(``); } } if (!(-1 < info['Time'])) { throw new Error(`Time: ${info['Time']}`); } // test target directory const targetPaths = utility.getFilePaths('./testwork/size'). concat(utility.getSymbolicLinkPaths('./testwork/size')). map(testPath => testPath.replaceAll(path.sep, '/')); if (targetPaths.length !== expectRecordList.length) { throw new Error(``); } const targetPathRegExp = /^(?:.+)\/(?<size>other\.d|\d+_\d+)\/(?<no>\d+)_\d{17}\-(?<name>.+)$/; for (let i = 0; i < targetPaths.length; i++) { const testPath = targetPaths[i]; if (!targetPathRegExp.test(testPath)) { throw new Error(``); } } const actualTargetPath_size_name = targetPaths.map(testPath => { const groups = targetPathRegExp.exec(testPath).groups; return `${groups.size}:${groups.name}`; }).sort(); const expectTargetPath_size_name = expectRecordList.map(record => { const groups = recordRegExp.exec(record).groups; return `${groups.size}:${groups.newName}`; }).sort(); for (let i = 0; i < actualTargetPath_size_name.length; i++) { const actual = actualTargetPath_size_name[i]; const expect = expectTargetPath_size_name[i]; if (actual !== expect) { console.log(actual); console.log(expect); throw new Error(``); } } // test extra directory const extraPaths = utility.getAllPaths(execIdDpath).map(testPath => testPath.replaceAll(path.sep, '/')); if (extraPaths.length !== expectExtraPathList.length) { throw new Error(``); } for (let i = 0; i < extraPaths.length; i++) { const testPath = extraPaths[i]; if (fs.lstatSync(testPath).isFile()) { throw new Error(``); } } const omittedExtraPaths = extraPaths.map(testPath => utility.omitPath(testPath, execIdDpath)).sort(); for (let i = 0; i < omittedExtraPaths.length; i++) { if (omittedExtraPaths[i] !== expectExtraPathList[i]) { throw new Error(``); } } }; const main = async () => { fs.emptyDirSync(baseDpath); utility.generateResourceFiles(baseDpath, resourceFpaths); utility.generateResourceSymbolicLinks(baseDpath, resourceSlpaths); await test_not_forced(); await test_forced(); }; main(). catch(e => console.error(e.stack)). finally(() => console.log('End'));
import React, { Fragment, useState, useCallback } from "react"; import { Link, withRouter } from "react-router-dom"; import { auth, db } from "./components/Firebase"; import { Button, Card, CardTitle, Form, Input, Container, Row, Col, } from "reactstrap"; const Register = (props) => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); // const [registering, setRegistering] = useState(true); const registerData = (e) => { e.preventDefault(); if (!email.trim()) { // console.log("Enter Email"); setError("Enter Email"); return; } if (!password.trim()) { // console.log("Enter Password"); setError("Enter Password"); return; } if (password.length < 6) { // console.log("Enter 6 characters or more"); setError("Enter 6 characters or more"); return; } console.log("It is right..."); setError(null); // if (isRegister) { // registrar(); // } else { // login(); // } }; const registering = useCallback(async () => { try { const res = await auth.createUserWithEmailAndPassword(email, password); console.log(res); await db .collection("users") .doc(res.user.email) .set({ email: res.user.email, uid: res.user.uid }); setEmail(""); setPassword(""); setError(null); props.history.push("/salsa"); } catch (error) { setError(error.message); } }, [email, password,props.history]); document.documentElement.classList.remove("nav-open"); React.useEffect(() => { document.body.classList.add("login-page"); document.body.classList.add("full-screen"); window.scrollTo(0, 0); document.body.scrollTop = 0; return function cleanup() { document.body.classList.remove("login-page"); document.body.classList.remove("full-screen"); }; }); return ( <Fragment> <div className="wrapper"> <div className="page-header" style={{ backgroundImage: "url(https://images.unsplash.com/photo-1531747056595-07f6cbbe10ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80)", // "url(" + require("assets/img/sections/bruno-abatti.jpg") + ")", }} > <div className="filter-black" /> <Container> <Row> <Col className="ml-auto mr-auto" lg="4" md="6" sm="6"> <Card className="card-register bg-transparent"> <CardTitle tag="h3" className="text-light font-weight-bolder"> Welcome </CardTitle> <Form className="register-form" onSubmit={registerData}> {error && <div className="alert alert-danger">{error}</div>} <label>Email</label> <Input className="no-border" placeholder="Email" type="email" onChange={(e) => setEmail(e.target.value)} value={email} /> <label>Password</label> <Input className="no-border" placeholder="Password" type="password" onChange={(e) => setPassword(e.target.value)} value={password} /> <Button block className="btn-sm" color="danger" type="submit" onClick={registering} > Register </Button> </Form> <div className="forgot"> <Button className="btn-sm btn-outline-light" color="danger" type="button" to="/classes" tag={Link} > Already Have an account? </Button> </div> </Card> </Col> </Row> </Container> </div> </div> </Fragment> ); }; export default withRouter(Register);
var express = require('express'); var User = require('../model/User');//database driver //var multer = require('multer'); //var upload = multer({ dest: 'uploads/' })//upload file module var fs = require('fs');//file system var os = require('os'); var formidable = require('formidable'); var gm = require('gm');//Grapihc Magic (resize image) var app = require('../app'); var router = express.Router(); /* GET users listing. */ var name; router.get('/', function(req, res, next) { //res.sendfile('views/user.html'); //res.sendFile('user.html',{"root":'views'}) console.log(req.session_notesource); var user = req.session_notesource.user; if(user){ name = user.fname; res.render( 'user', { name : user.fname ,host:req.app.get('host')});//parameter for ejs }else{ name = 'Wasin(ejs)'; res.render( 'user', { name : 'Wasin(ejs)',host:req.app.get('host')});//parameter for ejs } }); //log out router.get('/logout', function(req, res) { req.session_notesource.reset(); res.redirect('/'); }); //upload file router.post('/upload',(req,res,next)=>{ function generateFilename(filename){ var ext_regex = /(?:\.([^.]+))?$/; var ext = ext_regex.exec(filename)[1]; var date = new Date().getTime(); var charBank = 'abcdefghijklmnopqrstuvwxyz'; var fstring =''; for(var i=0;i<15;i++)fstring+=charBank[parseInt(Math.random()*26)]; return (fstring+=date+'.'+ext); } var tmpFile,nfile,fname; var newForm = new formidable.IncomingForm();//recieve new form that come in newForm.keepExtensions = true; newForm.parse(req,(err,fields,files)=>{ tmpFile = files.upload.path; fname = generateFilename(files.upload.name);//generate filename to store nfile = os.tmpDir()+'/'+fname;//os.tmpDir is tmp directory on the server res.writeHead(200,{'Content-Type':'text/plain'}); res.end(); }); newForm.on('end',()=>{//when 'end' method being called fs.rename(tmpFile,nfile,()=>{ //Resize the image and upload to S3 bucket gm(nfile).resize(300).write(nfile,()=>{ //upload to S3 bucket fs.readFile(nfile,(err,buffer)=>{ var knoxClient = app.knoxClient; var req = knoxClient.put(fname,{ 'Content-Length':buffer.length, 'Content-Type':'image/jpeg' });//PUT METHOD for putting the file req.on('response',(res)=>{ if(res.statusCode==200){ //file is in S3 bucket console.log('uploaded file!!'); } }); req.end(buffer); }); }); }); }); }); module.exports = { router, name }
module.exports = { read_if: read_if }; function read_if() { var ast = ast_new("if-statement"); if (!accept("if")) { return error("expected if literal"); } var test_expr = read_expression(); if (is_error(test_expr)) { return test_expr; } ast.test = test_expr; if (!accept("{")) { return error("expected: '{'"); } read_source_elements(ast, true); if (is_error(ast.body)) { return ast.body; } if (!accept("}")) { return error("expected: '}'"); } if (accept("else")) { if (test("if")) { ast.else = read_if(); } else { ast.else = read_block_statement(); } } return ast_end(ast); }
// 大宗商品列表文案 import React, { Component, PureComponent } from 'react'; import { StyleSheet, Dimensions, View, Text, Image, TouchableOpacity, } from 'react-native'; import CommonStyles from '../common/Styles'; const { width, height } = Dimensions.get('window'); import math from "../config/math.js"; import BlurredPrice from './BlurredPrice' import { getSalePriceText } from '../config/utils' export default class CommoditiesText extends PureComponent { static defaultProps = { subscription: 0, // 预约金 price: 0, // 原价 buyPrice: 0, // 购买价格 subscriptionStyle: {}, buyPriceStyle: {}, priceStyle: {}, } render() { const { subscription, price, buyPrice, priceStyle, buyPriceStyle, subscriptionStyle } = this.props return ( <View style={[styles.commoditiesWrap]}> <View style={[CommonStyles.flex_start]}> <Text style={styles.fz12color222}>特惠价:</Text> <Text style={[styles.fz14color222, buyPriceStyle]}>¥</Text> <BlurredPrice color='black'> <Text style={[styles.fz14color222, buyPriceStyle]}>{ getSalePriceText(math.divide(buyPrice || 0, 100)) }</Text> </BlurredPrice> </View> <View style={[CommonStyles.flex_start]}> { price !== 0 && <Text style={styles.fz12color222}>原价:<Text style={[styles.fz12color999, priceStyle]}>¥{ getSalePriceText(math.divide(price || 0, 100)) }</Text></Text> } </View> { subscription !== 0 ? <View style={[CommonStyles.flex_start]}> <Text style={styles.fz12color222}>预约金:</Text> <Text style={[styles.red_color, { fontSize:12 }]}>¥</Text> <BlurredPrice> <Text style={[styles.red_color, { fontSize: 15 }, subscriptionStyle]}>{ getSalePriceText(math.divide(subscription || 0, 100)) }</Text> </BlurredPrice> </View> : null } </View> ); } }; const styles = StyleSheet.create({ commoditiesWrap: { marginTop: 5 }, fz12color222: { fontSize: 12, color: '#222' }, fz14color222: { fontSize: 14, color: '#222' }, fz12color999: { fontSize: 12, color: '#999', textDecorationLine:'line-through', marginLeft: 5}, red_color: { color: '#EE6161'} })
import React, { useReducer } from "react"; import navigationReducer from "./navigation.reducer"; import navigationInitialState from "./navigation.initialState"; import Context from "./navigation.context"; export default function Provider({ children }) { const [state, dispatch] = useReducer(navigationReducer, navigationInitialState); return <Context.Provider value={{ data: state, dispatch }}>{children}</Context.Provider>; }
var canvas = document.getElementById('canva'); var ctx = canvas.getContext("2d"); canvas.width = document.getElementById('canva').offsetWidth; canvas.height = document.getElementById('canva').offsetHeight; var pixels = []; var myImageData = ctx.createImageData(canvas.width, canvas.height); var canvasTest = document.getElementById('canvaTest'); var ctxTest = canvasTest.getContext("2d"); c = 0; var animated = false; document.getElementById('btn').onclick = function(){ if(animated)return 0; c++; if(c%2 == 0){ destroy(); return 0; } ctxTest.fillStyle = "#000"; ctxTest.font = "80pt Arial"; ctxTest.fillText(document.getElementById('in').value, 0, 100,600); var text = ctxTest.measureText(document.getElementById('in').value); canvasTest.width = text.width; ctxTest.fillStyle = "#000"; ctxTest.font = "80pt Arial"; ctxTest.fillText(document.getElementById('in').value, 0, 100,600); var wordPixels = ctxTest.getImageData(0,0,canvasTest.width,canvasTest.height); var to = []; var time = 0; for(let i = 3;i < wordPixels.data.length;i+=4){ if(wordPixels.data[i] == 255){ let y = Math.round(i/4/canvasTest.width); let x = (i/4)%canvasTest.width; to.push([x+canvas.width/2-text.width/2,y+canvas.height/2-75]); } } setPixels(to.length); drawPixels(); var up = setInterval(update,20); setTimeout(function(){ clearInterval(up); animated = false; canvasTest.width = canvasTest.width; },3000); function setPixels(n){ if(pixels.length > 10){ if(pixels.length < n){ for(let i = pixels.length;i<to.length;i++){ var posX = Math.round(Math.random()*(canvas.width)); var posY = Math.round(Math.random()*(canvas.height)); var speed = []; speed[0] = (to[i][0] - posX)/3; speed[1] = (to[i][1] - posY)/3; var obj = { "color" : [0,0,0,255], "pos" : [posX,posY], "to" : [to[i][0],to[i][1]], "speed" : speed } pixels.push(obj); } } if(n < pixels.length){ for(i = pixels.length;i>=to.length;i--){ pixels.pop(); } } for(let i = 0;i<pixels.length;i++){ pixels[i].to = [to[i][0],to[i][1]]; pixels[i].speed = [(to[i][0] - pixels[i].pos[0])/3,(to[i][1] - pixels[i].pos[1])/3]; } return 0; } for(let i = 0;i<n;i++){ var posX = Math.round(Math.random()*(canvas.width)); var posY = Math.round(Math.random()*(canvas.height)); var speed = []; speed[0] = (to[i][0] - posX)/3; speed[1] = (to[i][1] - posY)/3; var obj = { "color" : [0,0,0,255], "pos" : [posX,posY], "to" : [to[i][0],to[i][1]], "speed" : speed } pixels.push(obj); } } function destroy(){ for(let i = 0;i<pixels.length;i++){ let x = Math.round(Math.random()*canvas.width); let y = Math.round(Math.random()*canvas.height); pixels[i].to[0] = x; pixels[i].to[1] = y; pixels[i].speed[0] = (x - pixels[i].pos[0])/3; pixels[i].speed[1] = (y - pixels[i].pos[1])/3; } var time = 0; up = setInterval(update,20); setTimeout(function(){ clearInterval(up); animated = false; canvasTest.width = canvasTest.width; $('#btn').trigger('click'); },3000); } function drawPixels(){ canvas.width = canvas.width; myImageData = ctx.createImageData(canvas.width, canvas.height); for(let i = 0;i<pixels.length;i++){ let color = pixels[i].color; let x = Math.round(pixels[i].pos[0]), y = Math.round(pixels[i].pos[1]); myImageData.data[ (y*canvas.width*4)+ ((x)*4 )] = color[0]; myImageData.data[ (y*canvas.width*4)+ ((x)*4 ) +1] = color[1]; myImageData.data[ (y*canvas.width*4)+ ((x)*4 ) +2] = color[2]; myImageData.data[ (y*canvas.width*4)+ ((x)*4 ) +3] = color[3]; } ctx.putImageData(myImageData, 0, 0); } function update(){ for(let i = 0;i<pixels.length;i++){ pixels[i].pos[0] += pixels[i].speed[0]/50; pixels[i].pos[1] += pixels[i].speed[1]/50; } drawPixels(); } }
var Config = { client_id: "XXXXXXXXXXXXXXXX" , client_secret: "XXXXXXXXXXXXXXXXX" , authorization_url: "https://prepiam.toronto.ca.ibm.com/idaas/oidc/endpoint/default/authorize" , token_url: "https://prepiam.toronto.ca.ibm.com/idaas/oidc/endpoint/default/token" , issuer_id: "https://prepiam.toronto.ca.ibm.com" , callback_url: "https://ibmidexp.mybluemix.net/auth/callback" }; module.exports = Config;
import { secureStorage } from "./context" export const reducer = (state,action) => { let cart = [] const exist = state.cartItems ? state?.cartItems?.find((x) => x.id === action.item?.id) : undefined switch(action.type){ case "ADD_CART": if (exist !== undefined) cart = state?.cartItems && state?.cartItems?.map((x) => x.id === action.item.id ? { ...exist, qty: exist.qty + 1 } : x) else cart = [...state?.cartItems, { ...action.item, qty: 1 }] secureStorage.setItem('cartItems',cart) return { ...state , cartItems:cart} case "REMOVE_CART": if (exist.qty === 1) cart = state?.cartItems && state.cartItems?.filter((x) => x.id !== action.item.id) else cart = state?.cartItems && state.cartItems?.map((x) => x.id === action.item.id ? { ...exist, qty: exist.qty - 1 } : x) secureStorage.setItem('cartItems',cart) return { ...state , cartItems:cart} case "SET_USER": secureStorage.setItem('user', action.user) secureStorage.setItem('token', action.token) return { ...state , user:action.user } case "UNSET_USER": secureStorage.removeItem('user') return {...state , user:{} } case "SET_PRICE": secureStorage.setItem('priceDetails', action.priceDetails) return {...state , priceDetails:action.priceDetails } case "EMPTY_CART": secureStorage.removeItem('cartItems') return {...state , cartItems:{} } default: return state } }
import './App.css'; import Main from './components/Main'; import Experience from './components/pages/Experience'; import Education from './components/pages/Education'; import Contact from './components/pages/Contact'; import 'bootstrap/dist/css/bootstrap.min.css'; import React from 'react'; import { Route } from 'react-router-dom'; function App() { return ( <div className="App"> {/* <Navbar /> */} <Route exact path='/' render={props => <Main {...props} />} /> {/* Routes */} <Route exact path='/Experience' render={props => <Experience {...props} />} /> <Route exact path='/Education' render={props => <Education {...props} />} /> <Route exact path='/Contact' render={props => <Contact {...props} />} /> </div> ); } export default App;
angular .module('Creator') .factory('CreatorService', CreatorService); CreatorService.$inject = [ '$log', '$http', '$translate' ]; function CreatorService ( $log, $http, $translate ) { /// CreatorService var service = { /// constants BASIS_TAB_INDEX : 0, CATEGORIES_TAB_INDEX : 1, MENU_TAB_INDEX : 2, SETTINGS_TAB_INDEX : 3, MOBIDUL_CODE_EXAMPLE : 'mobidul-code', DEFAULT_FONT : 'default', /// services getCategories : getCategories, getOptions : getOptions, getConfig : getConfig, existsMobidul : existsMobidul, createMobidul : createMobidul, updateMobidul : updateMobidul, deleteMobidul : deleteMobidul, saveOptions : saveOptions, updateCategories : updateCategories, removeCategory : removeCategory, saveMenu : saveMenu, getCodes : getCodes, requestCode : requestCode, lockCode : lockCode, unlockCode : unlockCode, deleteCode : deleteCode, }; /// services function existsMobidul (mobidulCode) { var mobidulCode = mobidulCode.replace(/[^a-z0-9]/g, ''); return $http.get(cordovaUrl + '/existsMobidul/' + mobidulCode) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function createMobidul (params) { var mobidulData = JSON.stringify(params); return $http.post(cordovaUrl + '/NewMobidul', mobidulData) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function updateMobidul (mobidulCode, params) { var mobidulData = JSON.stringify(params); return $http.post(cordovaUrl + '/' + mobidulCode + '/UpdateMobidul', mobidulData) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function deleteMobidul (mobidulCode) { var params = { mobidulCode : mobidulCode }; var mobidulData = JSON.stringify( params ); return $http.post(cordovaUrl + '/DeleteMobidul', mobidulData) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function saveOptions (mobidulCode, params) { return $http.post(cordovaUrl + '/' + mobidulCode + '/SetOptions', params) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function updateCategories (mobidulCode, params) { return $http.post(cordovaUrl + '/' + mobidulCode + '/UpdateCategories', params) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function removeCategory (mobidulCode, categoryId) { return $http.get(cordovaUrl + '/' + mobidulCode + '/RemoveCategory/' + categoryId) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function getCategories (mobidulCode) { return $http.get(cordovaUrl + '/' + mobidulCode + '/GetCategories') .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function getOptions (mobidulCode) { return $http.get(cordovaUrl + '/' + mobidulCode + '/GetOptions') .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function getConfig (mobidulCode) { return $http.get(cordovaUrl + '/' + mobidulCode + '/getConfig') .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function getCodes (mobidulCode) { return $http.get(cordovaUrl + '/Codes/' + mobidulCode) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function requestCode (mobidulCode) { return $http.post(cordovaUrl + '/' + mobidulCode + '/GetPlayCode', {}) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function lockCode (codeToLock) { return $http.get(cordovaUrl + '/CloseCode/' + codeToLock) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function unlockCode (codeToUnlock) { return $http.get(cordovaUrl + '/OpenCode/' + codeToUnlock) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function deleteCode (codeToDelete) { return $http.get(cordovaUrl + '/DeleteCode/' + codeToDelete) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } function saveMenu (mobidulCode, params) { var params = JSON.stringify(params); return $http.post(cordovaUrl + '/' + mobidulCode + '/UpdateNavigation', params) .error(function (response, status, headers, config) { $log.error(response); $log.error(status); // TODO: Check whether returning the response might be needed for // follow-up promise call such as .success() return response; }); } return service; }
const findMaxAverage = (nums, k) => { let i=0; let tempSum = 0; while(i < k){ tempSum += nums[i++]; } let result = tempSum / k; for(let i =k; i < nums.length; i++){ tempSum = tempSum + nums[i] - nums[i-k]; result = Math.max((tempSum/k), result); console.log(tempSum, result); } return result; } console.log(findMaxAverage([5], 1));
import { ISSUE_STATUS_FILTER_CHANGED } from './action-types' export const issueStatusFilterChanged = () => ({ type: ISSUE_STATUS_FILTER_CHANGED })
'use strict' function someConvertTest() { return Array.prototype.slice.apply(arguments) } console.log(someConvertTest(1, 2, 3, '…', 42)) // prints [1, 2, 3, '…', 42]
import React, { Component } from 'react'; export default class extends Component { constructor(props) { super(props); } handleChange = (e) => { const { onChange } = this.props; onChange && onChange(e.target.value); } render() { const { name, value, describe = {type: 'text'} } = this.props; return ( <input type={describe.type} name={name} value={value} onChange={this.handleChange} /> ) } }
function multiPoly(p1,p2){ let [prefix1,prefix2] = [parseFloat(p1),parseFloat(p2)]; prefix1 = isNaN(prefix1) ? 1 : prefix1; prefix2 = isNaN(prefix2) ? 1 : prefix2; let [power1,power2] = [p1.split('^'),p2.split('^')]; power1 = power1.length > 1 ? parseFloat(power1[1]) : (p1.match('x') ? 1 : 0); power2 = power2.length > 1 ? parseFloat(power2[1]) : (p2.match('x') ? 1 : 0); let x = power1+power2 === 0 ? 1 : (power1+power2) === 1 ? 'x' : `x^${power1+power2}` return prefix1 * prefix2 === 1 ? `${x}` : `${(prefix1 * prefix2)}${x}`; } var topEnv = Object.create(null); // var func = Object.create(null); function which3(...args){ if(args.length < 3) return args; let [value1,op,value2] = [...args] if(value1.toString() === value2.toString()) switch(op){ case "+" : return [2 ,"*", value2]; case "-" : return 0; case "*" : return [value1 ,"^", 2]; case "/" : return 1; } return [value1,op,value2]; } function which2(value1,op,value2){ switch(op){ case "+" : return typeof(value1) === 'number' && value1=== 0 ? value2 : (typeof(value2) === 'number' && value2=== 0? value1: [value1,op,value2]); // case "-" : return value1 - value2; case "*" : return typeof(value1) === 'number' && value1=== 0 ? 0 : (typeof(value2) === 'number' && value2=== 0? 0: (typeof(value1) === 'number' && value1=== 1 ? value2 : (typeof(value2) === 'number' && value2=== 1? value1: [value1,op,value2]))); case "/" : return typeof(value1) === 'number' && value1=== 0 ? 0 : [value1,op,value2]; } return [value1,op,value2]; } function which(value1,op,value2){ if(typeof(value1)==='number' && typeof(value2)==='number' ) switch(op){ case "+" : return value1 + value2; case "-" : return value1 - value2; case "*" : return value1 * value2; case "/" : return value1 / value2; } return [value1,op,value2]; } function _reduce(arr){ if(typeof(arr[0]) !== 'string') [arr[0],arr[1]] = [arr[1],arr[0]]; if(arr.length === 3) return `(${arr[0]} ${Array.isArray(arr[1]) ? _reduce(arr[1]): arr[1]} ${Array.isArray(arr[2]) ? _reduce(arr[2]): arr[2]})` else if(arr.length === 2) return `(${arr[0]} ${Array.isArray(arr[1]) ? _reduce(arr[1]): arr[1]})` } function reduceFn(operation){ let operator= typeof(operation.operator) === 'object' && 'name' in operation.operator ? operation.operator.name : operation.operator; let result = {type: 'func',body:[]} let left = reduce(operation.args[0]); left = typeof(left) === 'object' && 'body' in left ? left.body : left; result.body.push(operator); result.body.push(left); return result; } function reduce(operation){ if(operation.type !== 'apply'){ return operation.value ? operation.value : operation; }else{ if(operation.args.length < 2){ return reduceFn(operation); } let operator= typeof(operation.operator) === 'object' && 'name' in operation.operator ? operation.operator.name : operation.operator; let result = {type: 'func',body:[]} let left = reduce(operation.args[0]); left = typeof(left) === 'object' && 'body' in left ? left.body : left; result.body.push(left); result.body.push(operator); let right = reduce(operation.args[1]); right = typeof(right) === 'object' && 'body' in right ? right.body : right; result.body.push(right); result.body=which(...result.body); if(typeof(result.body) === 'number') return result.body; result.body = which2(...result.body); if(typeof(result.body) === 'number') return result.body; result.body = which3(...result.body); if(result.body.length < 3) return result; result.body = [result.body[1],result.body[0],result.body[2]]; // return _reduce(...result.body); return result; } } topEnv["*"] = function(f,g){ let _f = derive(Object.assign({},f),topEnv); let _g = derive(Object.assign({},g),topEnv); let args =[]; if(_f.type === 'value' && g.type === 'value'){ args.push({type: 'value',value : parseFloat(_f.value) * parseFloat(g.value)}) }else{ args.push({type: "apply",operator: "*", args: [_f ,g]}) } if(f.type === 'value' && _g.type === 'value'){ args.push({type: 'value',value : parseFloat(f.value) * parseFloat(_g.value)}) }else{ args.push({type: "apply",operator: "*", args: [f ,_g]}) } if(args[0].type === 'value' && args[1].type === 'value'){ return {type: 'value',value: args[0] + args[1]} }else{ return {type: "apply",operator: "+", args: args}; } } topEnv["-"] = function(f,g){ let _f = derive(Object.assign({},f),topEnv); let _g = derive(Object.assign({},g),topEnv); let args = [_f ,_g]; return {type: "apply",operator: "-", args: args}; } topEnv["+"] = function(f,g){ let _f = derive(Object.assign({},f),topEnv); let _g = derive(Object.assign({},g),topEnv); let args = [_f, _g]; return {type: "apply",operator:"+", args: args}; } topEnv["/"] = function(f,g){ let _f = derive(Object.assign({},f),topEnv); let _g = derive(Object.assign({},g),topEnv); let args =[]; args.push({type: "apply",operator: "*", args: [_f,g]}) args.push({type: "apply",operator: "*", args: [f,_g]}) let dividend = {type: "apply",operator: "-", args: args}; let divisor = {type: "apply",operator: "*", args: [g,g]}; return {type: "apply",operator: "/", args: [dividend,divisor]} // return `${((_f===0 ? 0 : g.value *_f ) - (_g===0 ? 0 : f.value*_g)) / (g.value*g.value)}` } topEnv["cos"] = function(x){ if(x.type === 'variable'){ return {type: "apply",operator:"*", args: [{type:'value',value: -1},{type: "apply",operator:"sin", args: [x.value]}]}; // return `(* -1 (sin ${x.value}))`; }else if(x.type === 'value'){ return -1*Math.sin(parseFloat(x.value)); }else if(x.type === 'apply'){ let args = []; args.push({type: "apply",operator:"*", args: [{type:'value',value: -1},derive(x)]}); args.push({type: "apply",operator:"sin", args: [x]}); return {type: "apply",operator:"*", args: args}; } } topEnv["sin"] = function(x){ if(x.type === 'variable'){ return {type:'apply',operator:'cos',args:[x.value]}; // return `(cos ${x.value})`; }else if(x.type === 'value'){ return Math.cos(parseFloat(x.value)); }else if(x.type === 'apply'){ let args = []; args.push(derive(x)); args.push({type: "apply",operator:"cos", args: [x]}); return {type: "apply",operator:"*", args: args}; } } topEnv["tan"] = function(x){ if(x.type === 'variable'){ let args = [{type:'value',value: 1}, {type: 'apply',operator:"^",args: [{type:'apply',operator:'tan',args:[x.value]}, {type:'value',value:2} ] } ]; return {type: 'apply' ,operator:"+",args :args}; // return `(+ 1 (^ (tan ${x.value}) 2))`; }else if(x.type === 'value'){ return 1 + Math.pow(Math.tan(parseFloat(x.value)),2); }else if(x.type === 'apply'){ let args = [{type:'value',value: 1}, {type: 'apply',operator:"^",args: [{type:'apply',operator:'tan',args:[x]}, {type:'value',value:2} ] } ]; return {type: 'apply',operator:"*",args: [derive(x,topEnv),{type: 'apply' ,operator:"+",args :args}]} } } topEnv["exp"] = function(x){ if(x.type === 'variable'){ return {type: 'apply',operator: 'exp',args:[x.value]}; // return `(exp ${x.value})`; }else if(x.type === 'value'){ return Math.exp(parseFloat(x.value)); }else if(x.type === 'apply'){ return {type: 'apply',operator: "*",args:[derive(x),{type: 'apply',operator: 'exp',args:[x]}]}; } } topEnv["ln"] = function(x){ if(x.type === 'variable'){ return {type: 'apply',operator: "/",args:[{type: 'value',value:1},x.value]}; // return `(/ 1 ${x.value})`; }else if(x.type === 'value'){ return 1/parseFloat(x.value) }else if(x.type === 'apply'){ return {type: 'apply',operator: "*",args:[derive(x),{type: 'apply',operator: "/",args:[{type: 'value',value:1},x]}]}; } } topEnv["^"] = function(f,n){ if(f.type === 'variable' && n.type === 'value'){ if(parseFloat(n.value) === 2) return {type: 'apply',operator:"*",args:[n,f]}; let _n=Object.assign({},n); _n.value = _n.value - 1; return {type: 'apply',operator:"*",args:[n,{type: 'apply',operator:"^",args:[f,_n]}]}; }else if(f.type === 'apply' && n.type === 'value'){ if(n === 2) return {type: 'apply',operator:"*",args:[n,f]}; let _n=Object.assign({},n); _n.value = _n.value - 1; return {type: 'apply',operator:"*",args:[n,{type: 'apply',operator:"^",args:[f,_n]}]}; //n*derive(f) } } function diff(expr) { let tokens = tokenize(expr); let program= parse(tokens); // return derive(program, topEnv); //don't forget to drop it let result= reduce(derive(program, topEnv)); if(result && result.type === 'func') return _reduce(result.body); return `${result}`; } function tokenize(program){ if (program === "") return []; var regex = /\s*(=>|[-+*\/\%=\(\)]|[A-Za-z_][A-Za-z0-9_]*|[0-9]*\.?[0-9]+)\s*/g; return program.split(regex).filter(function (s) { return !s.match(/^\s*$/); }); } function parseExpression(program) { var match, expr; if (match = /^\d+\b/.exec(program[0])) expr = {type: "value", value: Number(match[0])}; else if (program[0] === 'x') expr = {type: "variable", value: 'x'}; else if (program[0] === '(') expr = {type: "delimiter", value: '('}; else if (match = /^[^\s(),"]+/.exec(program[0])) expr = {type: "word", name: match[0]}; else throw new SyntaxError("Unexpected syntax: " + program[0]); program.shift(); return parseApply(expr, program); } function parse(program) { var result = parseExpression(program); if (program.length > 0) throw new SyntaxError("Unexpected text after program"); return result; } function parseApply(expr, program) { if (expr.type != "delimiter") return expr; expr = {type: "apply", operator: parseExpression(program), args: []}; while (program.length > 0 && program[0] != ")" ) { var arg = parseExpression(program); expr.args.push(arg); } if (program[0] != ")") throw new SyntaxError("Expected ')'"); program.shift(); return parseApply(expr, program); } function derive(expr, env) { switch(expr.type) { case "value":{ expr.value=0; return 0; } case "variable":{ expr.value=1; expr.type= 'value'; return 1; } case "apply": if (expr.operator.name in topEnv){ let result = topEnv[expr.operator.name](...expr.args); return result; } else throw new TypeError("Applying a non-function."); } } function calc(expr,env){ switch(expr.type) { case "value":{ return expr.value; } case "variable":{ return expr.value; } case "apply": if (expr.operator in func) return func[expr.operator](...expr.args); else // throw new TypeError("Applying a non-function."); return expr; } }
import { Component } from "./../component.component"; import { MetaComponent } from "../meta-component.component"; /** * @type {Location} */ export class Location extends MetaComponent { /** * @constructor * @param {Component} city * @param {Component} compass * @param {Component} cities */ constructor( city, compass, cities ) { super("location", [ city, compass, cities ]); } }
const Reports = () => (<div><h1>Reports</h1></div>) export default Reports
var parseQueryString = require('querystring').parse; var defaults = require('./default.js'); var config = require("../util/config.js").configData; var authorize = require("../auth/authorizer.js").authorize; var m3auth = require("../auth/m3-auth.js"); /** * Mimicing Model3 sessionless auth. * * This module handles * /session/aunthenticate * /session/secureCheck * /session/logout */ // JSON responses var AUTH_REQUIRED = { m3_condition : { name : "AUTH_REQUIRED", code : 1 } }; var AUTH_FAILED = { m3_condition : { name : "AUTH_FAILED", code : 2 } }; var M3_OK = { "m3_ok" : true }; var M3_NOK = { "m3_ok" : false }; /** * GET handles checking session state */ doGet = function(request, response, url) { defaults.addNoCacheHeaders(response); var respObject = { m3_string : null }; if (url.pathname.indexOf("/session/checkSecure")) { if ( request.authenticated && request.session.cookieModel.authenticated ) { respObject = M3_OK; } else { respObject = AUTH_REQUIRED; } } else if (url.pathname.indexOf("/session/check")) { var name = ""; if ( request.authenticated ) { name = request.session.cookieModel.data[0]; respObject.m3_string = name; } else { respObject = AUTH_REQUIRED; } } sendJson(response, respObject); }; /** * POST handles logins */ doPost = function(request, response, url) { if (url.pathname.indexOf("/session/authenticate") == 0) { var buffer = ''; request.on('data', function(data) { buffer += data; }); request.on('end', function() { var tokens = parseQueryString(buffer); authorize(tokens.username, tokens.password, function(ok) { if (ok) { var cm = new m3auth.CookieModel(); cm.athenticated = true; cm.data.push(tokens.username); var cookie = secureCookieData(config.key, cm); response.setHeader('Set-Cookie', 'M3=' + cookie + ";path=/"); sendJson(response, M3_OK); } else { response.setHeader('Set-Cookie', 'M3='); sendJson(response, AUTH_FAILED); } }); }); } else { sendJson(response, M3_NOK); } }; sendJson = function(response, respObject) { var respJson = JSON.stringify(respObject); response.writeHead(200, "OK", { "Content-Type" : "application/json", "Content-Length" : "" + Buffer.byteLength(respJson, 'utf-8') }); response.write(respJson); response.end(); }; exports.doGet = doGet; exports.doPost = doPost;
// Valider en dato på formen 31/8 2020 med et RegExp. // Det kan antages, at alle måneder kan have 31 dage og at årstallet er i dette århundrede. // Ikke rigtig - læs opgaven! (Århundrede og tjek evt. at dato ikke er 0) let regex = /^[\d]{1,2}\/[\d]{1,2}\s\d{4}$/; let string1 = '31/8 2020'; let string2 = '312/8 2020'; let string3 = '31/8 a2020'; console.log(regex.test(string1)); console.log(regex.test(string2)); console.log(regex.test(string3));
alert('hello wdi15');
/* variables locales de T_FCTRCJPFLCVFT_661*/
/* eslint-disable jsx-a11y/anchor-is-valid */ import styled from 'styled-components'; import icon from '../assets/img/logo.svg'; import React from 'react'; import { ReactComponent as FacebookIcon } from '../assets/img/icon-facebook.svg'; import { ReactComponent as InstagramIcon } from '../assets/img/icon-instagram.svg'; import { ReactComponent as TwitterIcon } from '../assets/img/icon-twitter.svg'; const FooterContainer = styled.footer` width: 100%; height: 50rem; background-color: rgba(158, 171, 178, 0.1); display: flex; justify-content: center; align-items: center; .inner-div { width: 16rem; height: 39.7rem; display: flex; flex-direction: column; justify-content: space-between; align-items: center; } .logo { width: 5.5rem; height: 5.5rem; } .links { height: 23rem; display: flex; flex-direction: column; justify-content: space-between; text-align: center; } .link { list-style: none; } .link :hover { color: hsl(171, 66%, 44%); } .link a { text-decoration: none; font-size: 1.8rem; line-height: 3rem; color: #4c545c; } .social-logo { cursor: pointer; } .social-logo:hover path { fill: hsl(171, 66%, 44%); } .social-icon-container { width: 100%; display: flex; justify-content: space-around; } @media screen and (min-width: 700px) { height: 15rem; width: 100%; .inner-div { width: 100%; height: 100%; padding: 0 3rem; flex-direction: row; } .links { height: 7.2rem; width: 50rem; flex-wrap: wrap; text-align: left; } .link { display: inline-block; width: auto; height: 3rem; } .social-icon-container { width: 12rem; } } @media screen and (min-width: 1440px) { .inner-div { width: 111rem; padding: 0; } } `; const Footer = () => { return ( <FooterContainer> <div className="inner-div"> <img src={icon} alt="logo" className="logo" /> <ul className="links"> <li className="link"> <a href="#">FAQs</a> </li> <li className="link"> <a href="#">Contact Us</a> </li> <li className="link"> <a href="#">Privacy Policy</a> </li> <li className="link"> <a href="#">Press Kit</a> </li> <li className="link"> <a href="#">Install Guide</a> </li> </ul> <div className="social-icon-container"> <FacebookIcon className="social-logo" /> <InstagramIcon className="social-logo" /> <TwitterIcon className="social-logo" /> </div> </div> </FooterContainer> ); }; export default Footer;
import styles from '../scss/footer.scss'; const Footer = () => { return ( <footer className={styles}> <p>&copy; 2020</p> </footer> ); }; export default Footer;
import React, { Component } from 'react'; import DisplayNumberContatiner from '../Containers/DisplayNumberContatiner'; export default class DisplayNumberRoot extends Component { render() { return ( <div> <h1>Display Number Root</h1> <DisplayNumberContatiner></DisplayNumberContatiner> </div> ) } }
const express = require("express"); const app = express(); const mongoose = require("mongoose"); const bodyparser = require("body-parser"); const path = require("path"); require("dotenv").config(); const mongoURI = process.env.MONGO_DB; // Import Routes from routes folder const indexRoute = require("./routes/index"); // setup body-parser middleware app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); // Serving Public folder app.use(express.static("public")); app.use(express.static(path.join(__dirname))); // view folder/engine setup app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); // MonogDb connection // MONGODB setup mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); var db = mongoose.connection; db.on("error", console.error.bind(console, "connection error:")); db.once("open", function () { console.log("Database has been connected"); }); // use actual route app.use("/", indexRoute); // const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log("APP RUNNING"));
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddCourseModule = void 0; const uuid_1 = require("uuid"); const Errors_1 = require("../../../domain/Errors"); class AddCourseModule { constructor(moduleRepo, userRepo) { this.moduleRepo = moduleRepo; this.userRepo = userRepo; } async execute(dto, id) { const { notation, name, description, views, is_archived, up_votes, down_votes, level_restriction, user_restriction } = dto; id = !id ? uuid_1.v4() : id; if (user_restriction) { const userExists = await this.userRepo.findById(user_restriction); if (!userExists) throw Errors_1.MkError.UserNotFound(); } const courseModule = { id, notation, name, description, views, is_archived, up_votes, down_votes, level_restriction, user_restriction }; const stored = await this.moduleRepo.save(courseModule); return stored; } } exports.AddCourseModule = AddCourseModule;
"use strict"; define(function() { var utils = { /* Function Name: clamp(val, min, max) Return Value: returns a value that is constrained between min and max (inclusive) */ 'clamp': function (val, min, max){ return Math.max(min, Math.min(max, val)); }, /* Function Name: getRandom(min, max) Return Value: a floating point random number between min and max */ 'getRandom': function (min, max) { return Math.random() * (max - min) + min; }, /* Function Name: getRandomInt(min, max) Return Value: a random integer between min and max */ 'getRandomInt': function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }, // Function Name: getMouse(e) // returns mouse position in local coordinate system of element 'getMouse': function () { var mouse = {}; mouse.x = event.clientX + document.body.scrollLeft; mouse.y = event.clientY + document.body.scrollTop; return mouse; }, // Function name: drawCircle // takes an object that has a drawColor and position 'drawCircle': function (ctx, object) { ctx.fillStyle = object.drawColor; ctx.beginPath(); ctx.arc(object.position.x, object.position.y, object.size, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } }; // the "public interface" of this module return utils; });
let DirectivaFor = { template: ` <div> <h1 v-text="title"></h1> <p v-html = "message"></p> <h3>Lista de un array</h3> <ol> <li v-for = "color in list" v-text = "color"></li> </ol> <h3>Lista de un objeto</h3> <ul> <li v-for = "(item,key,index) in object_list" :key = "index"> {{key}}: {{item}} </li> </ul> <h3>Lista de un array de objetos</h3> <ul> <li v-for = "(item,index) in other_list" :key = "index"> Nombre: {{item.name}}<br/> Apellido: {{item.lastName}}<br/> Nick: {{item.nick}}<br/> </li> </ul> </div> `, data() { return { title: 'Directiva v-for', message: '<b>Texto de prueba v-for</b>', list: ['Rojo', 'Verde', 'Azúl', 'Naranja'], object_list: { name: 'Carlos', lastName: 'Gutiérrez', nick: 'Guty' }, other_list: [ { name: 'Carlos', lastName: 'Gutiérrez', nick: 'Guty' }, { name: 'Mar', lastName: 'Saldaña', nick: 'Marsa' }, { name: 'Pedro', lastName: 'Martinez', nick: 'Pedrín' } ] } } }
import React from 'react' const ComponentA = (prop) => { return( <div> <h1>mounika</h1> </div> ) } export default ComponentA;
/** * @fileoverview Core PHP Social functions * @author Michael Robinson <mike@pagesofinterest.net> */ /** * Following section taken from Google's social media tracking documentation * A simple script to automatically track Facebook and Twitter * buttons using Google Analytics social tracking feature. * * @author api.nickm@google.com (Nick Mihailovski) * Copyright 2011 Google Inc. All Rights Reserved. */ /** * Namespace. * @type {Object}. */ var _ga = _ga || {}; /** * Ensure global _gaq Google Analytics queue has been initialized. * @type {Array} */ var _gaq = _gaq || []; /** * Returns the normalized tracker name configuration parameter. * @param {string} opt_trackerName An optional name for the tracker object. * @return {string} If opt_trackerName is set, then the value appended with * a . Otherwise an empty string. * @private */ _ga.buildTrackerName_ = function(opt_trackerName) { return opt_trackerName ? opt_trackerName + '.' : ''; }; /** * Extracts a query parameter value from a URI. * @param {string} uri The URI from which to extract the parameter. * @param {string} paramName The name of the query paramater to extract. * @return {string} The un-encoded value of the query paramater. underfined * if there is no URI parameter. * @private */ _ga.extractParamFromUri_ = function(uri, paramName) { if (!uri) { return; } uri = uri.split('#')[0]; // Remove anchor. var parts = uri.split('?'); // Check for query params. if (parts.length == 1) { return; } var query = decodeURI(parts[1]); // Find url param. paramName += '='; var params = query.split('&'); for (var i = 0, param; param = params[i]; ++i) { if (param.indexOf(paramName) === 0) { return unescape(param.split('=')[1]); } } return; }; /** * PHP Socializer functions */ /** * @type {mixed[]} List of social objects to be loaded when the document is ready */ _socialQueue = []; /** * @param {Object} w The window. * @param {Object} d The document. */ (function(w, d) { /** * Begin loading social assets. */ var go = function() { /** @type {Object} Fade handling object. */ var f = { /** * Simple fade in effect. * * @param {Array} elements An array of elements to fade in * @param {Integer} time Total animation time */ fadeIn: function(elements, time) { // If the browser supports CSS transitions, use them var transition = false, transitionNames = ['MozTransition', 'webkitTransition', 'OTransition']; for (var i = 0; i < transitionNames.length; i++) { if (typeof elements[0].style[transitionNames[i]] !== 'undefined') { transition = transitionNames[i]; break; } } for (i = 0; i < elements.length; i++) { if (transition) { elements[i].style[transition] = 'opacity ' + time + 'ms ease-in ' + time + 'ms'; elements[i].style.opacity = 1; } else { var startOpacity = 0, steps = 1 / 0.02; (function step(element) { element.style.opacity = +(element.style.opacity) + 0.02; // for IE element.style.filter = 'alpha(opacity=' + element.style.opacity * 100 + ')'; if(element.style.opacity < 1) { window.setTimeout(function() { step(element); }, time / steps); } })(elements[i]); } } }, /** * Attach the f.fadeIn function as an onload event to the iFrame, * then 'kick' it. * * @param {Element} fr The iFrame * @param {Element} b The wrapping div. * @param {int} d Fade animation duration. */ iframeOnload: function(fr, b, d) { fr.onload = function() { f.fadeIn([b], d); }; var src = fr.src; fr.src = ''; fr.src = src; }, /** * Repeatedly check if button is rendered, when it is, perform * appropriate action. * * @param {Element} b The wrapping div. * @param {Function} r Function to call with b, returns true or false * depending on whether button is rendered. * @param {int} d Fade animation duration. * @param {Function} m Optional function to be called when rendered. */ awaitRenderButton: function(b, r, d, m) { if (!r(b)) { // Button not rendered yet, wait window.setTimeout(function() { f.awaitRenderButton(b, r, d, m); }, 100); return; } // Button rendered if (typeof m !== 'undefined') { // An alternative rendered function was provided m(b, d); } else { // Fade in f.fadeIn([b], d); } }, /** * Entry point to the fade in handling object. * * @param {Object} o Hash of options. */ awaitRender: function(o) { for(var i = 0; i < o.buttons.length; i++) { f.awaitRenderButton(o.buttons[i], o.isRendered, o.duration, o.renderedMethod); } } }; var fjs = document.getElementsByTagName('script')[0]; /** * Load the social object * @param {Object} s A social object to be loaded */ var load = function(s, f) { // Ensure script isn't loaded yet if (d.getElementById(s.id)) { return; } if (s.preload) { s.preload(f); } if (s.url) { // Create and initialise script var js = d.createElement('script'); js.src = s.url; js.id = '_social' + s.id; js.async = true; if (s.onload) { // Attach the onload function if present js.onload = function() { s.onload(f); }; } fjs.parentNode.insertBefore(js, fjs); } }; // Process queue for (var i = 0; i < _socialQueue.length; i++) { load(_socialQueue[i], f); } }; // Bind 'go' function to load event if (w.addEventListener) { w.addEventListener('load', go, false); } else if (w.attachEvent) { w.attachEvent('onload', go); } })(window, document);
import React from 'react'; import {connect} from "react-redux"; const List = (props) => { let {fname, lname, isLiving, amount, isJedi, bounties} = props; return bounties.map((bounty, i) => { if (bounty.isLiving === "true"){ return (<div> <h1>Name: {bounty.fname} {bounty.lname}</h1> <h2>Status: Living</h2> <h2>Reward: {bounty.amount}</h2> <h2>Type: {bounty.isJedi}</h2> </div>) }else { return (<div> <h1>Name: {bounty.fname} {bounty.lname}</h1> <h2>Status: Dead</h2> <h2>Reward: {bounty.amount}</h2> <h2>Type: {bounty.isJedi}</h2> </div>) } }) } export default connect(state => state, {})(List);
var phe = require('../'); var keyLengths = [128, 256, 512, 1024, 2048, 4096]; keyLengths.forEach(function (keyLength) { console.time(keyLength); phe.generate_paillier_keypair(keyLength); console.timeEnd(keyLength); });
import React from 'react'; import { Statistic, Row, Col, Descriptions } from 'antd'; import 'antd/dist/antd.css'; import './Statistics.scss'; export const Statistics = ({people}) => { let males = 0; let females = 0; let Indeterminate = 0; people.forEach(person => { switch(person.gender){ case 'male': males++ break; case 'female': females++ break; default: Indeterminate++; }}); const nationalities = {} people.forEach(person=> nationalities.hasOwnProperty(person.nationality.name) ? nationalities[person.nationality.name]++ : nationalities[person.nationality.name] = 1 ); console.log(nationalities); return ( <div className="ant-statistic-footer"> <Row gutter={16}> <Col span={3}> <Statistic title="Collection size" value={people.length} /> </Col> <Col span={6}> <Row gutter={16}> <Col span={4}> <Statistic title="Males" value={males} /> </Col> <Col span={5}> <Statistic title="Females" value={females} /> </Col> <Col span={4}> <Statistic title="Indeterminate" value={Indeterminate} /> </Col> </Row> <div className="statistic__dominate"> {males > females ? 'Men predominate' : 'Women predominate'} </div> </Col> </Row> <div className="ant-description-box"> <Descriptions title="Nationalities" size="middle" column={6} > {Object.keys(nationalities).map(nat => <Descriptions.Item label={nat} key={nat}>{nationalities[nat]}</Descriptions.Item> )} </Descriptions> </div> </div> ) }
const arr = [1, [2, [3, [4, 5]]], 6]; //1 使用flat() const arr1 = arr.flat(Infinity); //2.使用正则 缺点:数据类型都会变成字符串 const arr2 = JSON.stringify(arr).replace(/\[|\]/g, '').split(','); //3.正则改良 const arr3 = '[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']'; // 4. 使用reduce const flatten = arr => { return arr.reduce((pre, cur) => { return pre.concat(Array.isArray(cur) ? flatten(cur) : cur); }, []) } const arr4 = flatten(arr); // 5.函数递归 const arr5 = []; const fn = arr => { for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { fn(arr[i]); } else { arr5.push(arr[i]); } } } fn(arr); // split() 方法用于把一个字符串分割成字符串数组。 //split() 方法用于把一个字符串分割成字符串数组。 // const arr1 = [1, [2, [3, [4, 5]]], 6]; // console.log(arr1.toString().split(',').map(item => { // return Number(item); // })) // join() 方法用于把数组中的所有元素放入一个字符串。 const arr1 = [1, [2, [3, [4, 5]]], 6]; console.log(arr1.join(',').split(',')) console.log(arr); console.log(arr1); console.log(arr2); console.log(arr3); console.log(arr4); console.log(arr5);
"use strict"; var React = require("react"); var ReactPropTypes = React.PropTypes; function getClassNames(status) { var transform = { good: "btn btn-success", bad: "btn btn-danger", neutral: "btn btn-warning" }; return transform[status]; } var NutritionSummary = React.createClass({ propTypes: { nutrition: ReactPropTypes.object.isRequired }, render: function() { var energy = this.props.nutrition; return ( <button type="button" className={getClassNames('neutral')}> F {energy.fat} | P {energy.protein} | C {energy.carbohydrate} </button> ); } }); module.exports = NutritionSummary;
module.exports = (User) => { User.buscar = (emp_id,nombre,options, next) => { var ds = User.dataSource; const valores = options && options.accessToken; const token = valores && valores.id; const userId = valores && valores.userId; Promise.resolve().then(()=>{ return new Promise(function(resolve, reject) {console.log("nombre:",nombre); if(emp_id==0){ var sql = "select * from seguridad.user where name ilike $1 or username ilike $2 or surname ilike $3 or email ilike $4"; //console.log("sql:",sql); ds.connector.execute(sql,['%'+nombre+'%','%'+nombre+'%','%'+nombre+'%','%'+nombre+'%'], function(err, data) { if (err){ reject(err); } else{ console.log("user:",data);next(null,data); } }); } else{ var sql = "select * from seguridad.user where name ilike $1 or username ilike $2 or surname ilike $3 or email ilike $4 and emp_id = $5"; //console.log("sql:",sql); ds.connector.execute(sql,['%'+nombre+'%','%'+nombre+'%','%'+nombre+'%','%'+nombre+'%',emp_id], function(err, data) { if (err){ reject(err); } else{ next(null,data); } }); } }) }) .catch(function(err){ console.log(err); next("Ocurrio un error al buscar usuario."); }); }; User.remoteMethod('buscar', { accepts: [ {arg: "emp_id", type: "number", required: false }, {arg: "nombre", type: "string", required: true }, {arg: "options", type: "object", 'http': "optionsFromRequest"} ], returns: { arg: 'response', type: 'object', root: true }, http: { verb: 'GET', path: '/buscar' } }); }
'use strict'; // Add "a" to every string in far var far = ["kuty", "macsk", "kacs", "r�k", "halacsk"]; for (let i = 0; i <= 4; i++) { far[i] += "a"; } console.log(far);
var buf = new Buffer(26); for(var i = 0;i<26;i++){ buf[i] = i+97 } console.log(buf.toString(undefined,0,5)); console.log(buf.toString("utf8",0,5)); var buf = new Buffer('www.runoob.com'); var json = buf.toJSON();//字符串buffer才可以调用 toJSON() console.log(json);
const path = require('path') const fs = require('fs') const Sequelize = require('sequelize') const debug = require('debug')('app:sequelize') const parameters = requireRoot('../parameters') function initConnection () { if (process.env.TEST_MODE) { parameters.postgres = parameters.test.postgres } return new Sequelize(parameters.postgres.database, parameters.postgres.username, parameters.postgres.password, { host: parameters.postgres.host, port: parameters.postgres.port, dialect: 'postgres', logging: false, pool: { max: 16, min: 0, idle: 10000 } }) } async function initModels (sequelize) { const MODELS_PATH = path.resolve('src/models') const modelNames = fs.readdirSync(MODELS_PATH) .map(file => { if (file[0] !== '_') { return file.substring(0, file.lastIndexOf('.')) } }) .filter(file => file) const models = {} modelNames.forEach(function (modelName) { const model = sequelize.import(path.resolve(MODELS_PATH, modelName)) models[modelName] = model }) for (let modelName in models) { const model = models[modelName] if ('associate' in model) { model.associate(models) } } return models } function isConnected (sequelize) { return sequelize.authenticate() .then(() => true) .catch(err => { debug('Connection error') throw err }) } async function startClient () { const sequelize = initConnection() const models = await initModels(sequelize) return isConnected(sequelize) .then(status => { debug('connected') return sequelize.sync() .then(data => { debug('sync') return models }) .catch(err => { debug('sync error', err) }) }) .catch(err => { debug('error', err) }) } module.exports = { startClient }
//This is the main game area which will likely have most of the logic and pulls everything together //**It will manage state so it will need to be a class. // import React from "react"; import "./play.css"; import dinos from "../../data.json"; import Header from "../Header"; import Footer from "../Footer"; import Instr from "../Instr"; import Container from "../Container"; import DinoCard from "../DinoCard"; console.log("dinos = " + JSON.stringify(dinos) ); class Play extends React.Component { state = { dinos, score: 0, highScore: 0 }; componentDidMount() { this.setState({ dinos: this.shuffleDinos(this.state.dinos), score: 0, highScore: 0 }); } //Shuffle the array - https://stackoverflow.com/questions/49555273/how-to-shuffle-an-array-of-objects-in-javascript shuffleDinos = (input) => { const newDinoOrder = input.sort(() => Math.random() - 0.5); return newDinoOrder; }; resetGame = data => { const resetData = data.map(data => ({ ...data, clicked: false })); return this.shuffleDinos(resetData); }; dinoClicked = id => { let correctGuess = false; // console.log("id = " + id); // console.log("index = " + this.state.dinos.indexOf(id)); // const newData = this.state.data.map(item => { // const newItem = { ...item }; //Cycle through the dinos looking for a match to id of the one clicked on const newData = this.state.dinos.map(dino => { const currentDino = { ...dino }; if (currentDino.id === id) { //Check to see if this dino has been clicked on before if (!currentDino.clicked) { // console.log("this dino matched: " + currentDino.id); // console.log("clicked = " + currentDino.clicked); correctGuess = true; currentDino.clicked = true; // console.log("***currentScore = " + currentScore); // console.log("***currentHighScore = " + currentHighScore); // console.log("currentDino = " + JSON.stringify(currentDino)); } }; // }; return currentDino; }); if(correctGuess) { // console.log("correct"); this.handleCorrectGuess(newData); } else { // console.log("incorrect"); this.handleIncorrectGuess(newData); } }; handleCorrectGuess = (input) => { let newHighScore; const currentScore = this.state.score; const currentHighScore = this.state.highScore; // console.log("***currentScore = " + currentScore); // console.log("***currentHighScore = " + currentHighScore); // console.log(JSON.stringify(input)); const newScore = currentScore + 1; if (currentScore >= currentHighScore) { newHighScore = currentScore + 1; // console.log("greater " + newHighScore); } else { newHighScore = currentHighScore; // console.log("lesser " + newHighScore); }; // const newHighScore = score > this.highscore ? score : highScore; let result = this.shuffleDinos(input); // console.log("newScore = " + newScore); // console.log("newHighScore = " + newHighScore); // console.log(JSON.stringify(result)); this.setState({ dinos: result, score: newScore, highScore: newHighScore }); }; handleIncorrectGuess = (input) => { this.setState({ dinos: this.resetGame(input), score: 0 }); }; render() { return ( <div> <Header score={this.state.score} highScore={this.state.highScore} /> <Instr /> <Container> {this.state.dinos.map(dino => ( <DinoCard key={dino.id} id={dino.id} clicked={dino.clicked} name={dino.name} image={dino.image} dinoClicked={this.dinoClicked} /> ))}; </Container> <Footer /> </div> ); }; }; export default Play;
"use strict"; // /*jslint noempty: false */ /*global alert: true, ODSA */ $(document).ready(function() { // Process help button: Give a full help page for this activity function help() { window.open("quicksortHelpPRO.html", 'helpwindow'); } // Process about button: Pop up a message with an Alert function about() { alert(ODSA.AV.aboutstring(interpret(".avTitle"), interpret("av_Authors"))); } $('#help').click(help); $('#about').click(about); // Processes the reset button function initialize() { // Clear existing array if (userArr) { userArr.clear(); } // Generate random numbers for the exercise initialArray = []; for (var i = 0; i < arraySize; i++) { initialArray[i] = Math.floor(Math.random() * 100); } // Log the initial state of the exercise var initData = {}; initData.gen_array = initialArray; ODSA.AV.logExerciseInit(initData); // Create the array the user will intereact with userArr = av.ds.array(initialArray, { indexed: true, layout: arrayLayout.val() }); // Assign a click handler function to the user array userArr.click(function(index) { clickHandler(this, index); }); resetStateVars(); av.forward(); av._undo = []; av.umsg(interpret("av_c1")); // Return the array containing the user's answer and the state // variables we use to grade their solution return [userArr, pivotIndex, pivotMoved, partitioned, left, right]; } // Create the model solution used for grading the exercise function modelSolution(av) { var modelArr = av.ds.array(initialArray, { indexed: true, layout: arrayLayout.val() }); // ModelSolution vars used for fixing the state var msPivotIndex = av.variable(-1); var msPivotMoved = av.variable(false); var msPartitioned = av.variable(false); var msLeft = av.variable(-1); var msRight = av.variable(-1); // Initialize the display or else the model answer won't show up until // the second step of the slideshow av.displayInit(); quicksort(av, modelArr, 0, modelArr.size() - 1, msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); // Return model array and all state variables needed to grade/fix state return [modelArr, msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight ]; } /** * Sorts the specified array using quicksort while marking various * steps where the model answer will be compared against the user's * solution for grading purposes */ function quicksort(av, arr, i, j, msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight) { // Select the pivot var pIndex = Math.floor((i + j) / 2); arr.highlightBlue(pIndex); av.umsg(interpret("av_c2")); av.step(); // Move the pivot to the end of the list being sorted av.umsg(interpret("av_c3")); arr.swapWithStyle(pIndex, j); msPivotIndex.value(j); msPivotMoved.value(true); av.stepOption("grade", true); av.step(); // Partition the array // k will be the first position in the right subarray av.umsg(interpret("av_c4")); var k = partition(arr, i, j - 1, arr.value(j)); arr.setLeftArrow(i); arr.setRightArrow(j - 1); msLeft.value(i); msRight.value(j - 1); msPartitioned.value(true); msPivotMoved.value(false); av.stepOption("grade", true); av.step(); arr.clearLeftArrow(i); arr.clearRightArrow(j - 1); av.umsg(interpret("av_c5")); // If the pivot is already in its final location, don't need to swap it if (k !== j) { arr.swapWithStyle(j, k); msPivotMoved.value(true); msPivotIndex.value(k); av.stepOption("grade", true); av.step(); } av.umsg(interpret("av_c6")); arr.markSorted(k); resetMSStateVars(msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); av.stepOption("grade", true); av.step(); // Sort left partition if ((k - i) > 1) { quicksort(av, arr, i, k - 1, msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); } else if ((k - i) === 1) { // If the sublist is a single element, mark it as sorted av.umsg(interpret("av_c7")); arr.markSorted(i); resetMSStateVars(msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); av.stepOption("grade", true); av.step(); } // Sort right partition if ((j - k) > 1) { quicksort(av, arr, k + 1, j, msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); } else if ((j - k) === 1) { // If the sublist is a single element, mark it as sorted av.umsg(interpret("av_c8")); arr.markSorted(j); resetMSStateVars(msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight); av.stepOption("grade", true); av.step(); } } /** * Partitions the elements of an array within the specified range * so that all values less than the pivot value are farthest to * the left and values larger than the pivot are farthest to the right * * arr - the array containing the elements to partition * l - the left endpoint of the range to partition * r - the right endpoint of the range to partition * pivot - the value to compare all the elements against */ function partition(arr, l, r, pivot) { while (l <= r) { // Move bounds inward until they meet while (arr.value(l) < pivot) { l++; } while ((r >= l) && (arr.value(r) >= pivot)) { r--; } if (r > l) { arr.swap(l, r); } } // Return first position in right partition return l; } // Fixstate function called if continuous feedback/fix mode is used function fixState(modelState) { // Pull the model array and state variables out of the modelState argument var modelArray = modelState[0]; var pIndex = modelState[1]; var pMoved = modelState[2]; var part = modelState[3]; var l = modelState[4]; var r = modelState[5]; // Get the raw array elements so we can access their list of class names var modArrElems = JSAV.utils._helpers.getIndices($(modelArray.element).find("li")); var userArrElems = JSAV.utils._helpers.getIndices($(userArr.element).find("li")); for (var i = 0; i < modelArray.size(); i++) { // Fix any incorrect values userArr.value(i, modelArray.value(i)); // Ensure the classes of each element in the user array match those in the model solution userArrElems[i].className = modArrElems[i].className; // Clear any arrows the user put in the wrong place userArr.clearLeftArrow(i); userArr.clearRightArrow(i); } // Make sure the value of each user state variable is correct pivotIndex.value(pIndex.value()); pivotMoved.value(pMoved.value()); partitioned.value(part.value()); left.value(l.value()); right.value(r.value()); // Fix the message being displayed av.umsg(interpret("av_c1")); if (pivotMoved.value() && !partitioned.value()) { av.umsg(interpret("av_c9")); } else if (partitioned.value() && !pivotMoved.value()) { av.umsg(interpret("av_c15")); } else if (partitioned.value() && pivotMoved.value()) { av.umsg(interpret("av_c6")); } } // Click handler for all array elements function clickHandler(arr, index) { if (!partitioned.value()) { if (pivotIndex.value() === -1) { // Select the pivot pivotIndex.value(index); arr.highlightBlue(index); } else if (pivotIndex.value() === index && !pivotMoved.value()) { // Deselect the pivot unless it has already been moved pivotIndex.value(-1); arr.unhighlightBlue(index); } else if (!pivotMoved.value()) { // Move the selected pivot to the specified index swapPivot(pivotIndex.value(), index); av.umsg(interpret("av_c9")); } else if (left.value() === -1) { // Select the left end of the range to partition left.value(index); arr.setLeftArrow(index); if (right.value() === -1) { av.umsg(interpret("av_c10")); } else { av.umsg(interpret("av_c11")); } } else if (right.value() === -1) { // Select the right end of the range to partition right.value(index); arr.setRightArrow(index); av.umsg(interpret("av_c12")); } else if (right.value() === index) { // Deselect the right end of the range to partition arr.clearRightArrow(index); right.value(-1); // Guide the user by telling them they just deselected the right endpoint av.umsg(interpret("av_c13")); } else if (left.value() === index) { // Deselect the left end of the range to partition arr.clearLeftArrow(index); left.value(-1); // Guide the user by telling them they just deselected the left endpoint av.umsg(interpret("av_c14")); } } else { if (pivotIndex.value() === -1) { // Select the pivot pivotIndex.value(index); arr.highlightBlue(index); } else if (pivotIndex.value() === index) { // Deselect the pivot pivotIndex.value(-1); arr.unhighlightBlue(index); } else { // Move the pivot to its final location swapPivot(pivotIndex.value(), index); } } } // Convenience function to swap the pivot from one position to another // and set the appropriate user state variables function swapPivot(pIndex, newPIndex) { // Move the selected pivot to the specified index userArr.swapWithStyle(pIndex, newPIndex); pivotIndex.value(newPIndex); pivotMoved.value(true); // Mark this as a step to be graded and a step that can be undone // (continuous feedback) exercise.gradeableStep(); } // Reset the variables used for each iteration of the algorithm function resetStateVars() { pivotIndex.value(-1); pivotMoved.value(false); partitioned.value(false); left.value(-1); right.value(-1); } // Reset the model solution variables function resetMSStateVars(msPivotIndex, msPivotMoved, msPartitioned, msLeft, msRight) { msPivotIndex.value(-1); msPivotMoved.value(false); msPartitioned.value(false); msLeft.value(-1); msRight.value(-1); } // Perform the partition operation on the user array // using the pivot value and range specified by the user function partitionButton() { // Input validation if (pivotIndex.value() === -1) { alert("Select a pivot element"); return; } if (left.value() === -1 || right.value() === -1) { alert("You must select the range to partition"); return; } partition(userArr, left.value(), right.value(), userArr.value(pivotIndex.value())); // Update state variables and clear left and right marker arrows partitioned.value(true); pivotMoved.value(false); userArr.clearLeftArrow(left.value()); userArr.clearRightArrow(right.value()); // Mark this as a step to be graded and a step that can be undone // (continuous feedback) exercise.gradeableStep(); av.umsg(interpret("av_c15")); } // Mark the currently selected element as sorted function markSortedButton() { // Input validation if (pivotIndex.value() === -1) { alert("Select an element to mark as sorted"); return; } userArr.markSorted(pivotIndex.value()); resetStateVars(); // Mark this as a step to be graded and a step that can be undone (continuous feedback) exercise.gradeableStep(); av.umsg(interpret("av_c1")); } // Attach the button handlers $('#partition').click(partitionButton); $('#markSorted').click(markSortedButton); ////////////////////////////////////////////////////////////////// // Start processing here ////////////////////////////////////////////////////////////////// // Load the config object with interpreter created by odsaUtils.js var config = ODSA.UTILS.loadConfig(), interpret = config.interpreter, // get the interpreter settings = config.getSettings(); // Settings for the AV // add the layout setting preference var arrayLayout = settings.add("layout", { "type": "select", "options": { "bar": "Bar", "array": "Array" }, "label": "Array layout: ", "value": "array" }); var arraySize = 10, initialArray = [], av = new JSAV($('.avcontainer'), { settings: settings }); av.recorded(); // we are not recording an AV with an algorithm // Initialize the variables var userArr; // JSAV array var pivotIndex = av.variable(-1); var pivotMoved = av.variable(false); var partitioned = av.variable(false); var left = av.variable(-1); var right = av.variable(-1); // Instantiate the exercise // modelSolution: // - Creates the model answer that is accessible on the page // - Creates the model answer used to grade the student's answer // - Returns a list containing the model array and all state // variables used for grading and fixing the state if the user makes a mistake // initialize: Function to initialize and return the array the user // interacts with and the state variables we use to grade their answer // [{css: "background-color"}, {}, {}, {}, {}, {}] // - Defines how to grade each value returned from 'initialize' and 'modelSolution' // - The values and the background-color css properties of both array will be compared // - Each of the state variables will only be compared by value // {fix: fixState}: The function to call to fix the state of the exercise // if the user makes a mistake in 'fix' mode var exercise = av.exercise(modelSolution, initialize, { compare: [{ "class": ["processing", "sorted"] }, {}, {}, {}, {}, {}], controls: $('.jsavexercisecontrols'), fix: fixState }); exercise.reset(); });
import SpaceForCustomers from "../SpaceForCustomers/spaceForCustomers"; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/swiper.min.css' function Swiperr() { return ( <Swiper slidePerPage={2.5} spaceBetween={50} slidesPerView={3} onSlideChange={() => console.log('slide change')} onSwiper={(swiper) => console.log(swiper)}> <SwiperSlide><SpaceForCustomers /></SwiperSlide> <SwiperSlide><SpaceForCustomers /></SwiperSlide> <SwiperSlide><SpaceForCustomers /></SwiperSlide> <SwiperSlide><SpaceForCustomers /></SwiperSlide> ... </Swiper> ) } export default Swiperr
console.log('dynamic module "one" loading'); export default function dynamic() { console.log('dynamic module "one": function dynamic() running'); }
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('util.navigator'); * mod.thing == 'a thing'; // true */ module.exports = function() { Creep.prototype.getDistanceTo = function(target) { return Math.sqrt(Math.pow(target.pos.x - this.pos.x,2) + Math.pow(target.pos.y - this.pos.y,2)); }, Creep.prototype.getResourceType = function() { resourceType = this.memory.resourceType; if(resourceType == undefined) { resourceType = RESOURCE_ENERGY; } // console.log(this.name + " testing member access " + resourceType); return resourceType; }, Creep.prototype.tryToRepairRoads = function () { if(this.memory.repairRoads && this.getActiveBodyparts(WORK) > 0 && this.carry.energy > 0) { var maybeRoad = this.room.lookForAt(LOOK_STRUCTURES, this.pos); // console.log("Maybe a road " + maybeRoad); if(maybeRoad.length > 0 && maybeRoad[0].structureType == 'road' && maybeRoad[0].hits < maybeRoad[0].hitsMax){ this.say("tink!"); this.repairAndReport(maybeRoad[0]); } else { var maybeConstruction = this.room.lookForAt(LOOK_CONSTRUCTION_SITES, this.pos); // console.log("Maybe a road " + maybeRoad); if(maybeConstruction.length > 0){ this.say("tink!"); this.buildAndReport(maybeConstruction[0]); } } } }, Creep.prototype.report = function(key, amount) { try { // console.log("trying to increment " + key + " by " + amount); if(amount > 0 && this.getResourceType() == RESOURCE_ENERGY) { Memory["cached_rooms"][this.pos.roomName]["stats"]["creep"][key] = Memory["cached_rooms"][this.pos.roomName]["stats"]["creep"][key] + amount; // console.log(this.name + " " + key + " " + amount + " " + this.getResourceType()); // console.log("total so far is " +JSON.stringify(Memory["cached_rooms"][this.pos.roomName]["stats"]["creep"][key])); } } catch (err) { console.log (err); } }, Creep.prototype.getReportValue = function(key) { return Memory["cached_rooms"][this.pos.roomName]["stats"]["creep"][key]; } Creep.prototype.clearReportValue = function(key) { Memory["cached_rooms"][this.pos.roomName]["stats"]["creep"][key] = 0; } Creep.prototype.harvestAndReport = function(target) { result = this.harvest(target); if(result == OK && this.getResourceType() == RESOURCE_ENERGY) { amount = Math.min(this.getActiveBodyparts(WORK) * 2, this.carryCapacity - _.sum(this.carry)); this.report("harvested", amount); this.report("harvested_keeper_count", amount); } return result; }, Creep.prototype.buildAndReport = function(target) { result = this.build(target); if(result == OK) { this.report("constructed", this.getActiveBodyparts(WORK)); } return result; }, Creep.prototype.repairAndReport = function(target) { result = this.repair(target); if(result == OK) { this.report("repaired", this.getActiveBodyparts(WORK)); } return result; }, Creep.prototype.dropAndReport = function(resourceType) { result = this.drop(resourceType); if(result == OK) { this.report("dropped", this.carry[resourceType]); } return result; }, Creep.prototype.transferAndReport = function(amount, resourceType) { result = this.transfer(target, resourceType); if(target.structureType == 'tower') { //Deposit to tower amount = Math.min(target.energyCapacity - target.energy, this.carry[resourceType]); this.report("towered", amount); } else if(target.structureType == 'storage') { //Deposit to storage amount = Math.min(target.storeCapacity - _.sum(target.store), this.carry[resourceType]); this.report("stored", amount); } else if(target.structureType == 'link') { //Deposit to link amount = Math.min(target.energyCapacity - target.energy, this.carry[resourceType]); this.report("linked", amount); } }, Creep.prototype.reportInvasion = function(invader) { //Set the evacuation time Memory["cached_rooms"][this.pos.roomName].evacuating = Game.time + invader.ticksToLive; //Notify via email the amount harvested harvestedSoFar = this.getReportValue("harvested_keeper_count"); Game.notify("There was " + harvestedSoFar + " harvested before an invasion occured in " + this.pos.roomName + "!"); this.clearReportValue("harvested_keeper_count"); } Creep.prototype.reportAllClear = function() { //Set the evacuation time // console.log("derp"); Memory["cached_rooms"][this.pos.roomName].evacuating = false; } };
import { makeStyles } from '@material-ui/styles'; import modelImg from '../../assets/img/model.png'; export default makeStyles(theme => ({ font1: { fontFamily: "Oswald", [theme.breakpoints.down("lg")] : { fontSize: "3.6em", fontWeight: "bold" }, [theme.breakpoints.down("md")] : { fontSize: "2.7em", fontWeight: "bold" }, [theme.breakpoints.down("sm")] : { fontSize: "2.5em", fontWeight: "bold", textAlign: "center" }, }, font2: { fontFamily: "Fira Code", [theme.breakpoints.down("lg")] : { fontSize: "6em", fontWeight: "bold" }, [theme.breakpoints.down("md")] : { fontSize: "4em", }, [theme.breakpoints.down("sm")] : { fontSize: "3em", textAlign: "center" }, }, font3: { fontFamily: "Oswald", [theme.breakpoints.down("lg")] : { fontSize: "1.5em", }, [theme.breakpoints.down("lg")] : { fontSize: "1.2em", }, [theme.breakpoints.down("sm")] : { fontSize: ".9em", textAlign: "center" }, }, heroBG: { backgroundImage: `radial-gradient(#FFFFFF ,#9DB4FA )`, backgroundSize: "cover", backgroundPosition: "50% 50%" , backgroundRepeat: "no-repeat", backgroundAttachment: "fixed", // height: "100vh", width: "100%", display: "flex", alignItems: "center", justifyContent: "space-around", flexWrap: "wrap", [theme.breakpoints.down('lg')]: { height: "100vh", }, [theme.breakpoints.down('sm')]: { height: "65vh", justifyContent: "center", paddingTop: 50 }, [theme.breakpoints.down('xs')]: { flexDirection: "column", height: "65vh", }, }, model :{ height: 400, width: 500, background: `url(${modelImg})`, backgroundSize: "cover", [theme.breakpoints.down('sm')] : { height: 200, width: 250 }, }, heroText: { display: "flex", flexDirection: "column", alignItems: "flex-end", justifyContent: "center", [theme.breakpoints.down('xs')]: { alignItems: "center", justifyContent: "center", textAlign: "center" }, [theme.breakpoints.down('xs')]: { alignItems: "center", justifyContent: "center", textAlign: "center" }, }, btn: { backgroundColor: "#000", color: "#fff", fontWeight: "bold", '&:hover' : { backgroundColor: "#333" }, [theme.breakpoints.down('lg')]: { height: 40, width: 150, fontSize: 12 }, [theme.breakpoints.down('sm')]: { height: 30, width: 130, fontSize: 11 }, } }))
angular.module('core.table2', ['ngResource']);
// load module var request = require('request'); var fs = require('fs'); // URL 지정 var url = "http://jpub.tistory.com"; var savepath = "test.html"; // download request(url).pipe(fs.createWriteStrea(savepath));
import React from 'react' import customTheme from '../styles/theme' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import Autocomplete from '../components/Autocomplete' class App extends React.Component { render () { return ( <div style={{padding: '20px 50px'}}> <MuiThemeProvider muiTheme={customTheme}> <Autocomplete /> </MuiThemeProvider> </div> ) } } export default App
import "./styles.css"; const Button = ({ children, className, ...props }) => { const classes = className ? `button ${className}` : "button"; return ( <button className={classes} {...props}> {children} </button> ); }; export default Button;
$(document).ready(function(){ $('.plantType').css({'height':parseInt($('.content').height()+25)+"px"}) }) $('.addType').on('click',function(){ $('#addPlantType').show(); }) $('.plantNew').on('click',function(){ $('body').find('#plantNewModal').show(); $('#plantNewModal [name="Plant[slot_id]"]').val($(this).data('slotid')); }) $('.close').on('click',function(){ $(this).closest('.modal').hide(); })
import percentInView from './index'; var rollerWords = window.document.getElementById('roller-chrome').getElementsByClassName('roll-phrase'); var rollerWordsCount = rollerWords.length; var wordSegmentLength = rollerWordsCount - 1; var scrollerOffset = 0.55; export default function scrollInit() { var position = setScale(percentInView(), 1 / (1 - scrollerOffset), scrollerOffset); position = trim(position, 1, -99999); for (var i = rollerWords.length - 1; i >= 0; i--) { // var wordPosition = setScale2(position, 5, i * 9 / 10); var wordPosition = setScale(position, wordSegmentLength, ((i / wordSegmentLength) - (1 / (wordSegmentLength * 2)))); rollerWords[i].style.top = getPosition(wordPosition) + '%'; rollerWords[i].style.opacity = getOpacity(wordPosition); rollerWords[i].style.filter = 'blur(' + getBlur(wordPosition) + 'px)'; rollerWords[i].style.transform = 'translate(-50%, -50%) scale(' + getSize(wordPosition) + ')'; } } function trim(number, max, min) { if (max || min) { return Math.min(Math.max(number, min), max); } if (max) { return Math.min(number, max); } if (min) { return Math.max(number, min); } return number; } function setScale(x, slope, offset) { var scale = slope * (x - offset); return scale; } // function setScale2(x, slope, offset) { // var scale = (slope * x) - offset; // return scale; // } function getPosition(x) { var position = 2 * Math.sin( (x - 0.5) / Math.PI ) + 0.5; return (1 - position) * 100; } function getOpacity(x) { var position = -4 * Math.pow((x - 0.5), 2) + 1; position = setScale(position, 0.5, -1); return trim(position, 1, 0); } function getSize(x) { var position = -2 * Math.pow((x - 0.5), 2) + 1; position = setScale(position, 0.5, -1); return trim(position, 1, 0); } function getBlur(x) { var position = -3 * Math.pow((x - 0.5), 2) + 1; position = setScale(position, 0.5, -1); return trim((1 - position), 1, 0) * 10; }
import React from 'react'; export default function Content() { return (<div>文档</div>); }
function NoPlayers() { return <h1>Please Add Players...</h1> } export default NoPlayers
import './App.css'; import Homepage from './pages/Homepage'; import Navbar from './components/Navbar'; function App() { return ( <div className="App"> <Navbar /> <div className="container"> <Homepage /> </div> <div className="footer-copyright light-blue darken-4"> <div className="container"> <p style={{color: 'white'}}> © 2014 Copyright YouFrame </p> </div> </div> </div> ); } export default App;
export default async (req, res) => { const movieData = await fetch( `http://www.omdbapi.com/?i=${req.query.id}&apikey=${process.env.OMDB_KEY}&type=movie` ); let movie = await movieData.json(); res.status(200).json(movie || {}); };
module.exports = app => { const userDef = require("../controllers/userDef.controller.js"); // Create a new UserDef app.post("/userDef", userDef.createUserDef); // Retrieve all UserDef app.get("/userDef", userDef.findAllUserDef); // Retrieve all UserDef for Assigning Reviewer app.get("/reviewerslist", async function(req, res) { const result = [ { label: "Select a mentor", value: null } ]; const promiseReviewersList = userDef.findAllUserDefAsReviewer().then(function(data) { for(let i = 0; i < data.length; i++) { const obj = {}; obj.label = data[i].empName; obj.value = data[i].empID; result.push(obj); if(i === data.length-1) { res.status(200).send(result) } } }).catch(err => res.status(500).send(err)); }); // Retrieve a single UserDef with empId app.get("/userDefByEmpID", userDef.findOneUserDefByEmpID); // // Retrieve a single UserDef with empId // app.get("/userDefByEmpIDLogin", userDef.findOneUserDefByEmpIDLogin); // Retrieve a single UserDef with userDefId app.get("/userDef/:userDefId", userDef.findOneUserDef); // Update a UserDef with userDefId app.put("/userDef", userDef.updateUserDef); // Delete a UserDef with userDefId app.delete("/userDef/:userDefId", userDef.deleteUserDef); };
import React from 'react' import PropTypes from 'prop-types' import { values } from 'lodash' function ShowList({name, list}) { if(!list || !list.length) return null return ( <div> <div>{name}</div> <ul> { list.map(value => { return <li>{value}</li> }) } </ul> </div> ) } ShowList.propTypes = { name: PropTypes.string.isRequired, list: PropTypes.array.isRequired, } export default ShowList
const lastMod = document.lastModified; document.querySelector("#currentDate").textContent = lastMod; const date = new Date(); const currentYear = date.getFullYear(); document.querySelector("#currentYear").textContent = currentYear;
import React from 'react'; import ReactDOM from 'react-dom'; import SeasonDisplay from './SeasonDisplay'; import Spinner from './Spinner'; import './index.css' class App extends React.Component { // simplified state initialization (thanks to babel) state = { latitude: null, errorMessage: '' }; componentDidMount() { // best practise is to put data loading here intead of constructor window.navigator.geolocation.getCurrentPosition( position => this.setState({ latitude: position.coords.latitude }), err => this.setState({ errorMessage: err.message}), console.log('loading') ); } componentDidUpdate() { console.log('Component is updated - it was rerendered!'); } render () { return ( <div className="app"> { this.state.latitude ? <SeasonDisplay latitude={this.state.latitude}/> : this.state.errorMessage ? <div className="errorWrapper"> {`Error message: ${this.state.errorMessage}`} </div> : <Spinner message="Please accept location request"/> } </div> ) } } ReactDOM.render(<App />, document.querySelector('#root'));
import React from "react"; import BeyCard from '../Components/BeyCard' class BeyContainer extends React.Component { // ---- Card Related ---- renderBeys =()=> {return( this.props.beyAPI.map(bey => <BeyCard key={bey.id} title={bey.name} img={bey.img} fav={bey.favorite} clickHandler={this.props.clickHandler} idForClick={bey.id} // *** Trying to Pass in the Whole Object // <BeyCard key={bey.id} bey={bey} // clickHandler={this.props.clickHandler} // idForClick={bey.id} />) )} //console.log("renderBeys") } // ---- Card Related ---- render(){ // console.log(this.props); // console.log(this.props.beyAPI); return ( <div className="index"> <h1>Index</h1> {this.renderBeys()} {/* <BeyCard/> */} </div> )}} export default BeyContainer;
require('dotenv').config() const express = require('express') const app = express() const mongo = require('mongoose') const {bgGreen,bgRed} = require('chalk') const { userRouter } = require('./Routes') const log = console.log app.use(require('cors')()) app.use(express.json()) app.use(userRouter) app.listen(process.env.PORT, (err)=>{ if(!err){ log();log(bgGreen.black('[+] SUCCESS. server is running at port :- '+process.env.PORT));log() mongo.connect('mongodb://127.0.0.1:27017/blogger',{ useNewUrlParser: true,useUnifiedTopology: true, useCreateIndex: true}, err=>{ if(!err){ log(bgGreen.black('[+] SUCCESS. connected to database..'));log() } else{ log(bgRed.black('[-] ERROR ! while connecting database'));log() } } ) } else{ log();log(bgRed.black('[-] ERROR ! while server running at:-'+process.env.PORT));log() } })
class Hasher{ constructor(capacity){ this.arr = []; this.capacity = capacity; this.arr.ensureCapacity(capacity); } put(key,value){ let node = this.getNodeForKey(key); if(node !== null){ let oldValue = node.value; node.value = value; return oldValue; } node = new LinkedListNode(key,value); let index = this.getIndexForKey(key); if(this.arr[index] !== null){ node.next = this.arr[index]; node.next.prev = node; } this.arr[index] = node; return node; }   remove(key){ let node = this.getNodeForKey(key); if(node === null){ return node; } if(node.prev !== null){ node.prev.next = node.next; }else{ //removing head - update let hashKey = this.getIndexForKey(key); this.arr[hashKey] = node.next; } if(node.next !== null){ node.next.prev = node.prev; } return node.value; } get(key){ const keyValue = key === null || this.getNodeForKey(key) === null; return keyValue === null ? null : keyValue; } getNodeForKey(key){ let index = this.getIndexForKey(key); let current = this.arr[index]; while(current !== null){ if(current.key === key){ return current; } current = current.next; } return null; } getIndexForKey(key){ return Math.abs(key.toString().length % this.capacity); } } class LinkedListNode { constructor(key,value) { this.prev = null; this.next = null; this.key = key; this.value = value; } }
/** * 화면 초기화 - 화면 로드시 자동 호출 됨 */ function _Initialize() { // 단위화면에서 사용될 일반 전역 변수 정의 // $NC.setGlobalVar({ }); // 추가 조회조건 사용 $NC.setInitAdditionalCondition(); // 그리드 초기화 grdMasterInitialize(); // 조회조건 - 물류센터 세팅 $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CSUSERCENTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_CENTER_CD: "%" }) }, { selector: "#cboQCenter_Cd", codeField: "CENTER_CD", nameField: "CENTER_NM", onComplete: function() { $("#cboQCenter_Cd").val($NC.G_USERINFO.CENTER_CD); } }); // 조회조건 - 사업부 세팅 $NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD); $NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM); $NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD); // 조회조건 - 운송사 세팅 $NC.setValue("#edtQCarrier_Cd"); $NC.setValue("#edtQCarrier_Nm"); // 조회조건 - 차량 세팅 $NC.setValue("#edtQCar_Cd"); $NC.setValue("#edtQCar_Nm"); // 조회조건 - 배송처 세팅 $NC.setValue("#edtQDelivery_Cd"); $NC.setValue("#edtQDelivery_Nm"); // 정산일자에 달력이미지 설정 $NC.setInitDatePicker("#dtpQAdjust_Date1", $NC.G_USERINFO.LOGIN_DATE, "F"); $NC.setInitDatePicker("#dtpQAdjust_Date2"); // 조회조건 - 정산항목 세팅 $NC.setInitCombo("/LF03020E/getDataSet.do", { P_QUERY_ID: "LF03020E.RS_SUB1", P_QUERY_PARAMS: $NC.getParams("{}") }, { selector: "#cboQFee_Head_Cd", codeField: "FEE_HEAD_CD", nameField: "FEE_HEAD_NM", fullNameField: "FEE_HEAD_CD_F", onComplete: function() { // 조회조건 - 정산세부 세팅 onGetFeeBaseCd(); } }); // 조회조건 - 출고구분 세팅 $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "INOUT_CD", P_CODE_CD: "%", P_SUB_CD1: "DM", P_SUB_CD2: "EM" }) }, { selector: "#cboQInout_Cd", codeField: "CODE_CD", nameField: "CODE_NM", fullNameField: "CODE_CD_F", addAll: true, onComplete: null }); // 사업부 검색 이미지 클릭 $("#btnQBu_Cd").click(showUserBuPopup); $("#btnQBrand_Cd").click(showBuBrandPopup); // 운송사 검색 이미지 클릭 $("#btnQCarrier").click(showCarrierPopup); // 차량 검색 이미지 클릭 $("#btnQCar").click(showCarPopup); // 배송처 검색 이미지 클릭 $("#btnQDelivery").click(showDeliveryPopup); } /** * 화면 리사이즈 Offset 세팅 */ function _SetResizeOffset() { $NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight; } /** * Window Resize Event - Window Size 조정시 호출 됨 */ function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_LAYOUT.border1; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; $NC.resizeContainer("#divMasterView", clientWidth, clientHeight); var height = clientHeight - $NC.G_LAYOUT.header; // Grid 사이즈 조정 $NC.resizeGrid("#grdMaster", clientWidth, height); } /** * Input, Select Change Event 처리 * * @param e * 이벤트 핸들러 * @param view * 대상 Object */ function _OnConditionChange(e, view, val) { // 조회 조건에 Object Change var id = view.prop("id").substr(4).toUpperCase(); switch (id) { case "BU_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: val }; O_RESULT_DATA = $NP.getUserBuInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onUserBuPopup(O_RESULT_DATA[0]); } else { $NP.showUserBuPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onUserBuPopup, onUserBuPopup); } return; case "BRAND_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var BU_CD = $NC.getValue("#edtQBu_Cd"); P_QUERY_PARAMS = { P_BU_CD: BU_CD, P_BRAND_CD: val }; O_RESULT_DATA = $NP.getBuBrandInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onBuBrandPopup(O_RESULT_DATA[0]); } else { $NP.showBuBrandPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onBuBrandPopup, onBuBrandPopup); } return; case "ADJUST_DATE1": $NC.setValueDatePicker(view, val, "정산 시작일자를 정확히 입력하십시오."); break; case "ADJUST_DATE2": $NC.setValueDatePicker(view, val, "정산 종료일자를 정확히 입력하십시오."); break; case "FEE_HEAD_CD": if (!$NC.isNull(val)) { onGetFeeBaseCd(); } break; case "CARRIER_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_CARRIER_CD: val, P_VIEW_DIV: "2" }; O_RESULT_DATA = $NP.getCarrierInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onCarrierPopup(O_RESULT_DATA[0]); } else { $NP.showCarrierPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onCarrierPopup, onCarrierPopup); } return; case "CAR_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_CENTER_CD: $NC.getValue("#cboQCenter_Cd"), P_CAR_CD: val, P_VIEW_DIV: "2" }; O_RESULT_DATA = $NP.getCarInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onCarPopup(O_RESULT_DATA[0]); } else { $NP.showCarPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onCarPopup, onCarPopup); } return; case "DELIVERY_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var CUST_CD = $NC.getValue("#edtQCust_Cd"); P_QUERY_PARAMS = { P_CUST_CD: CUST_CD, P_DELIVERY_CD: val, P_DELIVERY_DIV: "%", P_VIEW_DIV: "2" }; O_RESULT_DATA = $NP.getDeliveryInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onDeliveryPopup(O_RESULT_DATA[0]); } else { $NP.showDeliveryPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onDeliveryPopup, onDeliveryPopup); } return; } // 화면클리어 onChangingCondition(); } function onChangingCondition() { // 전역 변수 값 초기화 $NC.clearGridData(G_GRDMASTER); // 버튼 활성화 처리 $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "0"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } /** * Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨 */ function _Inquiry() { // 조회시 전역 변수 값 초기화 $NC.setInitGridVar(G_GRDMASTER); // 조회조건 체크 var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd"); var BU_NM = $NC.getValue("#edtQBu_Nm"); if ($NC.isNull(BU_NM)) { alert("사업부를 입력하십시오."); $NC.setFocus("#edtQBu_Cd"); return; } var ADJUST_DATE1 = $NC.getValue("#dtpQAdjust_Date1"); if ($NC.isNull(ADJUST_DATE1)) { alert("정산 시작일자를 입력하십시오."); $NC.setFocus("#dtpQAdjust_Date1"); return; } var ADJUST_DATE2 = $NC.getValue("#dtpQAdjust_Date2"); if ($NC.isNull(ADJUST_DATE2)) { alert("정산 종료일자를 입력하십시오."); $NC.setFocus("#dtpQAdjust_Date2"); return; } var FEE_HEAD_CD = $NC.getValue("#cboQFee_Head_Cd"); if ($NC.isNull(FEE_HEAD_CD)) { alert("정산항목을 선택하십시오."); $NC.setFocus("#cboQFee_Head_Cd"); return; } var FEE_BASE_CD = $NC.getValue("#cboQFee_Base_Cd"); if ($NC.isNull(FEE_BASE_CD)) { alert("정산세부를 선택하십시오."); $NC.setFocus("#cboQFee_Base_Cd"); return; } var INOUT_CD = $NC.getValue("#cboQInout_Cd"); if ($NC.isNull(INOUT_CD)) { alert("출고구분을 선택하십시오."); $NC.setFocus("#cboQInout_Cd"); return; } var BRAND_CD = $NC.getValue("#edtQBrand_Cd", true); var DEAL_ID = $NC.getValue("#edtQDeal_Id"); var ITEM_CD = $NC.getValue("#edtQItem_Cd"); var ITEM_NM = $NC.getValue("#edtQItem_Nm"); var CARRIER_CD = $NC.getValue("#edtQCarrier_Cd", true); var CAR_CD = $NC.getValue("#edtQCar_Cd", true); var DELIVERY_CD = $NC.getValue("#edtQDelivery_Cd", true); G_GRDMASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_ADJUST_DATE1: ADJUST_DATE1, P_ADJUST_DATE2: ADJUST_DATE2, P_FEE_HEAD_CD: FEE_HEAD_CD, P_FEE_BASE_CD: FEE_BASE_CD, P_CARRIER_CD: CARRIER_CD, P_CAR_CD: CAR_CD, P_DELIVERY_CD: DELIVERY_CD, P_ITEM_CD: ITEM_CD, P_ITEM_NM: ITEM_NM, P_BRAND_CD: BRAND_CD, P_DEAL_ID: DEAL_ID, P_INOUT_CD: INOUT_CD }); // 데이터 조회 $NC.serviceCall("/LF03020E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster); } /** * New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨 */ function _New() { } /** * Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨 */ function _Save() { if (G_GRDMASTER.lastRow == null || G_GRDMASTER.data.getLength() === 0) { alert("저장할 데이터가 없습니다."); return; } // 현재 수정모드면 if (G_GRDMASTER.view.getEditorLock().isActive()) { G_GRDMASTER.view.getEditorLock().commitCurrentEdit(); } var saveMasterDS = [ ]; var rowCount = G_GRDMASTER.data.getLength(); for (var row = 0; row < rowCount; row++) { var rowData = G_GRDMASTER.data.getItem(row); if (rowData.CRUD !== "R") { var saveData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_ADJUST_MONTH: rowData.ADJUST_MONTH, P_ADJUST_DATE: rowData.ADJUST_DATE, P_FEE_HEAD_CD: rowData.FEE_HEAD_CD, P_FEE_BASE_CD: rowData.FEE_BASE_CD, P_CAR_CD: rowData.CAR_CD, P_CUST_CD: rowData.CUST_CD, P_VENDOR_CD: rowData.VENDOR_CD, P_DELIVERY_CD: rowData.DELIVERY_CD, P_DELIVERY_BATCH: rowData.DELIVERY_BATCH, P_KEEP_DIV: rowData.KEEP_DIV, P_DEPART_CD: rowData.DEPART_CD, P_LINE_CD: rowData.LINE_CD, P_PERIOD_DIV: rowData.PERIOD_DIV, P_CLASS_CD: rowData.CLASS_CD, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD, P_ADJUST_FEE_AMT: rowData.ADJUST_FEE_AMT, P_REMARK1: rowData.REMARK1, P_CRUD: rowData.CRUD }; saveMasterDS.push(saveData); } } if (saveMasterDS.length > 0) { $NC.serviceCall("/LF03020E/save.do", { P_DS_MASTER: $NC.toJson(saveMasterDS), P_USER_ID: $NC.G_USERINFO.USER_ID }, onSave, onSaveError); } } /** * Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨 */ function _Delete() { } /** * Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨 */ function _Cancel() { var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, { selectKey: ["ADJUST_DATE", "CAR_CD", "CUST_CD", "DELIVERY_CD", "ITEM_CD", "BRAND_CD"], isCancel: true }); _Inquiry(); G_GRDMASTER.lastKeyVal = lastKeyVal; } /** * Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨 * * @param printIndex * 선택한 출력물 Index */ function _Print(printIndex, printName) { } function grdMasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "DEAL_ID", field: "DEAL_ID", name: "딜번호", minWidth: 90, summaryTitle: "[합계]" }); $NC.setGridColumn(columns, { id: "DEAL_NM", field: "DEAL_NM", name: "딜명", minWidth: 150 }); $NC.setGridColumn(columns, { id: "INOUT_NM", field: "INOUT_NM", name: "출고구분", minWidth: 90 }); $NC.setGridColumn(columns, { id: "BRAND_CD", field: "BRAND_CD", name: "판매사코드", minWidth: 100 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "판매사명", minWidth: 100 }); $NC.setGridColumn(columns, { id: "UNIT_DIV_D", field: "UNIT_DIV_D", name: "정산단위", cssClass: "align-right", minWidth: 90 }); $NC.setGridColumn(columns, { id: "FEE_QTY", field: "FEE_QTY", name: "정산수량", cssClass: "align-right", minWidth: 90, aggregator: "SUM" }); $NC.setGridColumn(columns, { id: "UNIT_PRICE", field: "UNIT_PRICE", name: "정산단가", cssClass: "align-right", minWidth: 90 }); $NC.setGridColumn(columns, { id: "FEE_AMT", field: "FEE_AMT", name: "정산금액", cssClass: "align-right", minWidth: 90, aggregator: "SUM" }); $NC.setGridColumn(columns, { id: "ADJUST_FEE_AMT", field: "ADJUST_FEE_AMT", name: "최종정산금액", cssClass: "align-right", minWidth: 90, editor: Slick.Editors.Number, aggregator: "SUM" }); $NC.setGridColumn(columns, { id: "ADJUST_DATE", field: "ADJUST_DATE", name: "정산일자", cssClass: "align-center", minWidth: 90 }); $NC.setGridColumn(columns, { id: "CAR_CD", field: "CAR_CD", name: "차량코드", minWidth: 100 }); $NC.setGridColumn(columns, { id: "CAR_NM", field: "CAR_NM", name: "차량명", minWidth: 150 }); $NC.setGridColumn(columns, { id: "CARRIER_NM", field: "CARRIER_NM", name: "운송사명", minWidth: 100 }); $NC.setGridColumn(columns, { id: "DELIVERY_CD", field: "DELIVERY_CD", name: "배송처", minWidth: 100 }); $NC.setGridColumn(columns, { id: "DELIVERY_NM", field: "DELIVERY_NM", name: "배송처명", minWidth: 150 }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "비고", minWidth: 150, editor: Slick.Editors.Text }); return $NC.setGridColumnDefaultFormatter(columns); } /** * 배송청구수수료 상세내역 */ function grdMasterInitialize() { var options = { editable: true, autoEdit: true, frozenColumn: 0, summaryRow: { visible: true } }; // Grid Object, DataView 생성 및 초기화 $NC.setInitGridObject("#grdMaster", { columns: grdMasterOnGetColumns(), queryId: "LF03020E.RS_MASTER", sortCol: "ADJUST_DATE", gridOptions: options }); G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll); G_GRDMASTER.view.onCellChange.subscribe(grdMasterOnCellChange); } /** * 그리드 행 선택 변경 했을 경우 * * @param e * @param args */ function grdMasterOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDMASTER.lastRow != null) { if (row == G_GRDMASTER.lastRow) { e.stopImmediatePropagation(); return; } } // 상단 현재로우/총건수 업데이트 $NC.setGridDisplayRows("#grdMaster", row + 1); } /** * 그리드의 편집 셀 값 변경시 처리 * * @param e * @param args */ function grdMasterOnCellChange(e, args) { var rowData = args.item; if (G_GRDMASTER.lastRow == null) return; if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTER.data.updateItem(rowData.id, rowData); // 마지막 선택 Row 수정 상태로 변경 G_GRDMASTER.lastRowModified = true; } /** * 배송수수료 상세내역 조회 * * @param ajaxData */ function onGetMaster(ajaxData) { $NC.setInitGridData(G_GRDMASTER, ajaxData); if (G_GRDMASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDMASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDMASTER, 0); } else { $NC.setGridSelectRow(G_GRDMASTER, { selectKey: ["ADJUST_DATE", "CAR_CD", "CUST_CD", "DELIVERY_CD", "ITEM_CD", "BRAND_CD"], selectVal: G_GRDMASTER.lastKeyVal, activeCell: true }); } } else { $NC.setGridDisplayRows("#grdMaster", 0, 0); } // 버튼 활성화 처리 $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "1"; $NC.G_VAR.buttons._cancel = "1"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } /** * 조회조건 - 정산세부 세팅 */ function onGetFeeBaseCd() { $NC.setInitCombo("/LF03020E/getDataSet.do", { P_QUERY_ID: "LF03020E.RS_SUB2", P_QUERY_PARAMS: $NC.getParams({ P_FEE_HEAD_CD: $NC.getValue("#cboQFee_Head_Cd") }) }, { selector: "#cboQFee_Base_Cd", codeField: "FEE_BASE_CD", nameField: "FEE_BASE_NM", fullNameField: "FEE_BASE_CD_F", onComplete: function() { $NC.setValue("#cboQFee_Base_Cd", 0); } }); } /** * 검색조건의 사업부 검색 이미지 클릭 */ function showUserBuPopup() { $NP.showUserBuPopup({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: "%" }, onUserBuPopup, function() { $NC.setFocus("#edtQBu_Cd", true); }); } function onUserBuPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBu_Cd", resultInfo.BU_CD); $NC.setValue("#edtQBu_Nm", resultInfo.BU_NM); $NC.setValue("#edtQCust_Cd", resultInfo.CUST_CD); } else { $NC.setValue("#edtQBu_Cd"); $NC.setValue("#edtQBu_Nm"); $NC.setValue("#edtQCust_Cd"); $NC.setFocus("#edtQBu_Cd", true); } onChangingCondition(); } /** * 검색조건의 브랜드 검색 팝업 클릭 */ function showBuBrandPopup() { var BU_CD = $NC.getValue("#edtQBu_Cd"); $NP.showBuBrandPopup({ P_BU_CD: BU_CD, P_BRAND_CD: "%" }, onBuBrandPopup, function() { $NC.setFocus("#edtQBrand_Cd", true); }); } /** * 브랜드 검색 결과 * * @param seletedRowData */ function onBuBrandPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBrand_Cd", resultInfo.BRAND_CD); $NC.setValue("#edtQBrand_Nm", resultInfo.BRAND_NM); } else { $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); $NC.setFocus("#edtQBrand_Cd", true); } onChangingCondition(); } /** * 검색조건의 운송사 검색 이미지 클릭 */ function showCarrierPopup() { $NP.showCarrierPopup({ queryParams: { P_CARRIER_CD: "%", P_VIEW_DIV: "2" } }, onCarrierPopup, function() { $NC.setFocus("#edtQCarrier_Cd", true); }); } function onCarrierPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQCarrier_Cd", resultInfo.CARRIER_CD); $NC.setValue("#edtQCarrier_Nm", resultInfo.CARRIER_NM); } else { $NC.setValue("#edtQCarrier_Cd"); $NC.setValue("#edtQCarrier_Nm"); $NC.setFocus("#edtQCarrier_Cd", true); } onChangingCondition(); } /** * 검색조건의 차량 검색 이미지 클릭 */ function showCarPopup() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); $NP.showCarPopup({ P_CENTER_CD: CENTER_CD, P_CAR_CD: "%", P_VIEW_DIV: "2" }, onCarPopup, function() { $NC.setFocus("#edtQCar_Cd", true); }); } function onCarPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQCar_Cd", resultInfo.CAR_CD); $NC.setValue("#edtQCar_Nm", resultInfo.CAR_NM); } else { $NC.setValue("#edtQCar_Cd"); $NC.setValue("#edtQCar_Nm"); $NC.setFocus("#edtQCar_Cd", true); } onChangingCondition(); } /** * 검색조건의 배송처 검색 이미지 클릭 */ function showDeliveryPopup() { var CUST_CD = $NC.getValue("#edtQCust_Cd"); $NP.showDeliveryPopup({ queryParams: { P_CUST_CD: CUST_CD, P_DELIVERY_CD: "%", P_DELIVERY_DIV: "%", P_VIEW_DIV: "2" } }, onDeliveryPopup, function() { $NC.setFocus("#edtQDelivery_Cd", true); }); } function onDeliveryPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQDelivery_Cd", resultInfo.DELIVERY_CD); $NC.setValue("#edtQDelivery_Nm", resultInfo.DELIVERY_NM); } else { $NC.setValue("#edtQDelivery_Cd"); $NC.setValue("#edtQDelivery_Nm"); $NC.setFocus("#edtQDelivery_Cd", true); } onChangingCondition(); } /** * 저장에 성공했을 경우의 처리 * * @param ajaxData */ function onSave(ajaxData) { var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, { selectKey: ["ADJUST_DATE", "CAR_CD", "CUST_CD", "DELIVERY_CD", "ITEM_CD", "BRAND_CD"] }); _Inquiry(); G_GRDMASTER.lastKeyVal = lastKeyVal; } /** * 저장에 실패 했을 경우의 처리 * * @param ajaxData */ function onSaveError(ajaxData) { $NC.onError(ajaxData); }
import Axios from 'axios'; import { stringify } from 'qs'; import { moduleA } from '@/utils/config'; export async function getAuthority_api (params) { return await Axios({ url: `${moduleA}/login/login.loginV4.do?${stringify(params)}&t=${new Date().getTime()}`, method: 'get', }); } // export async function getTestData_api (params) { // return axios({ // url: `${moduleC}/promoter/dict/list?${stringify(params)}&t=${Math.random()}`, // method: 'get', // headers: { // ticket: window.localStorage.getItem('token') || '', // client_id: 'ump', // client_type: 'web', // } // }); // } // export async function nextStep_api (params) { // return axios({ // url: `${moduleA}/tool/fixed_price`, // method: 'post', // data: params, // headers: { // ticket: window.localStorage.getItem('token') || '', // client_id: 'ump', // client_type: 'web', // } // }); // }
var searchData= [ ['y_5fmove_255',['y_move',['../menu_8c.html#a07d0e026b8eaaa6a35ef6cb233a88b98',1,'menu.c']]], ['y_5fovfl_256',['Y_OVFL',['../group__i8042.html#gad49b33d3abadec53a57d09a7f255315f',1,'i8042.h']]], ['y_5fsign_257',['Y_SIGN',['../group__i8042.html#ga2a0064e2f0979eea21b81e4fe6b2ac32',1,'i8042.h']]], ['year_258',['year',['../struct__l__elemento.html#aac3a162d2f192fe2360aba534eac7198',1,'_l_elemento']]], ['ym_259',['ym',['../group__makecodes.html#ga44fade6d459c638c80786d9aa6ee516b',1,'makecodes.h']]], ['ypont_260',['ypont',['../group__makecodes.html#ga482a031c5fe9ec480504ab6de127b332',1,'makecodes.h']]] ];
/*global ODSA */ // Written by Liling Yuan and Cliff Shaffer // Building a B+ Tree of order 5 $(document).ready(function() { "use strict"; var av_name = "BPbuild5CON"; var av = new JSAV(av_name); av.umsg("Example B+ Tree Visualization: Insert into a tree of degree 5"); var t = BPTree.newTree(av, 4, true); av.displayInit(); t.add(12, "T"); t.add(9, "E"); t.add(23, "Q"); t.add(5, "F"); t.add(2, "B"); t.add(7, "A"); t.add(38, "A"); t.add(39, "F"); t.add(40, "V"); t.add(45, "V"); av.recorded(); });
import React from "react"; import Play from "./components/Play"; function App() { return <Play />; } export default App;
window.WebApp = function () { }; window.WebApp.prototype = { renderTemplate: function (name, data, callback) { data = _.extend(data, { 'config': window.config }); var template = twig({ ref: name }); if (template) { if (callback && typeof(callback) === 'function') { callback(template.render(data)); } } else { twig({ id: name, href: '/rating_app/static/js_parse/tpl/' + name + '.twig', load: function (template) { if (callback && typeof(callback) === 'function') { callback(template.render(data)); } } }); } }, // Метод который полностью подменяет контекст вызова у переданной функции на тот что был передан // в параметрах. // Более быстрая альтернатива универсальному `fn.bind(context)` (http://jsperf.com/bind-experiment-2) // // __Пример:__ // // var a = { // handler: core._bind(fn, context) // } _bind: function(fn, context) { context || (context = window); if (typeof(fn) === 'function') { return function() { return fn.apply(context, arguments); }; } return false; } };
'use strict'; const msgpack = require('notepack.io') const os = require('os') const fs = require('fs-extra') const Debug = require('debug') const debug = Debug('keyv-file') function isNumber(val) { return typeof val === 'number' } module.exports = class KeyvFile { constructor(opts) { this.ttlSupport = true const defaults = { filename: `${os.tmpdir()}/keyv-file/default-rnd-${Math.random().toString(36).slice(2)}.msgpack`, expiredCheckDelay: 24 * 3600 * 1000, // ms writeDelay: 100, // ms encode: msgpack.encode, decode: msgpack.decode } this._opts = Object.assign(defaults, opts) this._lastSave = Date.now() try { const data = this._opts.decode(fs.readFileSync(this._opts.filename)) this._cache = data.cache this._lastExpire = data.lastExpire } catch (e) { debug(e) this._cache = {} this._lastExpire = Date.now() } } _isExpired(data) { return isNumber(data.expire) && data.expire <= Date.now() } get(key) { const data = this._cache[key] if (!data) { return undefined } else if (this._isExpired(data)) { this.delete(key) return undefined } else { return data.value } } keys() { return Object.keys(this._cache) .filter(key => !this._isExpired(this._cache[key])) } set(key, value, ttl) { if (ttl === 0) { ttl = undefined } this._cache[key] = { value: value, expire: isNumber(ttl) ? Date.now() + ttl : undefined } this.save() } delete(key) { let ret = key in this._cache delete this._cache[key] this.save() return ret } clear() { this._cache = {} this._lastExpire = Date.now() this.save() } clearExpire() { const now = Date.now() if (now - this._lastExpire <= this._opts.expiredCheckDelay) { return } Object.keys(this._cache).forEach(key => { const data = this._cache[key] if (this._isExpired(data)) { delete this._cache[key] } }) this._lastExpire = now } saveToDisk() { const data = this._opts.encode({cache: this._cache, lastExpire: this._lastExpire}) return new Promise((resolve, reject) => { fs.outputFile(this._opts.filename, data, err => { if (err) { reject(err) } else { resolve() } }) }) } save() { this.clearExpire() this._saveTimer && clearTimeout(this._saveTimer) return new Promise((resolve, reject) => { this._saveTimer = setTimeout( () => this.saveToDisk().then(resolve, reject), this._opts.writeDelay ) }) } }
const path = require("path"); const TypescriptDeclarationPlugin = require('typescript-declaration-webpack-plugin'); module.exports = { mode: 'development', devtool: "source-map", resolve: { extensions: ['.js', '.ts', '.tsx'], }, entry: { home: './src/index.tsx', }, output: { libraryTarget: 'umd', globalObject: 'this', filename: 'index.js', path: path.resolve(__dirname, 'dist'), }, plugins: [ new TypescriptDeclarationPlugin({ }), ], module: { rules: [ { test: /\.(ts|tsx)$/, use: ["ts-loader?configFile=tsconfig.json"], exclude: [/node_modules/, /.examples/], }, { test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'file-loader?name=./font/[name].[ext]', exclude: [/.examples/], }, ], }, };
define(function(require) { var Backbone = require('backbone'); var bootstrap = require('bootstrap'); var accordion = require('backbone-accordionPanel'); var Group = accordion.model; var AccordionCollection = accordion.collection; var Panel = accordion.view; var Item = Backbone.Model.extend(); var g1 = new Group({}); g1.set('name', "group1"); g1.get('items').push(new Item({ link: 'group1link', name: 'group1link' })); var g2 = new Group({name: 'group2'}); g2.get('items').push(new Item({link: 'group2link', name: 'group2link'})); var set = new AccordionCollection(); set.add(g1); set.add(g2); console.log(set); var instance = new Panel({ collection: set }); instance.$el.html = instance.template(instance.collection); $('#template-panel-content').html(instance.$el.html); });
(function () { 'use strict'; angular .module('media') .config(config); function config($stateProvider) { $stateProvider .state('media', { url: '/media', templateUrl: 'media/media.tpl.html', controller: 'MediaCtrl', controllerAs: 'media' }); } }());
var Backbone = require('backbone'); var async = require('async'); var _ = require('underscore'); var SQLiteSingleton = require('./SQLiteSingleton').SQLiteSingleton; var UserItem = Backbone.Model.extend({ initialize: function () { // body... }, getItemsByEmail: function(email, cb){ async.waterfall ([ function (callback){ callback(null, SQLiteSingleton); }, function (db, callback){ db.all("SELECT * FROM user_item WHERE email=?", email, callback); } ],cb); }, addItem: function(email, item, cb) { var _self = this; var db; async.waterfall ([ function (callback){ callback(null, SQLiteSingleton); }, function (_res, next) { db = _res; _self.getItemsByEmail(email, next); }, function (userItems, callback) { var found = _.find(userItems, function (ui){return ui.i_id==item.i_id;}); console.log(JSON.stringify(found)); if(found){ db.run("UPDATE user_item SET quantity = ? WHERE email=? AND i_id=?", [found.quantity +1 , email, item.i_id], callback); } else { db.run("INSERT INTO user_item VALUES(?,?,?)", [email, item.i_id, 1], callback); } } ],cb); }, }); exports.UserItem = new UserItem();
//When I was doing this, the count and movement of the tennis ball weren't quite synced and thus the count had to go up by 20 each time for it to work properly //however, I the speed of the tennis ball is really slow and if I were to go back to it now, I would speed everything up function Tennis() { this.roll = function() { textSize(20); //var ms = millis(); //text("Milliseconds \nrunning: \n" + ms, 95, 40); count += 20; //text("Count: " + count, 5, 120); //tennis ball if (count >= 1850) { push(); translate(0, -100); //rotate(TWO_PI); //make it rotate around origin so it looks like it is rolling image(tennis, x, y + 140); pop(); } //end ms1850 if (value == 1) { //Target 1 //pipe A if (count < 17500) x += 1.0; //pipe Z if ((count >= 17500) && (count <= 28200)) y += 1; //pipe W if ((count >= 28200) && (count <= 29700)) x -= 1; //pipe U if ((count >= 29700) && (count <= 31500)) y += 1; //pipe T if ((count >= 31500) && (count <= 33300)) x += 1; //pipecount S if ((count >= 33300) && (count <= 35500)) y += 1; } else if (value == 2) { //Target 2 //pipe A if (count < 17500) x += 1.0; //pipe B if ((count >= 17500) && (count <= 20500)) x -= 1.53, y += 1; //pipe Y if ((count >= 20500) && (count <= 23500)) x += 1.55, y += 1; //pipe X if ((count >= 23500) && (count <= 28200)) y += 1; //pipe W if ((count >= 28200) && (count <= 29700)) x -= 1; //pipe U if ((count >= 29700) && (count <= 31500)) y += 1; //pipe T if ((count >= 31500) && (count <= 33300)) x += 1; //pipecount S if ((count >= 33300) && (count <= 35500)) y += 1; } else if (value == 3) { //Target 3 //pipe A if (count < 17500) x += 1.0; //pipe B if ((count >= 17500) && (count <= 20500)) x -= 1.53, y += 1; //pipe C if ((count >= 20500) && (count < 30500)) x -= 1; //pipe I if ((count >= 30500) && (count <= 35000)) x -= .53, y += 1; //pipe J if ((count >= 35000) && (count <= 40000)) y += 1; //pipe O if ((count >= 40000) && (count <= 42000)) x += 1; //pipe P if ((count >= 42000) && (count <= 45500)) y += 1; } else if (value == 4) { //pipe A if (count < 17500) x += 1.0; //pipe Z if ((count >= 17500) && (count <= 23000)) y += 1; //pipe V if ((count >= 23000) && (count <= 27700)) x -= 1.7, y += 1; //pipe N if ((count >= 27700) && (count <= 33000)) x += .40, y += 1; } else if (value == 5) { //Target 3 + 5 //pipe A if (count < 17500) x += 1.0; //pipe B if ((count >= 17500) && (count <= 20500)) x -= 1.53, y += 1; //pipe C if ((count >= 20500) && (count < 30500)) x -= 1; //pipe I if ((count >= 30500) && (count <= 35000)) x -= .53, y += 1; //pipe K if ((count >= 35000) && (count <= 37700)) x += 1.43, y += 1; //pipe L if ((count >= 37700) && (count <= 42700)) x += 1; //pipe N if ((count >= 42700) && (count <= 50000)) x += .50, y += 1.3; } else if (value == 6) { //pipe A if (count < 17500) x += 1.0; //pipe Z if ((count >= 17500) && (count <= 23000)) y += 1; //pipe V if ((count >= 23000) && (count <= 28000)) x -= 1.7, y += 1; //pipe M if ((count >= 28000) && (count <= 33000)) x -= .50, y += 1.2; } else { //original path //pipe A if (count < 17500) x += 1.0; //pipe B if ((count >= 17500) && (count < 20500)) x -= 1.53, y += 1; //pipe C if ((count >= 20500) && (count < 30000)) x -= 1; //pipe D if ((count >= 30000) && (count < 35000)) y += 1; //pipe F if ((count >= 35000) && (count < 43300)) x += 1; //pipe G if ((count >= 43300) && (count < 45500)) x += 1.35, y += 1.2; //pipe H if ((count >= 45500) && (count <= 50000)) y += 1; } //end else }//end roll } //end function
import React, { Fragment } from 'react'; import { withRouter } from 'react-router-dom'; // MATERIAL COMPONENTS import Button from '@material-ui/core/Button'; const AppLinks = props => { return ( <Fragment> <Button onClick={() => props.history.push('/')} color='inherit'> Dashboard </Button> <Button onClick={() => props.history.push('/confirmed-cases')} color='inherit' > Confirmed Report </Button> <Button onClick={() => props.history.push('/death-cases')} color='inherit' > Death Report </Button> <Button onClick={() => props.history.push('/recovered-cases')} color='inherit' > Recovered Report </Button> <Button onClick={() => props.history.push('/charts')} color='inherit'> Visualizations </Button> </Fragment> ); }; export default withRouter(AppLinks);
'use strict'; var CronJob = require('cron').CronJob; var amazon = require('./amazon'); var redis = require('./redis'); // var Redis = require('ioredis'); // var r = new Redis(); var job; var init; console.log('Running index...'); require('./twitter'); /** - Multiple locales - Grab the locale settings - Bootstrap the settings and config to create an amazon query - Cron the amazon query every 10 seconds - Return that data as a json payload */ /* http://redis.io/topics/notifications amazon.init('UK').then(function(response) { redis.process_data(response); }); // amazon.init('US').then(function(response) { // redis.process_process_stock_table(response.in_stock_table); // redis.process_products_table(response.product_table); // }); init populate the stock table populate the persistent product table update stock table remove out of stock add in stock */ // var queryAmazon = require('./amazon').initAmazon; // var publisher = require('./publisher'); // job = new CronJob({ cronTime: '*/20 * * * * *', onTick: function callback() { // console.log('running cron'); amazon.init('UK').then(function callback(response) { redis.process_data(response); }); // queryAmazon('US'); }, start: false, timeZone: 'Europe/London' }); init = function init() { console.log('Initialising...'); // r.flushall(); // console.log('Db flushed, starting job...'); job.start(); }; init();
// IMPORTS // react import React from "react"; // styled components import styled from "styled-components"; // images import onboardlogo from "../../../images/refresh-yo-guy.svg"; const Landing = props => { //routes const routeToSignUp = e => { e.preventDefault(); props.history.push("/signup"); }; const routeToLogin = e => { e.preventDefault(); props.history.push("/login"); }; const routeToAdmin = e => { e.preventDefault(); props.history.push("/adminlogin"); }; //render return ( <OnBoardContainer> <LogoDiv> <Logo src={onboardlogo} /> </LogoDiv> <LeftDiv> <FlexHolder> <Refresh>Refresh</Refresh> <OnboardTxt className="slogan"> Encouraging healthier behaviors <br /> through teamwork. </OnboardTxt> <br /> <OnboardTxt> Because success starts with the <br /> body in mind. </OnboardTxt> </FlexHolder> <FlexHolder2> <Button onClick={routeToSignUp}>Get Started</Button> <ButtonNoColor onClick={routeToLogin}> I already have an account </ButtonNoColor> <AdminSignIn onClick={routeToAdmin}>Admin Login Here</AdminSignIn> </FlexHolder2> </LeftDiv> </OnBoardContainer> ); }; const OnBoardContainer = styled.div` display: flex; flex-direction:row-reverse; width: 100vw; height: 100vh; overflow-y: auto; font-family: "Catamaran", sans-serif; margin: auto; line-height: 1.5; /* &:nth-child(*) { margin-top: 10%; } */ `; const LogoDiv = styled.div` display: flex; justify-content: center; width: 50vw; /* border: 2px solid black; */ `; const Logo = styled.img` /* border: 2px solid red; */ width: 75%; margin: 5% auto 10% 0; /* width: 100%; max-width: 82%; height: auto; margin: 10% auto auto auto; @media screen and (min-width: 1000px) { padding-left: 300px; margin-top: 20px; } */ `; const LeftDiv = styled.div` display: flex; justify-content: center; flex-direction: column; width: 45%; `; const FlexHolder = styled.div` display: flex; flex-direction: column; justify-content: center; /* border: 2px solid blue; */ /* display: flex; flex-direction: column; justify-content: center; margin: 0 0 auto 10%; align-items: flex-start; width: 50%; .slogan { font-size: calc(100% + 3.9vw); line-height: 3.9rem; @media screen and (min-width: 1000px) { font-size: calc(100% + 2vw); line-height: 3rem; margin-top: 10px; } } */ `; const FlexHolder2 = styled.div` display: flex; flex-direction: column; justify-content: left; align-items: left; /* border: 2px solid green; */ width: 70%; margin: 3% auto; .slogan { font-size: calc(100% + 3.9vw); line-height: 3.9rem; @media screen and (min-width: 1000px) { font-size: calc(100% + 2vw); line-height: 3rem; margin-top: 10px; } } /* display: flex; flex-direction: column; justify-content: center; margin: 0 0 auto 3%; align-items: left; width: 50%; */ `; const Refresh = styled.h1` font-weight: bold; font-size: calc(100% + 9vw); line-height: 10vh; letter-spacing: 3.5px; color: black; margin-left:14.5%; margin-bottom: 2%; @media screen and (min-width: 1000px) { font-size: calc(100% + 6.5vw); margin-top: -20px; } `; const OnboardTxt = styled.p` font-size: calc(100% + 1.7vw); line-height: 4vh; letter-spacing: 0.035em; color: black; margin-left:15%; `; const Button = styled.a` display: inline-block; border-radius: 0.5rem; padding: 1.5rem 0.8rem; width: 50%; text-align: center; margin: 10px auto; margin-left: 0; background: #E05CB3; color: white; font-size: calc(100% + 0.5vw); &:hover { cursor: pointer; } `; const AdminSignIn = styled.a` display: inline-block; border-radius: 0.5rem; padding: 1.5rem 0.8rem; width: 50%; text-align: center; margin: 10px auto; margin-left: 0; background: rgb(61,162,237); color: white; font-size: calc(100% + 0.5vw); &:hover { cursor: pointer; } `; const ButtonNoColor = styled.a` margin: auto; padding: 0.7rem; font-size: 1.6rem; margin-left: 10%; &:hover { cursor: pointer; } `; //EXPORT export default Landing;
'use strict'; /** * @ngdoc function * @name photosApp.controller:PhotoCtrl * @description * # PhotoCtrl * Controller of the photosApp */ angular.module('photosApp') .controller('PhotoCtrl', function ($scope, $location, API) { var id = $location.path().split('/').pop(); $scope.reload = function(){ API.getPhoto(id, function(photo){ $scope.photo = photo; }); }; $scope.delete = function(){ API.deletePhoto(id, function(){ $location.path('/'); }); }; $scope.addTag = function(tag){ API.addTag(id, tag.name, function(){ $scope.reload(); }); }; $scope.deleteTag = function(tag){ API.deleteTag(id, tag.id, function(){}); }; $scope.reload(); });
/* Write a function intersect that takes any number of arguments. The function must return an array containing all the values that is present in every argument given to the function. - All arguments given will be arrays. - The first argument determines the order of the returned values. - Return an empty array for empty result set. Example: var a = ['dog', 'bar', 'foo']; var b = ['foo', 'bar', 'cat']; var c = ['gin', 'bar', 'foo']; intersect(a, b, c); // ['bar', 'foo']; */ function intersect(...args) { let arr = []; for (let i = 0; i < args.length; i++) { let currentArr = args[i]; for (let j = 0; j < currentArr.length; j++) { let element = currentArr[j]; if (args.every(a => a.includes(element))) arr.push(element); } } let uniqVals = Array.from(new Set(arr)); return uniqVals; }
import tests from "../test-wrapper-helper"; import pagination from "../../src/pagination-wrapper"; describe("Pagination Wrapper on Android", tests(pagination));
const axios = require('axios').default; const { ClientBuilder } = require('@iota/client'); // client will connect to testnet by default const client = new ClientBuilder() .node("https://api.lb-0.h.chrysalis-devnet.iota.cafe") .localPow(true) .build(); // client.getInfo().then(console.log).catch(console.error); baseurl = "http://localhost:8000" key = '123456' function verifyDoor() { url = baseurl + "/" + key axios.get(url) .then(function (response) { console.log("success:: status:", response.status, "| data:", response.data); if (response.status == 200) { // server is reachable. if (response.data == true) { // Valid Ticket console.log("Valid Ticket"); } else { console.log("In-Valid Ticket"); } } else { console.log("Something went wrong. Please find the doorman!"); } }) .catch(function (error) { console.log("error:", error); }); } // verifyDoor() topic = "ticket/door/1" async function verifyDoorMQTT() { const message = await client.message() .index(topic) .data(key) .submit(); console.log("message:", message); } // verifyDoorMQTT() async function getValidation() { listenTopic = 'messages/indexation/' + topic + "/result" client.subscriber().topics([listenTopic]).subscribe((err, data) => { console.log(data); // To get the message id from messages `client.getMessageId(data.payload)` can be used }) await new Promise(resolve => setTimeout(resolve, 1500)); // unsubscribe from 'messages' topic, will continue to receive events for 'milestones/confirmed' client.subscriber().topics(['messages']).unsubscribe((err, data) => { console.log(data); }) } getValidation()
const auctionDuration = 2 const WAVES = 10 ** 8; const SETSCRIPT_FEE = 0.01 * WAVES const ISSUE_FEE = 1 * WAVES const INV_FEE = 0.005 * WAVES const ADD_FEE = 0.004 * WAVES var issueTxId var auctionId var auctionStartTx var customer2Before async function rememberBalances(text, forAddress, tokenId) { const tokenBal = await assetBalance(tokenId, forAddress) const wavesBal = await balance(forAddress) console.log (text + ": " + wavesBal + " WAVES, " + tokenBal + " NFT") return [wavesBal, tokenBal] } describe('Auction test Suite', async function(){ this.timeout(100000) before(async function () { await setupAccounts({auction: SETSCRIPT_FEE, customer1: ISSUE_FEE + 2*INV_FEE, customer2: (0.1 + 0.2 + 0.3) * WAVES, customer3: (0.22) * WAVES}); const compiledDApp = compile(file('auction.ride')) const ssTx = setScript({script:compiledDApp/*, fee:1400000*/}, accounts.auction ) await broadcast(ssTx) const issueTx = issue({name:"MyNFTtest", description:"", quantity:1, decimals:0, reissuable:false}, accounts.customer1) await broadcast(issueTx) await waitForTx(issueTx.id) issueTxId = issueTx.id console.log("NFT Token id: " + issueTxId) await waitForTx(ssTx.id) }) it('Customer1: Start Auction', async function(){ const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: { function:"startAuction", args:[ {type:"integer", value: auctionDuration}, {type:"integer", value: 1000000}, {type:"string", value: "WAVES"} ]}, payment: [ {amount: 1, assetId:issueTxId } ] }, accounts.customer1) await broadcast(invTx) auctionStartTx = await waitForTx(invTx.id) auctionId = auctionStartTx.id console.log("Start auction height : " + auctionStartTx.height) }) it('Unable to bid less then start price', async function(){ const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"bid", args:[{type:"string", value: auctionId}]}, payment: [{amount: 999999, assetId:null }]}, accounts.customer2) expect(broadcast(invTx)).rejectedWith("Bid must be more then 1000000") }) it('Customer2: bid 0.1 WAVES', async function(){ customer2Before = await balance(address(accounts.customer2)) const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"bid", args:[{type:"string", value: auctionId}]}, payment: [{amount: 10000000, assetId:null }]}, accounts.customer2) await broadcast(invTx) await waitForTx(invTx.id) }) it('Customer3: bid 0.1 WAVES - should fail', async function(){ const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"bid", args:[{type:"string", value: auctionId}]}, payment: [{amount: 10000000, assetId:null }]}, accounts.customer3) expect(broadcast(invTx)).rejectedWith("Bid must be more then 10000000") }) it('Customer3: bid 0.2 WAVES - now should work', async function(){ const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"bid", args:[{type:"string", value: auctionId}]}, payment: [{amount: 20000000, assetId:null }]}, accounts.customer3) const resp = await broadcast(invTx) await waitForTx(invTx.id) }) it('Previous bid returned to bidder', async function(){ const customer2After = await balance(address(accounts.customer2)) expect(customer2After).to.equal(customer2Before - INV_FEE, "Bid must be returned") }) it('Wait for auction end', async function(){ const timeout = 180000 this.timeout(timeout) console.log("Cur height: " + await currentHeight()) console.log("Waiting " + (auctionStartTx.height + auctionDuration)) await waitForHeight(auctionStartTx.height + auctionDuration, {timeout})//waitForTxWithNConfirmations(auctionStartTx, auctionDuration, {timeout}) }) it('Customer2: bid 0.3 WAVES after acution end - should fail', async function(){ const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"bid", args:[{type:"string", value: auctionId}]}, payment: [{amount: 30000000, assetId:null }]}, accounts.customer2) expect(broadcast(invTx)).rejectedWith("Auction already finished") }) it('Customer3: Winner take prize', async function(){ console.log("Cur height: " + await currentHeight()) const winAmount = 20000000 const nftBalBefore = await assetBalance(issueTxId, address(accounts.customer3)) const wavesBalanceBefore = await balance(address(accounts.customer1)) const winnerBefore = await rememberBalances("Customer3 (winner): ", address(accounts.customer3), issueTxId) const organizerBefore = await rememberBalances("Customer1 (organizer): ", address(accounts.customer1), issueTxId) const invTx = invokeScript({fee:INV_FEE, dApp: address(accounts.auction), call: {function:"withdraw", args:[{type:"string", value: auctionId}]}, payment: []}, accounts.customer3) await broadcast(invTx) await waitForTx(invTx.id) console.log("withdraw tx sent") const winnerAfter = await rememberBalances("Customer3 (winner): ", address(accounts.customer3), issueTxId) const organizerAfter = await rememberBalances("Customer1 (organizer): ", address(accounts.customer1), issueTxId) expect(winnerAfter[0]).to.equal(winnerBefore[0] - INV_FEE, "WAVES Balance of winner is reduced only by fee") expect(winnerAfter[1]).to.equal(winnerBefore[1] + 1, "Winner get's his auction prize") }) })
import 'core-js/fn/object/assign'; import React from 'react'; import {render} from 'react-dom'; import App from './components/App'; import {Provider} from 'react-redux'; import {createStore} from 'redux'; import reducers from './reducers' // let store = createStore(reducers); let store = createStore(reducers, window.devToolsExtension ? window.devToolsExtension() : undefined); // Render the main component into the dom render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') );
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import './scss/index.scss'; const container = document.querySelector('#app'); container.innerHTML = ''; ReactDOM.render( <Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)} />, container, );
// code for getting id for individual control let image = document.getElementById("unicorn"); let heading = document.getElementById("mainheading"); // code for getting tag name for group control let allImages = document.getElementByTagName("img"); for (let img of allImages) { innerWidth: red; console.log(img.src); } // paragraph let allIPara = document.getElementByTagName("p"); for (let img of allPara) { innerWidth: red; console.log(img.src); } // div let allDiv = document.getElementByTagName("div"); for (let img of allDiv) { innerWidth: red; console.log(img.src); } // anchor tag const allAnchor = document.getElementByTagName("a"); for (let img of allAnchor) { innerWidth: red; console.log(img.src); } // class name const squareClass = document.getElementsByClassName(".square"); for (let img of squareClass) { innerWidth: red; console.log(img.src); } // query selector refering to all in one method select any element const idUni = document.querySelector("#unicorn"); const treeClass = document.querySelector(".tree"); // selecting the second image of all the image in the html const secimg = document.querySelector("img:nth-of-type(2)"); // selecting using attribute // const selAttri = document.querySelector('a[title="Java"]'); // selecting using attribute // const selAttri = document.querySelector('a[title="Java"]'); // selecting all anchor tag p // const seLink = document.querySelector("p a"); for (let img of seLink) { console.log(link.href); } // select all Paragraph const seLink = document.querySelector("p"); // all class // Your code goes in here! const doneTodos = document.getElementsByClassName("done"); // particular input type let checkbox = document.querySelector("input[type='checkbox']");
(function(){ var app = { url: 'http://localhost:2314/', init: function(){ this.listeners(); }, //soumission du formulaire listeners: function(){ $("form").on('submit', this.login.bind(this)); }, //récupération de la valeur des input en un objet login login: function(event){ event.preventDefault(); var identifiant = { id: $("#ident").val(), mdp: $("#motDePasse").val() }; this.ajaxLogin(identifiant); }, //Envoie des valeurs du formulaire au serveur ajaxLogin: function(identifiant){ $.ajax({ url: $("form").attr("action"), method: 'post', data: identifiant, success: function(data){ $("html").html(data); }, error: function(data){ $("#error").show().html("Erreur vous n'avez pas entré le bon login"); $("form").trigger('reset'); } }); } } app.init(); })();
import React from 'react' import { TransitionPortal } from 'gatsby-plugin-transition-link' // eslint-disable-next-line export default ({ getTransitionCover }) => { return ( <TransitionPortal> <div ref={getTransitionCover} style={{ position: 'fixed', background: '#4b2571', top: 0, left: 0, width: '100vw', height: '100vh', transform: 'translateY(100%)', }} /> </TransitionPortal> ) }
'use strict'; //YouTube video shit. var loader = $('.loader'), cover = $('.cover'); var tag = document.createElement('script'); tag.src = 'https://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange}, height: '100%', playerVars: { 'autoplay': 1, 'controls': 0, 'loop': 1, 'rel': 0, 'showinfo': 0}, videoId: 'm_Sb3IwqakY', width: '100%' }); }; function onPlayerReady(event) { event.target.mute(); loader.css('opacity',0); window.setTimeout(function(){ loader.css('display','none'); }, 500); }; function onPlayerStateChange(event) { if (event.data == YT.PlayerState.PLAYING) { cover.css('opacity',0); } else if (event.data == YT.PlayerState.ENDED) { cover.css('opacity',1); } }; //jQuery after everything loads. $(function(){ //Self explaining variables. Duh! var keepRatio = 1920/1080, //16:9 ratio video = $('.video'), wrapper = $('.wrapper'); //Helpers for keep this shit working. function resizeVideo() { var wrapperWidth = wrapper.width(), wrapperHeight = wrapper.height(); if (wrapperWidth / wrapperHeight >= keepRatio) { video.css({ height: wrapperWidth/keepRatio, width: wrapperWidth }); } else { video.css({ height: wrapperHeight, width: wrapperHeight*keepRatio }); } }; //This shit inits. resizeVideo(); $(window).resize(resizeVideo); });
/* * `keyCode` * * Maps a DOM event to a keyCode. Use on input's keyup and keydown events. * */ import map from '../signals/processes/map' import prop from 'ramda/src/prop' export default map(prop('keyCode'))
const $ = jQuery = jquery = require ("jquery") const switchElement = require ("cloudflare/generic/switch") $(document).on ( "cloudflare.firewall.javascript_detections.initialize", switchElement.initializeCustom ( "enable_js", true ) ) $(document).on ( "cloudflare.firewall.javascript_detections.toggle", switchElement.toggle )
import React, { Component } from 'react' import { Link } from 'react-router-dom' import {LOCAL} from '../Helper' export default class Cart extends Component { state = { items: JSON.parse(localStorage.getItem('cart')) !== null ? JSON.parse(localStorage.getItem('cart')) : [], carts: [], amounts: [], total: 0, msg: "", } fetchBook = (bookId, amount) => { fetch(LOCAL+'/api/books/' + bookId) .then(res => res.json()) .then((res) => { this.setState({ carts: [...this.state.carts, res.data], amounts: [...this.state.amounts, amount], total: this.state.total + res.data[0].final_price * amount }) } ) } componentDidMount() { this.state.items.map((book) => (this.fetchBook(book.bookId, book.amount))); } increaseValue = (idx, book_id) => { if (this.state.amounts[idx] + 1 <= 8) { let updateAmount = this.state.items.map(item => ( (item.bookId == book_id) ? { ...item, amount: item.amount + 1 } : item )) localStorage.removeItem('cart'); localStorage.setItem('cart', JSON.stringify(updateAmount)); this.setState({ items: updateAmount, amounts: [], total: 0, carts: [] }, () => this.state.items.map((book) => (this.fetchBook(book.bookId, book.amount)))); } else { console.log('false'); } } decreaseValue = (idx, book_id) => { let updateAmount; if (this.state.amounts[idx] - 1 > 0) { updateAmount = this.state.items.map(item => ( (item.bookId == book_id) ? { ...item, amount: item.amount - 1 } : item )) localStorage.removeItem('cart'); localStorage.setItem('cart', JSON.stringify(updateAmount)); this.setState({ items: updateAmount, amounts: [], total: 0, carts: [] }, () => this.state.items.map((book) => (this.fetchBook(book.bookId, book.amount)))); } else if (this.state.amounts[idx] - 1 == 0) { updateAmount = this.state.items.filter(item => (item.bookId != book_id)); localStorage.setItem('cart', JSON.stringify(updateAmount)); this.setState({ items: updateAmount, amounts: [], total: 0, carts: [] }, () => this.state.items.map((book) => (this.fetchBook(book.bookId, book.amount)))); this.props.handleCartRemove(); } else { console.log('false'); } } placeOrder = () => { const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', "X-CSRF-Token": csrfToken, "X-Requested-With": "XMLHttpRequest", }, credentials: "same-origin", body: JSON.stringify({ 'items': this.state.items, 'total': this.state.total, 'carts': this.state.carts, 'amounts': this.state.amounts }) }; fetch(LOCAL+'/api/orders', requestOptions) .then(response => response.json()) .then((response) => { if (response.data == 'success') { localStorage.clear(); this.setState({ items: [], carts: [], total: 0, amounts: [] }, () => this.alertMsg(response.data)) } else if (response.data == 'empty') { this.alertMsg(response.data) } else { this.alertMsg(response.data) } }) .catch(error => console.error(error)); } alertMsg = (msg) => { if (msg == 'success') { this.props.handleCartRemove(); this.setState({msg: <div className="alert alert-success" role="alert">Order successful! Redirect in 10s...</div>},()=> window.setTimeout(function() { window.location.href = '/'; }, 10000)) } else if (msg == 'empty') { this.setState({msg: <div className="alert alert-warning" role="alert">Cart is empty!</div>},()=>setTimeout(()=>this.setState({msg: ""}),5000)) } else { let invalidBookRemoved = JSON.parse(localStorage.getItem('cart')).filter((item)=>item.bookId != msg) localStorage.setItem('cart',JSON.stringify(invalidBookRemoved)); this.setState({msg: <div className="alert alert-danger" role="alert">Book with id {msg} is not available!</div>,items: invalidBookRemoved,amounts: [], total: 0, carts: []},() => this.state.items.map((book) => (this.fetchBook(book.bookId, book.amount)))) this.props.handleCartRemove(); setTimeout(()=>this.setState({msg: ""}),5000) } } render() { return ( <div className="container" style={{ marginTop: "80px" }}> <div className="row mb-5"> <div className="col-lg-12"> <h3><strong>Your cart: {this.state.carts != null ? this.state.carts.length : 0} items</strong></h3> <hr /> </div> <div className="col-lg-8"> <div className="card"> <div className="table-responsive"> <table className="table"> <thead className="text-center card-header"> <tr> <td className="cart-img"></td> <td className="font-weight-bold"> <strong>Book Title</strong> </td> <td className="font-weight-bold"> <strong>Price</strong> </td> <td className="font-weight-bold"> <strong>Quantity</strong> </td> <td className="font-weight-bold"> <strong>Total</strong> </td> </tr> </thead> <tbody className="card-body"> {this.state.carts.map((book, idx) => ( <tr className="text-center" key={book[0].id}> <td> <Link> <img src={book[0].book_cover_photo != null?"./bookcover/"+book[0].book_cover_photo+".jpg":"./bookcover/default.jpg"} alt="" className="img-fluid mx-auto d-block" /> </Link> </td> <td> <p onClick={()=>window.open("/#/detail/"+book[0].id)} className="h6 book-title">{book[0].book_title}</p> </td> <td>${book[0].final_price}</td> <td> <div className="row"> <div className="col-lg-3"> <button className="btn float-left" id="decrease" onClick={() => this.decreaseValue(idx, book[0].id)}><i className="fa fa-minus" aria-hidden="true"></i></button> </div> <div className="col-lg-6"> <input className="w-100 text-center" value={this.state.amounts[idx]} min="0" max="8" /> </div> <div className="col-lg-3"> <button className="btn float-right" id="increase" onClick={() => this.increaseValue(idx, book[0].id)}><i className="fa fa-plus" aria-hidden="true"></i> </button> </div> </div> </td> <td> <strong>${Number((this.state.amounts[idx] * book[0].final_price).toFixed(2))}</strong> </td> </tr> ))} </tbody> </table> </div> </div> </div> <div className="col-lg-4"> <div className="card text-center"> <div className="card-header">Cart Totals</div> <div className="card-body"> <h1>${Number((this.state.total).toFixed(2))}</h1> <button className="btn theme-color mt-5 border btn-block" onClick={() => this.placeOrder()}> Place order</button> </div> </div> <br /> {this.state.msg} </div> </div> </div> ) } }