text
stringlengths
7
3.69M
// Seeking a target (lone Thing chasing the mouse) // This example of Craig Reynolds'steering formula in action // (steering = desired-velocity) is from Dan Shiffman's Processing // book, The Nature of Code and modified for p5.js by al. // al 14 November 2016 function setup() { createCanvas(1000,600); background("#fefefe") t = new Thing(random(width),random(height)); } function draw() { gTarget = createVector(mouseX,mouseY); background("#fefefe"); t.seekTarget(gTarget); t.update(); t.render(); } function Thing(startX,startY) { // thing constructor this.d = 40; this.maxSpeed = 4; this.maxForce = 0.1; // euler integration physics engine this.acc = createVector(0,0); this.vel = createVector(0,0); this.pos = createVector(startX,startY); // vectors for Reynolds' steering formula this.desired = createVector(0,0); this.steering = createVector(0,0); this.update = function() { this.vel.add(this.acc); this.vel.limit(this.maxSpeed); this.pos.add(this.vel); this.acc.mult(0); // reset acc after each update } // update this.applyForce = function(aForce) { this.acc.add(aForce); } // applyForce this.seekTarget = function(target) { this.desired = p5.Vector.sub(target,this.pos); this.desired.normalize(); this.desired.mult(this.maxSpeed); this.steering = p5.Vector.sub(this.desired,this.vel); this.steering.limit(this.maxForce); this.applyForce(this.steering); } // seekTarget this.render = function() { noStroke(); fill(127,127,0,127); ellipse(this.pos.x,this.pos.y,this.d); } // render } // Thing
const main = require('../controllers/users'); module.exports = function(app) { app.get('/', main.index); app.post('/users', main.create); }
import React, { Fragment, Component } from "react"; import { Nav, NavItem } from 'reactstrap'; import { Link } from "react-router-dom"; export default class Header extends Component { constructor(props) { super(props); } render() { return ( <header className={"header"}> <img src="https://www.parfois.com/on/demandware.static/Sites-Parfois_World-Site/-/default/dw5ceda5e3/images/logo_parfois.svg" className={"header_logo"} /><Link to="/"></Link> <Nav className={"header_nav"}> <NavItem> <Link to="/">Главная</Link> </NavItem> <NavItem> <Link to="/catalog">Каталог</Link> </NavItem> <NavItem> {localStorage.getItem("auth") == false ? <Link to="/login">Корзина</Link> : <Link to="/basket">Корзина</Link> } </NavItem> <NavItem> <Link to="/login" onClick={this.exit}>Выйти</Link> </NavItem> </Nav> </header> ) } exit = (e) => { e.preventDefault; localStorage.setItem("auth", false); } }
/** * @file ToastLabel.js * @author leeight */ import {DataTypes, defineComponent} from 'san'; import {create} from './util'; const cx = create('ui-toastlabel'); /* eslint-disable */ const template = `<div class="{{mainClass}}"> <span s-if="text" class="${cx('content')}">{{text}}</span> <div s-else class="${cx('content')}"><slot/></div> </div>`; /* eslint-enable */ export default defineComponent({ template, computed: { mainClass() { const level = this.data.get('level'); const klass = [cx(), cx('x'), cx(level)]; return klass; } }, initData() { return { level: 'alert' // 'normal' | 'alert' | 'error' }; }, dataTypes: { /** * 组件的样式,可选值有 normal, alert, error * @default alert */ level: DataTypes.string, /** * 需要展示的内容,如果设置了 text,那么就忽略 default slot 的内容 */ text: DataTypes.string } });
class ProfileProvider { constructor() { this.gqlc = null } setGqlc(gqlc){ this.gqlc = gqlc } avatarUpload(file) { return this.gqlc.mutate({ mutation: require('./gql/avatarUpload.graphql'), variables: { file: file }, }) } changePassword( currentPassword, newPassword) { return this.gqlc.mutate({ mutation: require('./gql/changePassword.graphql'), variables: { currentPassword: currentPassword, newPassword: newPassword }, }) } } const profileProvider = new ProfileProvider() export default profileProvider
//Reference: The Multi-Source Interference Task: validation study with fMRI in individual subjects, Bush et al. //Condition records current block (practice/test control/interference), trial_id records stimulus ID (where the target is: left, middle or right) and whether the target is large or small /* ************************************ */ /* Define helper functions */ /* ************************************ */ /* ************************************ */ /* Define experimental variables */ /* ************************************ */ var large_font = 36 var small_font = 20 var practice_control_stimuli = [ { image: '<div class = centerbox><div class = center-ms-text ><span class = big>1</span>xx</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "practice_control"} }, { image: '<div class = centerbox><div class = center-ms-text >x<span class = big>2</span>x</div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "practice_control"} }, { image: '<div class = centerbox><div class = center-ms-text >xx<span class = big>3</span></div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "practice_control"} } ] var practice_interference_stimuli = [ { image: '<div class = centerbox><div class = center-ms-text >2<span class = big>1</span>2</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >22<span class = big>1</span></div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = small>1</span>2</div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >22<span class = small>1</span></div></div>', data: { correct_response: 49, trial_id: "small_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >3<span class = big>1</span>2</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = big>1</span></div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >3<span class = small>1</span>2</div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = small>1</span></div></div>', data: { correct_response: 49, trial_id: "small_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>2</span>11</div></div>', data: { correct_response: 50, trial_id: "large_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >11<span class = big>2</span></div></div>', data: { correct_response: 50, trial_id: "large_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>2</span>11</div></div>', data: { correct_response: 50, trial_id: "small_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >11<span class = small>2</span></div></div>', data: { correct_response: 50, trial_id: "small_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>2</span>33</div></div>', data: { correct_response: 50, trial_id: "large_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = big>2</span></div></div>', data: { correct_response: 50, trial_id: "large_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>2</span>33</div></div>', data: { correct_response: 50, trial_id: "small_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = small>2</span></div></div>', data: { correct_response: 50, trial_id: "small_right", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>3</span>11</div></div>', data: { correct_response: 51, trial_id: "large_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >1<span class = big>3</span>1</div></div>', data: { correct_response: 51, trial_id: "large_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>3</span>11</div></div>', data: { correct_response: 51, trial_id: "small_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >1<span class = small>3</span>1</div></div>', data: { correct_response: 51, trial_id: "small_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>3</span>22</div></div>', data: { correct_response: 51, trial_id: "large_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = big>3</span>2</div></div>', data: { correct_response: 51, trial_id: "large_middle", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>3</span>22</div></div>', data: { correct_response: 51, trial_id: "small_left", exp_id: 'multi-source', condition: "practice_interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = small>3</span>2</div></div>', data: { correct_response: 51, trial_id: "small_middle", exp_id: 'multi-source', condition: "practice_interference"} }, ]; var control_stimuli = [ { image: '<div class = centerbox><div class = center-ms-text ><span class = big>1</span>xx</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "control"} }, { image: '<div class = centerbox><div class = center-ms-text >x<span class = big>2</span>x</div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "control"} }, { image: '<div class = centerbox><div class = center-ms-text >xx<span class = big>3</span></div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "control"} } ] var interference_stimuli = [ { image: '<div class = centerbox><div class = center-ms-text >2<span class = big>1</span>2</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >22<span class = big>1</span></div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = small>1</span>2</div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >22<span class = small>1</span></div></div>', data: { correct_response: 49, trial_id: "small_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >3<span class = big>1</span>2</div></div>', data: { correct_response: 49, trial_id: "large_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = big>1</span></div></div>', data: { correct_response: 49, trial_id: "large_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >3<span class = small>1</span>2</div></div>', data: { correct_response: 49, trial_id: "small_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = small>1</span></div></div>', data: { correct_response: 49, trial_id: "small_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>2</span>11</div></div>', data: { correct_response: 50, trial_id: "large_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >11<span class = big>2</span></div></div>', data: { correct_response: 50, trial_id: "large_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>2</span>11</div></div>', data: { correct_response: 50, trial_id: "small_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >11<span class = small>2</span></div></div>', data: { correct_response: 50, trial_id: "small_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>2</span>33</div></div>', data: { correct_response: 50, trial_id: "large_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = big>2</span></div></div>', data: { correct_response: 50, trial_id: "large_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>2</span>33</div></div>', data: { correct_response: 50, trial_id: "small_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >33<span class = small>2</span></div></div>', data: { correct_response: 50, trial_id: "small_right", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>3</span>11</div></div>', data: { correct_response: 51, trial_id: "large_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >1<span class = big>3</span>1</div></div>', data: { correct_response: 51, trial_id: "large_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>3</span>11</div></div>', data: { correct_response: 51, trial_id: "small_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >1<span class = small>3</span>1</div></div>', data: { correct_response: 51, trial_id: "small_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = big>3</span>22</div></div>', data: { correct_response: 51, trial_id: "large_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = big>3</span>2</div></div>', data: { correct_response: 51, trial_id: "large_middle", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text ><span class = small>3</span>22</div></div>', data: { correct_response: 51, trial_id: "small_left", exp_id: 'multi-source', condition: "interference"} }, { image: '<div class = centerbox><div class = center-ms-text >2<span class = small>3</span>2</div></div>', data: { correct_response: 51, trial_id: "small_middle", exp_id: 'multi-source', condition: "interference"} }, ]; var num_blocks = 4 //number of control/interference pairs var blocks = [] for (var b = 0; b < num_blocks; b++) { var control_trials = jsPsych.randomization.repeat(control_stimuli, 8, true); var interference_trials = jsPsych.randomization.repeat(interference_stimuli, 1, true); blocks.push(control_trials) blocks.push(interference_trials) } practice_control = jsPsych.randomization.repeat(practice_control_stimuli, 8, true) practice_interference = jsPsych.randomization.repeat(practice_interference_stimuli, 1, true) practice_control.image = practice_control.image.slice(0,20) practice_interference.image = practice_interference.image.slice(0,20) practice_control.data = practice_control.data.slice(0,20) practice_interference.data = practice_interference.data.slice(0,20) var practice_blocks = [practice_control, practice_interference] /* ************************************ */ /* Set up jsPsych blocks */ /* ************************************ */ /* define static blocks */ var welcome_block = { type: 'text', text: '<div class = centerbox><p class = block-text>Welcome to the multi-source experiment. Press <strong>enter</strong> to begin.</p></div>', cont_key: 13, timing_post_trial: 0 }; var instructions_block = { type: 'instructions', pages: [ '<div class = centerbox><p class = block-text>In this task you will see stimuli consisting of three numbers or "x" letters. For instance, you may see "<span class = big_instructions>1</span>xx" or "<span class = small_instructions>3</span>22"</p><p class = block-text>Two of the characters will always be the same. Your job is to indicate the identity of the character that is different(the target character) using the three number keys. So in the last two examples you would press "1" for the first and "3" for the second.</p></div>', '<div class = centerbox><p class = block-text>There are two trial types: either the non-target numbers are also numbers, or they are "x`s". When the non-target characters are "x", the target number will always be big. When all three characters are numbers, the target character can either be larger or smaller than the other characters.</p><p class = block-text>You will complete 8 blocks of trials. Each block will either have only the "x" type trials (e.g. "xx3" type trials) or the number trials (e.g. "131" type trials). It is important that you respond as quickly as possible, but be sure to respond correctly! Respond by reporting <strong>what</strong> the target number was regardless of its position!</p></div>', ], allow_keys: false, show_clickable_nav: true, timing_post_trial: 1000 }; var end_block = { type: 'text', text: '<div class = centerbox><p class = center-block-text>Finished with this task.</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>', cont_key: 13, timing_post_trial: 0 }; var start_test_block = { type: 'text', text: '<div class = centerbox><p class = center-block-text>Starting test. Press <strong>enter</strong> to begin.</p></div>', cont_key: 13, timing_post_trial: 1000 }; /* create experiment definition array */ var multisource_experiment = []; multisource_experiment.push(welcome_block); multisource_experiment.push(instructions_block); /* define practice block */ for (var b = 0; b < practice_blocks.length; b++) { block = practice_blocks[b] var practice_block = { type: 'single-stim', stimuli: block.image, is_html: true, choices: [49,50,51], data: block.data, timing_stim: 1750, timing_response: 1750, response_ends_trial: false, timing_post_trial: 500 }; multisource_experiment.push(practice_block) } multisource_experiment.push(start_test_block) /* define test block */ for (var b = 0; b < num_blocks; b++) { block = blocks[b] var test_block = { type: 'single-stim', stimuli: block.image, is_html: true, choices: [49,50,51], data: block.data, timing_stim: 1750, timing_response: 1750, response_ends_trial: false, timing_post_trial: 500 }; multisource_experiment.push(test_block) } multisource_experiment.push(end_block)
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap"; class ModalBox extends Component { render() { return ( <div> <Modal isOpen={this.props.isOpen} toggle={this.props.toggle} className={this.props.className} backdrop="static" > <ModalHeader toggle={this.props.toggle}> {this.props.title} </ModalHeader> <ModalBody>{this.props.children}</ModalBody> <ModalFooter> {this.props.showAction ? ( <Button color="secondary" onClick={this.props.toggle}> Close </Button> ) : ( "" )} </ModalFooter> </Modal> </div> ); } } ModalBox.propTypes = { toggle: PropTypes.func, title: PropTypes.string, action: PropTypes.string, children: PropTypes.node, isOpen: PropTypes.bool }; export default ModalBox;
import React, { Component } from 'react'; import Apphead from '../apphead/apphead.js'; import Leaguepage from './league.js'; export default class League extends Component { constructor(props) { super(props); } render() { const ln = this.props.match.params.ln; // console.log(ln); return ( <div className='main' id = 'main'> <Apphead text = 'LEAGUE INFO'/> <Leaguepage link = {ln}/> </div> ); } }
import styles from '../../Global/styles/adminHousestyle.module.css' import firebase from '../../../../../db/firebase' import { useCollectionDataOnce } from 'react-firebase-hooks/firestore' import { Card } from '../../../Cards' const PageSelect = ({ changeSection }) => { const [ pages ] = useCollectionDataOnce( firebase.firestore().collection('pages').orderBy('ordering'), { idField: 'id' } ) const editPage = id => { console.log('Trying to navigate to ', id) changeSection('Page Edit', id) } return ( <> <h1>Page Content</h1> <h2>Select a page to edit</h2> <div className={styles.userInterface}> { !pages ? 'Loading pages...' : pages.map((page, i) => ( <Card action={editPage} id={page.id} title={page.title} /> )) } </div> </> ) } export default PageSelect
import Vue from 'vue' import Router from 'vue-router' import CreateUser from '@/views/CreateUser' import CreateVehicle from '@/views/CreateVehicle' import Schedule from '@/views/Schedule' Vue.use(Router) export default new Router({ routes: [ { path: '/user', name: 'CreateUser', component: CreateUser }, { path: '/vehicle', name: 'CreateVehicle', component: CreateVehicle }, { path: '/', name: 'Schedule', component: Schedule } ] })
import React from 'react' import PropTypes from 'prop-types' import c from 'classnames' import { getStyleInt, animateToScrollHeight, formatToMaterialSpans, callIfCallable, isValidString, removeClass, addClass, noop, } from '~utils' import style from './button.scss' export default class Button extends React.Component { static propTypes = { label: PropTypes.string, className: PropTypes.string, disabled: PropTypes.bool, isFlat: PropTypes.bool, type: PropTypes.oneOf(['normal', 'primary', 'secondary']), size: PropTypes.oneOf(['normal', 'small']), link: PropTypes.string, linkTarget: PropTypes.string, // 也可以用 oneOf, 这里不更深控制 onClick: PropTypes.func, } static defaultProps = { label: 'Button', className: '', disabled: false, type: 'normal', isFlat: false, size: 'normal', link: '', linkTarget: '_self', onClick: noop, } state = { rippleLeft: 0, rippleTop: 0, } rippleRadius = 0 buttonRef = null setButtonRef = ref => { if (this.buttonRef === null) { this.buttonRef = ref this.setRippleRadius() } } rippleRef = null setRippleRef = ref => { if (this.rippleRef === null) { this.rippleRef = ref this.rippleRef.addEventListener('animationend', () => { removeClass(this.rippleRef,'fade') }) } } startRipple = evt => { if (this.props.disabled === true) { return } addClass(this.buttonRef, 'mousedown') if (!this.rippling) { this.rippling = true const nativeEvt = evt.nativeEvent const rippleLeft = nativeEvt.offsetX - this.rippleRadius const rippleTop = nativeEvt.offsetY - this.rippleRadius this.setState({ rippleLeft, rippleTop, }) addClass(this.rippleRef, 'appear') } } endRipple = evt => { removeClass(this.buttonRef, 'mousedown', 'mouseup') if (this.rippling) { removeClass(this.rippleRef, 'appear') addClass(this.rippleRef, 'fade') this.rippling = false } } setRippleRadius = () => { this.rippleRadius = Math.max( getStyleInt(this.buttonRef, 'width'), getStyleInt(this.buttonRef, 'height'), ) } componentDidUpdate() { this.setRippleRadius() } render() { const rippleSize = isNaN(this.rippleRadius) ? 0 : this.rippleRadius * 2 const rippleStyle = { left: this.state.rippleLeft, top: this.state.rippleTop, width: rippleSize, height: rippleSize, } const className = c( 'rhaego-button', this.props.isFlat && 'flat', this.props.disabled && 'disabled', `type-${this.props.type}`, `size-${this.props.size}`, this.props.className ) const isAnchor = isValidString(this.props.link) // idea: 动态控制 dom node type, 不用 createElement // idea: https://stackoverflow.com/questions/30466129/window-open-blocked-by-chrome-with-change-event/35752647 // 非点击事件`直接目标`的事件, 所触发的 window.open 会被认为是恶意的, 被拦截 const DOMTag = isAnchor ? 'a' : 'button' // 更健壮地, 在自身事件触发时调用父组件的事件, 这里暂不处理 return ( <DOMTag className={className} ref={this.setButtonRef} onMouseDown={this.startRipple} onMouseUp={this.endRipple} onMouseOut={this.endRipple} onClick={this.props.onClick} href={isAnchor ? this.props.link : null} target={isAnchor ? this.props.linkTarget : null} > <span className={'button-content'}> {this.props.children} </span> <div className={'ripple'} ref={this.setRippleRef} style={rippleStyle} /> </DOMTag> ) } }
// Jikuu - Tumblr Theme <https://github.com/msikma/jikuu> // © 2008-2018, Michiel Sikma. MIT license. import { Luminous, LuminousGallery } from 'luminous-lightbox' // Our option modifications. const jikuuLumOpts = { // Attach to #root so we can style it based on the user's settings. appendToSelector: '#root' } // Slight modification of the LuminousGallery to allow captions on a per-image basis. export default class LuminousGalleryCaptions extends LuminousGallery { _constructLuminousInstances() { this.luminousInstances = [] for (let i = 0; i < this.triggers.length; i++) { const caption = el => el.getAttribute('data-caption') const lum = new Luminous(this.triggers[i], { ...this.luminousOpts, caption, ...jikuuLumOpts }) this.luminousInstances.push(lum) } } }
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.audio.play.TimeManager'); goog.require('audioCat.audio.play.PlayManager'); goog.require('audioCat.audio.play.events'); goog.require('audioCat.utility.EventTarget'); goog.require('goog.async.AnimationDelay'); /** * Manages the time of playing as well as the time into the audio that's * actually displayed to the user. These two times are usually equal, but can * differ when say the user drags the play cursor. This time value of course * only needs to be updated on every frame. * @param {!audioCat.audio.play.PlayManager} playManager Manages the playing of * audio. * @constructor * @extends {audioCat.utility.EventTarget} */ audioCat.audio.play.TimeManager = function(playManager) { goog.base(this); /** * Manages the playing of audio. * @private {!audioCat.audio.play.PlayManager} */ this.playManager_ = playManager; /** * The time that is displayed to the user. Not necessarily the play time, but * the two are usually equal. For instance, the user could be dragging the * cursor around. We don't want to keep changing the play time since doing so * can be expensive. This time is in seconds. * @private {number} */ this.indicatedTime_ = playManager.getTime(); /** * The animation delay pegged to frame times. Used to update the indicated * time. Null when not playing. * @private {goog.async.AnimationDelay} */ this.playAnimationDelay_ = null; // Change the indicated time as playing occurs. goog.events.listen(playManager, audioCat.audio.play.events.PLAY_BEGAN, this.handlePlayBegan_, false, this); goog.events.listen(playManager, audioCat.audio.play.events.PAUSED, this.handlePause_, false, this); // When the stable play time is manually changed, change the indicated time. goog.events.listen(playManager, audioCat.audio.play.events.PLAY_TIME_CHANGED, this.handlePlayTimeChanged_, false, this); }; goog.inherits(audioCat.audio.play.TimeManager, audioCat.utility.EventTarget); /** * @return {number} The time indicated to the user in seconds. */ audioCat.audio.play.TimeManager.prototype.getIndicatedTime = function() { return this.indicatedTime_; }; /** * Sets the indicated time. Throws an event notifying the change. * @param {number} time Sets the time indicated to the user. */ audioCat.audio.play.TimeManager.prototype.setIndicatedTime = function(time) { this.indicatedTime_ = time; this.dispatchEvent(audioCat.audio.play.events.INDICATED_TIME_CHANGED); }; /** * Handles what happens when the play time is manually changed. * @private */ audioCat.audio.play.TimeManager.prototype.handlePlayTimeChanged_ = function() { this.setIndicatedTime(this.playManager_.getTime()); }; /** * Sets the stable time. The stable time is the one actually considered by the * play manager for playing. Throws an event notifying the change. Also sets the * indicated time. * @param {number} time Sets the stable time used for playing. */ audioCat.audio.play.TimeManager.prototype.setStableTime = function(time) { this.playManager_.setTime(time); this.setIndicatedTime(time); this.dispatchEvent(audioCat.audio.play.events.STABLE_TIME_CHANGED); }; /** * Handles what happens on a pause. * @private */ audioCat.audio.play.TimeManager.prototype.handlePause_ = function() { this.playAnimationDelay_.stop(); this.playAnimationDelay_ = null; }; /** * Handles what happens when play begins. * @private */ audioCat.audio.play.TimeManager.prototype.handlePlayBegan_ = function() { this.playLoop_(); }; /** * Enters the animation loop while playing. * @private */ audioCat.audio.play.TimeManager.prototype.playLoop_ = function() { var animationDelay = new goog.async.AnimationDelay( this.updateOnEachFrame_, undefined, this); animationDelay.start(); this.playAnimationDelay_ = animationDelay; }; /** * Does operations for each frame while playing. * @private */ audioCat.audio.play.TimeManager.prototype.updateOnEachFrame_ = function() { this.setIndicatedTime(this.playManager_.getTime()); this.playLoop_(); };
/** * 用户数据权限分组管理初始化 */ var ChooseRule = { chooseRuleData : {} }; /** * 关闭此对话框 */ ChooseRule.close = function() { parent.layer.close(window.parent.DataPermissionGroupInfoDlg.layerIndex); } /** * 设置对话框中的数据 * * @param key 数据的名称 * @param val 数据的具体值 */ ChooseRule.set = function(key, val) { this.chooseRuleData[key] = (typeof val == "undefined") ? $("#" + key).val() : val; return this; } /** * 收集数据 */ ChooseRule.collectData = function() { var chk_value =[]; $('input[name="rule"]:checked').each(function(){ chk_value.push($(this).val()); }); if(chk_value.length==0){ Feng.info("你还没有选择任何内容!"); return false; } this.set('content',chk_value.toString()).set('groupId',parent.$('#groupId').val()).set('type'); return true; } ChooseRule.chooseRule = function(){ if(this.collectData()){ //提交信息 var ajax = new $ax(Feng.ctxPath + "/dataPermissionGroup/addRule", function(data){ Feng.success("添加成功!"); window.parent.DataPermissionGroupRule.table.refresh(); ChooseRule.close(); },function(data){ Feng.error("添加失败!" + data.responseJSON.message + "!"); }); ajax.set(this.chooseRuleData); ajax.start(); } }
import { shallowMount } from '@vue/test-utils' export default { // /** * helper function that mounts and returns the rendered text * @param component * @param propsData * @returns {string} */ getRenderedText : function (component, propsData) { // test data (could be generated programmatically) const wrapper = shallowMount(component, { propsData: propsData }) return wrapper.text() }, /** * Helper function to create a mounted component * @param component * @returns {Wrapper<Vue>} */ getVm : function (component) { return shallowMount(component) }, /** * @param component {Component} * @param prop {String} */ getVmPropValue : function (component, prop) { const wrapper = shallowMount(component) return wrapper[prop]; } }
const topla = (n1 , n2) => n1 + n2; const cikar = (n1 , n2) => n1 - n2; const arr = [0,1,2,3,4,5,6,7,8,9]; // module.exports.topla = topla; // module.exports.cikar = cikar; module.exports = { topla, cikar, arr, };
export const getAllScreens = translations => { const translate = key => translations[key] || key; return { openDoor: { headline: translate("openDoor.headline"), rules: translate("openDoor.rules"), icon: "🚪", buttons: [ { text: translate("openDoor.button.monster"), action: "DRAW_MONSTER" }, { text: translate("openDoor.button.curse"), action: "DRAW_CURSE_OR_TRAP" }, { text: translate("openDoor.button.other"), action: "DRAW_OTHER" } ] }, applyCurseOrTrap: { headline: translate("applyCurseOrTrap.headline"), rules: translate("applyCurseOrTrap.rules"), icon: "😣", buttons: [ { text: translate("applyCurseOrTrap.button"), action: "APPLY_CURSE" } ] }, keepOrPlayCard: { headline: translate("keepOrPlayCard.headline"), rules: translate("keepOrPlayCard.rules"), icon: "🃏", buttons: [ { text: translate("keepOrPlayCard.button.keep"), action: "KEEP" }, { text: translate("keepOrPlayCard.button.play"), action: "PLAY" } ] }, readyForTrouble: { headline: translate("readyForTrouble.headline"), rules: translate("readyForTrouble.rules"), icon: "🤔", buttons: [ { text: translate("readyForTrouble.button.fight"), action: "FIGHT_VOLUNTARY" }, { text: translate("readyForTrouble.button.takeLoot"), action: "TAKE_LOOT" } ] }, takeDungeonCard: { headline: translate("takeDungeonCard.headline"), rules: translate("takeDungeonCard.rules"), icon: "📤", buttons: [ { text: translate("takeDungeonCard.button"), action: "TAKE_CARD" } ] }, mildGift: { headline: translate("mildGift.headline"), rules: translate("mildGift.rules"), icon: "🖐", buttons: [ { text: translate("mildGift.button.moreThanFive"), action: "MORE_THAN_FIVE_CARDS" }, { text: translate("mildGift.button.lessOrEqualFive"), action: "LESS_THAN_FIVE_CARDS" } ] }, hasLowestLevel: { headline: translate("hasLowestLevel.headline"), rules: translate("hasLowestLevel.rules"), icon: "🐣", buttons: [ { text: translate("hasLowestLevel.button.yes"), action: "YES" }, { text: translate("hasLowestLevel.button.no"), action: "NO" } ] }, discard: { headline: translate("discard.headline"), rules: translate("discard.rules"), icon: "🗑", buttons: [{ text: translate("discard.button"), action: "DROP_CARDS" }] }, charity: { headline: translate("charity.headline"), rules: translate("charity.rules"), icon: "🎁", buttons: [ { text: translate("charity.button"), action: "DISTRIBUTE_CARDS" } ] }, fight: { fightOrRun: { headline: translate("fightOrRun.headline"), rules: translate("fightOrRun.rules"), icon: "⚔️", buttons: [ { text: translate("fightOrRun.button.fight"), action: "FIGHT" }, { text: translate("fightOrRun.button.run"), action: "RUN" } ] }, wait: { headline: translate("wait.headline"), rules: translate("wait.rules"), icon: "⏳", buttons: [] }, recheckConditions: { headline: translate("recheckConditions.headline"), rules: translate("recheckConditions.rules"), icon: "😯", buttons: [ { text: translate("recheckConditions.button.somethingChanged"), action: "SOMETHING_CHANGED" }, { text: translate("recheckConditions.button.nothingChanged"), action: "NOTHING_CHANGED" } ] }, victory: { headline: translate("victory.headline"), rules: translate("victory.rules"), icon: "🏆", buttons: [ { text: translate("victory.button"), action: "TAKE_TREASURE_AND_LEVEL_UP" } ] }, dice: { headline: translate("dice.headline"), rules: translate("dice.rules"), icon: "🎲", buttons: [ { text: translate("dice.button.lowerThanFive"), action: "LOWER_THAN_FIVE" }, { text: translate("dice.button.fiveOrSix"), action: "FIVE_OR_SIX" } ] }, badThings: { headline: translate("badThings.headline"), rules: translate("badThings.rules"), icon: "☠️", buttons: [{ text: translate("badThings.button"), action: "DONE" }] }, end: { type: "final" } }, done: { headline: translate("done.headline"), rules: translate("done.rules"), icon: "🏁", buttons: [{ text: translate("done.button"), action: "NEXT_PLAYER" }] } }; }; export const screenByState = (state, screens) => { if (!screens) { return undefined; } if (typeof state === "string") { return screens[state]; } else { const key = Object.keys(state)[0]; return screenByState(state[key], screens[key]); } };
(function ($) { /////////////// /** * @file * Attached the 'fixed' behavior to blocks. * * Basic algorithm code originally inspired by BoingBoing. Code entirely rewritten. * Extended to support multiple different floats on the same page. * * @usage Add the class '.sticky-block' to an element you wish to always remain onscreen. * * @author dman */ Drupal.behaviors.sticky_block = { attach: function (context, settings) { if ($('.sticky-block').length > 0) { // .sticky-block is the div we pin. May start anywhere on the page // Could have used an ID, but adding classes is easier in the template. // Insert a placeholder marker just above our target element. // This is used for positioning reference. $('.sticky-block').before($('<div class="sticky-block-pinpoint"></div>')); $('.sticky-block').after($('<div class="sticky-block-pinpoint2"></div>')); // Whenever the page is scrolled, let's see if we should pin the sidebar. $(window).scroll(function() { toggle_sticky_block(); }); $(window).resize(function(){ toggle_sticky_block(); }); } } } // End startup /** * Recalculate if the sticky-block needs to be positioned */ function toggle_sticky_block(){ var scrolled = $(document).scrollTop(); var winheight = $(window).height(); var baseline = scrolled + winheight; $('.sticky-block').each( function(index) { var block = $(this); // Find the placeholder that should be directly before the target block var pinpoint = $('.sticky-block-pinpoint', block.parent()); var pinpoint_y = parseInt(pinpoint.offset().top); // The location of the pinpoint // (a placeholder inserted just above the target that moves with the normal flow) // is the key. // When THAT is onscreen, use normal flow. // If it scrolls off, then switch to fixed behavior. var pinpoint2 = $('.sticky-block-pinpoint2', block.parent()); var pinpoint2_y = parseInt(pinpoint2.offset().top); // Pinpoint2 is a spaceholder that reserves space at the bottom of the element. if (pinpoint_y-10 < scrolled) { // If the pinpoint is offscreen, we should switch to position:fixed. // Switching to fixed may sometimes affect layout width unexpectedly, // so there's a fix for that here too. if (!block.hasClass('fixed')) { // In some themes removing the content of the sidebar block makes its // column collapse. Leave a sliver of the pinpoint behind to hold // the borders out. pinpoint.width(block.width()).height(1); block.addClass('fixed') .width(block.width()) .css({'position':'fixed', 'top':'10px', 'overflow':'hidden'}) // .css({'z-index':'700'}) // z-index can be added to show over the Drupal7 toolbar. // However, it then may conflict with the overlay. // It is only in effect when position:fixed, so there may be flicker. // Generally, too much bother. } } else if ((scrolled+winheight) < (pinpoint2_y)) { // Then the block is starting to go off the screen at the BOTTOM. //console.log("comparing baseline "+ (scrolled+winheight) +" with the boxes bottom " + (pinpoint_y + block.height() +parseInt(block.css('margin-bottom')) +parseInt(block.css('padding-bottom')) ) + " or the top of the item below it " + pinpoint2_y ); // Lock some space under the block to avoid jitters if (pinpoint2.css('position') != 'absolute') { pinpoint2.css({'position':'absolute', 'top':pinpoint2.position().top}); } // Fix the block to the bottom if (!block.hasClass('fixed')) { block.addClass('fixed') .width(block.width()) .css({'position':'fixed', 'bottom':'0px', 'overflow':'hidden'}) } } else { // Unpin it if the pinpoint becomes visible on the screen. Restore normal flow. if (block.hasClass('fixed')) { block.removeClass('fixed') .css({'position':'inherit', 'overflow':'visible', 'bottom':'auto', 'top':'auto'}) // Unpinning this placeholder however seems to confuse things. //pinpoint2.css({'position':'relative'}); } } }) } /////////// })(jQuery);
import React from 'react'; import './thanks.css'; const Thanks = () => { return ( <> <div className="thanksBackground"> <h1 className='thanks-content'>Thank-you.</h1> </div> </> ) } export default Thanks;
import React from 'react'; import { MyStylesheet } from './styles'; import DynamicStyles from './dynamicstyles'; import { goCheckIcon } from './svg'; import { validatePassword } from './functions'; class Password { handlePassword(text) { let validate = validatePassword(text); if (!validate.validate) { this.setState({ passwordcheck: false, password: text, message: validate.message }) } else { this.setState({ password: text, message: "", passwordcheck: true }) } } showpassword() { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const regularFont = dynamicstyles.getRegularFont.call(this); const goIcon = dynamicstyles.getgocheckheight.call(this); const password = new Password(); const goCheck = () => { if (this.state.password && this.state.passwordcheck) { return (<button style={{ ...styles.generalButton, ...goIcon }}>{goCheckIcon()}</button>) } else { return (<span>&nbsp;</span>) } } if (this.state.width > 800) { return ( <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex2, ...styles.generalFont, ...regularFont }}> Password </div> <div style={{ ...styles.flex3 }}> <input type="password" style={{ ...styles.generalFont, ...styles.generalField, ...regularFont }} onChange={event => { password.handlePassword.call(this, event.target.value) }} value={this.state.password} /> </div> <div style={{ ...styles.flex1 }}> {goCheck()} </div> </div> ) } else { return ( <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1, ...styles.generalFont, ...regularFont }}> Password </div> </div> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex2 }}> <input type="password" style={{ ...styles.generalFont, ...styles.generalField, ...regularFont }} onChange={event => { password.handlePassword.call(this, event.target.value) }} value={this.state.password} /> </div> <div style={{ ...styles.flex1 }}> {goCheck()} </div> </div> </div> </div> ) } } } export default Password;
"use strict"; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bookSchema = new Schema({ title: { type: String, required: true }, author: { type: String, required: true }, price: { type: String, required: true }, rating: { type: String, required: true } }, { timestamps: true }); //passing a constructor here var Book = mongoose.model('books', bookSchema); //books is Collection module.exports = Book;
const cron = require("node-cron"); const express = require("express"); const moment = require("moment"); const fs_sync = require("fs"); const fs = fs_sync.promises; const parse = require("csv-parse/lib/sync"); const stringify = require("csv-stringify"); const fetch = require("node-fetch"); const path = require("path"); require("dotenv").config(); const API_TOKEN = process.env.OKTA_API_TOKEN; const baseurl = process.env.BASE_URL; app = express(); // 일반적인 cron 스케줄 표시 매일 새벽 1시에 동작 // 테스트하려면 0 * * * * *로 교체 (매분 0초가 되면 동작) cron.schedule("0 * * * * *", async () => { try { // Read CSV and convert to JSON to include in 'arr' array for further work let arr = []; await (async function () { const normalPath = path.normalize(__dirname + "/data/membersUntil.csv"); const fileContent = await fs.readFile(normalPath); arr = parse(fileContent, { columns: true }, (err) => { if (err) { console.log("Error in reading .csv file!"); } }); })(); // 멤버십 제외 작업 처리된 사용자 const completed = []; // 아직 작업 처리되지 않은 사용자 const remaining = []; // 오늘 날짜 저장 let now = moment(); // API Rate Limit에 걸리지 않도록 각 사용자 작업 사이에 3000ms (3초) 간격 발생 // 한 사용자 당 3 call이므로 최대 분당 60 call로 제한 let idx = 0; let i = setInterval(async () => { let currentUser = arr[idx]; // to handle a library bug not catching the first key of the parsed object let userNameKey = Object.keys(arr[idx])[0]; let userName = arr[idx][userNameKey]; let groupName = arr[idx].groupName; if (idx === 0) { // 전처리 내용 console.log( "\x1b[36m%s\x1b[0m", "Starting the daily automation process: " + now.format("YYYY-MM-DD") ); } const normalizedMemberUntil = moment(new Date(currentUser.memberUntil)); // console.log(normalizedMemberUntil); // 권한 기간 만료 판단 const isExpired = moment(normalizedMemberUntil).isBefore(now, "day"); // console.log(isExpired); // 권한 기간이 만료된 경우, 해당 유저의 userId, 그룹의 groupId 확인 후 유저를 그룹에서 삭제 if (isExpired) { // 리퀘스트 헤더 세팅 let headers = { "Content-Type": "application/json", Authorization: `SSWS ${API_TOKEN}`, }; // GET userId let userResponse = await fetch(baseurl + `/api/v1/users/${userName}`, { method: "get", headers, }); let userJson = await userResponse.json(); let userId = userJson.id; // console.log(userName, userId); // GET GroupId let groupResponse = await fetch( baseurl + `/api/v1/groups?q=${groupName}&limit=1`, { method: "get", headers, } ); let groupJson = await groupResponse.json(); if (groupJson.length === 0) { throw new Error("Cannot find the group with the name: " + groupName); } let groupId = groupJson[0].id; // console.log(groupJson[0].profile.name, groupId); //Remove the user from the group let removeUserResponse = await fetch( baseurl + `/api/v1/groups/${groupId}/users/${userId}`, { method: "delete", headers, } ); // console.log( // removeUserResponse.status + " " + removeUserResponse.statusText // ); completed.push(currentUser); console.log( userName + " is removed from " + currentUser.groupName + ". The user is logged in ./logs/membersExcluded-" + now.format("YYYY-MM-DD") + ".csv" ); } else { // 해당 유저의 그룹 권한 기간이 아직 남아 있을 경우, // put this user to remaining array // log the result to console remaining.push(currentUser); console.log( userName + " has the membership to " + currentUser.groupName + " group until " + normalizedMemberUntil.format("YYYY-MM-DD") + ". The user will remain in membersUntil.csv." ); } idx += 1; if (idx === arr.length) { // 마무리 처리 // TODO: overwrite schedule.csv (use remaining array to convert JSON to CSV) if (completed.length !== 0) { // 그룹에서 빠져나간 사용자가 있을 경우에는, 일일 로그 파일 생성 const filePath_raw = "./logs/membersExcluded-" + now.format("YYYY-MM-DD") + ".csv"; const filePath = path.normalize(filePath_raw); fs_sync.closeSync(fs_sync.openSync(filePath, "w")); } // 멤버십 제외 대상자가 없어서 API 콜이 하나도 나가지 않았을 경우, Token expire를 방지하기 위해 domain 확인 API 콜 1회 요청 // token expiration date 리셋됨 if (completed.length === 0) { let headers = { "Content-Type": "application/json", Authorization: `SSWS ${API_TOKEN}`, }; // GET userId await fetch(baseurl + `/api/v1/domains`, { method: "get", headers, }); } stringify( remaining, { header: true, }, function (err, output) { if (err) { console.log("remaining members overwrite error"); } const normalPath = path.normalize( __dirname + "/data/membersUntil.csv" ); fs.writeFile(normalPath, output); } ); stringify( completed, { header: true, }, function (err, output) { if (err) { console.log("completed file write error"); } const normalPath = path.normalize( __dirname + "/logs/membersExcluded-" + now.format("YYYY-MM-DD") + ".csv" ); fs.writeFile(normalPath, output); } ); console.log( "\x1b[36m%s\x1b[0m", "Closing the daily automation process: " + now.format("YYYY-MM-DD") ); clearInterval(i); } }, 3000); } catch (err) { console.log(err); } }); app.listen(3000, () => { console.log("Node cronjob server is running on http://localhost:3000"); });
import React from 'react'; import { NavLink } from "react-router-dom"; const StyleSwitcher = () => { return ( <> <div id="switcher" class=""> <div class="content-switcher"> <h4>STYLE SWITCHER</h4> <ul> <li> <NavLink to="#" onclick="setActiveStyleSheet('purple');" title="purple" class="color"><img src="../../public/img/styleswitcher/purple.png" alt="purple"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('red');" title="red" class="color"><img src="../../public/img/styleswitcher/red.png" alt="red"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('blueviolet');" title="blueviolet" class="color"><img src="../../public/img/styleswitcher/blueviolet.png" alt="blueviolet"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('blue');" title="blue" class="color"><img src="../../public/img/styleswitcher/blue.png" alt="blue"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('goldenrod');" title="goldenrod" class="color"><img src="../../public/img/styleswitcher/goldenrod.png" alt="goldenrod"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('magenta');" title="magenta" class="color"><img src="../../public/img/styleswitcher/magenta.png" alt="magenta"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('yellowgreen');" title="yellowgreen" class="color"><img src="../../public/img/styleswitcher/yellowgreen.png" alt="yellowgreen"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('orange');" title="orange" class="color"><img src="../../public/img/styleswitcher/orange.png" alt="orange"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('green');" title="green" class="color"><img src="../../public/img/styleswitcher/green.png" alt="green"/></NavLink> </li> <li> <NavLink to="#" onclick="setActiveStyleSheet('yellow');" title="yellow" class="color"><img src="../../public/img/styleswitcher/yellow.png" alt="yellow"/></NavLink> </li> </ul> <div id="hideSwitcher">&times;</div> </div> </div> <div id="showSwitcher" class="styleSecondColor"><i class="fa fa-cog fa-spin"></i></div> </> ) } export default StyleSwitcher;
var sql = require('./BaseModel'); var Task = function (task) { this.task = task.task; }; Task.getService_TypeBy = function getService_TypeBy() { return new Promise(function (resolve, reject) { var str = "SELECT * FROM tb_service_type"; sql.query(str, function (err, res) { if (err) { const require = { data: [], error: err, query_result: false, }; resolve(require); } else { const require = { data: res, error: [], query_result: true, }; resolve(require); } }); }); } Task.getService_TypeByService_TypeCode = function getService_TypeByService_TypeCode(data) { return new Promise(function (resolve, reject) { var str = "SELECT * FROM tb_service_type WHERE service_type_id = '" + data.service_type_id + "' "; sql.query(str, function (err, res) { if (err) { const require = { data: [], error: err, query_result: false, }; resolve(require); } else { const require = { data: res, error: [], query_result: true, }; resolve(require); } }); }); } Task.insertService_Type = function insertService_Type(data, last_code) { return new Promise(function (resolve, reject) { var str = "INSERT INTO tb_service_type (service_type_id, service_group_id, service_type_name)" + " VALUES ('" + last_code + "', " + " '" + data.service_group_id + "', " + " '" + data.service_type_name + "') "; sql.query(str, function (err, res) { if (err) { const require = { data: [], error: err, query_result: false, }; resolve(require); } else { const require = { data: res, error: [], query_result: true, }; resolve(require); } }); }); } Task.updateService_TypeByService_TypeCode = function updateService_TypeByService_TypeCode(data) { return new Promise(function (resolve, reject) { var str = " UPDATE tb_service_type " + " SET service_type_name = '" + data.service_type_name + "'" + " WHERE service_type_id = '" + data.service_type_id + "'"; sql.query(str, function (err, res) { if (err) { const require = { data: [], error: err, query_result: false, }; resolve(require); } else { const require = { data: res, error: [], query_result: true, }; resolve(require); } }); }); } Task.deleteService_TypeByService_TypeCode = function deleteService_TypeByService_TypeCode(data) { return new Promise(function (resolve, reject) { var str = "DELETE FROM tb_service_type WHERE service_type_id = '" + data.service_type_id + "' "; sql.query(str, function (err, res) { if (err) { const require = { data: [], error: err, query_result: false, }; resolve(require); } else { const require = { data: res, error: [], query_result: true, }; resolve(require); } }); }); } Task.getLastCode = function getLastCode() { return new Promise(function (resolve, reject) { var str = "SELECT IFNULL(CONCAT('ST',LPAD( SUBSTRING(max(service_type_id), 2, 5)+1,4,'0')), 'ST001') AS last_code FROM tb_service_type "; sql.query(str, function (err, res) { if (err) { resolve(err); } else { resolve(res[0].last_code); } }); }); } module.exports = Task;
export const SUPPORTED_LOCALES = ['fr', 'en'] export const DEFAULT_LOCALE = 'fr' export const COOKIE_NAMES = { auth: 'KT-Auth', csrfToken: 'KT-CSRF' }
import React from 'react'; import styled from 'styled-components'; export default function MapNav({ setFilterBox }) { return ( <Header onClick={() => setFilterBox(false)}> <span>다방</span> <Nav> <a href="/">지도</a> <a href="/">분양</a> <a href="/">관심목록</a> <a href="/">방 내놓기</a> <a href="/">알림</a> <a href="/">로그인 / 회원가입</a> </Nav> </Header> ); } const Header = styled.header` display: flex; justify-content: space-between; padding: 24px; border-bottom: 1px solid rgb(233, 233, 233); & > span { color: rgb(50, 108, 249); font-size: 22px; font-weight: bold; cursor: pointer; } `; const Nav = styled.nav` display: inline-block; & > a { margin-right: 18px; color: rgb(134, 134, 134); font-size: 14px; text-decoration: none; } & > a:nth-last-child(1) { padding: 5px; border: 1px solid rgb(233, 233, 233); } `;
import React, { Component } from "react"; import Link from "next/link"; import { activePath } from "../libs/activePath"; import classnames from "classnames"; import { i18n, withTranslation } from "~/i18n"; import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd"; class ColumnModal extends Component { constructor(props) { super(props); this.state = { columnList: [] }; } componentWillReceiveProps(props) { this.setState({ columnList: [...props.columnList] }); } __hasDefaultColumn(col) { if (col.defaultOrder) { if (col.requiredColumn == true) { return "li fixed"; } else { return "li default"; } } else { if (col.requiredColumn == true) { return "li fixed"; } else { return "li"; } } } cancelAction = () => { let { cancelAction } = this.props; this.setState({ columnList: [...this.props.columnList] }); }; removeColumn = (column, index) => { const { columnList } = this.state; const newColumnList = columnList.map(item => ({ ...item })); newColumnList[index].hidden = true; this.setState({ columnList: newColumnList }); }; addColumn = (column, index) => { const { columnList } = this.state; const newColumnList = columnList.map(item => ({ ...item })); newColumnList[index].hidden = false; this.setState({ columnList: newColumnList }); }; addAll = () => { const { columnList } = this.state; this.setState({ columnList: columnList.map(column => ({ ...column, hidden: false })) }); }; onSetDefault = () => { let { columnList } = this.state; columnList = columnList.map(column => ({ ...column, hidden: !column.defaultOrder })); columnList = columnList.sort((a, b) => a.defaultOrder - b.defaultOrder); this.setState({ columnList }); }; onDragEnd = item => { const { columnList } = this.state; if (item.destination) { const dragableIndex = item.source.index; const dropableIndex = item.destination.index; const newColumnId = item.destination.droppableId; const oldColumnId = item.source.droppableId; let leftArray = columnList.filter(column => column.hidden); let rightArray = columnList.filter(column => !column.hidden); let newItem; if (newColumnId === oldColumnId && oldColumnId === "droppableRight") { newItem = rightArray.splice(dragableIndex, 1); rightArray.splice(dropableIndex, 0, ...newItem); } this.setState({ columnList: [...rightArray, ...leftArray] }); } }; onSave = () => { const { columnList } = this.state; this.props.onSave(columnList); }; getStyle = (style, snapshot, id) => { if (!snapshot.isDropAnimating) { return { ...style, left: "none" }; } const { moveTo, curve, duration } = snapshot.dropAnimation; const translate = `translate(${moveTo.x}px, ${moveTo.y - 25}px)`; return { ...style, transform: `${translate}`, left: "none", transition: `all ${curve} ${duration + 1}s` }; }; render() { const { t } = this.props; var style1 = { height: "60vh" }; let { modalId, title, menukey } = this.props; const { columnList } = this.state; if (menukey == undefined) { menukey = "3wm"; } return ( <div> <div className="modal fade" id={modalId ? modalId : `openColumnDisplay`} test="dddddd" tabIndex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false" > <div className="modal-dialog modal-lg" role="document"> <div className="modal-content bg-lightgray mb-3"> <div className="modal-header"> <h5 className="modal-title">{t("Column Lists")}</h5> <button onClick={this.cancelAction} type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <DragDropContext onDragEnd={this.onDragEnd}> <div className={`modal-body column-display-${menukey}`}> <div className="row justify-content-center" style={style1}> <div className="col w-45 h-100 pr-0"> <div data-force="30" className="lists h-100"> <div className="lists__header justify-content-between"> <span>{t("Choose Column Display")}</span> <button className="list-btn add-all green" onClick={this.addAll} > All <i className="fa fa-plus" /> </button> </div> <ul id="allColumn" className="lists__sortlist"> {columnList.map((column, i) => { if ( !column.hidden == false && column != undefined ) { if (column.default) { return ( <li className={this.__hasDefaultColumn(column)} data-id={i} // id={column.data.replace(/\./g, "_")} data-name={column.header} key={i} > <span>{column.header}</span> <button className="list-btn fixed"> <i className="fa fa-plus" /> </button> </li> ); } else { return ( <li className={this.__hasDefaultColumn(column)} data-id={i} // id={column.data.replace(/\./g, "_")} data-name={column.header} key={i} > <span>{column.header}</span> <button className="list-btn add" onClick={e => this.addColumn(column, i)} > <i className="fa fa-plus" /> </button> </li> ); } } })} </ul> </div> </div> <div className="col w-10 p-0 h-100 column-display" /> <div className="col w-45 h-100 pl-0"> <div data-force="18" className="lists h-100"> <div className="lists__header justify-content-between"> <span>{t("Current Column Display")}</span> </div> <Droppable droppableId="droppableRight"> {(provided, snapshot) => ( <ul id="currentColumn" className="lists__sortlist sortable" ref={provided.innerRef} > {columnList.map((column, i) => { if ( !column.hidden == true && column != undefined ) { return ( <Draggable key={i} draggableId={"drag" + column.header} index={i} > {(provided, snapshot) => ( <li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} className={this.__hasDefaultColumn( column )} data-id={i} data-name={column.header} key={i} style={this.getStyle( provided.draggableProps.style, snapshot )} > <span>{column.header}</span> {column.requiredColumn ? ( <button className="list-btn remove"> <i className="fa fa-plus" /> </button> ) : ( <button className="list-btn remove" onClick={e => this.removeColumn(column, i) } > <i className="fa fa-plus" /> </button> )} </li> )} </Draggable> ); } })} </ul> )} </Droppable> </div> </div> </div> </div> </DragDropContext> <div className="modal-footer justify-content-center"> <button type="button" className="btn btn--transparent btn-wide remove-all" onClick={this.onSetDefault} > {t("Reset Default")} </button> <button type="button" className="btn btn--transparent btn-wide" data-dismiss="modal" onClick={this.cancelAction} > {t("Cancel")} </button> <button type="button" className="btn btn-primary btn-save-column btn-wide" data-dismiss="modal" onClick={this.onSave} > {t("Save")} </button> </div> </div> </div> </div> </div> ); } } export default withTranslation(["detail", "invoice-detail", "common", "menu"])( ColumnModal );
const imageContainer = document.getElementById('imgs'); const previousButton = document.getElementById('previous'); const nextButton = document.getElementById('next'); const images = document.querySelectorAll('#imgs img'); let index = 0; let interval; const run = () => { index++; changeImage(); }; const changeImage = () => { if (index >= images.length) { index = 0; } else if (index < 0) { index = images.length - 1; } imageContainer.style.transform = `translateX(${-500 * index}px)`; }; const resetInterval = () => { if (interval) clearInterval(interval); interval = setInterval(run, 1000); }; previousButton.addEventListener('click', () => { index--; changeImage(); resetInterval(); }); nextButton.addEventListener('click', () => { index++; changeImage(); resetInterval(); }); resetInterval();
require(['knockout', 'webApiClient', 'messageBox', 'page', 'moment', 'common'], function (ko, webApiClient, messageBox, page, moment, common) { "use strict"; var homeViewModel = new function(){ var self = this; self.recentResults = ko.observableArray([]); self.GetData = function () { messageBox.Hide(); webApiClient.ajaxGet("reports/myResults", null, null, function (data) { if (data) { var resultRows = []; ko.utils.arrayForEach(data, function (item) { resultRows.push({ ReportName: item.ReportName, ResultId: item.Id, RequestDate: moment(item.RunDate).format(common.CLIENT_DATETIME_FORMAT) }) }); self.recentResults(resultRows); } }, function (errorResponse) { messageBox.ShowErrors("Error loading results:", errorResponse); }); } }; homeViewModel.GetData(); ko.applyBindings(homeViewModel, $("#homePage")[0]); return homeViewModel; });
//1-need a secret number --> math 06; 11 12 var secretNumero = Math.floor((Math.random() * 100) + 1) console.log(secretNumero) //number of guesses var userGuesses = 1 //number of tries var userTry = 0 //2-get user data --> prompt or form //Number(prompt("Choose a number from 1 - 100")) function showGuess(){ var userGuess = document.getElementById("userGuess") var outCome = document.getElementById("outCome") // // stop function if input is not correct or to small or to big if (!userGuess.value || userGuess.value > 100 || userGuess.value < 0) { // add a class of success to results outCome.className = "failure" // update the text content of results outCome.textContent = "incorrect input, please try again" // clears input tag out userGuess.value = "" // stop function to allow user to try again return } // if user guesses the secret number correctly if(userGuess.value == secretNumero) { // add a class of success to results outCome.className = "success" // update the text content of results outCome.textContent = "Congrats, You won! got it in " + (userTry + 1) + " guesses!" return // otherwise check if the guess is greater than the secret number } else if(userGuess.value > secretNumero) { // add a class of failure to results outCome.className = "failure" // update the content of results outCome.textContent = "Guess a lower number" // refocus on input for user userGuess.focus() // otherwise the guess is less than the secret number } else { // add a class of failure to results outCome.className = "failure" // update the content of results outCome.textContent = "Guess a higher number" // refocus on input for user userGuess.focus() } // clears input tag out userGuess.value = "" // increment guess counter userTry = userTry + 1 // stop game if out of guesses if(userTry >= 10){ // add a class of success to results outCome.className = "failure" // update the text content of results outCome.textContent = "Sorry you're out of guesses, refresh to play again" // remove onclick attribute if user runs out of guesses document.getElementById('btn').onclick = null; } }
(function() { 'use strict'; angular .module('template.Home') .controller("HomeController", function(GetListDataLastFive, ListDataService){ var self = this; self.name = "Nevendra's Home Page"; self.nameOne = "custom directive"; self.getTheList = GetListDataLastFive.listAll(function(isValid, response){ if(isValid){ // console.log(response); self.homeHeros = response; } }); self.getFirstFive = GetListDataLastFive.listFirstFive(function(isValid, response){ if(isValid) { // console.log(response); self.homeHerosTwo = response; } }) self.oneArticle = []; self.getArticle = function(article) { ListDataService.getDetailsOfOne(article, function(isValid, response){ self.oneSuperhero = response; console.log(self.oneSuperhero); self.oneArticle.push(self.oneSuperhero); }) } }); })();
describe('Receipt Validation Test', function () { // 1 it('should validate the values of the fields', function () { var receipts = require('/receipts.json'); //regex for validating field for (var i = 0; i < receipts.length; i++) { cy.readFile('receipts.json').its(i).its('storeId').should('match', /[A-Z0-9]{3}/g); cy.readFile('receipts.json').its(i).its('pinCode').should('match', /(?<!\d)\d{5}(?!\d)/g); cy.readFile('receipts.json').its(i).its('receiptNumber').should('match', /\d+/g); cy.readFile('receipts.json').its(i).its('itemsSold').should('match', /\d+/g); cy.readFile('receipts.json').its(i).its('total').should('match', /[+-]?([0-9]*[.])?[0-9]+/g); // cy.readFile('receipts.json').its(i).its('timestamp').should('match', '2021-02-01 14:00:00 EST'); //for(var j = 0; receipts[i].items.length; j++ ){ cy.readFile('receipts.json').its(i).its('items').its(0).its('itemId').should('match', /[A-Za-z0-9]/g); cy.readFile('receipts.json').its(i).its('items').its(0).its('itemPrice').should('match', /[+-]?([0-9]*[.])?[0-9]+/g); cy.readFile('receipts.json').its(i).its('items').its(0).its('taxRate').should('match', /^(0(\.\d+)?|1(\.0+)?)$/g); cy.readFile('receipts.json').its(i).its('items').its(0).its('discount').should('match', /^(0(\.\d+)?|1(\.0+)?)$/g); //} } }); // 2 it('should validate grand totals', function () { var receipts = require('/receipts.json'); for (var i = 0; i < receipts.length; i++) { var total = 0.0; var itemTotal = 0.0; var price = 0; var taxRate = 0.00; var discount = 0.00; for (var j = 0; j < receipts[i].items.length; j++) { price = receipts[i].items[j].itemPrice; taxRate = receipts[i].items[j].taxRate; discount = receipts[i].items[j].discount; itemTotal = price + (price * taxRate) - (price * discount); total += itemTotal; } cy.readFile('receipts.json').its(i).its('total').should('eq', Math.round(total * 10) / 10); } }); //3 it('should validate count of items sold', function () { var receipts = require('/receipts.json'); var count = 0; var itemsCount = []; var items = []; for (var i = 0; i < receipts.length; i++) { for (var j = 0; j < receipts[i].items.length; j++) { if (receipts[i].items[j].itemPrice >= 0) { items.push(receipts[i].items[j].itemId); count++; } if (receipts[i].items[j].itemPrice < 0) { items.pop(receipts[i].items[j - 1].itemId); count--; } } itemsCount.push(count); count = 0; cy.readFile('receipts.json').its(i).its('itemsSold').should('be.gt', 0); cy.readFile('receipts.json').its(i).its('itemsSold').should('eq', itemsCount[i]); } }); // 4. it('should ensure receipts are valid', function () { var receipts = require('/receipts.json'); // Expect receipts to come from the same date //all receipt come from same store var pinCode = 30234; var storeId = 'WAL001'; for (var i = 0; i < receipts.length - 1; i++) { cy.expect(receipts[i].timestamp).to.deep.equal(receipts[i+1].timestamp); cy.readFile('receipts.json').its(i).its('receiptNumber').should('eq', receipts[i].receiptNumber); cy.readFile('receipts.json').its(i).its('timestamp').should('eq', receipts[i].timestamp); cy.readFile('receipts.json').its(i).its('receiptNumber').should('not.eq', receipts[i+1].receiptNumber); cy.readFile('receipts.json').its(i+1).its('receiptNumber').should('not.eq', receipts[i].receiptNumber); cy.readFile('receipts.json').its(i+1).its('timestamp').should('eq', receipts[i].timestamp); cy.readFile('receipts.json').its(i+1).its('receiptNumber').should('eq', receipts[i+1].receiptNumber); cy.readFile('receipts.json').its(i).its('pinCode').should('eq', pinCode); cy.readFile('receipts.json').its(i).its('storeId').should('eq', storeId); cy.readFile('receipts.json').its(i).its('pinCode').should('eq', pinCode); cy.readFile('receipts.json').its(i).its('storeId').should('eq', storeId); } }); // 5 it('should return most sold item', function () { var receipts = require('/receipts.json'); var mostFrequentItem = ''; var mostFrequent = 1; var mostCount = 0; var items = []; for (var i = 0; i < receipts.length; i++) { for (var j = 0; j < receipts[i].items.length; j++) { if (receipts[i].items[j].itemPrice >= 0) { items.push(receipts[i].items[j].itemId); } if (receipts[i].items[j].itemPrice < 0) { items.pop(receipts[i].items[j - 1].itemId); } } } for (var x = 0; x < items.length; x++) { for (var y = x; y < items.length; y++) { if (items[x] === items[y]) { mostCount++; } if (mostFrequent < mostCount) { mostFrequent = mostCount; mostFrequentItem = items[x]; } } mostCount = 0; } cy.expect(mostFrequentItem).to.deep.equal('GROC001'); //hard coded most sold item }); });
import { combineReducers, applyMiddleware, createStore } from 'redux' import thunk from 'redux-thunk' import { composeWithDevTools } from 'redux-devtools-extension' import { userRegister, userUpdate, userDeleteAccount, userLogin, userProfile, userEmailUpdate, userPhotoUpdate, userChangePassword } from './reducers/user' import { createReview, getProducts, getSingleProduct, createProduct, deleteReview } from './reducers/product' import { cart } from './reducers/cart' import { createOrder, getOrder, userOrder } from './reducers/order' const reducer = combineReducers({ userRegister, userLogin, userProfile, userEmailUpdate, userPhotoUpdate, userChangePassword, userDeleteAccount, getProducts, getSingleProduct, cart, createOrder, getOrder, userOrder, createProduct, createReview, deleteReview, userUpdate }) const userInfoFromStorage = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null const cartItemsFromStorage = localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : [] const shippingAddressFromStorage = localStorage.getItem('shippingAddress') ? JSON.parse(localStorage.getItem('shippingAddress')) : {} const initialState = { userLogin: { userInfo: userInfoFromStorage }, cart: { cartItems: cartItemsFromStorage, shippingAddress: shippingAddressFromStorage } } const middleware = [thunk] const store = createStore( reducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ) export default store
var qs = require('q-stream'); module.exports = seq; function seq(streams, opts) { var t = qs(opts || {}); if (!(streams || 0).length) { done(); return t; } var pushes = streams.map(function(s) { s.pause(); return s .pipe(qs(push)) .on('error', error); }); streams.forEach(function(s, i) { if (i < 1) return; pushes[i - 1].on('finish', function() { s.resume(); }); }); pushes[pushes.length - 1].on('finish', done); streams[0].resume(); function done() { t.push(null); } function push(d) { t.push(d); } function error(e) { t.emit('error', e); } return t; }
const objectSchema = { field1: 'a', field2: 'b', field3: { myProp: { anotherProp: 'c' } }, field4: 'foo' }; const arraySchema = [ 'a', 'b', { myProp: { anotherProp: 'c' } }, 'foo' ] const input = { a: 4, b: 6, c: 11 } const nestedReplacer = (schema, input) => { for (prop in schema) { if (typeof schema[prop] === 'object') nestedReplacer(schema[prop], input) else schema[prop] = input[schema[prop]] ? input[schema[prop]] : schema[prop] } return schema } console.log(nestedReplacer(objectSchema, input))
/** * Created by han on 31.08.14. */ var rink = function () { var rootNode, events = { callCardClick : function () {} }, class_postfix = "nr_", config = { createNewBoardDelay : 2000 }, gameEvents = { rootClickedQueue : [], clearRootClickedQueue : function () { var fc = function () {}; while (fc !== undefined) { fc = this.rootClickedQueue.pop(); fc && fc(); } } }, selectors = { templates : "templates", game : { rootId : 'board', state : { open : 'open', hidden : 'hidden', empty : 'empty', matched : 'matched' } } }, getImage = function (type) { var img = new Image(); img.src = 'images/animals/' + type + '.png'; img.alt = type; img.width = 100; img.height = 100; return img; }, fadeoutImage = function (img) { var delay = 20, pixelSteps = 2, scaleImage = function () { var w = img.width, h = img.height, wDone = false, hDone = false; if (w > 0) { img.width = w - pixelSteps; img.style.paddingTop = (parseInt(img.style.paddingTop || 0, 10) + pixelSteps / 2) + 'px'; } else { wDone = true; } if (h > 0) { img.height = h - pixelSteps; img.style.paddingLeft = (parseInt(img.style.paddingLeft || 0, 10) + pixelSteps / 2) + 'px'; } else { hDone = true; } if (!wDone && !hDone) { setTimeout(scaleImage, delay); } else { img.parentNode.removeChild(img); } }; scaleImage(); }, addClickEvent = function (card) { card.addEventListener('click', function Select(e) { var id = this.getAttribute('id'), position = id.split(class_postfix)[1]; events.callCardClick(position); console.log('Ask server for take a card'); }, false); }, emitter = { cards : { show : function (gameConf, card) { // TODO is no state passed from server than the card was already matched - add a state for matched cards (is this the curios empty state?) var cardNode = document.getElementById(class_postfix + card.position); // if (!card.hasOwnProperty('state')) { // cardNode.domAddClass(selectors.game.state.matched); // } cardNode.innerHTML = ''; cardNode.domRemoveClass(selectors.game.state.hidden).domAddClass(card.type + ' ' + selectors.game.state.open); cardNode.appendChild(getImage(card.type)); }, match : function (gameConf, firstCard, secondCard) { emitter.cards.show(gameConf, secondCard); setTimeout(function () { // TODO check wich type is used - than use eqeqeq if (gameConf.gameId === parseInt(rootNode.getAttribute('gameId'), 10)) { emitter.cards.remove(gameConf, firstCard); emitter.cards.remove(gameConf, secondCard); } }, 2e3); }, hide : function (gameConf, cards) { console.log('CALL HIDE', cards); cards.forEach(function (card) { var cardNode = document.getElementById(class_postfix + card.position), callMeHasBeenCalled = false, timer, callMe = function () { if (callMeHasBeenCalled === false) { timer.hasOwnProperty('clearTimeout') && timer.clearTimeout(); cardNode.domRemoveClass(card.type + ' ' + selectors.game.state.open).domAddClass(selectors.game.state.hidden); cardNode.innerHTML = ''; callMeHasBeenCalled = true; } }; timer = setTimeout(function () { callMe(); }, 2e3); gameEvents.rootClickedQueue.push(callMe); }); }, remove : function (gameConf, card) { var cardNode = document.getElementById(class_postfix + card.position); if (cardNode) { cardNode.domRemoveClass().domAddClass(selectors.game.state.empty + ' card'); fadeoutImage(cardNode.children[0]); } else { // TODO find out why this is called - could be a bug console.log('No cardnode was found'); } } }, board : { clear : function () { var cards = Array.prototype.slice.call(rootNode.children); cards.forEach(function (node) { rootNode.removeChild(node); }); }, generateNew : function (gameConf, numberOfcards) { emitter.board.clear(); canny.rinkMessages.show('New game starts in some seconds'); setTimeout(function () { var i, node; canny.rinkMessages.hide(); rootNode.setAttribute('gameId', gameConf.gameId); for (i = 0; i < numberOfcards; i++) { node = domOpts.createElement('div', class_postfix + i, 'card').domAppendTo(rootNode); addClickEvent(node); } }, config.createNewBoardDelay); } } }; return { onCardClick : function (fc) { events.callCardClick = fc; }, emitter : emitter, add : function (node, attr) { rootNode = node; }, ready : function () { // register click lister to board root rootNode.addEventListener('click', function ClickListener() { console.log('Register a click'); gameEvents.clearRootClickedQueue(); }, false); } } }; module.exports = rink;
const { defineConfig } = require('@vue/cli-service'); // const path = require('path'); const webpack = require('webpack'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const CompressionWebpackPlugin = require('compression-webpack-plugin'); const productionGzipExtensions = ['js', 'css']; // const isProduction = process.env.NODE_ENV === 'production'; module.exports = defineConfig({ transpileDependencies: true, chainWebpack: (config) => { config .plugin('webpack-bundle-analyzer') .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin); // 入口文件 config.entry.app = ['babel-polyfill', './src/main.ts']; // element-ui自动就挂载在Vue上了,这里不需要写它,在入口文件main.js中也不用再vue.use了 config.externals = { vue: 'Vue', vuex: 'vuex', 'vue-router': 'VueRouter', }; }, productionSourceMap: false, configureWebpack: { plugins: [ // Ignore all locale files of moment.js // new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // 配置compression-webpack-plugin压缩 new CompressionWebpackPlugin({ algorithm: 'gzip', test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), threshold: 10240, minRatio: 0.8, // deleteOriginalAssets: true // 删除源文件 }), new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 5, // minChunkSize: 100 }), new UglifyJsPlugin({ uglifyOptions: { compress: { // warnings: false, drop_console: true, drop_debugger: true, }, output: { // 去掉注释内容 comments: true, }, }, sourceMap: false, parallel: true, }), ], }, });
// Constants used in tgui; these are mirrored from the BYOND code. export const UI_INTERACTIVE = 2 export const UI_UPDATE = 1 export const UI_DISABLED = 0 export const UI_CLOSE = -1
const express = require('express') const { check } = require('express-validator') //middlewares const {auth, checkLevel} = require('../middlewares/auth') const usersControllers = require('../controllers/users.controllers') const router = express.Router() // @route GET /users/ // @desc Get all users // @access Private // @level Admin router.get("/", auth, checkLevel, usersControllers.getUsers) // @route GET /users/:uid // @desc Get a single user // @access Private // @level User router.get("/:id", auth, usersControllers.getUserbyId) // @route PATCH /users/:uid // @desc edit single user // @access Private // @level User router.patch("/:id", [ auth, check("name").optional().exists(), check("email").optional().normalizeEmail().isEmail(), check("password").optional().isLength({min:7}) ], usersControllers.editUser) // @route DELETE /users/:uid // @desc Remove current single user and its contents in other tables // @access Private router.delete("/:id", auth, usersControllers.deleteUser) module.exports = router
require('dotenv').config({ path: '../.env' }) const express = require('express'); const router = express.Router(); const bcrypt = require('bcrypt'); const Cloudant = require('@cloudant/cloudant'); const { validate_student, validate_professor} = require('../classes/validators'); const Student = require('../classes/Student'); const Professor = require('../classes/Professor'); router.post('/professor', async (req, res) => { if ('0'.localeCompare(req.body.gender)) req.body.gender = 'male'; else if ('1'.localeCompare(req.body.gender)) req.body.gender = 'female'; else req.body.gender = 'other'; req.body.age = parseInt(req.body.age) const { error } = validate_professor(req.body); if (error) return res.status(400).send(error.details[0].message); const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } }); if (query_response.docs[0]) return res.status(404).send('Error: email already in use'); const professor = new Professor(req.body.email, req.body.password, req.body.first_name, req.body.middle_name, req.body.last_name, req.body.age, req.body.gender, req.body.department); const salt = await bcrypt.genSalt(10); professor.password = await bcrypt.hash(professor.password, salt); await users_db.insert(professor); return res.status(201).send({ email: professor.email, first_name: professor.first_name, middle_name: professor.middle_name, last_name: professor.last_name, age: professor.age, gender: professor.gender, department: professor.department }); }); router.post('/student', async (req, res) => { if ('0'.localeCompare(req.body.gender)) req.body.gender = 'male'; else if ('1'.localeCompare(req.body.gender)) req.body.gender = 'female'; else req.body.gender = 'other'; req.body.age = parseInt(req.body.age); req.body.semester = parseInt(req.body.semester); const { error } = validate_student(req.body); if (error) return res.status(400).send(error.details[0].message); const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } }); if (query_response.docs[0]) return res.status(400).send('Error: email already in use'); const student = new Student(req.body.email, req.body.password, req.body.first_name, req.body.middle_name, req.body.last_name, req.body.age, req.body.gender, req.body.major, req.body.semester); const salt = await bcrypt.genSalt(10); student.password = await bcrypt.hash(student.password, salt); await users_db.insert(student); return res.status(201).send({ email: student.email, first_name: student.first_name, middle_name: student.middle_name, last_name: student.last_name, age: student.age, gender: student.gender, major: student.major, semester: student.semester }); }); module.exports = router;
import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./style.css"; class HelloUser extends React.Component { constructor(props) { super(props); this.state = { name: "FOULEN", number: ".... .... .... ....", month: "..", day: ".." }; } //Name of Card Owner nameChange(n) { this.setState({ name: n.target.value }); } //Card Number numberChange(c) { this.setState({ number: c.target.value }); } //Expiration monthChange(m) { this.setState({ month: m.target.value }); } dayChange(d) { this.setState({ day: d.target.value }); } renderCardNumber = number => { number = this.state.number.toString(); // '7253325678951245' let resultStr = ""; for (let i = 0; i < this.state.number.length; i += 4) { resultStr += this.state.number.slice(i, i + 4) + " "; } return resultStr.trim(); }; render() { return ( <div className="card"> <div className="card-container"> <h1 className="card-title">Company name</h1> <img className="card-logo" src="https://cdn4.iconfinder.com/data/icons/payment-method/160/payment_method_master_card-512.png" alt="" /> <p className="card-number">{this.state.number}</p> <div style={{ display: "flex", justifyContent: "space-around" }}> <div className="name"> <label1> CARDHOLDER <p className="card-name">{this.state.name}</p> </label1> </div> <div className="expiration"> <br /> <label1> <p className="card-date"> {this.state.month} / {this.state.day} </p> </label1> </div> </div> <br /> <br /> <br /> <label2> NAME <input type="text" maxLength="20" onChange={this.nameChange.bind(this)} /> </label2>{" "} <br /> <br /> <label2> NUMBER <input type="text" maxLength="19" onChange={this.numberChange.bind(this)} /> </label2>{" "} <br /> <br /> <label2 className="exp" style={{ display: "flex" }}> EXPIRATION DATE </label2> <input type="text" maxLength="2" onChange={this.monthChange.bind(this)} /> <input type="text" maxLength="2" onChange={this.dayChange.bind(this)} /> </div> </div> ); } } ReactDOM.render(<HelloUser />, document.getElementById("root"));
var nb_states = 0; function State(inst) { this.id = nb_states++; this.inst = inst; this.parents = []; }; State.prototype.addParent = function(st) { this.parents.push(st); }; State.prototype.getParents = function() { return this.parents; }; function Graph() { this.first = undefined; this.last = undefined; this.states = []; }; Graph.prototype.getFirst = function() { return this.first; }; Graph.prototype.setFirst = function(st) { this.first = st; }; Graph.prototype.getLast = function() { return this.last; }; Graph.prototype.setLast = function(st) { this.last = st; }; Graph.prototype.addState = function(st) { this.states.push(st); }; Graph.prototype.addLastState = function(st) { this.states.push(st); this.last = st; }; Graph.prototype.getStates = function() { return this.states; }; Graph.prototype.addStates = function(stats) { for (var i = 0; i < stats.length; i++) { this.states.push(stats[i]); }; }; module.exports.State = State; module.exports.Graph = Graph;
chrome.runtime.onConnect.addListener(function(port) { port.onMessage.addListener(function(response) { console.log(response); port.postMessage({ content : "background.js sendResponse" }); }); });
$(document).ready(function () { // if the page is loaded and the view window is not on top, add effect to the nav bar if ($(window).scrollTop() > 0) {$(".nav_bar").addClass("fixed_nav");} // adding effect to nav bar when scroll $(window).scroll(function () { page_top = $(this).scrollTop(); if (page_top > 0) { $(".nav_bar").addClass("fixed_nav"); } else if (page_top == 0) {$(".nav_bar").removeClass("fixed_nav");} // highlight nav links when scroll to their correspond sections $("section").each(function () { var section_top = $(this).offset().top, section_id = $(this).attr('id'), section_first_top = $("section#services").offset().top; if (page_top >= section_top) { $("a.nav_link").removeClass("highligh_link"); $("[href='#"+section_id+"']:not(.heading_btn)").addClass("highligh_link"); } else if (page_top < section_first_top) {$("a.nav_link").removeClass("highligh_link");} }) }) // scrolling to section for menu $("a.nav_link").on('click', function(event) { // Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault(); // Store hash var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top //scroll top position of the selected section }, 800, function(){ // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } }); // back to top $("a[href$='#page_top']").click(function () { $('html, body').animate({ scrollTop: 0 }, 800); }) // check if all boxes are filled before submit $(".submit_btn button").click(function () { $('#contact input').each(function () { if ($(this).val() === '') { $(this).next().addClass("alert"); } }) if ($('#contact textarea').val() === '') { $('#contact textarea').next().addClass("alert"); } }) // modals $("a.portfolio_link").click(function () { event.preventDefault(); var modal_id = $(this).data("modal"); $("#" + modal_id).addClass("show_modal"); $('body').addClass("modal_open"); }) $(".close_modal, .modal_background, .modal_body button").click(function () { $('.modal_portfolio').removeClass("show_modal"); $('body').removeClass("modal_open"); }) });
var bomberManBoard=[ ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""] ]; function genrateTable(){ var body = document.getElementsByTagName("body")[0]; var table = document.createElement("table"); var tblBody = document.createElement("tbody"); for(var i=0;i<9;i++) { var row = document.createElement("tr"); for(var j=0;j<9;j++){ var cell = document.createElement("td"); cell.setAttribute("onClick","clickOnCell(this,"+i+","+j+")"); cell.setAttribute("onmousedown","rightclick("+i+","+j+")"); row.appendChild(cell); } tblBody.appendChild(row); } table.appendChild(tblBody); table.setAttribute("border", "2"); body.appendChild(table); } var l=0; while(l!=10){ let a=Math.floor(Math.random()*9); // returns a random integer from 0 to 9 let b=Math.floor(Math.random()*9); if(bomberManBoard[a][b]!=="1"){ bomberManBoard[a][b]="1"; console.log("board:"+bomberManBoard[a][b]); l++; } } var count=0; var bcount=0; function selectCell(k,j) { if(j-1>=0){ if(!document.querySelectorAll("td")[k*9+(j-1)].classList.contains("green")) document.querySelectorAll("td")[k*9+(j-1)].classList.add("coral"); if(bomberManBoard[k][j-1]==="1") bcount++; } if(!document.querySelectorAll("td")[k*9+j].classList.contains("green")) document.querySelectorAll("td")[k*9+j].classList.add("coral"); if(bomberManBoard[k][j]==="1") bcount++; if(j+1<9){ if(!document.querySelectorAll("td")[k*9+(j+1)].classList.contains("green")) document.querySelectorAll("td")[k*9+(j+1)].classList.add("coral"); if(bomberManBoard[k][j+1]==="1") bcount++; } } function rightclick(i,j) { var e = window.event; if (e.which == 3) { //alert("hi"); if(bomberManBoard[i][j]==="1"){ document.querySelectorAll("td")[i*9+j].innerHTML="!"; } } } function clickOnCell(element,i,j){ bcount = 0; if(bomberManBoard[i][j]==="1"){ for(var p=0;p<9;p++){ for(var q=0;q<9;q++){ // for highlight all cell that contains bomb if(bomberManBoard[p][q]==="1"){ document.querySelectorAll("td")[q+p*9].classList.add("red"); console.log("q:"+ [q+p*9]); document.querySelectorAll("td")[q+p*9].innerHTML="💣"; } document.querySelectorAll("td")[q+p*9].setAttribute("onclick",""); } } document.querySelectorAll('button')[0].classList.remove(); document.getElementById("winner").innerHTML="<strong>Your Score is </strong>"+"<strong>"+count+"</strong>"; } else{ if(i==0) { console.log("i==0"); for(var k=i;k<=i+1;k++) { console.log("k:"+k); selectCell(k,j); } } else if(i==8) { console.log("i==8"); for(var k=i;k>=i-1;k--){ selectCell(k,j); } } else{ console.log("else"); for(var k=i-1;k<=i+1;k++) { selectCell(k,j); } } count++; document.querySelectorAll("td")[i*9+j].classList.remove("coral"); document.querySelectorAll("td")[i*9+j].classList.add("green"); document.querySelectorAll("td")[j+i*9].innerHTML=bcount; } if(count===71){ document.getElementById("winner").innerHTML="<strong>Congratualtion you won the game</strong>"; } } // reload the current board function reset(){ location.reload(); }
'use strict'; module.exports = { name: process.env.APPNAME || 'API Rest', port: process.env.PORT || 8000, version: process.env.APPVERSION || '1.0.0', env: process.env.NODE_ENV || 'development', pageLimit: 10 };
import { combineReducers } from 'redux' import methodReducer from './methodReducer' export default combineReducers({ methods: methodReducer })
const { LOG_LEVELS } = require('../support/constants'); class CucumberReportLog{ setScenarioWorld(world){ this.scenarioWorld = world; this.logLevel = process.env.LOG_LEVEL !== undefined ? process.env.LOG_LEVEL : LOG_LEVELS.Info; } FormatPrintJson(jsonObj, basePad){ basePad = basePad ? basePad : 0; const keys = Object.keys(jsonObj); let maxSize = 0; for(let key of keys){ maxSize = key.length > maxSize ? key.length : maxSize; } let startPadding = basePad + maxSize + 1; for (let key of keys) { if (!this.scenarioWorld) { return; } try { this.scenarioWorld.attach(`${key.padEnd(startPadding)} : ${jsonObj[key]}`); } catch (err) { console.log('Error occured adding message to report. ' + err.stack); } console.log(`${key.padEnd(startPadding)} : ${jsonObj[key]}`); } } LogTestDataInput(message){ this.AddMessage(`>>>>>>> [ Test data input ]: ${message}`); } AddMessage(message, logLevel){ if (!this._isLevelEnabled(logLevel)) { return; } if (!this.scenarioWorld){ return; } try{ this.scenarioWorld.attach(new Date().toTimeString() + ' : ' + message); } catch(err){ console.log('Error occured adding message to report. '+err.stack); } console.log(new Date().toTimeString() + ' : ' + message); } AddMessageToReportOnly(message, logLevel) { if (!this._isLevelEnabled(logLevel)) { return; } if (!this.scenarioWorld) { return; } this.scenarioWorld.attach(new Date().toTimeString() + ' : ' + message); } AddJson(json, logLevel){ if (!this._isLevelEnabled(logLevel)) { return; } if (!this.scenarioWorld) { return; } try { this.scenarioWorld.attach(JSON.stringify(json, null, 2)); } catch(err) { console.log('Error occured adding message to report. ' + err.stack); } console.log(JSON.stringify(json, null, 2)); } AddJsonToReportOnly(json, logLevel) { if (!this._isLevelEnabled(logLevel)) { return; } if (!this.scenarioWorld) { return; } this.scenarioWorld.attach(JSON.stringify(json, null, 2)); } async AddScreenshot(onbrowser, logLevel){ if (!this._isLevelEnabled(logLevel)) { return; } onbrowser = onbrowser ? onbrowser : browser; if (!this.scenarioWorld) { return; } const decodedImage = await this.getScreenshot(onbrowser); await this.scenarioWorld.attach(decodedImage, 'image/png'); } async getScreenshot(onbrowser){ const scrrenshotBrowser = onbrowser ? onbrowser : browser; const stream = await scrrenshotBrowser.takeScreenshot(); const decodedImage = new Buffer(stream.replace(/^data:image\/(png|gif|jpeg);base64,/, ''), 'base64'); return decodedImage; } _isLevelEnabled(msgLoglevel){ msgLoglevel = msgLoglevel !== undefined ? msgLoglevel : LOG_LEVELS.Info; return msgLoglevel >= this.logLevel; } } module.exports = new CucumberReportLog();
import * as LogSlider from 'app-utils/logSlider'; import * as Difficulty from 'app-utils/difficulty'; function BoostCalculator(signals, contentBoosts, maxDiffInc) { const signalsList = signals && signals.list ? signals.list : []; const currentBoostValue = contentBoosts.totalDifficulty_ || 0; const ranksCtrl = LogSlider.GetTopNFromSignals(signalsList, currentBoostValue); const sliderCtrl = LogSlider.NewContentSliderCtrl(currentBoostValue, ranksCtrl, maxDiffInc); const currentRank = Difficulty.getDiffRank(signalsList, currentBoostValue); const range = {}; range.min = 0; range.max = 1; range.initial = 0; // these functions determine the relationship between values on the // slider bar and boosted values. let sliderToAddedBoost; let boostToSlider; if (ranksCtrl.ranks.length === 1) { if (currentBoostValue === 0) { // we arbitrarily allow a top value of 40 in this case. sliderToAddedBoost = function(x) { return 1 + 39 * x; }; boostToSlider = function(z) { return (z - currentBoostValue - 1) / 39; }; } else { // we allow the user to boost up to twice the current value. sliderToAddedBoost = function(x) { return 1 + (currentBoostValue - 1) * x; }; boostToSlider = function(z) { return (z - currentBoostValue - 1) / (currentBoostValue - 1); }; } } else if (ranksCtrl.ranks.length === 2) { const top = ranksCtrl.ranks[0].boostValue; // we allow the user to boost up to twice the top boosted value sliderToAddedBoost = function(x) { return (2 * top - currentBoostValue - 1) * x + 1; }; boostToSlider = function(z) { return (z - currentBoostValue - 1) / (2 * top - currentBoostValue - 1); }; } else { const max = 2 * ranksCtrl.ranks[0].boostValue; const normalization = currentBoostValue + 1; const slope = Math.log(max / normalization); sliderToAddedBoost = function(x) { return normalization * Math.exp(slope * x) - currentBoostValue; }; boostToSlider = function(z) { return Math.log(z / normalization) / slope; }; } function sliderProps(userConfig, sliderValue) { // calculates sliderProps for rendering // user config is the payProps.slider if (sliderValue < range.min || sliderValue > range.max) { sliderValue = range.initial; } let rankMarkers; if (userConfig.rankMarkers === true) { rankMarkers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; } else if (Array.isArray(userConfig.rankMarkers) && userConfig.rankMarkers.length > 0) { rankMarkers = userConfig.rankMarkers; } const markers = LogSlider.sliderRankMarkers(sliderCtrl, rankMarkers, boostToSlider); return { min: range.min, max: range.max, value: sliderValue, markers }; } function newTotalBoost(addedBoost) { return currentBoostValue + addedBoost; } function newRank(addedBoost) { return LogSlider.rankAfterAddedDiff(currentBoostValue, addedBoost, ranksCtrl.ranks) .rank; } return { currentBoostValue, currentRank, signals: signalsList, contentBoosts, sliderCtrl, ranksCtrl, range, sliderToAddedBoost, boostToSlider, sliderProps, newTotalBoost, newRank }; } export default BoostCalculator;
import { useState } from "react"; import { api } from "../../api/api"; import { Link } from "react-router-dom"; export const PrivateComponent = () => { const [message, setMessage] = useState(null); const authorizedEndpoint = () => { api.get('home').then(res => setMessage(res.data.message)).catch(e => setMessage('error')); }; return ( <div> <h1>PrivateComponent</h1> <Link className="btn btn-primary" to='/account/logout'>Logout</Link> <button className="btn btn-primary" onClick={authorizedEndpoint}>Authorized Endpoint</button> <div>{message}</div> </div> ); }
var express = require("express"); var logger = require("morgan"); var exphbs = require("express-handlebars"); var mongoose = require("mongoose"); var axios = require("axios"); var cheerio = require("cheerio"); var db = require("./model"); var PORT = process.env.PORT || 3000; var app = express(); app.use(logger("dev")); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(express.static("public")); app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); app.set('index', __dirname + '/views'); var MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/mongoscraper4"; mongoose.connect(MONGODB_URI, { useNewUrlParser: true }); //api routes app.get("/", function(req,res){ db.Article.find({saved : false}).then(result => { res.render('index', { result: result.map(result => result.toJSON()) }) }) }); app.get("/scrape", function(req,res){ axios.get("https://www.theonion.com/").then(function (response) { var $ = cheerio.load(response.data); var results = []; $(".story-wrap").each(function (i, element) { var headline = $(this).find(".title").text(); var link = $(this).find(".title").parent().attr("href"); var summary = $(this).find(".teaser").text(); var image = $(this).find(".imagewrap").find("a").find("img").attr('src'); if (headline && summary && link && image) { results.push({ headline: headline, summaryOne: summary, link: link, image: image }) } }); db.Article.create(results) .then(function (dbArticle) { res.render("index", { dbArticle }); console.log(dbArticle); }) .catch(function (err) { console.log(err); }) app.get("/", function (req, res) { res.render("index"); }) }) }); app.put("/update/:id", function (req, res) { db.Article.updateOne({ _id: req.params.id }, { $set: { saved: true } }, function (err, result) { if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).end(); } }); }); app.put("/newnote/:id", function(req, res) { db.Article.updateOne({ _id: req.body._id }, { $push: { note: req.body.note }}, function(err, result) { console.log(result) if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).end(); } }) }) app.put("/unsave/:id", function(req, res) { console.log(req.body) db.Article.updateOne({ _id: req.params.id }, { $set: { saved: false }}, function(err, result) { if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).end(); } }) }) app.delete("/articles", function (req, res) { db.Article.remove({}) .then(function (dbArticle) { res.json(dbArticle); }) .catch(function (err) { res.json(err); }); }); app.get("/newnote/:id", function(req, res) { db.Article.findOne({ _id: req.params.id }) .populate("note") .then(function(dbArticle) { res.json(dbArticle); }) .catch(function(err) { res.json(err); }); }); app.post("/newnote/:id", function(req, res) { db.Note.create(req.body) .then(function(dbNote) { return db.Article.findOneAndUpdate({ _id: req.params.id }, { note: dbNote._id }, { new: true }); }) .then(function(dbArticle) { res.json(dbArticle); }) .catch(function(err) { res.json(err); }); }) app.get("/saved", function (req, res) { var savedArticles = []; db.Article.find({saved : true}).then(saved => { savedArticles.push(saved); res.render('saved', { saved: saved.map(saved => saved.toJSON()) }) }) }) app.listen(PORT, function () { console.log("Server listening on: http://localhost:" + PORT); });
// import { Image } from "antd"; // import DashkitButton, { ButtonType } from "components/dashkit/Buttons"; // import DashkitIcon from "components/dashkit/Icon"; // import { LS } from "components/diginext/elements/Splitters"; // import { HorizontalList, HorizontalListAlign, ListItem, ListItemSize } from "components/diginext/layout/ListLayout"; import { useRouter } from "next/router"; import Logo from "components/website/logo/Logo"; import Link from "next/link"; import asset from "plugins/assets/asset"; import { TweenMax, TimelineLite } from "gsap"; import useWindowSize from "components/website/hooks/useWindowsSize"; import SelectLanguage from "components/website/elements/Language"; import { MainContent } from "components/website/contexts/MainContent"; import { useEffect, useRef, useState, useContext, useLayoutEffect, } from "react"; import { Affix, Button } from "antd"; import useScroll from "components/website/hooks/useScroll"; import Preloader from "components/website/elements/Spin"; // import useScrollPosition from '@react-hook/window-scroll'; // const listItemsMenu= { // en: [ // { route : "/", name : "HomePage"}, // { route: "/our-product", name : "Our Product"}, // { route: "/about-us", name : "About Us"}, // { route: "/news", name : "News"}, // { route: "/where-to-buy", name : "Where to buy"}, // { route: "/contact-us", name : "Contact Us"}, // ], // vi: [ // { route : "/", name : "Trang chủ"}, // { route: "/our-product", name : "Sản phẩm"}, // { route: "/about-us", name : "Về chúng tôi"}, // { route: "/news", name : "Tin tức"}, // { route: "/where-to-buy", name : "Nơi mua"}, // { route: "/contact-us", name : "Liên hệ"}, // ] // } const Language = { en: { name: "en", listMenu: [ { route: "/", name: "HomePage" }, { route: "/about-us", name: "About Us" }, { route: "/our-product", name: "Our Product" }, { route: "/news", name: "News" }, { route: "/where-to-buy", name: "Where to buy" }, { route: "/contact-us", name: "Contact Us" }, ], }, vi: { name: "vi", listMenu: [ { route: "/", name: "Trang chủ" }, { route: "/about-us", name: "Về chúng tôi" }, { route: "/our-product", name: "Sản phẩm" }, { route: "/news", name: "Tin tức" }, { route: "/where-to-buy", name: "Điểm mua hàng" }, { route: "/contact-us", name: "Liên hệ" }, ], }, }; export default function Header({ children }) { const router = useRouter(); const headerRef = useRef(); const listRef = useRef(); const navRef = useRef(); const [statusLoader, setStatusLoader] = useState(); const valueLanguageContext = useContext(MainContent); const [dataHeader, setDataHeader] = useState(); const [top, setTop] = useState(0.01); const scrollOption = useScroll(); // const [classFix, setClassFix] = useState(""); // useEffect(()=>{ // if(scrollOption.scrollDirection === "up"){ // console.log("UP", scrollOption.scrollY); // setClassFix(""); // setTop(100) // }else{ // console.log("DOWN", scrollOption.scrollY); // setClassFix("affix"); // setTop(0.1) // if(scrollOption.scrollY < 200 ){ // setClassFix("") // } // } // },[scrollOption.scrollY, scrollOption.scrollDirection]) // detect screen size const [responsiveMobile, setResponsiveMobile] = useState(false); const [responsiveTablet, setResponsiveTablet] = useState(false); const windowSize = useWindowSize(); useEffect(() => { setStatusLoader(true); }, []); useEffect(() => { if (statusLoader === true) { setTimeout(() => { setStatusLoader(false); }, 5000); } }, [statusLoader]); //check responsive useEffect(() => { if (windowSize.width <= 1025) { setResponsiveTablet(true); if (windowSize.width <= 480) { setResponsiveTablet(false); setResponsiveMobile(true); } } else { setResponsiveTablet(false); setResponsiveMobile(false); } }, [windowSize]); const [statusShow, setStatusShow] = useState(false); useEffect(() => { if (listRef.current) { statusShow ? animationIn() : animationIn2(); // animationIn2(); } }, [statusShow]); const setStatus = () => setStatusShow(!statusShow); useEffect(() => { if (valueLanguageContext.languageCurrent) { setDataHeader(Language[`${valueLanguageContext.languageCurrent}`]); } }, []); useEffect(() => { if (valueLanguageContext.languageCurrent) { setDataHeader(Language[`${valueLanguageContext.languageCurrent}`]); } }, [valueLanguageContext.languageCurrent]); const animationIn2 = function () { const tl = new TimelineLite(); TweenMax.set(listRef.current, { autoAlpha: 0 }); tl.add(TweenMax.staggerTo(listRef.current, 0.3, { autoAlpha: 1 })); }; const animationIn = function () { const tl = new TimelineLite(); TweenMax.set(listRef.current.getElementsByTagName("li"), { y: 50, autoAlpha: 0, }); tl.add( TweenMax.staggerTo( listRef.current.getElementsByTagName("li"), 0.4, { y: 0, autoAlpha: 1 }, 0.1 ) ); }; const Mobile = ( <> <div ref={navRef} className={`${ statusShow ? "headerContainer mobile open" : "headerContainer mobile" }`} > <Logo></Logo> <ul> <SelectLanguage></SelectLanguage> <li className="item social"> <Link href={"#"}> <img src={asset("/images/youtube.png")} alt="" /> </Link> </li> <li className="item social"> <Link href={"#"}> <img src={asset("/images/FB.png")} alt="" /> </Link> </li> <li className="item social openNav" onClick={setStatus}> {statusShow ? ( <img className="close" src={asset("/images/icon-close.png")} alt="" /> ) : ( <img className="open" src={asset("/images/icon-menu.png")} alt="" /> )} </li> </ul> <div className="menuMobile" ref={listRef}> {dataHeader ? ( dataHeader.listMenu.map((value, index) => ( <li key={index} // className={"item"} className={ router.asPath === value.route ? "active item" : "item" } > <Link href={value.route}>{value.name}</Link> </li> )) ) : ( <></> )} </div> </div> </> ); const Desktop = ( <> <div className="headerContainer"> <Logo></Logo> <ul className="menu"> {dataHeader ? ( dataHeader.listMenu.map((value, index) => ( <li key={index} className={ router.asPath === value.route ? "active item" : "item" } > <Link href={value.route}>{value.name}</Link> </li> )) ) : ( <></> )} {children} </ul> <ul> <SelectLanguage></SelectLanguage> <li className="item social"> <Link href={"#"}> <img src={asset("/images/youtube.png")} alt="" /> </Link> </li> <li className="item social"> <a href={"https://www.facebook.com/LipovitanVN"} target="_blank"> <img src={asset("/images/FB.png")} alt="" /> </a> </li> </ul> </div> </> ); return ( <> <Preloader size="large" status={statusLoader} fullScreen={true} /> <header ref={headerRef}> <Affix offsetTop={top}> <div className={"affix"}> {responsiveMobile || responsiveTablet ? Mobile : Desktop} </div> </Affix> <style jsx>{` .fix { transition: 0.2s; background-color: rgba(0, 0, 0, 0); position: unset; } .affix { //position: fixed; //top:0; //left:0; transition: 0.2s; background-color: #005ae18f; max-width: 100vw; } `}</style> </header> </> ); }
var adminurl = "http://104.197.111.152/"; // var adminurl = "http://192.168.1.122:1337/"; var imgpath = adminurl + "uploadfile/getupload?file="; angular.module('starter.services', []) .factory('MyServices', function($http) { return { loginUser: function(userData, callback, err) { $http({ url: adminurl + 'user/login', method: 'POST', data: { "mobile": userData.mobile, "password": userData.password } }).success(callback).error(err); }, signupUser: function(signupData, callback, err) { $http({ url: adminurl + 'user/save', method: 'POST', data: signupData }).success(callback).error(err); }, register: function(signupData, callback, err) { $http({ url: adminurl + 'user/register', method: 'POST', data: signupData }).success(callback).error(err); }, validateOTP: function(signupData, callback, err) { $http({ url: adminurl + 'user/validateOTP', method: 'POST', data: signupData }).success(callback).error(err); }, checkMob: function(checkData, callback, err) { $http({ url: adminurl + 'user/checkMob', method: 'POST', data: checkData }).success(callback).error(err); }, readMoney: function(signupData, callback, err) { $http({ url: adminurl + 'user/readMoney', method: 'POST', data: signupData }).success(callback).error(err); }, findUser: function(signupData, callback, err) { $http({ url: adminurl + 'user/findone', method: 'POST', data: signupData }).success(callback).error(err); }, logoutUser: function(logoutData, callback, err) { $http({ url: adminurl + 'user/logout', method: 'POST', data: logoutData }).success(callback).error(err); }, updateUser: function(userData, callback, err) { console.log(userData); $http({ url: adminurl + 'user/save', method: 'POST', data: userData }).success(callback).error(err); }, findUserByMobile: function(userData, callback, err) { console.log(userData); $http({ url: adminurl + 'user/findUserByMobile', method: 'POST', data: userData }).success(callback).error(err); }, changePass: function(userData, callback, err) { $http({ url: adminurl + 'user/changepassword', method: 'POST', data: userData }).success(callback).error(err); }, forgotPass: function(userData, callback, err) { $http({ url: adminurl + 'user/forgotpassword', method: 'POST', data: userData }).success(callback).error(err); }, validateMobile: function(userData, callback, err) { console.log(userData); $http({ url: adminurl + 'user/validateMobile', method: 'POST', data: userData }).success(callback).error(err); }, updateReferrer: function(userData, callback, err) { console.log(userData); $http({ url: adminurl + 'user/updateReferrer', method: 'POST', data: userData }).success(callback).error(err); }, addTransaction: function(transactionData, callback, err) { $http({ url: adminurl + 'transaction/save', method: 'POST', data: transactionData }).success(callback).error(err); }, findCategories: function(callback, err) { $http({ url: adminurl + 'category/find', method: 'GET' }).success(callback).error(err); }, findBanner: function(callback, err) { $http({ url: adminurl + 'banner/find', method: 'GET' }).success(callback).error(err); }, findCoupon: function(couponData, callback, err) { console.log("inside findCoupon"); $http({ url: adminurl + 'coupon/findcode', method: 'POST', data: couponData }).success(callback).error(err); }, updateCoupon: function(couponData, callback, err) { $http({ url: adminurl + 'coupon/save', method: 'POST', data: couponData }).success(callback).error(err); }, findVendorByCategory: function(category, callback, err) { $http({ url: adminurl + 'vendors/findVendorByCategoryID', method: 'POST', data: { "category": category.id } }).success(callback).error(err); }, findByType: function(transactionType, callback, err) { $http({ url: adminurl + 'transaction/findByType', method: 'POST', data: { "type": transactionType.type } }).success(callback).error(err); }, findByTypeUser: function(transactionFilter, callback, err) { $http({ url: adminurl + 'transaction/findByTypeUser', method: 'POST', data: transactionFilter }).success(callback).error(err); }, findPassbookEntry: function(transactionFilter, callback, err) { $http({ url: adminurl + 'transaction/findPassbookEntry', method: 'POST', data: { "type": transactionFilter.type, "from": transactionFilter.from, "passbook": transactionFilter.passbook } }).success(callback).error(err); }, findCategory: function(category, callback, err) { $http({ url: adminurl + 'category/findone', method: 'POST', data: { "_id": category.id } }).success(callback).error(err); }, findVendor: function(vendor, callback, err) { $http({ url: adminurl + 'vendors/findone', method: 'POST', data: { "_id": vendor.id } }).success(callback).error(err); }, sendSMS: function(message, callback, err) { $http({ url: adminurl + 'transaction/sendSMS', method: 'POST', data: message }).success(callback).error(err); }, notify: function(message, callback, err) { $http({ url: adminurl + 'notification/notify', method: 'POST', data: message }).success(callback).error(err); }, sendOTP: function(message, callback, err) { $http({ url: 'http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=Paiso&password=157699462&sendername=PAISOO&mobileno=91' + message.mobile + '&message=Dear User, welcome to PAiSO. Your OTP is ' + message.otp + '.', method: 'GET' }); }, sendRedeem: function(message, callback, err) { $http({ url: 'http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=Paiso&password=157699462&sendername=PAISOO&mobileno=91' + message.mobile + '&message=Voucher No ' + message.vouchernumber + ' for Rs.' + message.amount + ' spent on ' + message.vendor + ' at ' + message.timestamp + '(Current Balance: Rs.' + message.currentbalance + '). Valid Till : ' + message.validtill + '. Paiso.', method: 'GET' }); }, addNewCard: function(consumer, callback, err) { $http.get(adminurl + 'user/saveCard?consumer=' + consumer).success(callback).error(err); }, getListOfCards: function(consumer, callback, err) { $http({ url: adminurl + 'user/getListOfCards', method: 'POST', data: { "consumer": consumer } }).success(callback).error(err); }, walletAdd: function(wallet, callback, err) { $http({ url: adminurl + 'user/walletAdd', method: 'POST', data: wallet }).success(callback).error(err); }, generateOtpForDebit: function(consumer, callback, err) { $http({ url: adminurl + 'user/generateOtpForDebit', method: 'POST', data: { "consumer": consumer } }).success(callback).error(err); }, moneySend: function(sendmoney, callback, err) { $http({ url: adminurl + 'user/moneySend', method: 'POST', data: sendmoney }).success(callback).error(err); }, sendMoney: function(sendmoney, callback, err) { $http({ url: adminurl + 'user/sendMoney', method: 'POST', data: sendmoney }).success(callback).error(err); }, redeem: function(redeemobj, callback, err) { $http({ url: adminurl + 'user/redeem', method: 'POST', data: redeemobj }).success(callback).error(err); }, addToWallet: function(wallet, callback, err) { $http({ url: adminurl + 'user/addToWallet', method: 'POST', data: wallet }).success(callback).error(err); }, netBanking: function(wallet, callback, err) { $http({ url: adminurl + 'user/netBanking', method: 'POST', data: wallet }).success(callback).error(err); }, setNotify: function(data) { $.jStorage.set("notify", data); }, getNotify: function() { return $.jStorage.get("notify"); }, setNotify: function(data) { $.jStorage.set("notify", data); }, getNotify: function() { return $.jStorage.get("notify"); }, setOTP: function(data) { $.jStorage.set("otp", data); }, getOTP: function() { return $.jStorage.get("otp"); }, setUser: function(data) { $.jStorage.set("user", data); }, getUser: function() { return $.jStorage.get("user"); }, setDevice: function(data) { $.jStorage.set("device", data); }, getDevice: function() { return $.jStorage.get("device"); }, setOS: function(data) { $.jStorage.set("os", data); }, getOS: function() { return $.jStorage.get("os"); }, setReferrer: function(data) { $.jStorage.set("referrer", data); }, getReferrer: function() { return $.jStorage.get("referrer"); } }; });
if (3+5) { var a; a=5;} else {var b; b = 5;}
const user = require('./user'); const error = require('./error'); const weet = require('./weet'); const parameters = require('./parameters'); module.exports = { ...user, ...error, ...weet, ...parameters };
import React from 'react'; import styled, {css} from 'styled-components'; import {useIntl} from 'react-intl'; import {Blinking, StandardTopBottomMargin} from '../../ReuseStyles'; import VerticalScroll from '../../components/Vertical Scroll'; const PageContainer = styled.div` ${StandardTopBottomMargin}; max-width: 930px; `; const ContentContainer = styled.div` width: 100%; min-height: 100%; box-sizing: border-box; display: flex; flex-wrap: wrap; justify-content: center; align-content: center; position: relative; `; const Text = styled.p` font-family: NeueMontrealLight, sans-serif; flex: 100% 0 0; max-width: 100%; margin-bottom: 24px; font-weight: 300; font-size: 1.75em; line-height: 129%; white-space: pre-line; `; const LinksContainer = styled.div` flex: 100% 0 0; box-sizing: border-box; padding-left: 20%; margin-bottom: 20px; @media only screen and (max-width: ${({theme}) => theme.mobileBreakpoint()}px) { padding-left: 0; } `; const LinksInnerContainer = styled.div` display: inline-block; &:hover a { animation: none; color: ${({theme}) => theme.app.textColor}; } `; const LinkStyle = css` &&:hover { color: ${({theme}) => theme.app.emphasisedTextColor}; } `; const Mail = styled.a` ${Blinking()}; ${LinkStyle}; display: block; `; const Instagram = styled.a` ${Blinking(200)}; ${LinkStyle}; display: block; `; const Facebook = styled.a` ${Blinking(400)}; ${LinkStyle}; display: block; `; const Authorship = styled.p` z-index: 999; font-size: 0.6em; line-height: 125%; position: fixed; left: 50%; transform: translateX(-50%); bottom: ${({theme}) => theme.app.bottomMargin * 2}px; @media only screen and (max-width: ${({theme}) => theme.mobileBreakpoint()}px) { bottom: ${({theme}) => theme.app.bottomMarginMobile * 2}px; } `; const Unbreakable = styled.span` white-space: nowrap; `; const Asia = styled.a` ${Blinking(600)}; ${LinkStyle}; `; const Alex = styled.a` ${Blinking(800)}; ${LinkStyle}; `; const ContactPage = ({ text = {}, mail, instagramLink, facebookLink, phone, authorship: { designBy = {}, codeBy = {}, joannaName, alekseiName, joannaMail, alekseiMail } }) => { const {locale} = useIntl(); return ( <PageContainer> <VerticalScroll> <ContentContainer> {text[locale] && <Text>{text[locale]}</Text>} <LinksContainer> <LinksInnerContainer> {mail && <Mail href={`mailto:${mail}`} target="_blank" rel="noopener noreferrer">{mail}</Mail> } {instagramLink && <Instagram href={instagramLink} target="_blank" rel="noopener noreferrer">Instagram</Instagram> } {facebookLink && <Facebook href={facebookLink} target="_blank" rel="noopener noreferrer">Facebook</Facebook> } {phone} </LinksInnerContainer> </LinksContainer> {designBy[locale] && joannaName && codeBy[locale] && alekseiName && <Authorship> <Unbreakable> <span>{designBy[locale]} </span> <Asia href={`mailto:${joannaMail}`} target="_blank" rel="noopener noreferrer">{joannaName}</Asia> </Unbreakable> <span> </span> <Unbreakable> <span>{codeBy[locale]} </span> <Alex href={`mailto:${alekseiMail}`} target="_blank" rel="noopener noreferrer">{alekseiName}</Alex> </Unbreakable> </Authorship> } </ContentContainer> </VerticalScroll> </PageContainer> ); }; export default ContactPage;
import React, { Component } from 'react'; import {Link} from 'react-router-dom' import $ from 'jquery' class Game extends Component { constructor(props){ super(props); this.state={ "res":[], "listAll":[], "list":[] } console.log(this.props) } finddata(key,key2){ console.log(key) $.ajax({ type:"get", url:"https://api.m.panda.tv/ajax_get_live_list_by_cate?pageno=1&pagenum=10&__plat=h5&cate="+key, async:true, dataType:'jsonp', success:function(data){ var arr = data.data.items; this.setState({ "res":arr }) }.bind(this) }); this.refs.flist.innerHTML = key2; var temarr = []; for(var i=0;i<this.state.listAll.length;i++){ temarr.push(this.state.listAll[i]); } for(var i=0;i<temarr.length;i++){ if(key === temarr[i].ename){ temarr.splice(i,1); } } var boxarr = []; for(var j=0;j<3;j++){ boxarr.push(temarr[j]); } this.setState({ "list":boxarr }); } render() { return ( <div> <ul className="gameList"> <li className="active" ref="flist">{this.props.match.params.cname}</li> { this.state.list.map((val,ind) => ( <li onClick={this.finddata.bind(this,val.ename,val.cname)} key={ind}>{val.cname}</li> )) } <li><Link to="/gamekinds"><img src={'https://i.h2.pdim.gs/695ff30ecdc843f58a1e7b9d53783144.png'} alt=""/></Link></li> </ul> <ul className="vlist clearfix"> { this.state.res.map((value,index) => ( <li key={index}> <div className="vedio"> <Link to={"/vedioplay/" + value.id}><img src={value.pictures.img} alt=""/></Link> <div className="vedioDes">{value.name}</div> </div> <div className="vedioName">{value.userinfo.nickName}<span>{value.person_num}</span></div> </li> )) } </ul> </div> ); } componentDidMount(){ $.ajax({ type:"get", url:"https://api.m.panda.tv/index.php?method=category.list&type=game", async:true, dataType:'jsonp', success:function(data){ this.setState({ "listAll":data.data }) var boxarr2 = []; for(var j=1;j<4;j++){ boxarr2.push(data.data[j]); } console.log(boxarr2) this.setState({ "list":boxarr2 }); }.bind(this) }); $.ajax({ type:"get", url:"https://api.m.panda.tv/ajax_get_live_list_by_cate?pageno=1&pagenum=10&__plat=h5&cate="+this.props.match.params.ename, async:true, dataType:'jsonp', success:function(data){ var arr = data.data.items; this.setState({ "res":arr }) this.finddata(this.props.match.params.ename,this.props.match.params.cname); }.bind(this) }); } } export default Game;
let arr = [{"A" : "Key1", "B" : "Key2", "C" : "Key3"}, {"A" : "Data1", "B" : "Data2", "C" : "Data3"}, {"A" : "Data5", "B" : "Data5", "C" : "Data7"}]; const keys = Object.keys(arr[0]).map(i => arr[0][i]); let result = arr.map(obj => { const replacedObj = {}; const oriKeys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { replacedObj[keys[i]] = obj[oriKeys[i]] }; return replacedObj; }); console.log(JSON.stringify(result));
const express = require('express') const conversions = require('./conversions') const cors = require('cors') const app = express() const PORT = process.env.PORT || 3001 const corsOptions = { origin : process.env.ORIGIN || 'http://localhost:3000', optionsSuccessStatus: 200 // For legacy browser support } app.use(express.urlencoded({extended: true})) app.use(express.json()) app.use(cors(corsOptions)) app.get('/toRoman/:num', (req, res) => { const {num} = req.params try { const romanNumeral = conversions.toRomanNumeral(num) res.send({ "success": true, "message": romanNumeral }) } catch (err) { res.send({ "success": false, "message": err.message }) } }) app.get('/toArabic/:str', (req, res) => { const {str} = req.params try { const arabicNumeral = conversions.toArabicNumeral(str) res.send({ "success": true, "message": arabicNumeral }) } catch (err) { res.send({ "success": false, "message": err.message }) } }) app.listen(PORT, () => { console.log(`App running on port ${PORT}!`) })
import { connect } from 'react-redux'; import TasksIndex from './tasks_index'; import { fetchTasks } from '../../../actions/task_actions'; const mapStateToProps = state => ({ tasks: state.tasks, errors: state.errors.task, list: state.list }); const mapDispatchToProps = ( dispatch ) => ({ fetchTasks: (listId) => dispatch(fetchTasks(listId)) }); export default connect( mapStateToProps, mapDispatchToProps )(TasksIndex);
// client/pages/doctororder/doctororder.js var app = getApp() var API = require('../../utils/api.js'); Page({ /** * 页面的初始数据 */ data: { }, dataorder: function () { wx.navigateTo({ url: '../dataorder/dataorder' }) }, introduce: function (event) { var newid = event.currentTarget.dataset.id; let str = JSON.stringify(newid); // console.log(newid); wx.navigateTo({ url: '../introduces/introduces?id=' + str }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function () { // console.log('onLoad') // var that = this // // 使用 Mock // API.ajax('', function (res) { // //这里既可以获取模拟的res // // console.log(res) // that.setData({ // doctorlist: res.data['doctor'] // }) // }); wx.request({ url: 'https://us5qsybm.qcloud.la/infor/get_doctor', success: res => { this.setData({ doctorlist: res.data }) // console.log(this.data.doctorlist); } }); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
/** @format */ import StartupLogin from "../Startups/StartupLogin"; const Routes = [ { path: "/startup/login", name: "login", exact: true, pageTitle: "Login", component: StartupLogin, }, ]; export default Routes;
// Utilities: import { camel } from 'change-case'; // Module: import { FeaturesModule } from '../features.module'; // Template: import template from './step-input.html'; // Dependencies: import './example-name.validator'; import './step-input.controller'; function StepInputDirective () { return { restrict: 'E', scope: { model: '=', label: '@', example: '@', availableStepDefinitions: '=' }, template, link, controller: 'StepInputController', controllerAs: 'stepInput', bindToController: true }; function link ($scope, $element, $attrs) { if ($scope.stepInput.model == null) { throw new Error('The "tractor-step-input" directive requires a "model" attribute.'); } if ($scope.stepInput.label == null) { throw new Error('The "tractor-step-input" directive requires a "label" attribute.'); } if ($attrs.form == null) { throw new Error('The "tractor-step-input" directive requires a "form" attribute.'); } $scope.stepInput.form = $scope.$parent[$attrs.form]; $scope.stepInput.id = Math.floor(Math.random() * Date.now()); $scope.stepInput.property = camel($scope.stepInput.label); $scope.handleKeyDown = event => { if (event.keyCode === 40) { event.preventDefault(); if ($scope.selectedIndex !== $scope.stepInput.items.length - 1) { $scope.selectedIndex += 1; } } else if (event.keyCode === 38) { event.preventDefault(); if ($scope.selectedIndex !== 0) { $scope.selectedIndex -= 1; } } else if (event.keyCode === 27) { $scope.stepInput.isOpen = false; } } } } FeaturesModule.directive('tractorStepInput', StepInputDirective);
$(document).ready(function() { $(".productCategory").change(function (e) { $("#abc").closest("form").submit(); }) });
import React from 'react'; import {storiesOf} from '@storybook/react'; import {Grid} from './grid'; const data = [ 2, 2, 3, 4, 2, 1, 3, 5, 2, 1, 3, 3, 2, 5, 1, 5, 3, 2, 2, 4, 2, 2, 1, 2, 4, 3, 4, 5, 3, 4, 4, 2, 2, 5, 3, 2, ]; storiesOf('Components|Grid', module) .add('Default', () => ( <Grid data={data}/> ));
const { getCurrentWindow } = window.require('electron').remote; import EventEmitter from 'events'; import { format } from 'url'; import { join } from 'path'; import VideoFrameRenderer from './VideoFrameRenderer'; import CanvasScene from '../CanvasScene'; import execBinary from '../exec-binary'; const { PixelPass, GrayscalePass, BlurPass } = require('../effects'); const browserWindow = getCurrentWindow(); try { browserWindow.on('init', async (frames, savePath, passes) => { passes = parsePasses(passes); const videoFrameRenderer = new VideoFrameRenderer(frames, savePath, passes); videoFrameRenderer.on('progress', progress => browserWindow.emit('progress', progress)); await videoFrameRenderer.render(); browserWindow.emit('done'); }); function parsePasses(passes) { return passes.map(objString => { let { Constructor, options } = JSON.parse(objString); return { Constructor: eval(Constructor), options }; }); } } catch (e) { browserWindow.emit('error', e.message); }
/** * @file SMSCodeBox.js * @author leeight */ import {DataTypes, defineComponent} from 'san'; import {create} from './util'; import Button from './Button'; import TextBox from './TextBox'; import {asInput} from './asInput'; const cx = create('ui-smscode'); /* eslint-disable */ const template = `<div class="{{mainClass}}"> <ui-textbox type="number" on-input="onInput" placeholder="{{placeholder}}" width="{{width}}" value="{=value=}" disabled="{{disabled}}" /> <ui-button on-click="onBtnClick" width="{{60}}" disabled="{{freezed || disabled}}">{{btnText}}</ui-button> </div>`; /* eslint-enable */ const SMSCodeBox = defineComponent({ template, components: { 'ui-textbox': TextBox, 'ui-button': Button }, initData() { return { freezed: false, disabled: false, freezeTime: 60, btnText: '获取验证码', value: '', width: null, placeholder: '请输入验证码' }; }, dataTypes: { /** * 用户输入的手机号 * @bindx */ value: DataTypes.string, /** * 输入框的宽度 */ width: DataTypes.number, /** * 组件的禁用状态 * @default false */ disabled: DataTypes.bool, /** * 发送短信之后的冷冻时间 * @default 60 */ freezeTime: DataTypes.number, /** * 按钮上面的文案 * @default 获取验证码 */ btnText: DataTypes.string, /** * 输入框的 placeholder * @default 请输入验证码 */ placeholder: DataTypes.string }, computed: { mainClass() { const klass = cx.mainClass(this); const freezed = this.data.get('freezed'); if (freezed) { klass.push('state-freezed'); klass.push(cx('freezed')); } return klass; } }, onInput() { this.fire('input'); }, onBtnClick() { this.fire('click'); this.data.set('freezed', true); let freezeTime = this.data.get('freezeTime'); const countdown = () => { if (freezeTime <= 0) { this.data.set('freezed', false); this.data.set('btnText', '获取验证码'); } else { this.data.set('btnText', '剩余 ' + freezeTime-- + ' 秒'); setTimeout(countdown, 1000); } }; countdown(); } }); export default asInput(SMSCodeBox);
/* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. */ var helper = require('./helper.js'), m, numbers = new Array(2000000), p = 2, result, MAX = numbers.length; while (p < MAX) { numbers[p] = true; m = 2; while (m * p < MAX) { numbers[m++ * p] = false; } while (p < MAX && false === numbers[++p]) {} } result = numbers .reduce(function (acc, isPrime, num) { return isPrime ? acc + num : acc; }, 0); helper(result);
var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(requirePrecedingComma) { assert( typeof requirePrecedingComma === 'boolean', this.getOptionName() + ' option requires boolean value' ); assert( requirePrecedingComma === true, this.getOptionName() + ' option requires true or should be removed' ); }, getOptionName: function() { return 'requirePrecedingComma'; }, check: function(file, errors) { var lines = file.getLines(); for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i]; if (line[line.length-1] == ","){ errors.add('Succeeding Comma', i, line.length - 1); } } } };
import util from '../../utils/util.js' var app = getApp(); Page({ data: { showtList: '0', showSupplier: false, shopData: [], orderShopList: [], oneData: [], supplierData: [], showdel: false, shopAllNum: 0, allPrice: 0, disabled: false, isScope: false }, onLoad: function() { console.log(app.loginInfoData.scope == 'company' && app.loginInfoData.store_id == "0" ? true : false) this.setData({ showdel: false, isScope: app.loginInfoData.scope == 'store' && app.loginInfoData.store_id == "0" ? true : false }) }, onReady: function() { }, showList: function(e) { //展开或折叠起来某个分类的菜品 var i = e.currentTarget.dataset.id; var up = "shopData[" + i + "].showList" this.setData({ [up]: !this.data.shopData[i].showList }) }, onShow: function() { this.shopCart(); }, onPullDownRefresh: function() { var _this = this; app.netWork.postJson(app.urlConfig.shopCarListUrl, {}).then(res => { if (res.errorNo == '0') { this.data.shopData = res.data; var num = 0; var price = 0; _this.data.shopData.filter(function(item, index) { //遍历json对象的每个key/value对,p为key item.price = 0; item.showList = true; item.son.filter(function(val, i) { num = parseInt(num) + 1; // if (!_this.isScope) { // price = price + val.offer_price * val.nums; // item.price += val.offer_price * val.nums; // } else { price = price + val.supply_price * val.nums; item.price += val.supply_price * val.nums; // } }) }) _this.setData({ shopData: _this.data.shopData }) this.setData({ shopAllNum: num, allPrice: price }) } wx.stopPullDownRefresh(); }).catch(res => { wx.stopPullDownRefresh(); }) }, shopCart: function() { //购物车列表 var _this = this; wx.showLoading({ title: '加载中', }) app.netWork.postJson(app.urlConfig.shopCarListUrl, {}).then(res => { if (res.errorNo == '0') { _this.data.shopData = res.data; var num = 0; var price = 0; _this.data.shopData.filter(function(item, index) { //遍历json对象的每个key/value对,p为key item.price = 0; item.showList = true; item.son.filter(function(val, i) { num = parseInt(num) + 1; // if (!_this.data.isScope) { // price = price + val.offer_price * val.nums; // item.price += val.offer_price * val.nums; // }else{ price = price + val.supply_price * val.nums; item.price += val.supply_price * val.nums; // } }) }) _this.setData({ shopData: _this.data.shopData }) this.setData({ shopAllNum: num, allPrice: price }) } wx.hideLoading() }).catch(res => {}) }, shopDel: function(e) { //删除某个菜品 var _this = this; var data = { keys: JSON.stringify([e.currentTarget.dataset.code]), isAll: 0, } app.netWork.postJson(app.urlConfig.shopCarDelUrl, data).then(res => { if (res.errorNo == '0') { wx.showToast({ title: '删除成功', icon: 'success', duration: 2000, mask: true, success: function() { _this.shopCart(); _this.setData({ showSupplier: false, oneData: [], showdel: false, }) } }) } else { wx.showToast({ title: res.errorMsg, image: '../../images/warning.png', duration: 2000, mask: true }) } }).catch(res => {}) }, allShopDel: function() { //删除购物车所有菜品 var _this = this; var data = { isAll: 1, } app.netWork.postJson(app.urlConfig.shopCarDelUrl, data).then(res => { if (res.errorNo == '0') { _this.shopCart(); wx.showToast({ title: '清空成功', icon: 'success', duration: 2000, mask: true }) } else { wx.showToast({ title: res.errorMsg, image: '../../images/warning.png', duration: 2000, mask: true }) } }).catch(res => {}) }, shopJian: function(e) { //减号 var arr = this.data.shopData; var flg = e.currentTarget.dataset.flg; var i = 0; //子级的索引 var index = 0; //父级的索引 var value = e.currentTarget.dataset.item; this.data.shopData.filter(function(item, m) { if (value.pid == item.pid) { item.son.filter(function(val, n) { if (val.code == value.code) { return index = m, i = n; } }) } }) if (value.nums == 1) { return } arr[index].price = arr[index].price - 1 * value.supply_price value.nums = parseFloat(value.nums) - 1; var up = "shopData[" + index + "].son[" + i + "].nums"; //先用一个变量,把(info[0].gMoney)用字符串拼接起来 var pirce = "shopData[" + index + "].price"; this.setData({ [up]: value.nums, [pirce]: arr[index].price }) if (flg == 1) { this.setData({ oneData: value }) } // 数量的减处理 if (value.nums < 0 || value.nums == 0) { this.data.shopAllNum = this.data.shopAllNum - 1; } this.data.allPrice = this.data.allPrice - 1 * value.supply_price this.setData({ shopAllNum: this.data.shopAllNum, allPrice: this.data.allPrice }) }, shopJia: function(e) { //加号 if (util.authFind('shopcar_update')) { //检验权限 var arr = this.data.shopData; var flg = e.currentTarget.dataset.flg; var i = 0; //子级的索引 var index = 0; //父级的索引 var value = e.currentTarget.dataset.item; this.data.shopData.filter(function(item, m) { if (value.pid == item.pid) { item.son.filter(function(val, n) { if (val.code == value.code) { return index = m, i = n; } }) } }) if (value.nums < 0 || value.nums == 0) { this.data.shopAllNum = this.data.shopAllNum + 1; } value.nums = parseFloat(value.nums) + 1; arr[index].price = arr[index].price + 1 * value.supply_price; var up = "shopData[" + index + "].son[" + i + "].nums"; //先用一个变量,把(shopData[0].son[0].nums)用字符串拼接起来 var pirce = "shopData[" + index + "].price"; this.setData({ [up]: value.nums, [pirce]: arr[index].price, shopAllNum: this.data.shopAllNum }) if (flg == 1) { this.setData({ oneData: value }) } this.data.allPrice = this.data.allPrice + value.supply_price * 1 // 数量的加处理 this.setData({ allPrice: this.data.allPrice }); } else { wx.showToast({ title: '暂无权限', image: '../../images/warning.png', duration: 2000, mask: true }) } }, changeShop: function(e) { //手动修改数量 var arr = this.data.shopData; var flg = e.currentTarget.dataset.flg; var newNum = e.detail.value; var i = 0; //子级的索引 var index = 0; //父级的索引 var value = e.currentTarget.dataset.item; this.data.shopData.filter(function(item, m) { if (value.pid == item.pid) { item.son.filter(function(val, n) { if (val.code == value.code) { return index = m, i = n; } }) } }) this.data.allPrice = this.data.allPrice + value.supply_price * parseFloat(util.toFix(newNum) - value.nums) arr[index].price = arr[index].price + value.supply_price * parseFloat(util.toFix(newNum) - value.nums); value.nums = util.toFix(newNum); var up = "shopData[" + index + "].son[" + i + "].nums"; //先用一个变量,把(shopData[0].son[0].nums)用字符串拼接起来 var pirce = "shopData[" + index + "].price"; this.setData({ [up]: value.nums, [pirce]: arr[index].price }) // 数量的加处理 this.setData({ allPrice: this.data.allPrice }) if (flg == 1) { this.setData({ oneData: value }) } }, cartUpdateNum: function(item) { //修改购物车的数量接口 wx.showLoading({ title: '加载中', }) var arr = []; arr.push({ num: item.nums, code: item.code }) var data = { info: JSON.stringify(arr) } var _this = this; app.netWork.postJson(app.urlConfig.shopCarUpdateUrl, data).then(res => { if (res.errorNo == '0') { setTimeout(function() { wx.hideLoading() }, 100) _this.shopCart(); } }).catch(res => {}) }, submitOrder: function() { //结算 var listData = this.data.shopData; var arrList = []; //所有产品 var arrSupplier = []; //所有产品的所有供应商的id var arrClass = []; //分类的 var arr1 = []; //最终的数据 listData.filter(function(item, index) { arrClass.push({ name: item.name, pid: item.pid }) item.son.filter(function(val, i) { arrSupplier.push(val.supplier_id); arrList.push(val); }) }) var supData = util.unique(arrSupplier); //供应商id数据去重 supData.filter(function(val, i) { arr1.push({ supplier_id: val, supplier_name: '', allNum: 0, allPrice: 0, remarks: '', children: [], classifly: [] }) }) arrList.filter(function(value, index) { //所有产品去分一下供应商 arr1.filter(function(item, m) { if (value.supplier_id == item.supplier_id) { arr1[m].supplier_name = value.supplier_name; arr1[m].children.push(value); arr1[m].allPrice += value.supply_price * value.nums - 0; arr1[m].allNum += 1; } }) }) arr1.filter(function(item, index) { item.children.filter(function(value, m) { arrClass.filter(function(val, n) { //所有供应商下的产品去做分类 if (val.pid == value.pid) { if (item.classifly.length > 0) { var res = item.classifly.findIndex(function(v, i) { return v.pid == value.pid }) if (res != '-1') { console.log(3333) item.classifly[res].kindPrice = item.classifly[res].kindPrice + value.supply_price * value.nums; item.classifly[res].kindNum += 1; item.classifly[res].children.push(value); } else { item.classifly.push({ name: val.name, pid: val.pid, kindNum: 1, kindPrice: value.supply_price * value.nums, carDetailIsShow: false, children: new Array(value) }) // console.log(item.classifly) // item.classifly[m].kindPrice = item.classifly[m].kindPrice + value.supply_price * value.nums; // item.classifly[m].kindNum += 1; // item.classifly[m].children.push(value); } } else { item.classifly.push({ name: val.name, pid: val.pid, kindNum: 1, kindPrice: value.supply_price * value.nums, carDetailIsShow: false, children: new Array(value) }) // item.classifly[m].kindPrice = item.classifly[m].kindPrice + value.supply_price * value.nums; // item.classifly[m].kindNum += 1; // item.classifly[m].children.push(value); } } }) }) }) console.log(arr1) wx.setStorageSync('shoplist', JSON.stringify(arr1)) wx.setStorage({ key: "shoplist", data: JSON.stringify(arr1), success: function(res) { wx.redirectTo({ url: '../confirmShoppingCart/confirmShoppingCart' }) } }) }, goOrderList: function() { //去采购 wx.switchTab({ url: '../orderList/orderList' }) }, editBtn: function() { //完成 app.netWork.postJson(app.urlConfig.shopCarUpdateSupplierUrl, this.data.oneData).then(res => { console.log(res) if (res.errorNo == '0') { } }).catch(res => {}) this.setData({ showSupplier: false, oneData: [], showdel: false, }); console.log(this.data.oneData) // var data = { // } }, changeSupplier: function(e) { var _this = this; var item = e.currentTarget.dataset.item; var data = { product_id: item.id, page: '1', page_size: '10', } // console.log(item) app.netWork.postJson(app.urlConfig.productOfferUrl, data).then(res => { if (res.errorNo == '0') { _this.setData({ showSupplier: true, oneData: item, showdel: true, supplierData: res.data }) // console.log('购物车供应商列表') // console.log(res.data) } else { _this.setData({ oneData: item, }) } }).catch(res => {}) }, changeSelect: function(e) { //更改供应商 var _this = this; var oneprice = e.currentTarget.dataset.item.supply_price; var dataOne = e.currentTarget.dataset.item; this.data.supplierData.filter(function(item, i) { if (dataOne.id == item.id) { _this.data.supplierData[i].is_default = 1; _this.data.oneData.supplier_id = item.supplier_id; _this.data.oneData.supplier_name = item.supplier_name; _this.data.oneData.offer_name = item.offer_name; _this.data.oneData.offer_id = item.id; // _this.data.oneData.supply_price = item.supply_price; } else { _this.data.supplierData[i].is_default = 0; } }) var j = 0; //父级索引 var n = 0; //子级索引 this.data.shopData.filter(function(val, i) { val.son.filter(function(value, m) { if (_this.data.oneData.id == value.id) { return j = i, n = m; } }) }) this.data.shopData[j].price = this.data.shopData[j].price + (oneprice - this.data.oneData.supply_price) * this.data.oneData.nums; this.data.allPrice = this.data.allPrice + (oneprice - this.data.oneData.supply_price) * this.data.oneData.nums this.data.oneData.supply_price = oneprice; var up = "shopData[" + j + "].son[" + n + "]"; //先用一个变量,把(shopData var pirce = "shopData[" + j + "].price"; this.setData({ supplierData: this.data.supplierData, oneData: this.data.oneData, [up]: this.data.oneData, [pirce]: this.data.shopData[j].price, allPrice: this.data.allPrice }) } })
//commenting to see if this forces a push and a build on Travis var express = require('express'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var passport = require('passport'); var BasicStrategy = require('passport-http').BasicStrategy; mongoose.Promise = global.Promise; //instead of using mongoose lib, use node lib var User = require('./models/user'); var Message = require('./models/message'); var app = express(); var jsonParser = bodyParser.json(); //Basic strategy var stategy = new BasicStrategy(function(username, password, callback) { User.findOne({ username: username }, function(err, user) { if (err) { callback(err); return; } if (!user) { return callback(null, false, { message: 'Incorrect username.' }); } user.validatePassword(password, function(err, isValid) { if (err) { return callback(err); } if (!isValid) { return callback(null, false, { message: 'Incorrect password.' }); } return callback(null, user); }); }); }); passport.use(stategy); app.use(passport.initialize()); //API endpoints for USERS // Users can only see the list of usernames app.get('/users', passport.authenticate('basic', { session: false }), function(req, res) { console.log(typeof req.user.username); console.log(typeof req.user.password); User.find({}, function(err, users) { //blank obj means it searches for EVERYTHING if (err) { return res.status(err + 'basic authentication failed'); } var newUsersArray = []; users.forEach(function(user) { newUsersArray.push({_id: user._id, username: user.username}); }) res.json(newUsersArray); }); } ); app.post('/users', jsonParser, function(req, res) { if (!req.body) { return res.status(400).json({ message: "No request body" }) } if (!('username' in req.body)) { return res.status(422).json({ message: 'Missing field: username' }); } var username = req.body.username; if (typeof username !== 'string') { return res.status(422).json({ message: 'Incorrect field type: username' }); } username = username.trim(); if (username === '') { return res.status(422).json({ message: 'Incorrect field length: username' }); } if (!('password' in req.body)) { return res.status(422).json({ message: 'Missing field: password' }); } var password = req.body.password; if (typeof password !== 'string') { return res.status(422).json({ message: 'Incorrect field type: password' }); } password = password.trim(); if (password === '') { return res.status(422).json({ message: 'Incorrect field length: password' }); } bcrypt.genSalt(10, function(err, salt) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } bcrypt.hash(password, salt, function(err, hash) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } var user = new User({ username: username, password: hash }); user.save(function(err) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } // return res.status(201).json({}); console.log('Username and password created'); return res.status(201).location('/users/' + user._id).json({}); }); }) }); /* User.create({username: req.body.username}, function(err, user) { if(!req.body.username) { return res.status(422).json({'message': 'Missing field: username'}); } else if(typeof req.body.username !== 'string') { return res.status(422).json({'message': 'Incorrect field type: username'}) } res.status(201).location('/users/' + user._id).json({}); }); */ }); //after authorization, the user should only be able to see their own username, and password, and can only view other's username but not password app.get("/users/:userId", function(req, res) { var id = req.params.userId; User.findOne({ _id: id }, function(err, user) { if (!user) { //console.log("You made it! good job! :+1:"); return res.status(404).json({ "message": "User not found" }); } res.status(200).json({ "username": user.username, "_id": user._id }); }); }); //only the user can change his/her own username - lavie done app.put("/users/:userId", jsonParser, passport.authenticate('basic', { session: false }), function(req, res) { var id = req.params.userId, newName = req.body.username, newPassword = req.body.password, authenticatedId = req.user._id, type = req.body.type; if (id.toString() !== authenticatedId.toString()) { return res.status(422).json({ 'message': 'Unauthorized user' }); } if(type === "updateUsernamePassword") { bcrypt.genSalt(10, function(err, salt) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } bcrypt.hash(newPassword, salt, function(err, hash) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } User.findByIdAndUpdate( id, {username: newName.toString(), password: hash.toString()}, {upsert: true}, function(err, user) { res.status(200).json({}) }); }); }); } if(type === "updateUsername") { User.findByIdAndUpdate( id, {username: newName.toString()}, {upsert: true}, function(err, user) { res.status(200).json({}) } ); } if(type === "updatePassword") { bcrypt.genSalt(10, function(err, salt) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } bcrypt.hash(newPassword, salt, function(err, hash) { if (err) { return res.status(500).json({ message: 'Internal server error' }); } User.findByIdAndUpdate( id, {password: hash.toString()}, {upsert: true}, function(err, user) { res.status(200).json({}) }); }); }); }; }); //only the authenticated username can delete his/her own account app.delete("/users/:userId", jsonParser, function(req, res) { var id = req.params.userId; User.findOneAndRemove({ _id: id }, function(err, user) { if (!user) { return res.status(404).json({ 'message': 'User not found' }); } res.status(200).json({}); }); }); //API endpoints for MESSAGES app.get('/messages', passport.authenticate('basic', { session: false }), function(req, res) { var messages = []; var options = [{ path: 'from' }, { path: 'to' }]; var query = req.query; Message.find(query) .populate('from to') .exec(function(err, message) { return res.status(200).json(message); }); }); app.post('/messages', jsonParser, passport.authenticate('basic', { session: false }), function(req, res) { var fromId = req.user._id.toString(); var fromIdInput = req.body.from; if (!req.body.text) { return res.status(422).json({ "message": "Missing field: text" }); } else if (typeof(req.body.text) !== "string") { return res.status(422).json({ "message": "Incorrect field type: text" }); } else if (typeof(req.body.to) !== "string") { return res.status(422).json({ "message": "Incorrect field type: to" }); } if (fromId !== fromIdInput) { return res.status(422).json({ "message": "you can't steal another person's identication" }); } // else if(typeof(req.body.from) !== "string") { // console.log(req.body.from); // return res.status(422).json({"message": "Incorrect field type: from"}); // } User.findOne({ _id: req.body.to }) //checks if query passes(syntax errors only) .then(function(user) { //checks if user is found/not if (!user) return res.status(422).json({ message: 'Incorrect field value: to' }); User.findOne({ _id: req.body.from }); }) // .then(function(user) { //chain continues // if (!user) return res.status(422).json({ message: 'Incorrect field value: from'}); //have id = _id, and store all messages Message.create(req.body, function(err, message) { //console.log(message); if (err) { console.error(err); return res.sendStatus(500); } return res.status(201).location("/messages/" + message._id).json({}); }); }); //catch runs when there is query runs into an error // .catch(function(err){ // console.error(err); // return res.sendStatus(500); // }); // }); // app.get('/users', // passport.authenticate('basic', {session: false}), // function(req, res) { // User.find({}, function(err, user) { //blank obj means it searches for EVERYTHING // if(err) { // return res.status(err + 'basic authentication failed'); // } // res.json(user); // }); // } // ); app.get("/messages/:messageId", jsonParser, passport.authenticate('basic', { session: false }), function(req, res) { //authentication username should be able to see messages that he/she sent(from) or received(to) //this is the user id from the authentication var userId = req.user._id.toString(); var msgID = req.params.messageId; Message .findOne({ _id: msgID }) .populate('to from') .exec(function(err, message) { //these are the user id's from the message to and from based on found message var msgUserFromId = message.from._id.toString(); var msgUserToId = message.to._id.toString(); if (err) { console.error(err); return res.sendStatus(500); } if (!message) { return res.status(404).json({ "message": "Message not found" }); } //if the id from authentication matches either the sent or receiver //message will show if (userId === msgUserFromId || userId === msgUserToId) { return res.status(200).json(message); } //otherwise, return error return res.status(404).json({ "message": "Cannot retrieve unauthorized message" }); }); }); var runServer = function(callback) { var databaseUri = process.env.DATABASE_URI || global.databaseUri || 'mongodb://localhost/sup'; mongoose.connect(databaseUri).then(function() { var port = process.env.PORT || 8080; var server = app.listen(port, function() { console.log('Listening on localhost:' + port); if (callback) { callback(server); console.log('server running'); } }); }) .catch(function(err){ console.log(err) }); }; if (require.main === module) { runServer(); }; exports.app = app; exports.runServer = runServer;
$(function() { $.ajax({ type: 'GET', url: '/archillect', success: function(media) { for(let i = 0; i < media.length; i++) { if(media[i].type === 'image') { $('#image'+[i]).append("<a href=" + media[i].source + "><img src="+ media[i].url + "></img></a>") } if(media[i].type === 'video') { $('#image'+[i]).append("<a href=" + media[i].source + "><video autoplay loop><source src=" + media[i].url + " type='video/mp4'></video></a>") } } } }) })
'use strict'; const Plugin = require('broccoli-plugin'); const fs = require('fs'); const path = require('path'); const symlinkOrCopy = require('symlink-or-copy'); const symlinkOrCopySync = symlinkOrCopy.sync; module.exports = class ModuleNormalizer extends Plugin { constructor(input) { super([input], { persistentOutput: true, }); this._hasRan = false; } build() { if (this._hasRan && symlinkOrCopy.canSymlink) { return; } let symlinkSource; let modulesPath = path.join(this.inputPaths[0], 'modules'); if (fs.existsSync(modulesPath)) { symlinkSource = modulesPath; } else { symlinkSource = this.inputPaths[0]; } if (this._hasRan) { fs.unlinkSync(this.outputPath); } else { fs.rmdirSync(this.outputPath); } symlinkOrCopySync(symlinkSource, this.outputPath); this._hasRan = true; } }
import React, { Component } from 'react'; import { Jumbotron, Col } from 'react-bootstrap'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import { Redirect } from 'react-router-dom'; import axios from 'axios'; import "./Question.css"; import Report from './Report'; import Pagination from '../base/Pagination'; class Home extends Component { constructor() { super(); this.state = { questions: [], options:[], row:null, renderedQuestions: [], page: 1 } this.handlePageChange = this.handlePageChange.bind(this); } componentWillMount() { axios.get(`http://172.24.125.116:8000/api/question/user/question`).then(res => { this.setState({ questions: res.data, renderedQuestions:res.data.slice(0, 5), total: res.data.length }) }) } handlePageChange(page) { const renderedQuestions = this.state.questions.slice((page - 1) * 5, (page - 1) * 5 + 5); this.setState({page, renderedQuestions}); } componentDidMount() { if(localStorage.getItem("user_id")!==null && localStorage.getItem("admin")==="1") { this.props.history.push("/report"); } else { this.props.history.push("/"); } } render() { const { page, total } = this.state; const options = { onRowClick:(row)=> { this.setState( { row:row._id, options:row.option, question:row.question, endDate:row.end_date } ) this.props.history.push(`/report/${row._id}`); }, onRowDoubleClick:(row)=> { this.setState( { row:row._id, options:row.option, question:row.question, endDate:row.end_date } ) this.props.history.push(`/report/${row._id}`); } }; if((localStorage.getItem("user_id")!=null) && (localStorage.getItem("admin")==="1")) { if(this.state.row==null) { return ( <div className="Home" > <Jumbotron> <Col xsOffset={5} smOffset={5}> <h1>Report</h1> </Col> </Jumbotron> <BootstrapTable data={ this.state.renderedQuestions } options={ options } hover > <TableHeaderColumn dataField='_id' isKey > Question Id </TableHeaderColumn> <TableHeaderColumn dataField='question' filter={ { type: 'TextFilter', delay: 1000 } } dataSort> Question </TableHeaderColumn> <TableHeaderColumn ref='count' dataField='TotalCount' filter={ { type: 'TextFilter', delay: 1000 } } dataSort> User Attended </TableHeaderColumn> </BootstrapTable> <Pagination margin={2} page={page} count={Math.ceil(total / 5)} onPageChange={this.handlePageChange}/> </div> ); } else { return( <div> <Report row={this.state.row} options={this.state.options} question={this.state.question} endDate={this.state.endDate}/> </div> ); } } else { return( <Redirect to="/"/> ); } } } export default Home;
import { get as g } from 'lodash'; import { createSelector } from 'reselect'; export const getAccountsByIds = state => g(state, 'accounts.accountsByIds', []); export const getAccountsEntities = state => g(state, 'accounts.accounts', {}); export const getAccounts = createSelector( getAccountsByIds, getAccountsEntities, (ids, accounts) => ids.map(id => accounts[id]) );
import Contact from '../../../../../models/im/contact' import Relation from '../../../../../models/im/relation' import { tableColumnsByDomain } from '../../../../../scripts/utils/table-utils' import { constantText, longText } from '../../../../../scripts/utils/table-renders' import { buttonActions } from '../../../../../scripts/utils/table-renders' import Constant from '../../../../../configs/constant' import { parseUrl } from '../../../../../scripts/utils/url' const { query } = parseUrl(location.href, true) const profilePlatformUid = query.platformUid const width = App.options.styles.table.width const actions = [ { 'delete': { title: '删除', icon: '', type: 'info', onAction: ($table, { row }) => { App.modal({ title: '确认删除', width: 400, content: '确认,则该好友将从微信上删除?', loading: true, onOk: async(view, $modal) => { try { await Relation.deleteFriend(profilePlatformUid, row.platformUid, row.serviceID) $table.load() App.removeModal() this.$Notice.success({ title: '操作成功!' }) } catch (error) { $modal.cancelLoading() } } }) } }}, { 'viewDup': { title: '重复详情', type: 'info', scrollable: true, onAction($list, { row }) { // console.log($list) App.modal({ width: 800, title: '重复好友 - 运营号列表', okText: '关闭', render: h => { h = this.$root.$createElement return <duplicate-contact contact={row}></duplicate-contact> } }) } }} ] const options = { 'avatar': { width: width.w_12, align: 'center', render(h, context) { const url = context.row.avatar return <im-avatar url={ url }></im-avatar> } }, 'customID': { width: width.w_12, render(h, context) { return <span>{context.row.customID || context.row.platformUid}</span> } }, 'nickname': { width: width.w_12 }, 'signature': { width: width.w_13, ellipsis: true, render(h, context) { const signature = context.row.signature return longText.call(this, h, context, signature, true) } }, 'gender': { width: width.w_12, render(h, context) { const value = context.row.gender || 0 return constantText.call(this, h, context, value, Constant.Gender) } }, 'country': { width: width.w_10 }, 'state': { width: width.w_12 }, 'city': { width: width.w_12 }, 'ctime': { width: width.datetime, render(h, context) { const ctime = dateformat(new Date(context.row.ctime), 'yyyy-mm-dd HH:MM:ss') return <span>{ctime}</span> } }, _actions: actions.length > 0 ? { title: '操作', after: 'nickname', width: width[`label_actions_${actions.length + 1}`], render(h, context) { return buttonActions.call(this, h, context, Contact, actions) } } : false } export default tableColumnsByDomain(Contact, options)
import React, { useState, useEffect } from "react"; import "./burgerapp.css"; import firebase from "../firebase"; function BurgerApp() { const [task, setTask] = useState(""); const [tasklist, setTaskList] = useState([]); const [idOfUpdate, setIdOfUpdate] = useState(null); const [truth, setTruth] = useState(); const handleChange = (e) => { setTask(e.target.value); }; useEffect(() => { populate(); }, []); useEffect(() => { let id = idOfUpdate; if (id !== null) { markCompleteGlobal(); } }, [truth]); /////////////////////////////////////// const AddTask = () => { const datas = { id: firebase .firestore() .collection("burgers") .doc().id, }; const db = firebase.firestore(); db.collection("burgers") .doc(datas.id) .set({ task: task, completed: false, id: datas.id,value: task }) .then(() => { populate(); }) }; const populate = (data) => { setTaskList([]); return firebase .firestore() .collection("burgers") .get() .then(function(querySnapshot) { querySnapshot.forEach(function(doc) { let newData = doc.data(); if (tasklist.indexOf(newData.id) === -1) { setTaskList((arr) => { return [...arr, newData]; }); } }); }) }; /////////////////////////////////////////////////////////// const taskCompleted = (e,id) => { e.preventDefault(); debugger setIdOfUpdate(id); setTaskList( tasklist.map((task) => { if (task.id === id) { task.completed = !task.completed; setTimeout(function() { setTruth(task.completed); }, 1000); } return task; })) }; const markCompleteGlobal = () => { let id = idOfUpdate; const itemtoupdate = firebase .firestore() .collection("burgers") .doc(id) itemtoupdate.update({ completed: truth, }) setIdOfUpdate(null); setTruth(null); }; /////////////////////////////////////////////////////////// const deletetask = (e,id) => { e.preventDefault(); const db = firebase.firestore(); db.collection("burgers") .doc(id) .delete() .then(() => { console.log("Document successfully deleted!", id); }) .catch((error) => { console.error(id, "Error removing document: ", error); }) .then((res) => setTaskList([...tasklist.filter((task) => task.id !== id)])); console.log(id, "here is an id", id); }; /////////////////////////////////////////////////////////// return ( <div className="todo"> <h1>Burgers Made</h1> New Burger : <input type="text" name="text" id="text" onChange={(e) => handleChange(e)}/> <button className="add-btn" onClick={AddTask}>Make it</button> <br /> <div>{task.value}</div> <br /> {tasklist !== [] ? ( <div> {tasklist.map((task) => (!task.completed ? <div>{task.value} Burger <button className="completed" onClick={(e) => taskCompleted(e, task.id)}> Eat it!! </button></div> : null ))} </div> ) : null} <h1>Burgers Eaten</h1> {tasklist !== [] ? ( <div> {tasklist.map((task) => (task.completed ? <div><br></br>{task.value} Burger<button className="delete" onClick={(e) => deletetask(e, task.id)}> Delete it!</button></div> : null ))} </div> ) : null} </div> ); } // export default BurgerApp;
import {connect} from 'react-redux' import {fetchSalesData} from '../../../actions' import DelayedSelector from '../../../components/delayed-selector' //redux mapping to store const mapStateToProps = state => { const {seasons:items, season:selected} = state return { items, selected } } //redux mapping to actions const mapDispatchToProps = (dispatch) => { return { onItemSelect: (season) => { dispatch(fetchSalesData(season)) } } } export default connect(mapStateToProps, mapDispatchToProps)(DelayedSelector)
import React, {Component} from 'react' import {connect} from 'react-redux' import { SearchUser } from './requests' import { SET_USER_LIST, SET_PAGE, SET_COMPLETED, RESET_SEARCH } from './reducer' import ResultList from './components/resultList/' import Header from './components/header/' export class Search extends Component { constructor(props){ super(props) } async componentDidMount(){ const {match: {params: {query}}, term, reset} = this.props if(term != query) { reset(query) await this.load(query) } } async load(query){ const {setUsers, setPage, setCompleted} = this.props if(query){ setPage(1) const response = (await SearchUser(query, 1)).data setUsers(response.items, response.total_count) setCompleted((response.total_count == response.items.length)) } else { const {page: currentPage, users, done, term} = this.props if(done) return setPage(currentPage + 1) const response = (await SearchUser(term, currentPage + 1)).data setUsers(response.items, response.total_count) setCompleted((response.total_count ==users.length + response.items.length)) } } render(){ const { users, total, done, loading, term} = this.props const loadMore = () => this.load() return ( <div> <Header term={term} total={total} /> <ResultList done={done} loading={loading} users={users} loadMore={loadMore} /> </div> ) } } export default connect( (state) => ({...state.search}), (dispatch) => ({ reset: (term) => dispatch({type: RESET_SEARCH, term}), setUsers: (users, total) => dispatch({type: SET_USER_LIST, value: users, total}), setPage: (page) => dispatch({type: SET_PAGE, value: page}), setCompleted: (state) => dispatch({type: SET_COMPLETED, value: state}) }) )(Search)
(() => { 'use strict'; angular .module('radarApp') .config([ '$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => { $stateProvider .state('home', { url: '/', templateUrl: '../templates/home/home.html' }) .state('report', { url: '/report', templateUrl: '../templates/report/report.html' }) .state('errorCanvasNotSupported', { url: '/errorCanvasNotSupported', templateUrl: '../templates/errors/error-canvas-not-supported.html' }); $urlRouterProvider.otherwise('/'); } ]); })();
import styled, { css } from "styled-components"; export default styled.span` padding: 0.25rem 0.5rem; font-size: var(--fs-small); color: var(--coror-text-gray); border: 1px solid var(--color-gray); border-radius: var(--br); background-color: var(--color-plain); cursor: pointer; margin-right: 0.25rem; &:hover, &:focus { background-color: white; } ${(props) => props.light && css` background-color: white; &:hover, &:focus { background-color: var(--color-plain); } `} `;
/** * input 的验证属性,当输入元素上面有ng-pattern的时候,该标签起作用 */ app.directive("patternStyle",[function(){ return { restrict:"A", replace:true, scope:{ formInput:'=', inputMessage:'=' }, template:'<div class="inputerror" ng-show="formInput.$invalid">\ <span class="glyphicon glyphicon-warning-sign" ></span> : <span ng-show="formInput.$error.pattern">{{inputMessage.pattern}};</span>\ <span ng-show="formInput.$error.required&&inputMessage.required">{{inputMessage.required}};</span><span ng-show="formInput.$error.required&&!inputMessage.required">{{defaultRequiredMessage}};</span>\ <span ng-show="formInput.$error.minlength&&inputMessage.minlength">{{inputMessage.minlength}};</span><span ng-show="formInput.$error.minlength&&!inputMessage.minlength">{{defaultMinLengthMessage}};</span>\ <span ng-show="formInput.$error.maxlength&&inputMessage.maxlength">{{inputMessage.maxlength}};</span><span ng-show="formInput.$error.maxlength&&!inputMessage.maxlength">{{defaultMaxLengthMessage}};</span>\ <span ng-show="formInput.$error.email&&inputMessage.email">{{inputMessage.email}};</span><span ng-show="formInput.$error.email&&!inputMessage.email">{{defaultEamilMessage}};</span>\ <span ng-show="formInput.$error.min&&inputMessage.min">{{inputMessage.min}};</span><span ng-show="formInput.$error.min&&!inputMessage.min">{{defaultMinMessage}};</span>\ <span ng-show="formInput.$error.max&&inputMessage.max">{{inputMessage.max}};</span><span ng-show="formInput.$error.max&&!inputMessage.max">{{defaultMaxMessage}};</span>\ <span ng-show="formInput.$error.number&&inputMessage.number">{{inputMessage.number}};</span><span ng-show="formInput.$error.number&&!inputMessage.number">{{defaultNumberMessage}};</span>\ <span ng-show="formInput.$error.custom_pattern&&inputMessage.custom_pattern">{{inputMessage.custom_pattern}};</span>\ </div>', link:function(scope,ele,attr){ scope.defaultRequiredMessage = "字段不能为空"; scope.defaultEamilMessage = "必须为邮箱格式"; scope.defaultNumberMessage = "必须为数字格式"; if(ele.prev().attr("ng-minlength")){ scope.defaultMinLengthMessage = "该字段不能少于"+ele.prev().attr("ng-minlength")+"个字符"; } if(ele.prev().attr("ng-maxlength")){ scope.defaultMaxLengthMessage = "该字段不能大于"+ele.prev().attr("ng-maxlength")+"个字符"; } if(ele.prev().attr("min")){ scope.defaultMinMessage = "输入的值不能小于"+ele.prev().attr("min"); } if(ele.prev().attr("max")){ scope.defaultMaxMessage = "输入的值不能大于"+ele.prev().attr("max"); } } }; }]);
import React from "react"; import { connect } from "react-redux"; import { createStructuredSelector } from "reselect"; import { selectCartItems, selectCartItemsCount, selectIsHidden, selectIsHiddenTriangle, } from "../../redux/cart/cart.selectors"; import { showCart, hideCart, showTriangle, hideTriangle, } from "../../redux/cart/cart.actions"; import { CartContainer, CartIconContainer, CartCounter, TriangleContainer, } from "./cart.styles"; import { ReactComponent as CartIcon } from "../../assets/cart.svg"; import { showCartDropdown, hideCartDropdown, } from "../../redux/cart/cart.utils"; const Cart = ({ count, isHidden, isHiddenTriangle, showCartAction, hideCartAction, showTriangle, hideTriangle, }) => { const showCart = () => { if (isHiddenTriangle) showTriangle(); showCartAction(); showCartDropdown(); }; const hideCart = () => { hideTriangle(); hideCartAction(); hideCartDropdown(); }; return ( <CartContainer> <CartIconContainer onMouseOver={() => { if (!isHidden) return; showCart(); }} onMouseLeave={() => hideCart()} > <CartCounter>{count}</CartCounter> <CartIcon className="cart-icon" title="Cart" /> </CartIconContainer> <TriangleContainer onMouseOver={() => showCart()} onMouseLeave={() => hideCart()} > <div className={`cart-triangle ${ !isHiddenTriangle ? "visible-triangle" : "" }`} ></div> </TriangleContainer> </CartContainer> ); }; const mapStateToProps = createStructuredSelector({ items: selectCartItems, count: selectCartItemsCount, isHidden: selectIsHidden, isHiddenTriangle: selectIsHiddenTriangle, }); const mapDispatchToProps = (dispatch) => ({ showCartAction: () => dispatch(showCart()), hideCartAction: () => dispatch(hideCart()), showTriangle: () => dispatch(showTriangle()), hideTriangle: () => dispatch(hideTriangle()), }); export default connect(mapStateToProps, mapDispatchToProps)(Cart);
const { DataTypes, Model } = require('sequelize'), sequelize = require('../Sequelize Config'), call_center_info = require('./call_center_info'), call_center_compaign = require('./call_center_compaign_info'), did_Number_info_Modal = require('./did_Number_info') class call_cent_employee extends Model { } call_cent_employee.init({ emp_id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true, validate: { max: 11 } }, emp_fullName: { allowNull: false, type: DataTypes.TEXT }, emp_username: { allowNull: false, type: DataTypes.TEXT }, emp_email: { allowNull: false, type: DataTypes.TEXT }, emp_password: { allowNull: false, type: DataTypes.TEXT }, emp_role: { allowNull: false, type: DataTypes.TEXT }, emp_timing: { allowNull: false, type: DataTypes.TEXT }, emp_salary: { allowNull: false, type: DataTypes.TEXT }, emp_commission: { allowNull: false, type: DataTypes.TEXT }, emp_target: { allowNull: false, type: DataTypes.INTEGER }, emp_deleted: { allowNull: false, type: DataTypes.BOOLEAN, defaultValue: false }, emp_isPaused: { allowNull: false, type: DataTypes.BOOLEAN, defaultValue: false }, emp_profile_pic: { allowNull: true, type: DataTypes.TEXT }, call_cent_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: "call_center_info", key: "call_cent_id" } }, compaign_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: "call_cent_compaign_info", key: "compaign_id" } }, did_Num_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: "did_Number_Info_modal", key: "did_Num_id" } } }, { freezeTableName: true, updatedAt: false, createdAt: false, sequelize, modelName: 'call_cent_employee', tableName: 'call_center_employees', }) //creating one to many relationship of // call center have many employees call_center_info.hasMany(call_cent_employee, { foreignKey: 'call_cent_id' }) call_cent_employee.belongsTo(call_center_info, { foreignKey: 'call_cent_id', targetKey: 'call_cent_id' }) //creating relationship of call center compaigns // one compaign have many employees call_center_compaign.hasMany(call_cent_employee, { foreignKey: 'compaign_id' }) call_cent_employee.belongsTo(call_center_compaign, { foreignKey: 'compaign_id' }) /** * Creating One to One Relationship with the * DID Number because one employee can only have access * to one DID Number */ did_Number_info_Modal.hasOne(call_cent_employee, { foreignKey: "did_Num_id" }) call_cent_employee.belongsTo(did_Number_info_Modal, { targetKey: "did_Num_id", foreignKey: "did_Num_id" }) module.exports = call_cent_employee
$( document ).ready(function(){ var txt = '{"item_info":[' + '{"src":"../img/default.jpg","type":"实体卡", "quantity":"99", "value":"¥100", "off":"10%", "price":"¥90", },' + '{"src":"../img/default.jpg","type":"实体卡", "quantity":"89", "value":"¥100", "off":"10%", "price":"¥90", },' + '{"src":"../img/default.jpg","type":"实体卡", "quantity":"79", "value":"¥100", "off":"10%", "price":"¥90", },' + '{"src":"../img/default.jpg","type":"实体卡", "quantity":"69", "value":"¥100", "off":"10%", "price":"¥90", },' + ']}'; var obj = eval ("(" + txt + ")"); for (var i in obj.item_info) { var src=obj.item_info[i].src; var type=obj.item_info[i].type; var quantity=obj.item_info[i].quantity; var value=obj.item_info[i].value; var off=obj.item_info[i].off; var price=obj.item_info[i].price; part1 = "<tr data-index=\""+i+"\"><td style=\"text-align: center; \"><div style=\"background-size: 100% auto; width:69px;\">"; part1 +="<img src=\""; part1 +=src; part1 +="\" width=\"69\" height=\"43\">"; part1 +="</div></td><td><div class=\"cardtags text-center\"><span class=\"online-only\" style=\"border:2px solid #3c4d67!important;\">"; part1 += type; part1 += "</span></div></td><td>"; part1 += quantity; part1 += "</td><td>"; part1 += value; part1 += "</td><td>"; part1 += off; part1 += "</td><td>"; part1 += price; part1 += "</td><td><button type=\"button\" class=\"btn btn-sm btn-success add-to-cart disableBtn\" "; //part1 += "onclick=\"buyCar('22',this,'184','10','cardQty-0','','1','','1')\">ADD TO CART</button></td></tr>"; part1 += "onclick=\"buyCar()\">ADD TO CART</button></td></tr>"; //$("#tbody_show").append(part1); } // $("button:contains('ADD TO CART')").click(function(){ // var row =this.parentNode.parentNode; // alert(row.rowIndex + " qty is "+row.cells[2].innerHTML); // }); }); jQuery(document).ready(function($){ fetchCartStatus(); $("#myTable").tablesorter(); $("#myTable thead th").click(function(){ $(".showdetail").remove(); var html = ''; html += '<tr class="showdetail">'; html += '<td colspan="7">'; html += '<h4>Delivery & Redemption</h4>'; html += '<ul class="unstyled">'; html += '<li>This eGift card can be redeemed online.</li>'; html += '<li>This printable voucher can be redeemed on location.</li>'; html += '<li>This eGift + voucher will be delivered to your Card Cash account within 24 hours.</li>'; html += '<li>Please note, items purchased with a Home Depot gift card are final sale. </li> '; html += '</ul>'; html += '</td>'; html += '</tr>'; var numTr = 1; var totaltr = 0; $("#myTable tbody tr").each(function(){ totaltr++; }) console.log("count",totaltr); setTimeout(function(){ for(var i = 0; i< totaltr; i++) { $("table tbody tr:nth-child("+numTr+")").after(html) numTr = numTr+2; } },100) }); }); function sortByPrice(mName, sort){ //alert(mName + '>>' +sort); window.location = '/buy-gift-cards/discount-' + mName.toLowerCase() + "-cards/?price=" + sort + '/' ; } function SortByType(mName, type){ window.location = '/buy-gift-cards/discount-' + mName.toLowerCase() + "-cards/?type=" + type + '/' ; } jQuery(document).ready(function($){ $('.filterable .filters input').keyup(function(e){ var code = e.keyCode || e.which; if (code == '9') return; var $input = $(this), inputContent = $input.val().toLowerCase(), $panel = $input.parents('.filterable'), column = $panel.find('.filters td').index($input.parents('td')), $table = $panel.find('.table'), $rows = $table.find('tbody tr'); var $filteredRows = $rows.filter(function(){ var value = $(this).find('td').eq(column).text().toLowerCase(); return value.indexOf(inputContent) === -1; }); $table.find('tbody .no-result').remove(); $rows.show(); $filteredRows.hide(); if($filteredRows.length === $rows.length) $table.find('tbody').prepend($('<tr class="no-result text-center"><td colspan="'+ $table.find('.filters th').length +'">No result found</td></tr>')); }); }); function setPercent(value) { return value+'%'; } function setValue(value) { var actualValue = parseFloat(value).toFixed(2) return '$'+actualValue; } function cardType(value) { var displayNameHtml = '<div class="cardtags text-center">'; if(value){ displayNameHtml+='<span class="online-only">'+value+'</span></div>'; } return displayNameHtml; } function setPrice(value,row) { var cashValue = parseFloat(row.value-(((row.value)/100)*row.percent)).toFixed(2); return '$'+cashValue; } function imgDate(){ if('merchants/AMC-Theaters.png') { var imageName = 'merchants/AMC-Theaters.png'; imageName = imageName.replace('merchants', ''); imageName = imageName.replace('/', ''); } else { var imageName = 'empity_img.png'; } return '<div style="background-image: url(\'https://s3.amazonaws.com/new-cardcash-images/images/merchants/'+imageName+'\');background-size: 100% auto; width:69px;"><img src="https://s3.amazonaws.com/new-cardcash-images/images/merchants/'+imageName+'" width="69" height="43" />'; } function setAddToCart(val,row,index) { if(row.qty>0){ var disableB ='disableBtn'; } var addToCartHtml = '<button type="button" class="btn btn-sm btn-success add-to-cart '+disableB+'" onclick="buyCar(\''+row.percent+'\',this,\''+row.merchant_id+'\',\''+row.value+'\',\'cardQty-'+index+'\',\'\',\'1\',\'\',\''+row.card_type+'\')">ADD TO CART</button>'; return addToCartHtml = addToCartHtml; } function smallView(val,row,index) { var actualValue = parseFloat(row.value).toFixed(2) console.log("smallView", actualValue); if('merchants/AMC-Theaters.png') { var imageNameSmall = 'merchants/AMC-Theaters.png'; imageNameSmall = imageNameSmall.replace('merchants', ''); imageNameSmall = imageNameSmall.replace('/', ''); } else { var imageNameSmall = 'empity_img.png'; } var cashValueSmall = parseFloat(row.value-(((row.value)/100)*row.percent)).toFixed(2); if(row.card_display_name) { var displayNameHtmlSmall='<div> <span class="cart-online-only3">'+row.card_display_name+'</span></div>'; } if(row.qty>0) { var disableB ='disableBtn'; } var addToCartHtmlSmall = '<button type="button" style="padding:5px" class="btn btn-sm btn-success add-to-cart '+disableB+'" onclick="buyCar(\''+row.percent+'\',this,\''+row.merchant_id+'\',\''+row.value+'\',\'cardQty-'+index+'\',\'\',\'1\',\'\',\''+row.card_type+'\')">ADD TO CART</button>'; var viewHtml = '<div class="row_small"><div class="col-xs-3"><img style="max-width:187px;width:100%; height:auto;margin-top: 8px;" class="card-image" src="https://s3.amazonaws.com/new-cardcash-images/images/merchants/'+imageNameSmall+'"></div>'; viewHtml+='<div class="col-xs-5"><div class="price_small">$'+actualValue+' for <strong>$'+cashValueSmall+'</strong></div>'; viewHtml+=displayNameHtmlSmall; viewHtml+='</div><div class="col-xs-4 text-center"><div class="m_b5"><strong>QTY:</strong><span class="cardQty-'+index+'">'+row.qty+'</span></div>'; viewHtml+=addToCartHtmlSmall; viewHtml+='</div></div>'; return viewHtml; } function checkQty(value,row,index) { return '<span class="cardQty-'+index+'">'+value+'</span>'; }
export default { // Providers messages unable_to_connect: 'We were unable to connect to wallet provider', connect_rejected: 'You rejected connection to the wallet', metamask_unlock: 'Please unlock your MetaMask first', metamask_account: 'We were unable to access your wallet address', };
; (() => { const URL = window.location.href const idStr = 'method_id' const PageItemName = 'ProcessMethod' let isSubmitting = false const targetId = +URL.split('/')[URL.split('/').length - 1] // const table = document.getElementById('customer-input-form') const input = document.querySelector('input') const textareaList = document.querySelectorAll('textarea') const submitBtn = document.getElementById('btn-submit') const deleteBtn = document.getElementById('btn-delete') const title = document.querySelector('.title') let data = {} let handleSubmit = null const loadInputToData = () => { data[input.name] = input.value textareaList.forEach((e) => { data[e.name] = e.value }) } const createItem = () => { isSubmitting = true console.log('add customer') loadInputToData() if (!input.value) { const form = input.closest('.form-group') form.scrollIntoView() form.classList.toggle('has-error') setTimeout(() => { alert('請輸入顧客代號') form.classList.toggle('has-error') isSubmitting = false }, 500) return } console.log(data) $.ajax({ url: '/processMethods/create', type: 'POST', data, dataType: 'json', success (json) { console.log('success') isSubmitting = false }, fail (json) { console.log('fail') isSubmitting = false }, }) } const updateItem = ({ id }) => { isSubmitting = true console.log('update') loadInputToData() if (!input.value) { const form = input.closest('.form-group') form.scrollIntoView() form.classList.toggle('has-error') setTimeout(() => { alert('請輸入加工方式') form.classList.toggle('has-error') isSubmitting = false }, 500) return } console.log(data) $.ajax({ url: `/processMethods/update/${id}`, type: 'POST', data, dataType: 'json', success (json) { console.log('success') isSubmitting = false }, fail (json) { console.log('fail') isSubmitting = false }, }) } const deleteItem = ({ id }) => { isSubmitting = true console.log('delete') console.log(data) $.ajax({ url: `/processMethods/delete/${id}`, type: 'GET', dataType: 'json', success (json) { console.log('success') isSubmitting = false }, fail (json) { console.log('fail') isSubmitting = false }, }) } const getItem = ({ id }) => { $.ajax({ url: `/processMethods/${id}`, type: 'GET', dataType: 'json', success (json) { const result = json.results[0] data[input.name] = result[input.name] input.value = data[input.name] textareaList.forEach((e, i) => { const { name } = e data[name] = result[name] e.value = data[name] }) }, fail (json) { console.log('fail') }, }) } if (targetId) { // update customer const str = '更新加工方式' title.innerText = str submitBtn.innerText = str getItem({ id: targetId }) handleSubmit = () => { updateItem({ id: targetId }) } } else { // open input // create customer deleteBtn.style.display='none' handleSubmit = () => { createItem() } } deleteBtn.onclick = () => { if (isSubmitting) return deleteItem({ id: targetId }) } submitBtn.onclick = function (e) { if (isSubmitting) return handleSubmit() } document.getElementById('btn-cancel').onclick = function () { location.href = `/pages/Dashboard_${PageItemName}.html` } })()
var isiPhone = !!navigator.userAgent.match(/[iPhone|iPad|iPod].*Mobile/); var isAndroid = !!navigator.userAgent.match(/[Android].*Mobile/); /* * -------------------------------------------------- * Const * -------------------------------------------------- */ var ROW = 30; var COL = 30; var OBJ_DISTANCE = 30; var SIZE_X = 3 * 12; var SIZE_Y = 4 * 12; var GOLDEN_PROBABILITY = 200; // 1/200 var namekoSrc = "./nameko.png" var goldenSrc = "./golden.png" /* * -------------------------------------------------- * Global * -------------------------------------------------- */ var shiftX; var shiftY var arObj; var namekoNum = 0; /* * -------------------------------------------------- * Object * -------------------------------------------------- */ function _Object(_id, _x, _y) { this.id = _id; this.x = _x; this.y = _y; this.isAnimation = false; this.onMouse = false; } /* * -------------------------------------------------- * Event * -------------------------------------------------- */ function onLoad() { if (isiPhone) { document.addEventListener("touchmove", onMouseMove, false); document.addEventListener("touchstart", onMouseDown, false); //window.parent.document.addEventListener("orientationchange", onResize, false); } else { document.onmousemove = onMouseMove; document.onmousedown = onMouseDown; //document.onmouseout = onMouseOut; window.parent.onresize = onResize; } $("#footer").hide(); $("#footer").css({"color": "#777"}); $("#footer a").css({"color": "#777"}); setTimeout(function(){ $("#footer").fadeTo(1000, 1.0); }, 5000); $("<div />"). attr("id", "txt"). css({"fontSize":10, "textAlign":"center"}). appendTo("#main"); createObj(); } function onMouseMove(e) { onMouseDown(e); } function onMouseDown(e) { // サウンド再生 var mouseX = getMouseX(e); var mouseY = getMouseY(e); var objWidth = shiftX + COL*OBJ_DISTANCE; var objHeight = shiftY + ROW*OBJ_DISTANCE; if (mouseX>shiftX && mouseX<objWidth && mouseY>shiftY && mouseY<objHeight) { var x = Math.floor((mouseX - shiftX) / OBJ_DISTANCE); var y = Math.floor((mouseY - shiftY) / OBJ_DISTANCE); var obj = arObj[x][y]; if (!obj.isAnimation) { if(isAndroid) { android_sound.playPanchi(); } obj.isAnimation = true; var id = "#" + obj.id; $(id).animate({height:"+=20", top:"-=20"}, "fast"); $(id).animate({height:"-=25", top:"+=5"}, "fast"); $(id).animate({height:"+=5"}, "fast"); $(id).animate({ width:"hide", height:"hide", top:0, left:0 }, "normal"); $(id).animate({top:obj.y+SIZE_Y/2, left:obj.x+SIZE_X/2}, "fast", function(){ var n = Math.floor( Math.random() * GOLDEN_PROBABILITY ); $(id).attr("src", n == 1 ? goldenSrc : namekoSrc); } ); $(id).animate({ width:"show", height:"show",top:obj.y, left:obj.x}, "normal", function(){ obj.isAnimation = false; if(isAndroid) { android_sound.playHow(); } } ); } } } function onResize() { $("#main").empty(); onLoad(); } /* * -------------------------------------------------- * Function * -------------------------------------------------- */ function createObj() { shiftX = Math.round((document.body.clientWidth - COL*OBJ_DISTANCE)/2); shiftY = 0; arObj = new Array(); for (var i=0; i<COL; i++) { arObj[i] = new Array(); for (var j=0; j<ROW; j++) { var obj_id = "obj_" + i + "_" + j; var posX = i*OBJ_DISTANCE + shiftX; var posY = j*OBJ_DISTANCE + shiftY; createImg(obj_id, posX, posY); arObj[i][j] = new _Object(obj_id, posX, posY); } } } function createImg(_id, _x, _y) { $("<img />"). attr("id", _id). attr("src", namekoSrc). css({"position":"absolute", "top":_y, "left":_x, "width":SIZE_X, "height":SIZE_Y}). appendTo("#main"); } /* * -------------------------------------------------- * CommonFunction * -------------------------------------------------- */ function getMouseX(e) { if (isiPhone) { e.preventDefault(); return e.touches[0].pageX; } else { return (document.all) ? event.clientX : e.pageX; } } function getMouseY(e) { if (isiPhone) { e.preventDefault(); return e.touches[0].pageY; } else { return (document.all) ? event.clientY : e.pageY; } }
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ /** * Makes an element draggable. */ define([ 'jquery', 'util/Event', 'util/PubSub' ], function ($, Event, PubSub) { 'use strict'; var Draggable = function (selector) { this.draggable = $(selector); this.offX = this.offY = 0; this.startCoords = null; this.draggable[0].addEventListener(Event.eventName('start'), this.onDragStart.bind(this)); }; Draggable.prototype.onDragStart = function (event) { var draggableEl = this.draggable[0], pos = this.draggable.css(['left', 'top']), locEvent = Event.getLocEvent(event); this.startCoords = { x: locEvent.clientX, y: locEvent.clientY }; this.offX = locEvent.pageX - (parseInt(pos.left, 10) || draggableEl.offsetLeft); this.offY = locEvent.pageY - (parseInt(pos.top, 10) || draggableEl.offsetHeight); this.onDragProxy = this.onDragProxy || this.onDrag.bind(this); this.onDragEndProxy = this.onDragEndProxy || this.onDragEnd.bind(this); document.addEventListener(Event.eventName('move'), this.onDragProxy, false); document.addEventListener(Event.eventName('end'), this.onDragEndProxy, false); }; /** * Always preventDefault to stop the whole page from scrolling on the device. */ Draggable.prototype.onDrag = function (event) { var locEvent = Event.getLocEvent(event); event.preventDefault(); if (this.dragging || !Event.inThreshold(locEvent, this.startCoords)) { this.dragging = true; this.draggable.css({ 'left': locEvent.pageX - this.offX, 'top': locEvent.pageY - this.offY }); } }; Draggable.prototype.onDragEnd = function (event) { if (this.dragging) { event.preventDefault(); this.dragging = false; PubSub.publish('draggable.dragend', this.draggable[0]); } this.offX = this.offY = 0; this.startCoords = null; document.removeEventListener(Event.eventName('move'), this.onDragProxy); document.removeEventListener(Event.eventName('end'), this.onDragEndProxy); }; function create(selector) { return new Draggable(selector); } return { create: create }; });
const input = document.querySelector("#data"); const btn = document.querySelector("#submit"); const p = document.querySelectorAll("div.scores p"); const allP = [...p]; const img = document.querySelector("img"); const showText = document.querySelector("p.showtext"); const API = "https://api.openweathermap.org/data/2.5/weather"; const pictures = { clouds: "images/cloud.png", drizzle: "images/drizzle.png", fog: "images/fog.png", ice: "images/ice.png", rain: "images/rain.png", sun: "images/sun.png", thunderstorm: "images/thunderstorm.png", clear: "images/unknown.png", mist: "images/unknown.png", }; const getData = async (city) => { const useAxios = await axios.get(API, { params: { q: city, units: "metric", appid: "6902aee046e845d62fe8779cdd3683d4", }, }); showText.textContent = useAxios.data.name; const { temp, humidity } = useAxios.data.main; allP[1].textContent = Math.round(temp) + " ℃"; allP[2].textContent = humidity + "%"; const currentWeather = useAxios.data.weather[0].main.toLowerCase(); allP[0].textContent = currentWeather; img.src = pictures[currentWeather]; }; const getCurrentData = (e) => { if (e.key === "Enter") { getData(e.target.value); e.target.value = ""; } }; input.addEventListener("keydown", getCurrentData); btn.addEventListener("click", function () { getData(input.value); input.value = ""; });
/** * @file productHeader.js * * @description: Contains the header of main view including the back button, main CECOTEC label * and shop button * * @todo Shop button does not work. Requires an implementation. */ import React from 'react'; import {View, StyleSheet, TouchableOpacity, Text} from 'react-native'; //ICONS import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; const ProductHeader = ({theme, category, nav}) => { //INLINE STYLES const textHeaderInline = { color: theme.colors.text, }; return ( <View style={styles.container}> <View style={styles.row}> <TouchableOpacity style={styles.iconContainer} onPress={() => nav.goBack()}> <MaterialCommunityIcons name={'keyboard-backspace'} size={30} color={theme.colors.text} style={styles.icon} /> </TouchableOpacity> <Text style={[styles.headerText, textHeaderInline]}>{category}</Text> <TouchableOpacity style={styles.iconContainer}> <MaterialCommunityIcons name={'shopping-outline'} size={30} color={theme.colors.text} style={styles.icon} /> </TouchableOpacity> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 0.12, justifyContent: 'flex-end', }, row: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginHorizontal: 10, }, iconContainer: { justifyContent: 'center', }, icon: { alignSelf: 'center', }, headerText: { fontFamily: 'System', fontSize: 20, fontWeight: 'bold', alignSelf: 'center', }, }); export default ProductHeader;
import React, {useRef, useEffect, useState} from 'react' import {Card, CardHeader, CardHeaderTitle, CardFooter, CardContent, CardImage, Media, MediaLeft, Image, MediaContent, Title, Subtitle, Content} from 'bloomer' import {Link} from 'react-router-dom' export default function BookCard(props) { const createMarkup = () => { return {__html: props.info}; }; return ( <Card> <CardHeader> <CardHeaderTitle> {props.authors} </CardHeaderTitle> </CardHeader> <CardContent> <Media> <MediaLeft> <Image isSize='96x96' src={props.smallThumb} /> </MediaLeft> <MediaContent> <Title className="media-content-title" isSize={4}> {props.title}</Title> </MediaContent> </Media> <Content dangerouslySetInnerHTML={createMarkup()}> </Content> </CardContent> <CardFooter> <Link to={{ pathname :`/books/${props.title}`, state:{id:props.id} }}>See More</Link> </CardFooter> </Card> ) }
import 'react-native-gesture-handler'; import React from "react"; //Navigation componets import { NavigationContainer } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import About from '../screens/About' import Home from '../screens/Home' import Templates from '../screens/Templates' import Ionicons from 'react-native-vector-icons/Ionicons' import { Text, View , ImageBackground} from 'react-native'; import Login from '../screens/Login'; function HomeScreen(){ return( <Home/> ); } function AboutScreen(){ return( <About/> ); } function ThemeScreen(){ return( <Templates/> ); } const Tab = createBottomTabNavigator(); export default function Navigation(){ return( <NavigationContainer> <Tab.Navigator screenOptions={({route}) => ({ tabBarIcon: ({focused, color, size, padding}) =>{ let iconName; if(route.name === "DreamCloudEnt"){ iconName = focused ? "home" : "home-outline"; } else if (route.name === "About"){ iconName = focused ? "information-circle" : "information-circle-outline"; }else if(route.name === "Templates"){ iconName = focused ? "apps" : "apps-outline"; } return <Ionicons name={iconName} size={size} color={color} />; }, tabBarActiveTintColor: 'purple', tabBarInactiveTintColor: 'gray', })} > <Tab.Screen name={"DreamCloudEnt"} component={HomeScreen}></Tab.Screen> <Tab.Screen name={"About"} component={AboutScreen}></Tab.Screen> <Tab.Screen name={"Templates"} component={ThemeScreen}></Tab.Screen> </Tab.Navigator> </NavigationContainer> ); }
import React from 'react'; import { Row, Col, Card } from 'react-bootstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCheck, faTimes } from '@fortawesome/free-solid-svg-icons'; import { useSocket } from '../../utils/useSocket'; /** * Composant InvitationsListItem : * Affiche une demande à rejoindre la partie * * props : * - invitation : La demande à rejoindre la partie */ function InvitationsListItem({ invitation }) { const { socket } = useSocket(); const accept = (accepted) => { socket.emit('acceptInvitation', { gameId: invitation.GameId, invitationId: invitation.id, accepted, playerId: invitation.User.id, username: invitation.User.username, }); }; return ( <Card> <Card.Body> <Row className="justify-content-between"> <Col xs="auto">{invitation.User.username}</Col> <Col xs="auto"> <Row> <Col xs="auto"> <FontAwesomeIcon style={{ cursor: 'pointer' }} icon={faCheck} color="#28a745" size="lg" onClick={() => accept(true)} /> </Col> <Col xs="auto"> <FontAwesomeIcon style={{ cursor: 'pointer' }} icon={faTimes} color="#c82333" size="lg" onClick={() => accept(false)} /> </Col> </Row> </Col> </Row> </Card.Body> </Card> ); } export default InvitationsListItem;
// // Omaha, NE coordinates // // center of map - at least at the beginning - may change later var omahaCoords = [41.29, -96.22]; var mapZoomLevel = 2; // start zoom level, shows most of N/S America, at least on my screen var maximumZoom = 10; // zooming in closer than this is not useful // ********** here is wher eyou comment/uncomment the data set you want to look at ********** // significant quakes last week // var quakesjson = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson" // 4.5+ during past week // var quakesjson = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson" // 2.5+ during past week var quakesjson = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson" // 1+ during past week // var quakesjson = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.geojson" // All quakes past week //var quakesjson = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson" //var quakesjson = //var quakesjson = // Perform API call to USGS API to get earthquake data d3.json(quakesjson, function(earthquakeData) { createFeatures(earthquakeData.features); }); // Function to scale the Magnitude function markerSize(magnitude) { return magnitude * 20000; }; // Function to assign color depends on the Magnitude function getColor(m) { // var colors = ['green','yellow','gold','orange','pink','red']; var colors = ["#85c1c8", "#9c8184", "#af4980", "#c0182a", "#d33300", "#e99900", "#ffff00"]; return m > 5? colors[5]: m > 4? colors[4]: m > 3? colors[3]: m > 2? colors[2]: m > 1? colors[1]: colors[0]; }; function createFeatures(earthquakeData) { var earthquakes = L.geoJSON(earthquakeData,{ // Give each feature a popup describing with information pertinent to it onEachFeature: function(feature, layer){ layer.bindPopup("<b> Magnitude: </b>"+ feature.properties.mag + "<hr><b>Location: </b>" + feature.properties.place + "<hr>" + new Date(feature.properties.time) ); }, // figure out if this is the right color/size combo for mag/depth*************************************** pointToLayer: function(feature, latlng){ //*************************************** return new L.circle(latlng, //*************************************** { radius: markerSize(feature.properties.mag), //*************************************** fillColor: getColor(feature.properties.mag), //*************************************** fillOpacity: .8, //*************************************** color: 'grey', //*************************************** weight: .5 //*************************************** }) } }); // ************************************************************************************************************ createMap(earthquakes); }; function createMap(earthquakes) { // Define lightmap, outdoorsmap, and satellitemap layers let mapboxUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}'; let lightmap = L.tileLayer(mapboxUrl, {id: 'mapbox.light', maxZoom: maximumZoom, id: "mapbox/light-v10", accessToken: API_KEY}); let darkmap = L.tileLayer(mapboxUrl, {id: 'mapbox.run-bike-hike', maxZoom: maximumZoom, id: "mapbox/outdoors-v11", accessToken: API_KEY}); let satellitemap = L.tileLayer(mapboxUrl, {id: 'mapbox.streets-satellite', maxZoom: maximumZoom, id: "mapbox/satellite-v9", accessToken: API_KEY}); // L.tileLayer("https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", { // attribution: "© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>", // tileSize: 512, // maxZoom: 18, // zoomOffset: -1, // id: "mapbox/streets-v11", // accessToken: API_KEY // }).addTo(myMap); var tectonicPlates = new L.LayerGroup(); d3.json("https://raw.githubusercontent.com/fraxen/tectonicplates/master/GeoJSON/PB2002_boundaries.json", function (plateData) { L.geoJSON(plateData, { color: 'orange', weight: 2 }) .addTo(tectonicPlates); }); // Define a baseMaps object to hold our base layers var baseMaps = { "Grayscale": lightmap, "Dark Map": darkmap, "Satellite Map" : satellitemap }; // Create overlay object to hold our overlay layer var overlayMaps = { "Earthquakes": earthquakes, "Tectonic Plates": tectonicPlates }; // Create our map, giving it the lightmap and earthquakes layers to display on load var myMap = L.map("mapid", { center: omahaCoords, zoom: mapZoomLevel, layers: [lightmap, earthquakes] }); // Create a layer control // Pass in our baseMaps and overlayMaps // Add the layer control to the map L.control.layers(baseMaps, overlayMaps, { collapsed: false }).addTo(myMap); // Create a legend to display information in the bottom right var legend = L.control({position: 'bottomleft'}); legend.onAdd = function(map) { var div = L.DomUtil.create('div','info legend'), magnitudes = [0,1,2,3,4,5], labels = []; div.innerHTML += "<h4 style='margin:4px'>Magnitude</h4>" // loop through our density intervals and generate a label for each interval for (var i=0; i < magnitudes.length; i++){ div.innerHTML += '<i style="background:' + getColor(magnitudes[i] + 1) + '"></i> ' + magnitudes[i] + (magnitudes[i+1]?'&ndash;' + magnitudes[i+1] +'<br>': '+'); } return div; }; legend.addTo(myMap); }
angular.module("MainApp").controller('CaseHistory', ['$scope','$http','$location','SharedService','RestService', function ($scope, $http, $location, SharedService, RestService) { var patientData; (function() { patientData = SharedService.patientData; var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); $scope.visitDate = ('0' + dd).slice(-2) + '/' + ('0' + (mm)).slice(-2) + '/' + yyyy; })(); $scope.month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; $scope.viewCaseSheet = function(visit) { SharedService.setVisitData(visit); $location.path("patientProfile/caseSheet_"+visit.visitType) } $scope.initCaseHistory = function (){ $('#profileMenu').show(); $('#backToProfileCaseHistory').hide(); if( patientData.id != undefined ){ RestService.visit.getVisitsByPatient({patientId:patientData.id}).$promise.then(function(data){ $scope.visits =data; if (data[0]) { $scope.initVisitDetails(data[0]) } }); } } $scope.addCaseSheet = function () { SharedService.setVisitData({}); $location.path("patientProfile/caseSheet_OP") }; $scope.initVisitDetails = function(visit) { resetDetails(); $scope.activeVisit = visit; var visitId = visit.id; $scope.visitId = visitId; // PRESCRIPTIONS $scope.prescriptions = RestService.prescription.getPrescriptionsByVisit({visitId:visitId}); // LABORATORY $scope.diagnosticOrders = RestService.diagnosticReport.getDiagnosticReportsByVisit({visitId:visitId}); // RADIOLOGY RestService.diagnostics.getRadiologyTestsByVisit({visitId : visitId}).$promise.then(function(data) { $scope.radiologyTests = data; }); // CASE SHEET RestService.caseSheet.getCaseSheetByVisit({visitId : visitId}).$promise.then(function(data) { var clinicalTemplate; if( clinicalTemplate = data[0] ) { $scope.clinicalTemplate = { id : clinicalTemplate.template.id, data : clinicalTemplate.data } } }); // ATTACHMENTS $scope.mScope.attachments = []; $http.get('/attachment/' + visitId + '?attachmentType=Clinical').success(function (data) { if( !data[0] ) return; var count = 0; angular.forEach(data, function(value, key) { if( value.contentType.indexOf('image') == 0 ) { value.baseImageSource = getBase64Image(value); value.isImage = true; count += 1; } else { value.isDoc = true; } }); $scope.isAllImages = count == data.length ? true : false; $scope.isAllFiles = count == 0 ? true : false; $scope.mScope.attachments = data; }); } $scope.resetAttachment = function() { $scope.attachmentMeta = { tMode : 'view' }; } $scope.resetAttachment(); $scope.getAttachment = function(id) { $http.get('/attachment/'+id+'?attachmentType=ClinicalMetaEdit').success(function (data) { showImage(data); }); } function showImage(data) { angular.forEach(data, function(value, key) { $scope.attachmentMeta[key] = value; }) $scope.attachmentMeta.baseImageSource = getBase64Image(data); $scope.attachmentMeta.imageLoaded = true; } function getBase64Image(data) { var binary = ''; var bytes = new Uint8Array( data.content ); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode( bytes[ i ] ); } return 'data:'+data.contentType+';base64,'+window.btoa(binary); } $scope.fileDownload = function(attachment){ $http({method:'GET', responseType:'arraybuffer', url:'/attachment/download/'+attachment.id}). success(function(response) { var myBlob = new Blob([response],{type:attachment.contentType}) var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob); var anchor = document.createElement("a"); anchor.download = attachment.fileName; anchor.href = blobURL; anchor.click(); }); } function resetDetails() { delete $scope.prescriptions; delete $scope.diagnosticOrders; delete $scope.radiologyTests; delete $scope.clinicalTemplate; delete $scope.mScope.attachments; } $scope.mScope.fileDownload = function(attachment){ $http({method:'GET', responseType:'arraybuffer', url:'/attachment/download/'+attachment.id}). success(function(response) { var myBlob = new Blob([response],{type:attachment.contentType}) var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob); var anchor = document.createElement("a"); anchor.download = attachment.fileName; anchor.href = blobURL; anchor.click(); }); } $scope.report = { fileDownload : $scope.mScope.fileDownload }; $scope.initReportData = function(radiologyTest) { $scope.report.template = {}; $scope.report.attachments = {}; loadCustomReport(radiologyTest); loadAttachments(radiologyTest); } function loadCustomReport(diagnosticDetail) { var diagnosticDetailId = diagnosticDetail.id; var diagnosticTemplateId = diagnosticDetail.charge.diagnosticTemplate.id; if( !(diagnosticDetailId && diagnosticTemplateId) ) { return; } $http.get('/diagReport/getCustomReport?diagnosticDetailId=' + diagnosticDetailId + '&diagTemplateId=' + diagnosticTemplateId) .success(function (data) { if( data.templateData ) { $scope.report.template = { id : data.templateData.template.id, data : data.templateData.data , testname:diagnosticDetail.charge.name }; } }); } function loadAttachments(diagnosticDetail) { $http.get('/attachment/' + diagnosticDetail.id + '?attachmentType=Diagnostic&chargeId=' + diagnosticDetail.charge.id).success(function (data) { $scope.report.attachments = data; }); } $scope.availableResultFilter = function(diagnosticReport) { return !!diagnosticReport.value; } $scope.analysis = { init : function() { var analysis = $scope.analysis; analysis.vitalSigns.render(); analysis.diagnostics.init(); }, vitalSigns : { init : function() { var vitalSigns = $scope.analysis.vitalSigns; vitalSigns.bp.init(); vitalSigns.temperature.init(); vitalSigns.pulseRate.init(); vitalSigns.respiratoryRate.init(); vitalSigns.bmi.init(); }, bp : { showable : true, init : function() { var bp = $scope.analysis.vitalSigns.bp; bp.load(); if( !(bp.visits && bp.visits.length > 1) ) { bp.showable = false return; } bp.render(); }, load : function() { var visits = ['Visit Date']; var systolics = ['Systolic']; var diastolics = ['Diastolic']; angular.forEach($scope.analysis.vitalSigns.data, function(value, key) { var systolic = value.bpUp; var diastolic = value.bpBelow; if( systolic && diastolic ) { systolics.push(systolic); diastolics.push(diastolic); visits.push(new Date(value.visitDate)); } }) var bp = $scope.analysis.vitalSigns.bp; bp.visits = visits; bp.systolics = systolics; bp.diastolics = diastolics; }, render : function() { var bp = $scope.analysis.vitalSigns.bp; bp.chart = c3.generate({ bindto: '#bpChart', data: { x : 'Visit Date', columns: [ bp.visits, bp.systolics, bp.diastolics ], colors : { 'Systolic' : 'green', 'Diastolic' : 'orange', } }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-middle' } }, y : { label : { text : 'BP', position : 'outer-middle' } } } }); } }, temperature : { showable : true, init : function() { var temperature = $scope.analysis.vitalSigns.temperature; temperature.load(); if( !(temperature.visits && temperature.visits.length > 1) ) { temperature.showable = false; return; } temperature.render(); }, load : function() { var visits = ['Visit Date']; var temperatures = ['Temperature']; angular.forEach($scope.analysis.vitalSigns.data, function(value, key) { var heat = value.temperature; if( heat ) { temperatures.push(heat); visits.push(new Date(value.visitDate)); } }) var temperature = $scope.analysis.vitalSigns.temperature; temperature.visits = visits; temperature.temperatures = temperatures; }, render : function() { var temperature = $scope.analysis.vitalSigns.temperature; temperature.chart = c3.generate({ bindto: '#temperatureChart', data: { x : 'Visit Date', columns: [ temperature.visits, temperature.temperatures, ], colors : { 'Temperature' : 'red' } }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-middle' } }, y : { label : { text : 'Temperature', position : 'outer-middle' } } } }); } }, pulseRate : { showable : true, init : function() { var pulseRate = $scope.analysis.vitalSigns.pulseRate; pulseRate.load(); if( !(pulseRate.visits && pulseRate.visits.length > 1) ) { pulseRate.showable = false; return; } pulseRate.render(); }, load : function() { var visits = ['Visit Date']; var pulseRates = ['Pulse Rate']; angular.forEach($scope.analysis.vitalSigns.data, function(value, key) { var pulse = value.pulseRate; if( pulse ) { pulseRates.push(pulse); visits.push(new Date(value.visitDate)); } }) var pulseRate = $scope.analysis.vitalSigns.pulseRate; pulseRate.visits = visits; pulseRate.pulseRates = pulseRates; }, render : function() { var pulseRate = $scope.analysis.vitalSigns.pulseRate; pulseRate.chart = c3.generate({ bindto: '#pulseChart', data: { x : 'Visit Date', columns: [ pulseRate.visits, pulseRate.pulseRates, ], colors : { 'Pulse Rate' : '#4ed4f3' } }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-middle' } }, y : { label : { text : 'Pulse Rate', position : 'outer-middle' } } } }); } }, respiratoryRate : { showable : true, init : function() { var respiratoryRate = $scope.analysis.vitalSigns.respiratoryRate; respiratoryRate.load(); if( !(respiratoryRate.visits && respiratoryRate.visits.length > 1) ) { respiratoryRate.showable = false; return; } respiratoryRate.render(); }, load : function() { var visits = ['Visit Date']; var respiratoryRates = ['Respiratory Rate']; angular.forEach($scope.analysis.vitalSigns.data, function(value, key) { var respiratory = value.respiratoryRate; if( respiratory ) { respiratoryRates.push(respiratory); visits.push(new Date(value.visitDate)); } }) var respiratoryRate = $scope.analysis.vitalSigns.respiratoryRate; respiratoryRate.visits = visits; respiratoryRate.respiratoryRates = respiratoryRates; }, render : function() { var respiratory = $scope.analysis.vitalSigns.respiratoryRate; respiratory.chart = c3.generate({ bindto: '#respiratoryChart', data: { x : 'Visit Date', columns: [ respiratory.visits, respiratory.respiratoryRates, ], colors : { 'Respiratory Rate' : '#d05710' } }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-middle' } }, y : { label : { text : 'Respiratory Rate', position : 'outer-middle' } } } }); } }, bmi : { showable : true, init : function() { var bmi = $scope.analysis.vitalSigns.bmi; bmi.load(); if( !(bmi.visits && bmi.visits.length > 1) ) { bmi.showable = false; return; } bmi.render(); }, load : function() { var visits = ['Visit Date']; var bmis = ['BMI']; angular.forEach($scope.analysis.vitalSigns.data, function(value, key) { var height = value.height; var weight = value.weight; if( height && weight ) { var bmi = ((weight) / (height * height)) * 10000; bmis.push(bmi); visits.push(new Date(value.visitDate)); } }) var bmi = $scope.analysis.vitalSigns.bmi; bmi.visits = visits; bmi.bmis = bmis; }, render : function() { var bmi = $scope.analysis.vitalSigns.bmi; bmi.chart = c3.generate({ bindto: '#bmiChart', data: { x : 'Visit Date', columns: [ bmi.visits, bmi.bmis, ], colors : { 'BMI' : '#d08c10' } }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-middle' } }, y : { label : { text : 'BMI', position : 'outer-middle' } } } }); } }, render : function() { if( !(patientData && patientData.id) ) { return; } RestService.caseSheet.getVitalSignsDataByPatient({patientId : patientData.id}).$promise.then(function(data){ var vitalSigns = $scope.analysis.vitalSigns; vitalSigns.data = data; $(document).ready(function($) { vitalSigns.init(); }); }); }, destroy : function() { var vitalSigns = $scope.analysis.vitalSigns; if(vitalSigns.bp.chart) vitalSigns.bp.chart = vitalSigns.bp.chart.destroy(); if(vitalSigns.temperature.chart) vitalSigns.temperature.chart = vitalSigns.temperature.chart.destroy(); if(vitalSigns.pulseRate.chart) vitalSigns.pulseRate.chart = vitalSigns.pulseRate.chart.destroy(); if(vitalSigns.respiratoryRate.chart) vitalSigns.respiratoryRate.chart = vitalSigns.respiratoryRate.chart.destroy(); if(vitalSigns.bp.chart) vitalSigns.bp.chart = vitalSigns.bmi.chart.destroy(); } }, diagnostics : { showable : true, init : function() { if( !(patientData && patientData.id) ) { return; } RestService.diagnosticReport.getDiagnosticReportsByPatient({patientId : patientData.id}) .$promise.then(function(data){ var diagnostics = $scope.analysis.diagnostics; diagnostics.data = data; $(document).ready(function($) { diagnostics.load(); if( !diagnostics.xs ) { diagnostics.showable = false; return; } diagnostics.render(); }); }); }, load : function() { var unique = {}; var data = $scope.analysis.diagnostics.data; for(var i=0; i<data.length; i++) { var value = data[i]; var resultValue = value.value; var unit = value.labTemplateDetail.unit; if( isNaN(resultValue) || !unit ) { continue; } var resultName = value.labTemplateDetail.resultName + '(' + unit + ')'; var normRange = value.labTemplateDetail.normalRange; var dateParts = value.diagnosticDetail.orderId.visit.date.split("/"); var visitDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]); var values = unique[resultName]; if( !values ) { values = {}; unique[resultName] = values; values.dates = []; values.values = []; } values.dates.push(visitDate); values.values.push(resultValue); } var xs = {}; var rows = []; var columns = []; var i = 1; angular.forEach(unique, function(result, name){ var x = 'x' + i++; xs[name] = x; var dates = result.dates; dates.splice(0, 0, x); rows.push(dates); var values = result.values; values.splice(0, 0, name); columns.push(values); }); var diagnostics = $scope.analysis.diagnostics; diagnostics.xs = xs; angular.forEach(columns, function(value, key) { rows.push(value); }); diagnostics.columns = rows; }, render : function() { var diagnostics = $scope.analysis.diagnostics; diagnostics.chart = c3.generate({ bindto: '#diagnosticsChart', data: { xs : diagnostics.xs, columns: diagnostics.columns }, axis : { x : { type : 'timeseries', tick : { format : '%d-%m-%y' }, label : { text : 'Visit Date', position : 'outer-center' } }, y : { label : { text : 'Result Value', position : 'outer-middle' } }, }, legend: { position: 'right' } }); }, destroy : function() { var diagnostics = $scope.analysis.diagnostics; if( diagnostics.chart ) diagnostics.chart = diagnostics.chart.destroy(); } }, destroy : function() { var analysis = $scope.analysis; analysis.vitalSigns.destroy(); analysis.diagnostics.destroy(); }, height : function() { return (window.innerHeight - 185) + 'px'; } } }])
var ConfigOfHome = { isShowMapFirst: true, // true false 配置默认初始化的时候是否展开地图 mapIframeSrc: jasTools.base.rootPath + '/jasmvvm/pages/module-gis/index.html', menuWith: 200, // 数字 }; window.app = new Vue({ el: '#app', data: function () { return { appId: '', projectOid: sessionStorage.getItem('projectOid') || '', gisUrl: '', username: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user')).userName, userunit: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user')).unitName, userImg: '../../common/images/enterlogo.png', direction: 'right', panelShowed: ConfigOfHome.isShowMapFirst, isExpend: true, menuWith: ConfigOfHome.menuWith, menusOpened: [], currentTap: null, tabs: [], // 打开的标签页 items: [], //菜单数组 // isMapInited: false, //地图未初始化 panelLayout: 'horizontal', //地图未初始化 todoNum: 0, //待办数量 isGoPage: false, isUserInfo: null } }, computed: { menuStyle: function () { return { width: this.isCollapse ? '64px' : (this.menuWith || 200) + 'px' } }, isCollapse: function () { return !this.isExpend; }, }, created: function () { console.log(location.hash) this.currentTap = (location.hash && location.hash.slice(1)) || ''; this.currentTap && (this.menusOpened = [this.currentTap]); var params = jasTools.base.getParamsInUrl(location.href.split('#')[0]); this.appId = params.appId || jasTools.base.getAppId() || '402894a152681ba30152681e8b320003'; this._queryTodoNum(); this._queryMenuData(); this._isGoPage(); }, mounted: function () { this._setWindowResizeEventToCloseMenu(); // this._requestLoginInfo(); this.bindHashEvent(); this.bindTabsMenuEvent(); this.statuschanged(this.panelShowed); // 加载地图 }, watch: { currentTap: function (val) { val && (location.hash = val); } }, methods: { _isGoPage: function () { var that = this; //进行登录人员所属地区的查询 var url = jasTools.base.rootPath + '/nmpsp/basedatastatistics/queryLoginUserArea.do'; jasTools.ajax.get(url, {}, function (data) { if (data.status == 1) { if (data.data.areaType) { that.isGoPage = true; } that.isUserInfo = data.data; } }); }, _goPage: function () { var that = this; var url = jasTools.base.rootPath + '/jasmvvm/pages/group-onepage-new/basic/basic.html?areaType=' + that.isUserInfo.areaType + "&areaId=" + that.isUserInfo.areaId; window.open(url) // location.href = jasTools.base.rootPath + '/jasmvvm/pages/group-onepage-new/basic/basic.html?areaType=' + that.isUserInfo.areaType + "&areaId=" + that.isUserInfo.areaId; }, backToDesk: function () { location.href = jasTools.base.rootPath + "/jasmvvm/pages/page-plateform/index.html"; }, bindHashEvent: function () { var that = this; window.addEventListener("popstate", function (a, b, c) { var index = location.hash && location.hash.slice(1); console.log(index) index && that.selectMenu(index); //doSomething }, false); }, bindTabsMenuEvent: function () { var that = this; $('.el-tabs__nav-scroll').on('contextmenu', function (e) { e.preventDefault(); e.returnValue = false; that.$refs.popover.reference = e.currentTarget; that.$refs.popover.showPopper = true; return false; //取消window自带的菜单弹出来 }); $(document).on('click', function () { that.$refs.popover.showPopper = false; }); }, handleTabsOptions: function (index) { var that = this; if (index == 1) { var id = "pane-" + this.currentTap; document.getElementById(id).querySelector("iframe").contentWindow.location.reload(true); } if (index == 2) { // 关闭当前选项卡 this.removeTab(this.currentTap); } if (index == 3) { this.tabs = this.tabs.filter(function (tab) { return (tab.name == that.currentTap) || !tab.closable; }); } if (index == 4) { this.tabs = this.tabs.filter(function (item) { return !item.closable }); this.currentTap = this.tabs[0] ? this.tabs[0].name : undefined; } this.$refs.popover.showPopper = false; }, _getFirstMenuId: function (items) { var that = this; var obj = items[0]; if (obj.subs && obj.subs.length > 0) { return this._getFirstMenuId(obj.subs); } return obj.id; }, _queryMenuData: function () { var that = this; // 获取左侧菜单 if (this.projectOid) { var url = jasTools.base.rootPath + '/jasframework/multiprojectPrivilege/getChildrenMenuList.do'; jasTools.ajax.get(url, { id: this.projectOid, appId: that.appId, }, function (data) { console.log(data) if (typeof data === 'object' && data.length > 0) { that.items = that._formatMenus(data); if (!that.currentTap || that.currentTap == 0) { that.currentTap = that._getFirstMenuId(that.items); that.menusOpened = [that.currentTap]; } that.tabs = that._createTabsArr(that.menusOpened, that.items); } }); } else { var url = jasTools.base.rootPath + '/jasframework/privilege/privilege/getAllUserFuntion.do'; $.ajax({ url: url + "?token=" + localStorage.getItem('token'), type: 'get', async: true, data: { "menutype": "0", "appId": that.appId, "language": "zh_CN" }, success: function (data, xhr, param) { if (typeof data === 'object' && data.length > 0) { that.items = that._formatMenus(data); if (!that.currentTap || that.currentTap == 0) { that.currentTap = that._getFirstMenuId(that.items); that.menusOpened = [that.currentTap]; } that.tabs = that._createTabsArr(that.menusOpened, that.items); } } }); } }, _formatMenus: function (aMenu) { var _aMenu = JSON.parse(JSON.stringify(aMenu)); var switcher = function (arr) { if (typeof arr === "object") { arr.forEach(function (item) { item.index = item.id || ''; item.icon = item.icon || ''; //fa-bars fa-bookmark item.title = item.text; if (!item.attributes) { item.attributes = {}; item.attributes.URL = 'jasmvvm/pages/module-jasdoc/doc-verify/doc-verify.html'; } if (item.attributes && item.attributes.URL) { if (item.attributes.URL.indexOf('http') > -1) { item.link = item.attributes.URL; } else { item.link = jasTools.base.rootPath + '/' + item.attributes.URL; } } item.subs = item.children; if (item.subs) { switcher(item.subs); } }) } }; switcher(_aMenu); return _aMenu; }, selectMenu: function (index) { var that = this; var newTap = ''; this.tabs.forEach(function (item) { //循环打开的标签页,判断选中的菜单是否带开过 if (item.name === index) { newTap = index; } }); if (!newTap) { var aTab = this._createTabsArr([index], this.items); this.tabs.push(aTab[0]); } this.currentTap = index; this.changeLayersVisiable(); }, changeLayersVisiable: function () { var that = this; var baseLayer = ["BASE_STATION", "BASE_VALVE_ROOM", "BASE_PIPELINE", "BASE_MARKER", "BASE_PIPELINE_NAME", "BIZ_HCA_POLYGON", "BASE_PIPELINE_SEGMENT"]; var layers = JSON.parse(localStorage.getItem("allLayers")); layers.forEach(function (layerId) { if (baseLayer.includes(layerId)) { top.frames['gisWindow'].jasMap.layerVisibleSwitch(layerId, true); } else { top.frames['gisWindow'].jasMap.layerVisibleSwitch(layerId, false); } }); }, removeTab: function (targetName) { var tabs = this.tabs; var activeName = this.currentTap; //如果当前显示的tab页被删除,更改当前显示的tab页为下一页 if (activeName === targetName) { tabs.forEach(function (tab, index) { if (tab.name === targetName) { var nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.name; } } }); } //设定当前显示的tab页 this.currentTap = activeName; //在原数组中删除这个要被删除的tab this.tabs = tabs.filter(function (tab) { return tab.name !== targetName; }) }, _getMenuInfoByIndex: function (index, aMenu) { var _icon = ''; var _title = ''; var _closable = true; var _link = ''; var isGetResult = false; var getTitle = function (index, aMenu) { for (var i = 0; i < aMenu.length; i++) { var item = aMenu[i]; if (item.subs) { //如果有子集递归处理 if (!isGetResult) { _icon = item.icon; _title = item.title; getTitle(index, item.subs); } } else { if (index === item.index) { isGetResult = true; _icon = item.icon; _title = item.title; _link = item.link; _closable = item.closable !== false ? true : false; return; } } } }; getTitle(index, aMenu); return { icon: _icon, title: _title, closable: _closable, link: _link || '', } }, _setWindowResizeEventToCloseMenu: function () { var that = this; window.addEventListener('resize', function () { if (document.body.clientWidth < 900 && that.isExpend) { that.isExpend = false; } }); }, _loginOut: function () { var url = jasTools.base.rootPath + '/jasframework/login/logout.do'; jasTools.ajax.get(url, {}, function (data) { localStorage.removeItem('token'); localStorage.removeItem('user'); location.href = jasTools.base.rootPath + "/jasmvvm/pages/page-login/login.html"; }, function () { localStorage.removeItem('token'); localStorage.removeItem('user'); location.href = jasTools.base.rootPath + "/jasmvvm/pages/page-login/login.html"; }); }, _createTabsArr: function (aIndex, aMenu) { var that = this; return aIndex.map(function (index) { var info = that._getMenuInfoByIndex(index, aMenu); return { title: info.title, name: index, link: info.link, icon: info.icon, closable: info.closable } }); }, handleCommand: function (command) { if (command === 'loginout') { this._loginOut(); } else if (command === 'fullscreen') { this._goFullscreen(); } else if (command === 'resetPassword') { this._resetPassword(); } else if (command === 'changeLayout') { this.changeLayout(); } else if (command === 'personInfo') { this._showPersonInfo() } }, changeLayout: function () { this.panelLayout = (this.panelLayout == 'horizontal') ? 'vertical' : 'horizontal'; }, _goFullscreen: function () { if (screenfull.enabled) { // screenfull.toggle($('.tabswrapper .el-tabs__content')[0]); screenfull.toggle(); } else { window.top.Vue.prototype.$message({ message: '您的浏览器不支持全屏', type: 'error' }); // Ignore or do something else } }, _resetPassword: function () { var that = this; jasTools.dialog.show({ title: '修改密码', width: '530px', height: '530px', src: '../page-password/resetword.html', cbForClose: function (param) { if (param === 1) { that._loginOut(); } } }); }, _showPersonInfo: function () { var that = this; jasTools.dialog.show({ title: '个人信息', width: '530px', height: '380px', src: '../page-person/personInfo.html', cbForClose: function (param) { } }); }, _requestLoginInfo: function () { var that = this; var url = jasTools.base.rootPath + '/jasframework/log/login/getUserStatisticsInfo.do'; jasTools.ajax.get(url, {}, function (data) { var obj = data.data; that.$notify({ type: 'success', title: '登录成功', position: 'bottom-right', dangerouslyUseHTMLString: true, message: [ '<div style="font-size:12px;">', ' <div><span style="color:#409EFF;font-weight: 700;">' + obj.userName + '</span>,您好!</div>', ' <div>登录次数:<span style="color:#409EFF;">' + obj.loginCount + '</span></div>', ' <div>累计在线时长:<span style="color:#409EFF;">' + obj.totalLoginDate + '</span></div>', ' <div>上次登录IP:<span style="color:#409EFF;">' + obj.clientIp + '</span></div>', ' <div>上次登录时间:<span style="color:#409EFF;">' + obj.lastLoginDate + '</span></div>', '</div>' ].join('') }); }, function () { }); }, paneresize: function () { !this.gisUrl && (this.gisUrl = ConfigOfHome.mapIframeSrc); }, statuschanged: function (val) { if (val) { !this.gisUrl && (this.gisUrl = ConfigOfHome.mapIframeSrc); } }, locate: function (oid, tableName) { this.$refs.resizer.panelShowed = true; var options = { scale: 100, expand: 10, } top.frames['gisWindow'].jasMap.flashGraphic(oid, tableName, options); // if (tableName == "BIZ_HCA") { // top.frames['gisWindow'].jasMap.flashGraphic(oid, "BIZ_HCA_polygon", options); // } // if (tableName == "BIZ_MAJOR_WORK_SITE") { // top.frames['gisWindow'].jasMap.flashGraphic(oid, "BIZ_MAJOR_WORK_SITE_point", options); // } // if (tableName == "BIZ_GEOLOGIC_HAZARD") { // top.frames['gisWindow'].jasMap.flashGraphic(oid, "BIZ_GEOLOGIC_HAZARD_point", options); // } }, _queryTodoNum: function () { var that = this; //获取数量 var url = jasTools.base.rootPath + '/jasframework/workflow/task/myTodoList.do'; jasTools.ajax.post(url, {}, function (data) { if (data.status == 1) { that.todoNum = data.total; } }, function () { }); }, _goTodo: function () { var that = this; that.selectMenu("P-DW-000001"); } }, })
window.addEventListener('load', function(){ const inputPrice = document.getElementById("item-price"); const taxPrice = document.getElementById("add-tax-price") const profit = document.getElementById("profit") inputPrice.addEventListener("input", function(){ itemPrice = inputPrice.value; taxPrice.innerHTML = Math.floor(itemPrice * 0.1).toLocaleString(); profit.innerHTML = Math.floor(itemPrice * 0.9).toLocaleString(); }) })
"use strict"; module.exports = { up: async (queryInterface, Sequelize) => { const date = new Date(); await queryInterface.bulkInsert( "Comments", [ { id: 1, postId: 1, userId: 3, content: "Aenean fringilla ligula ipsum, vulputate auctor lectus scelerisque a. Phasellus eros enim, lobortis nec sagittis eu, scelerisque vel mauris. Aenean eu posuere risus, in mollis augue. Proin id turpis purus. Fusce scelerisque sodales lobortis. Sed.", createdAt: date, updatedAt: date, }, { id: 2, postId: 1, userId: 2, content: "Fusce neque lacus, vehicula ut finibus in, tristique et leo. Phasellus vel mattis purus, sed dapibus risus.", createdAt: date, updatedAt: date, }, { id: 3, postId: 2, userId: 2, content: "Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus ac nibh felis. Sed vestibulum dolor eu fringilla pulvinar. Quisque.", createdAt: date, updatedAt: date, }, { id: 4, postId: 2, userId: 1, content: "Quisque pulvinar felis ut odio luctus lobortis. Praesent iaculis pharetra lorem ac efficitur. Phasellus.", createdAt: date, updatedAt: date, }, { id: 5, postId: 2, userId: 3, content: "Quisque cursus varius justo ut iaculis. Fusce lacinia aliquam fermentum. Nunc vulputate rhoncus libero et efficitur. Duis.", createdAt: date, updatedAt: date, }, { id: 6, postId: 5, userId: 1, content: "Suspendisse libero nulla, egestas id tellus et, sodales.", createdAt: date, updatedAt: date, }, { id: 7, postId: 5, userId: 2, content: "Sed faucibus id dolor sed euismod. Aenean id commodo neque, vitae blandit justo. Nunc in nibh vitae massa faucibus faucibus eget non urna. Praesent.", createdAt: date, updatedAt: date, }, { id: 8, postId: 4, userId: 4, content: "Vivamus non arcu lobortis urna pulvinar dictum eget eget ante. Donec eget est ut lectus gravida commodo quis eget eros. In faucibus, justo quis congue porttitor, neque augue lacinia erat.", createdAt: date, updatedAt: date, }, { id: 9, postId: 4, userId: 2, content: "Nullam non efficitur nisl. Sed euismod.", createdAt: date, updatedAt: date, }, { id: 10, postId: 5, userId: 3, content: "Cras vel est diam. Integer tincidunt.", createdAt: date, updatedAt: date, }, { id: 11, postId: 6, userId: 1, content: "Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus ac nibh felis. Sed vestibulum dolor eu fringilla pulvinar. Quisque.", createdAt: date, updatedAt: date, }, { id: 12, postId: 6, userId: 3, content: "Nulla vestibulum iaculis lorem eget scelerisque. Nam porta tristique blandit. Pellentesque habitant morbi tristique.", createdAt: date, updatedAt: date, }, { id: 13, postId: 6, userId: 1, content: "Cras at blandit dolor, vitae tristique metus. Vivamus sollicitudin suscipit aliquet. Class aptent taciti.", createdAt: date, updatedAt: date, }, { id: 14, postId: 7, userId: 2, content: "Maecenas scelerisque ligula odio, a ullamcorper elit fringilla id. Duis pulvinar ultricies gravida. Fusce aliquet semper molestie. Vestibulum pellentesque semper velit, vitae bibendum libero vulputate vel. Quisque sit amet nibh.", createdAt: date, updatedAt: date, }, ], {} ); }, down: async (queryInterface, Sequelize) => { await queryInterface.bulkDelete("Comments", null, {}); }, };
var response_directory = {}; exports.response_directory = response_directory;