text
stringlengths
7
3.69M
const fs = require ('fs'); const inquirer = require ('inquirer'); // array of questions for user function nodePrompt () { return inquirer.prompt([ { type: "input", message: "What is the title of your ReadMe?", name: "Title", }, { type: "input", message: "Please enter a description of your project", name: "Description", }, { type: "input", message: "List instaliation steps if needed", name: "Instalation", }, { type: "input", message: "Usage Information", name: "Usage", }, { type: "input", message: "Contribution Guidelines", name: "Contributions", }, { type: "input", message: "Test Instructions", name: "Tests", }, { type:"list", message: "select license", choices: [ "MIT", "GVL-GPL 3.0", "APACHE 2.0", "BSD 3", "None", ] } ])}; //const questions = [ //]; // function to write README file function writeToFile(fileName, data) { fs.writeFile (fileName,data,err => { if (err) { throw err; } }); } // function to initialize program function init() { } // function call to initialize program init();
import React from 'react'; import axios from 'axios'; class ProductForm extends React.Component { state = { name: '', price: '' }; async componentDidMount() { const id = this.props.match.params.id; if (id == 'new') return; const { data } = await axios.get('http://localhost:3000/products/' + id); const state = {}; state.name = data.name; state.price = data.price; state.id = data.id; this.setState(state); } handleSubmit = async (e) => { e.preventDefault(); const id = this.props.match.params.id; const obj = { ...this.state, count: 0, isInCart: false }; if (id === 'new') { await axios.post('http://localhost:3000/products/', obj); } else { await axios.put('http://localhost:3000/products/' + id, obj); } this.props.history.replace('/admin'); }; handleChange = (e) => { let state = { ...this.state }; state[e.currentTarget.name] = e.currentTarget.value; this.setState(state); }; render() { return ( <React.Fragment> <h1>{this.props.match.params.id === 'new' ? 'Add' : 'Edit'}</h1> <form onSubmit={this.handleSubmit}> <div className="form-group"> <lable htmlFor="name">Name</lable> <input type="text" className="form-control" value={this.state.name} id="name" name="name" onChange={this.handleChange} /> </div> <div className="form-group"> <lable htmlFor="price">Price</lable> <input type="text" className="form-control" value={this.state.price} id="price" name="price" onChange={this.handleChange} /> </div> <button className="btn btn-primary"> {this.props.match.params.id === 'new' ? 'Add' : 'Edit'} </button> </form> </React.Fragment> ); } } export default ProductForm;
const db = require("../model"); const { user } = require("../model"); const User = db.users; const Op = db.Sequelize.Op; const express = require("express"); const {validationResult } = require("express-validator/check"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const router = express.Router(); const auth = require("../middleware/auth"); exports.create = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const {email, password } = req.body; //check if user already exist try { let dbuser = await User.findOne({where:{ email }}); if (dbuser) { return res.status(400).json({ msg: "User Already Exists" }); } // Create a User const user = { email: req.body.email, password: req.body.password, isAdmin: false, }; const salt = await bcrypt.genSalt(10); user.password = await bcrypt.hash(password, salt); // Save User in the database await User.create(user) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Some error occurred while creating user.", }); }); const payload = { user: { email: user.email } }; jwt.sign( payload, "randomString", { expiresIn: 10000 }, (err, token) => { if (err) throw err; console.log(token) res.status(200).json({ token }); } ); } catch (err) { console.log(err.message); res.status(500).send("Error in Saving"); } }; // Find a single user with an id exports.findOne = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; try { let user = await User.findOne({where:{ email }}); if (!user) return res.status(400).json({ message: "User Not Exist" }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message: "Incorrect Password !" }); const payload = { user: { id: user.id } }; jwt.sign( payload, "randomString", { expiresIn: 3600 }, (err, token) => { if (err) throw err; res.status(200).json({ token }); } ); } catch (e) { console.error(e); res.status(500).json({ message: e.message + "Server Error" }); } }; exports.fetch = async (req, res) => { try { // request.user is getting fetched from Middleware after token authentication const user = await User.findById(req.user.id); res.json(user); console.log(user); } catch (e) { res.send({ message: "Error in Fetching user" }); } };
angular.module('mainApp').controller('mapCtrl', function($scope, $stateParams, $state, parksSrv) { $scope.populateMap = parksSrv.showMap($stateParams.id) let location = $scope.populateMap.location_1.coordinates console.log(location) mapboxgl.accessToken = 'pk.eyJ1Ijoic2FyZ2VudDg4IiwiYSI6ImNqMzY0aHRoODAwbGszMmxpdjd5NTl6OHgifQ.zWE7w8Bs3NvC6rhFXguUTQ'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/basic-v9', center: location, zoom: 13.5 }); map.on('load', function() { map.addLayer({ "id": "points", "type": "symbol", "source": { "type": "geojson", "data": { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Point", "coordinates": location } }] } }, "layout": { "icon-image": "marker-15", "icon-size": 1 }, }) }) })
(function() { 'use strict'; angular .module('app.login.controller', []) .controller('LoginCtrl', LoginCtrl); LoginCtrl.$inject = ['$auth', '$location', '$mdToast']; function LoginCtrl($auth, $location, $mdToast) { var vm = this; vm.signIn = signIn; vm.getCurrentUser = getCurrentUser; vm.getCurrentIdUser = getCurrentIdUser; vm.isAuthenticated = isAuthenticated; vm.logout = logout; vm.isAdmin = isAdmin; vm.isUser = isUser; vm.isFisio = isFisio; vm.isRecep = isRecep; vm.isRoot = isRoot; function signIn() { console.log('llego'); $auth.login(vm.user) .then(function() { vm.user = {}; console.log($auth.getPayload()); if ($auth.getPayload().roles.indexOf('ROOT') !== -1) { $location.path('/admin'); } else if ($auth.getPayload().roles.indexOf('ADMIN') !== -1) { $location.path('/admin'); } else if ($auth.getPayload().roles.indexOf('FISIO') !== -1) { $location.path('/fisioterapeuta'); } else if ($auth.getPayload().roles.indexOf('REC') !== -1) { $location.path('/recepcionista'); } else { $location.path('/paciente'); } $mdToast.show( $mdToast.simple() .textContent('Sesión iniciada...') .position('bottom left')); }) .catch(function(error) { $mdToast.show( $mdToast.simple() .textContent(error.status + ' ' + error.data) .position('bottom left')); }); } function isAuthenticated() { return $auth.isAuthenticated(); } function getCurrentUser() { if (isAuthenticated()) { return $auth.getPayload().user; } else { return ''; } } function getCurrentIdUser() { if (isAuthenticated()) { return $auth.getPayload().id; } else { return ''; } } function logout() { if (!$auth.isAuthenticated()) { return; } $auth.logout() .then(function() { $location.path('/'); $mdToast.show( $mdToast.simple() .textContent('Sesión finalizada...') .position('bottom left')); }); } function isRoot() { if (isAuthenticated()) { return $auth.getPayload().roles.indexOf('ROOT') !== -1; } else { return false; } } function isAdmin() { if (isAuthenticated()) { return $auth.getPayload().roles.indexOf('ADMIN') !== -1; } else { return false; } } function isUser() { if (isAuthenticated()) { return $auth.getPayload().roles.indexOf('USR') !== -1; } else { return false; } } function isFisio() { if (isAuthenticated()) { return $auth.getPayload().roles.indexOf('FISIO') !== -1; } else { return false; } } function isRecep() { if (isAuthenticated()) { return $auth.getPayload().roles.indexOf('REC') !== -1; } else { return false; } } } })();
'use strict'; module.exports = { name: 'code', classNames: ['scrollable'] };
import React, { Component } from 'react'; import { Link } from 'react-router'; class Topbar extends Component { constructor(props){ super(props); } render() { return ( <div className="navbar navbar-default navbar-fixed-top"> <div className="navbar-header"> <button type="button" onClick={this.props.onClick} className="navbar-toggle"> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link to="/dashboard"> <h3> <em className="title1">PlaceHolder </em> <em className="title2">Dashboard</em> </h3> </Link> </div> <div className="navbar-user"> {this.props.user != null?this.props.user.username:""} </div> </div> ); } } export default Topbar;
import React from 'react' import styled from 'styled-components' export function Link ({ internal, ...props }) { if (internal) return <A {...props} /> return ( <A {...props} target='_blank' rel='noreferrer noopener' onClick={e => e.stopPropagation()} /> ) } export function Letter ({ children, title }) { return ( <Wrapper> <Heading>{title}</Heading> <Text>{children}</Text> </Wrapper> ) } export const Em = styled.span` font-weight: bold; ` export const Br = styled.div` height: 30px; ` const A = styled.a` color: #61a0ff; text-decoration: none; &:hover { text-decoration: underline; } ` const Wrapper = styled.div` margin: 0 auto; padding: 50px 0; max-width: 750px; ` const Heading = styled.h1` color: #222; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 2.75rem; font-weight: 300; line-height: 1.4; margin-bottom: 20px; margin-top: 0.2rem; text-align: center; ` const Text = styled.div` line-height: 1.6; margin-bottom: 1.25rem; `
var Exposure={ init: function($target,handler){ this.$c =$(window); this.$target=$target; this.handler=handler; this.bind(); this.checkShow(); }, bind: function(){ var me =this, timer =null, interval=100; $(window).on('scroll',function(e){ timer && clearTimeout(timer); timer = setTimeout(function(){ me.checkShow(); },interval); }) }, checkShow: function(){ var me =this; this.$target.each(function(){ var $cur=$(this); if(me.isShow($cur)){ me.handler && me.handler.call(this,this); $cur.data('loaded',true) } }) }, isShow: function($el){ var scrollH =$(window).scrollTop(), winH =$(window).height(), top =$el.offset().top; if(top<winH+scrollH){ return true; }else{ return false } }, hasLoaded: function($el){ if($el.data('loaded')){ return true; }else{ return false; } } }
const path = require ('path'); const ExtractTextPlgin = require ('extract-text-webpack-plugin'); module.exports = env => { const isProduction = env === 'production'; const CSSExtract = new ExtractTextPlgin ('styles.css'); return { entry: './client/index.js', output: { path: path.resolve (__dirname, 'public'), filename: 'client.bundle.js', }, module: { rules: [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.s?css$/, use: CSSExtract.extract ({ use: [ { loader: 'css-loader', options: { sourceMap: true, }, }, { loader: 'sass-loader', options: { sourceMap: true, }, }, ], }), }, ], }, devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map', plugins: [CSSExtract], }; };
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/ Ext.define('MyRetirement.store.asset.Growth', { extend: 'Ext.data.Store' ,fields: [ { name: 'year', type: 'integer' } ,{ name: 'Retirement', type: 'integer' } ,{ name: 'Investment', type: 'integer' } ] });
import React from "react"; import {Badge, Card} from "antd"; const Basic = () => { return ( <Card className="gx-card" title="Basic"> <Badge count={5}> <span className="head-example"/> </Badge> <Badge count={0} showZero> <span className="head-example"/> </Badge> </Card> ); }; export default Basic;
var express = require('express'); var router = express.Router(); const models = require("../../../../models"); const errors = require("../../../errors"); const ResponseTemplate = require("../../../ResponseTemplate"); const SequelizeUtil = require("../../../../util/SequelizeUtil"); const TypeChecker = require("../../../../util/TypeChecker"); const JalaliDate = require("../../../../util/JalaliDate"); const JalaliTime = require("../../../../util/JalaliTime"); const {asyncFunctionWrapper} = require("../../util"); router.get('', asyncFunctionWrapper(getPhysicianInfo)); async function getPhysicianInfo(req, res, next) { throw new Error("not implemented"); } module.exports = router;
import { Box, Flex } from 'reflexbox'; import { useState, useEffect } from 'react'; import styled from 'styled-components'; import _ from 'lodash'; import Layout from '../components/layout'; import Button from '../components/button'; import Input from '../components/input'; import { Row } from '../components/grid'; import { movies as data } from '../data'; const Heading = styled.h2` text-align: center; font-size: 2rem; `; const Emoji = styled.div` font-size: 4rem; `; const Hint = styled.span` font-style: italic; `; const movies = [...data]; const Play = () => { const [loading, setLoading] = useState(true); const [movie, setMovie] = useState({}); const [playerInput, setPlayerInput] = useState(''); const [points, setPoints] = useState(0); const [incorrect, setIncorrect] = useState(); const [hint, setHint] = useState(); const [showHint, setShowHint] = useState(false); const [usedHint, setUsedHint] = useState(false); useEffect(() => { if (movies.length > 0) { randomiseMovie(); } setLoading(false); }, []); const randomiseMovie = () => { const randomMovie = _.shuffle(movies)[0]; setMovie(randomMovie); setShowHint(false); setHint(randomMovie.hint); }; const skipMovie = () => { if (movies.length > 1) { const skippedMovie = movie; _.remove(movies, skippedMovie); // remove the movie to be skipped randomiseMovie(); movies.push(skippedMovie); // add back the movie that was skipped } }; const checkAnswer = () => { _.each(movie.answers, (answer) => { if (playerInput.toUpperCase().replace(/\s/g, '') === answer.toUpperCase().replace(/\s/g, '')) { setPoints(points + 1); setPlayerInput(''); setIncorrect(false); _.remove(movies, movie); if (movies.length > 0) { randomiseMovie(); } return false; } else { setIncorrect(true); } }); }; return ( <Layout> <Row justifyContent="center"> <Heading>Guess the Movie!</Heading> </Row> <Row justifyContent="center" mb="0.5rem"> <div> Points: {points} out of {data.length} </div> </Row> {!loading && movies.length > 0 && ( <> <Row justifyContent="center" mb="2rem"> <Emoji>{movie.emoji}</Emoji> </Row> <Row justifyContent="center" mb="2rem" mx={[2, 4]}> <Input type="text" placeholder="Please enter your answer" value={playerInput} onChange={(e) => setPlayerInput(e.target.value)} onKeyPress={(event) => { if (event.key === 'Enter') { checkAnswer(); } else { setIncorrect(false); } }} incorrect={incorrect} /> </Row> <Flex justifyContent="center" textAlign="center" flexWrap={['wrap', 'nowrap']}> <Box width={[1, 4 / 5, 'auto']} mr={['0', '1rem']}> <Button type={'button'} onClick={checkAnswer} mr="1rem"> Submit </Button> </Box> <Box width={[1, 4 / 5, 'auto']} mt={['0.5rem', 0]} mr={['0', '1rem']}> <Button type={'button'} onClick={skipMovie} mr="1rem"> Skip </Button> </Box> {hint && ( <Box width={[1, 4 / 5, 'auto']} mt={['0.5rem', 0]}> <Button type={'button'} onClick={() => { setShowHint(!showHint); setUsedHint(true); }} > {showHint ? 'Hide hint' : 'Show hint'} </Button> </Box> )} </Flex> {showHint && hint && ( <Row justifyContent="center" mt="2rem"> <div> Hint: <Hint>{hint}</Hint> </div> </Row> )} </> )} {!loading && movies.length === 0 && ( <Box width="auto" textAlign="center" mt="1rem" mx="2rem"> <div>Congratulations 🎉 You've guessed all the movies — thanks for playing!</div> {!usedHint && <div>You also used no hints! Wow 👏</div>} </Box> )} </Layout> ); }; export default Play;
//String primitive const message = 'hi'; //String object const another = new String('hi');
/** * * @param {*} state This is not an application state, only the state this reducer is responsible for * @param {*} action */ export default function(state = null, action) { switch (action.type) { case "BOOK_SELECTED" : return action.payload default : return state; } }
const Sequelize = require ('sequelize'); const dbConfig = require('../../config/database'); const Department = require('../models/Department'); const Seller = require('../models/Seller'); const SalesRecord = require('../models/SalesRecord'); const connection = new Sequelize(dbConfig); Department.init(connection); Seller.init(connection); SalesRecord.init(connection); module.exports = connection;
/* eslint-disable jsx-a11y/iframe-has-title */ /* eslint-disable jsx-a11y/alt-text */ /* eslint-disable jsx-a11y/anchor-is-valid */ import { useState , useEffect } from "react"; import AddPostPopup from "./AddPostPopup"; import { useDispatch ,useSelector} from 'react-redux'; import {fetchconnectuser,selectoneuser,selectSessionUser} from "../../../redux/slices/userSlice"; export default function AddPost({groupid}) { console.log(groupid); const [openPopup, setopenPopup] = useState(false); const dispatch = useDispatch(); useEffect(() => { dispatch(fetchconnectuser()); }, [dispatch]); const connecteduser=useSelector(selectSessionUser)[0]; return ( <> <div class="bg-white shadow border border-gray-100 rounded-lg dark:bg-gray-900 lg:mx-0 p-4"> <div class="flex space-x-3"> <img src={connecteduser.profilePicture} class="w-10 h-10 rounded-full" /> <input onClick={() => setopenPopup(true)} placeholder="What's Your Mind ?" class="bg-gray-100 hover:bg-gray-200 flex-1 h-10 px-6 rounded-full" /> </div> <AddPostPopup openPopup={openPopup} setopenPopup={setopenPopup} groupid={groupid}></AddPostPopup> <div class="grid grid-flow-col pt-3 -mx-1 -mb-1 font-semibold text-sm"> <div class="hover:bg-gray-100 flex items-center p-1.5 rounded-md cursor-pointer"> <img src="assets/user/images/post/photo.png"></img> &ensp; Photo/Video </div> <div class="hover:bg-gray-100 flex items-center p-1.5 rounded-md cursor-pointer"> <img src="assets/user/images/post/add-user.png"></img> &ensp; Tag Friend </div> <div class="hover:bg-gray-100 flex items-center p-1.5 rounded-md cursor-pointer"> <img src="assets/user/images/post/smile.png"></img> &ensp; <button>Fealing /Activity</button> </div> </div> </div> </> ); }
const React = require('react'); const hashHistory = require('react-router').hashHistory; const Rating = require('react-rating'); const ErrorStore = require('../../stores/error_store'); const SessionStore = require('../../stores/session_store'); const DrinkStore = require('../../stores/drink_store'); const VenueStore = require('../../stores/venue_store'); const UserStore = require('../../stores/user_store'); const CheckinActions = require('../../actions/checkin_actions'); const DrinkActions = require('../../actions/drink_actions'); const VenueActions = require('../../actions/venue_actions'); const CheckinIndex = require('./checkin_index'); const FriendRequestIndex = require('../user/friend_request_index'); const UserInfoBox = require('../user/user_info_box'); const CheckinForm = React.createClass({ getInitialState(){ return ({drink: "", drinkList: {}, venue: "", venueList: {}, rating: "", initialRating: 0, review: "", focused: false, venueFocused: false, errors: ErrorStore.formErrors("checkin"), user: SessionStore.currentUser()}); }, componentDidMount(){ this.errorListener = ErrorStore.addListener(this.trackErrors); this.userListener = UserStore.addListener(this._onChange); DrinkActions.fetchAllDrinks(); VenueActions.fetchAllVenues(); }, componentWillUnmount(){ this.errorListener.remove(); this.userListener.remove(); }, trackErrors(){ this.setState({errors: ErrorStore.formErrors("checkin")}); }, _onChange(){ this.setState({user: UserStore.find(this.state.user.id)}); }, updateDrink(e){ e.preventDefault(); const drinks = {}; this.allDrinks = DrinkStore.all(); Object.keys(this.allDrinks).forEach( id => { if (this.allDrinks[id].name.toLowerCase().includes(e.target.value.toLowerCase())) { drinks[id] = this.allDrinks[id]; } }); this.setState({drink: e.target.value, drinkList: drinks, focused: true}); }, autoDrink(e){ e.preventDefault(); const drink = {}; Object.keys(this.allDrinks).forEach( drinkId => { if (this.allDrinks[drinkId].name === (e.target.className)) { drink[drinkId] = this.allDrinks[drinkId]; } }); this.setState({drink: e.target.className, drinkList: drink, focused: false}); }, updateVenue(e){ e.preventDefault(); const venues = {}; this.allVenues = VenueStore.all(); Object.keys(this.allVenues).forEach( id => { if (this.allVenues[id].name.toLowerCase().includes(e.target.value.toLowerCase())) { venues[id] = this.allVenues[id]; } }); this.setState({venue: e.target.value, venueList: venues, venueFocused: true}); }, autoVenue(e){ e.preventDefault(); const venue = {}; Object.keys(this.allVenues).forEach( venueId => { if (this.allVenues[venueId].name === (e.target.className)) { venue[venueId] = this.allVenues[venueId]; } }); this.setState({venue: e.target.className, venueList: venue, venueFocused: false}); }, updateRating(rating){ this.setState({rating: rating}); }, updateInitial(rating){ this.setState({initialRating: rating}); }, updateReview(e){ e.preventDefault(); this.setState({review: e.target.value}); }, handleSubmit(e){ e.preventDefault(); let drinkId; let venueId; if (Object.keys(this.state.drinkList).length !== 0 && this.state.drinkList.constructor === Object) { drinkId = this.state.drinkList[Object.keys(this.state.drinkList)[0]].id; } if (Object.keys(this.state.venueList).length !== 0 && this.state.venueList.constructor === Object) { venueId = this.state.venueList[Object.keys(this.state.venueList)[0]].id; } CheckinActions.createCheckin({user_id: SessionStore.currentUser().id, drink_id: parseInt(drinkId), venue_id: parseInt(venueId), rating: parseInt(this.state.rating), review: this.state.review}); this.setState({drink: "", drinkList: {}, venue: "", venueList: {}, rating: "", review: "", initialRating: 0}); }, focus(e){ e.preventDefault(); this.setState({focused: true}); }, blur(e){ e.preventDefault(); this.setState({focused: false}); }, venueFocus(e){ e.preventDefault(); this.setState({venueFocused: true}); }, venueBlur(e){ e.preventDefault(); this.setState({venueFocused: false}); }, render(){ let errors = ""; if(this.state.errors){ errors = this.state.errors.map(error => { return (<div className="checkin-error" key={error}>{error}<br/></div>); }); } let drinkList = this.state.drinkList; const drinkDropdown = Object.keys(drinkList).map( drinkId => { return <li key={drinkList[drinkId].id} className={drinkList[drinkId].name} onMouseDown={this.autoDrink}>{drinkList[drinkId].name} </li>; }); let className = "drink-dropdown"; if (this.state.focused){ className += " focus"; } let venueList = this.state.venueList; const venueDropdown = Object.keys(venueList).map( venueId => { return <li key={venueList[venueId].id} className={venueList[venueId].name} onMouseDown={this.autoVenue}>{venueList[venueId].name} </li>; }); let venueClassName = "drink-dropdown venue-dropdown"; if (this.state.venueFocused){ venueClassName += " focus"; } return ( <div className="main-flex"> <div className="checkin-flex"> <div className="feed"> <h3>Check In</h3> <div className="checkin-item"> {errors} <form onSubmit={this.handleSubmit} className="form" id="checkin" autoComplete="off"> <input type="text" onFocus={this.focus} onBlur={this.blur} onChange={this.updateDrink} value={this.state.drink} placeholder="Drink" id="checkin-drink"/> <ul onMouseOver={this.focus} className={className}>{drinkDropdown}</ul> <input type="text" onFocus={this.venueFocus} onBlur={this.venueBlur} onChange={this.updateVenue} value={this.state.venue} placeholder="Venue (optional)"/> <ul onMouseOver={this.venueFocus} className={venueClassName}>{venueDropdown}</ul> <div> <Rating initialRate={this.state.initialRating} empty="fa fa-glass grey fa-2x" full="fa fa-glass gold fa-2x" onChange={this.updateRating} onClick={this.updateInitial}/> </div> <textarea onChange={this.updateReview} value={this.state.review} placeholder="Review (optional)" rows="2" cols="30"/> <br /> <input type="submit" value="Check in!" id="checkin-button"/> </form> </div> </div> <CheckinIndex source={{loc: "feed", id: SessionStore.currentUser().id}}/> </div> <div className="friend-flex"> <UserInfoBox user={this.state.user} /> <FriendRequestIndex /> </div> </div> ); } }); module.exports = CheckinForm;
import "./assets/css/reset.scss"; import "./assets/css/style.scss"; import {experienceHeaders} from "./components/experienceHeader"; import {experienceNavbar} from "./components/experienceNavbar"; import {experienceImagesBoard} from "./components/experienceImagesBoard"; import {experienceBanner} from "./components/experienceBanner"; import {experienceTraval} from "./components/experienceTraval"; import {experienceAffiliations} from "./components/experienceAffiliations"; import {experienceNearby} from "./components/experienceNearby"; import {experienceOffers} from "./components/experienceOffers"; import {experienceAbout} from "./components/experienceAbout"; import {experienceContact} from "./components/experienceContact"; import {experienceFeatured} from "./components/experienceFeatured"; import {experienceFooter} from "./components/experienceFooter"; import {experienceWc} from "./components/experience"; customElements.define('exp-header', experienceHeaders); customElements.define('exp-navbar', experienceNavbar); customElements.define('exp-images-board', experienceImagesBoard); customElements.define('exp-banner', experienceBanner); customElements.define('exp-traval', experienceTraval); customElements.define('exp-affiliations', experienceAffiliations); customElements.define('exp-nearby', experienceNearby); customElements.define('exp-offers', experienceOffers); customElements.define('exp-about', experienceAbout); customElements.define('exp-contact', experienceContact); customElements.define('exp-featured', experienceFeatured); customElements.define('exp-footer', experienceFooter); customElements.define('exp-wc', experienceWc);
var ProductTnList = function() { this.mytns={}; this.loginStatus =false this.data=[]; // this.rows = 9; this.styles='style1'; this.param = { channelOid : channelOid, page : 1, rows : 9, sort : "", order : "asc", durationPeriodDaysStart : "", durationPeriodDaysEnd : "", expArorStart : "", expArorEnd : "", }; return this; } ProductTnList.prototype = { init: function() { this.pageInit(); this.bindEvent(); }, pageInit:function(){ var _this = this; var styles= GHutils.getCookie("style"); if(styles){ _this.styles=styles $("[data-style='"+styles+"']").addClass('active') }else{ $("[data-style]").eq(0).addClass('active') } _this.getData(true) _this.getMyTn(); }, bindEvent:function(){ var _this = this $('#sort li a').on('click',function(){ var order = $(this).is('.desc') ? 'desc':'asc' $('#sort').find('a').removeClass('desc').removeClass('active').removeClass('tn_listarrow').removeClass('tn_listarrow2') $(this).addClass('active') if($(this).is('.no')){ $(this).removeClass('tn_listarrow2') order=''; }else{ $('.no').addClass('tn_listarrow2') if(order == 'asc'){ $(this).addClass('desc').addClass('tn_listarrow2') }else{ $(this).addClass('tn_listarrow') } } _this.param.order = order; _this.param.sort = $(this).attr('data-sort') _this.param.page = 1; // $('#sort').find('a').attr('data-sort','desc') // var urlParam = ''; // if($(this).attr('data-sort')){ // urlParam = '&sort='+$(this).attr('data-sort') // } _this.getData(true) }) $('.product_tnlist_stylebtn li a').on('click',function(){ if($(this).hasClass('active')){ return } $(this).closest('ul').find('a').removeClass('active') $(this).addClass("active") var styles = $(this).attr('data-style') GHutils.setCookie("style",styles) _this.styles=styles _this.changeStyle(); }) $("#filters").on('click','li',function(){ var dom = $(this); if(dom.hasClass('active') || !$(this).attr('data-sort')){ return; } dom.addClass('active').siblings().removeClass('active') dom.parent().prev().find("span").removeClass("active") var sorts = JSON.parse(dom.attr('data-sort')||'{}'); if(typeof(sorts)=="object"){ for(var key in sorts){ _this.param[key] = sorts[key]; } } _this.param.page = 1; _this.getData(true); }) $(".all_choose_btn").on('click',function(){ var dom = $(this); if(dom.hasClass('active')){ return; } dom.addClass('active').parent().next().find("li").removeClass('active') var sorts = JSON.parse(dom.attr('data-sort')||'{}'); if(typeof(sorts)=="object"){ for(var key in sorts){ _this.param[key] = sorts[key]; } } _this.param.page = 1; _this.getData(true); }) }, getMyTn:function(){ var _this = this GHutils.load({ url:GHutils.API.ACCOUNT.protnlist, data:{}, type:'post', async:false, callback:function(result){ if(result.errorCode != 0){ // _this.getData('&order=asc',1,true) return false; } GHutils.forEach(result.holdingTnDetails.rows,function(idx,product){ _this.mytns[product.productOid]= true }) GHutils.forEach(result.toConfirmTnDetails.rows,function(idx,product){ _this.mytns[product.productOid]= true }) GHutils.forEach(result.closedTnDetails.rows,function(idx,product){ _this.mytns[product.productOid]= true }) } }) }, getData:function(isFlag){ var _this = this _this.data=[] GHutils.load({ url: GHutils.API.PRODUCT.gettnproductlist+GHutils.parseParam(_this.param), data: {}, type: "post", async: false, callback: function(result) { if(result.errorCode != 0) { return; } else { GHutils.forEach(result.rows,function(idx,product){ if(GHutils.label(product.labelList,'8')){ return false } product.labelList = GHutils.parseLabel(product.labelList) product.investMin+=0 product.netUnitShare = 1 var raisedTotalNumber = product.raisedTotalNumber product.raisedTotalNumber = GHutils.formatCurrency(raisedTotalNumber/10000) product.expArrorDisp = product.expArrorDisp.replace('~','-') var rewardInterest = product.rewardInterest || null if(rewardInterest){ rewardInterest = GHutils.toFixeds(product.rewardInterest, 2) } product.rewardInterest = rewardInterest var gobuy1={"cssStyle":"block"} var gobuy2 = {"clazz":"tnlist-no-buy","notSale":{"text":"已售罄"},"sale":null} var amount =0,percent = 100; var showProcess = "gh_none" // if(product.state == "REVIEWPASS"){ // gobuy2.notSale.text = "敬请期待" // amount = raisedTotalNumber - ((product.lockCollectedVolume*product.netUnitShare)+product.collectedVolume); // percent = GHutils.toFixeds(GHutils.Fmul(GHutils.Fdiv(GHutils.Fadd(product.collectedVolume, GHutils.Fmul(product.lockCollectedVolume, product.netUnitShare)), raisedTotalNumber), 100),0); // }else if(product.state == "RAISEFAIL" || (product.state == "RAISING" && product.isOpenPurchase == "NO")){ // percent = 100; // amount=0; gobuy2.notSale.text = "不可购买" }else if(product.state == "RAISING" && (product.maxSaleVolume == product.lockCollectedVolume || GHutils.Fmul(GHutils.Fsub(product.maxSaleVolume, product.lockCollectedVolume), 1) < product.investMin)){ // percent = 100; // amount=0; // gobuy2.notSale.text = "已售罄" }else if(product.state == "RAISEEND" || product.state == "DURATIONING" || product.state == "DURATIONEND" || product.state == "CLEARING" || product.state == "CLEARED"){ // percent = 100; // amount=0; // gobuy2.notSale.text = "已售罄" }else{ amount = raisedTotalNumber - ((product.lockCollectedVolume*product.netUnitShare)+product.collectedVolume); percent = GHutils.toFixeds(GHutils.Fmul(GHutils.Fdiv(GHutils.Fadd(product.collectedVolume, GHutils.Fmul(product.lockCollectedVolume, product.netUnitShare)), raisedTotalNumber), 100),0); if(product.state == "REVIEWPASS"){ gobuy2.notSale.text = "敬请期待" }else{ gobuy1["cssStyle"]="" gobuy1["sale"]=true gobuy2.sale = {"text":"立即抢购"} gobuy2.clazz="" gobuy2.notSale=null showProcess="" } } product["amount"] = GHutils.toFixeds(amount,2) product["percent"] = percent product["showProcess"] = showProcess product["gobuy1"]=gobuy1 product["gobuy2"]=gobuy2 product["clas"]=gobuy2 _this.data.push(product) }) _this.changeStyle(); var total = result.total // $('.tn_pagenum').html(' 第'+_this.param.page+'页 &nbsp;共'+Math.ceil(total/_this.rows)+'页 &nbsp;共'+total+'个产品</div>') if(isFlag){ _this.createPage(Math.ceil(total/_this.param.rows)); } } } }); }, changeStyle:function(){ var _this = this; var data = {} if(_this.data.length > 0){ $("#tn-list-noRecord").addClass("gh_none") data[_this.styles] = {"prodTnList":_this.data} GHutils.mustcache("#product-tn-list-template","#tn-list",data) _this.toProductInfo(); }else{ $("#tn-list-noRecord").removeClass("gh_none") $("#tn-list").html('') } }, createPage: function(pageCount) { var _this = this; if(pageCount <= 1){ $(".gh_tcdPageCode").hide() return } $(".gh_tcdPageCode").show().createPage({ pageCount: pageCount, current: 1, backFn: function(page) { _this.param.page = page; _this.getData(false); } }); }, toProductInfo:function(){ var _this = this $('.tnProductInfo').off().on('click',function(){ var oid = $(this).attr('data-oid') if(oid){ window.location.href='product-tn.html?productOid='+oid }else{ var noSaleOid = $(this).attr('data-noSale') var _msg = $(this).html(); if(_msg == "敬请期待"){ _msg = "项目暂未开放购买,敬请期待" }else{ _msg = "项目"+_msg+",项目详情仅对本项目投资人公开"; } $("#prodStatus").html(_msg) if(_this.loginStatus){ if(_this.mytns[noSaleOid]){ window.location.href='product-tn.html?productOid='+noSaleOid }else{ $('#content-box').modal('show') } }else{ GHutils.isLogin(function(){ _this.loginStatus = true _this.getMyTn() if(_this.mytns[noSaleOid]){ window.location.href='product-tn.html?productOid='+noSaleOid }else{ $('#content-box').modal('show') } }) } } }) } } $(function() { new ProductTnList().init(); })
import React, { Component } from 'react'; import { Input, Icon, Upload, Modal, Progress } from 'antd'; import Tips from '../common/tips'; import ChatShortcut from './chatSendShortcut'; import EmojiPicker from './chatEmoji'; import {cutStr} from '../common/utils'; let shortListIndex=0, shortcutWord; class ChatSend extends Component{ constructor(props){ super(props); this.state = { isSendReady: false, isEmojiShow: false, isShowProcess: false, isShortShow: false, socket: props.socket, percent: 0, textereaValue: "", matchText: ';', sNum: 0 }; } textChangeHandle = (e) => { this.setState({ textereaValue: e.target.value.substr(0, 512) }); this.props.statusHandle(1); }; blurHandle = () => { let that = this; this.props.statusHandle(2); setTimeout(function(){ that.setState({ isShortShow: false }); }, 500); }; textFocusHandle = () => { this.setState({ isEmojiShow: false }); }; sendMessage = (e) => { e.preventDefault(); let msgVal = e.target.value; let msg = msgVal.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /gi, '&nbsp;').replace(/\n/gi, '#'); if (msgVal.length > 0 && !this.state.isShortShow) { this.props.sendMessage(cutStr(msg, 256)); this.setState({ isEmojiShow: false, textereaValue: "", isSendReady: true }); } }; onKeyDown = (e) => { if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 9) { e.preventDefault(); } }; onKeyup = (e) => { let tg = e.target; let val = tg.value; let keyCode = e.keyCode; let sIndex = tg.selectionStart; let matchVal = val.slice(0, sIndex); let matchArr; if (keyCode === 38 && this.state.isShortShow) { shortListIndex--; this.shortcutSelect(-1); } if (keyCode === 40 && this.state.isShortShow) { shortListIndex++; this.shortcutSelect(1); } if (/(\s;\w*)|(^;\w*)/.test(matchVal)) { matchArr = matchVal.match(/(\s;\w*)|(^;\w*)/g); this.shortcutFilter(matchArr); } else { this.setState({ isShortShow: false }); } if (keyCode === 9 || keyCode === 13) { if (document.querySelector('.short-list .on')) { this.insertToCursorPosition(val.replace(new RegExp(shortcutWord, 'g'), ' '), document.querySelector('.short-list .on .key-value').innerHTML+' '); } this.setState({ isShortShow: false }); } }; shortcutFilter = (matchArr) => { let shortcutLists = localStorage.getItem("shortcutList") || []; let mtext = matchArr[matchArr.length - 1].replace(' ', ''); let isShortShow = false; let matchReg = new RegExp(mtext.slice(1), 'ig'); shortcutWord = mtext; if (shortcutLists.length > 0) { shortcutLists = JSON.parse(shortcutLists); for (let i = 0, l = shortcutLists.length; i < l; i++) { if (matchReg.test(shortcutLists[i].shortcut)) { isShortShow = true; break; } } } else { isShortShow = true; } this.setState({ matchText: mtext, isShortShow: isShortShow }); }; shortcutMouseover = (i) => { shortListIndex = i; }; shortcutSelectClick = (val) => { this.insertToCursorPosition(this.state.textereaValue.replace(new RegExp(shortcutWord, 'g'), ''), val); }; shortcutSelect = (direction) => { if (document.querySelector('.shortListUl li')) { let h = document.querySelector('.shortListUl li').offsetHeight; let list = document.querySelectorAll('.shortListUl li'); let len = list.length; let shortList = document.querySelector('.short-list'); if (direction === 1) { if (shortListIndex*h >= shortList.offsetHeight) { shortList.scrollTop += direction*h; } if (shortListIndex*h >= shortList.scrollHeight) { shortList.scrollTop = 0; shortListIndex = 0; } } else { if (shortListIndex < 0) { shortListIndex = len - 1; shortList.scrollTop = shortListIndex * h; } if ((shortListIndex + 1) *h <= shortList.scrollTop) { shortList.scrollTop += direction*h; } } for (let i = 0; i < len; i++) { if (i === shortListIndex) { list[i].className += ' on'; } else { list[i].className = 's-'+i; } } } }; emojiBtnHandle = () => { this.setState({ isEmojiShow: !this.state.isEmojiShow }); }; addEmojiHandle = (emoji) => { this.insertToCursorPosition(this.state.textereaValue, emoji); }; insertToCursorPosition = (s1, s2) => { let obj = document.getElementsByClassName("chat-textarea")[0]; obj.focus(); if (document.selection) { let sel = document.selection.createRange(); sel.text = s2; } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') { let startPos = obj.selectionStart, endPos = obj.selectionEnd, cursorPos = startPos, tmpStr = s1, s3 = tmpStr.substring(0, startPos) + s2 + tmpStr.substring(endPos, tmpStr.length); this.setState({ textereaValue: s3 }); cursorPos += s2.length; obj.selectionStart = obj.selectionEnd = cursorPos; } else { this.setState({ textereaValue: this.state.textereaValue+ s2 +" " }); } }; rateHandle = () => { let {socket, cid, rateFeedBack} = this.props; Modal.confirm({ title: 'Invite user rate', okText: 'Yes', cancelText: 'Cancel', content: ( <p>Are you sure invite the user rate?</p> ), onOk(){ socket && socket.emit('cs.rate', cid, function(success){ if (success) { rateFeedBack(); } }); } }); }; beforeUpload = (file) => { let isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { Tips.error('Image must smaller than 2MB!'); } if (!/(.jpg|.png|.gif|.jpeg)/g.test(file.name)) { Tips.error('Image type must be jpg、jpeg、png、gif!'); isLt2M = false; } return isLt2M; }; render(){ let {sendMessage, cid, csid} = this.props; let {percent, isShowProcess, isEmojiShow, isSendReady, textereaValue, isShortShow, matchText} = this.state; let _self = this; let props = { name: 'image', action: '/messages/customer/'+cid+'/cs/'+csid+'/image', accept: 'image/*', headers: { authorization: 'authorization-text' }, beforeUpload: _self.beforeUpload, onChange(info) { let status = info.file.status; if (status === 'uploading') { if (info.event){ _self.setState({ isShowProcess: true, percent: Math.ceil(info.event.percent) }); } } else if (status === 'done') { if (info.file.response.code === 200) { sendMessage(info.file.response.msg.resized+'|'+info.file.response.msg.original+'|'+info.file.response.msg.w+'|'+info.file.response.msg.h); } setTimeout(function(){ _self.setState({ isShowProcess: false }); }, 2000); } else if (status === 'error') { Tips.error(info.file.name+' file upload failed.', 6, function(){ _self.setState({ isShowProcess: false }); }); } } }; if (!isShortShow) { shortListIndex = 0; } return ( <div className="chat-send"> <Progress type="circle" percent={percent} className="upload-process" width={60} style={{display: isShowProcess ? 'block' : 'none'}} /> <div className="send-tools"> <div className="tool-box tool-emoji"> <Icon onClick={this.emojiBtnHandle} className={"emoji-icon "+(isEmojiShow ? 'active' : '')} /> { isEmojiShow && <EmojiPicker addEmojiHandle={this.addEmojiHandle} /> } </div> <div className="tool-box"> <Upload {...props}> <Icon type="folder" className="upload-icon" /> </Upload> </div> <div className="tool-box"> <span className="rate-icon" title="Invite user evaluation" onClick={this.rateHandle}></span> </div> </div> <div className="chat-text"> {isShortShow && <ChatShortcut shortcutSelectClick={this.shortcutSelectClick} csid={csid} matchText={matchText} shortcutMouseover={this.shortcutMouseover} />} <Input.TextArea className="chat-textarea" onPressEnter={this.sendMessage} placeholder={isSendReady ? "" : "Enter message.Type ;to bring up shortcuts."} onChange={this.textChangeHandle} onKeyUp={this.onKeyup} onKeyDown={this.onKeyDown} value={textereaValue} onFocus={this.textFocusHandle} onBlur={this.blurHandle} maxLength="256" /> </div> </div> ); } } export default ChatSend;
"use strict"; function nth(n) { switch (n+1) { case 1: return "first"; case 2: return "second"; case 3: return "third"; default: return (n+1) + "th"; } } function typeCheckPrimitiveOp(op,args,typeCheckerFunctions) { var numArgs = typeCheckerFunctions.length; if (args.length !== numArgs) { throw "Wrong number of arguments given to '" + op + "'."; } for( var index = 0; index<numArgs; index++) { if ( ! (typeCheckerFunctions[index])(args[index]) ) { throw "The " + nth(index) + " argument of '" + op + "' has the wrong type."; } } } function applyPrimitive(prim,args) { switch (prim) { case "+": typeCheckPrimitiveOp(prim,args,[isNum,isNum]); return createNum( getNumValue(args[0]) + getNumValue(args[1])); case "*": typeCheckPrimitiveOp(prim,args,[isNum,isNum]); return createNum( getNumValue(args[0]) * getNumValue(args[1])); case "add1": typeCheckPrimitiveOp(prim,args,[isNum]); return createNum( 1 + getNumValue(args[0]) ); } } function myEval(p) { if (isProgram(p)) { return evalExp(getProgramExp(p),initEnv()); } else { alert( "The input is not a program."); } } function evalExp(exp,env) { if (isIntExp(exp)) { return createNum(getIntExpValue(exp)); } else if (isVarExp(exp)) { return lookup(env,getVarExpId(exp)); } else if (isFnExp(exp)) { return createClo(getFnExpParams(exp),getFnExpBody(exp),env); } else if (isAppExp(exp)) { var f = evalExp(getAppExpFn(exp),env); var args = getAppExpArgs(exp).map( function(arg) { return evalExp(arg,env); } ); if (isClo(f)) { return evalExp(getCloBody(f),update(getCloEnv(f),getCloParams(f),args)); } else { throw f + " is not a closure and thus cannot be applied."; } } else if (isPrimAppExp(exp)) { return applyPrimitive(getPrimAppExpPrim(exp), getPrimAppExpArgs(exp).map( function(arg) { return evalExp(arg,env); } )); } else { throw "Error: Attempting to evaluate an invalid expression"; } } function valueToString(value) { if (isNum(value)) { return getNumValue(value)+""; } else if (isClo(value)) { return "Closure( params=" + getCloParams(value) + " , body="+ expToString(getCloBody(value)) + " , env=" + envToString(getCloEnv(value)) +" )"; } } function interpret(source) { var output=''; try { if (source === '') { alert('Nothing to interpret: you must provide some input!'); } else { var ast = parser.parse(source); var value = myEval( ast ); return valueToString(value); } } catch (exception) { alert(exception); return "No output [Runtime error]"; } return output; } // the code below is not functional function stringRepresentation(value) { switch (value[0]) { case "Num": return getNumValue(value); case "Clo": return; } } function expToString(exp) { return "<omitted>"; } function envToString(e) { function aux(e) { if (isEmptyEnv(e)) { return "EmptyEnv"; } else { var result = "|| " + aux(getEnvEnv(e)); var bindings = getEnvBindings(e); for(var i=0; i<bindings.length; i++) { result = bindings[i][0] + " = " +valueToString(bindings[i][1]) + " " + result; } return result; } } return "{ " + aux(e) + " }"; }
import styled from 'styled-components'; const Card = styled.div` padding: 0 0 0 0; background: #fff; box-shadow: 0 1px 5px rgba(0,0,0,0.05); @media only screen and (max-width: 350px) { background: #fda; } `; export default Card;
import React, {useState, useEffect, useContext} from "react"; import * as Question from "../components"; import {FormContext} from "../contexts/form"; import {MatchContext} from "../contexts/match"; import {SettingsContext} from "../contexts/settings"; import style from "./form.module.css"; import {compile} from "../validation-parser"; import {db} from "../firebase"; // custom useEffect for form validation. const useValidation = store => { const [valid, setValid] = useState([]); useEffect(() => { let errors = []; for (const section in store) { for (const question of store[section]) { const test = question.validation ? compile(question.validation, {...question, parent: store[section]}) : true; errors.push({test, name: question.name, value: question.value, section}); } } setValid(errors); }, [store]); return [valid, setValid]; }; const Form = () => { const {store, dispatch} = useContext(FormContext); const {store: matchStore} = useContext(MatchContext); const {store: settingStore} = useContext(SettingsContext); const [valid] = useValidation(store); useEffect(() => { dispatch({type: "RESET"}); }, [dispatch]); // this function generates a serve-ready component with everything in place. const questionGen = (question, section, index) => { const color = matchStore.alliance; switch (question.type) { case "enum": return <Question.Enum color={color} options={question.options} active={store[section][index].value} onClick={value => dispatch({type: "regular", path: `${index}#${section}`, value})} />; case "boolean": return <Question.Enum color={color} active={store[section][index].value} onClick={value => dispatch({type: "regular", path: `${index}#${section}`, value})} />; case "number": return <Question.Number value={store[section][index].value} onClick={{ right: () => dispatch({ type: "regular", path: `${index}#${section}`, value: store[section][index].value + 1, }), left: () => dispatch({ type: "regular", path: `${index}#${section}`, value: Math.max(store[section][index].value - 1, 0), }), }} />; case "text": return <Question.Input value={store[section][index].value} onChange={e => dispatch({type: "regular", path: `${index}#${section}`, value: e.target.value})} />; case "multiple": return <Question.MultipleChoice color={color} options={question.options} active={store[section][index].value} onClick={target => dispatch({ type: "regular", path: `${index}#${section}`, // the value should be an array of booleans. i.e. [true, false, false]. // here we create a new array which merges the previous state with the toggle of the clicked button. // example - we had [true, false, false] and we clicked the last button (index of 2), so we get a new array which containes [true, false, true]. value: Object.assign([], store[section][index].value, {[target]: !store[section][index].value[target]}), })} />; case "double": return <Question.DoubleNumber right={store[section][index].options.right.map((question, questionIndex) => ( {...question, onClick: { right: () => dispatch({ type: "nested", path: `${index}#${section}#right#${questionIndex}`, value: store[section][index].options.right[questionIndex].value + 1, }), left: () => dispatch({ type: "nested", path: `${index}#${section}#right#${questionIndex}`, // set the value's lower boundry to 0. value: Math.max(store[section][index].options.right[questionIndex].value - 1, 0), }), }} ))} left={store[section][index].options.left.map((question, questionIndex) => ( {...question, onClick: { right: () => dispatch({ type: "nested", path: `${index}#${section}#left#${questionIndex}`, value: store[section][index].options.left[questionIndex].value + 1, }), left: () => dispatch({ type: "nested", path: `${index}#${section}#left#${questionIndex}`, // set the value's lower boundry to 0. value: Math.max(store[section][index].options.left[questionIndex].value - 1, 0), }), }} ))}/>; default: return null; } }; const handleSubmit = () => { // flatten the data from our state to include only the values. const flatData = Object.keys(store).reduce((obj, section) => { obj[section] = store[section].reduce((questions, question) => { questions[question.name] = question.type !== "double" ? question.value : // this part is for the "double" questions, //it will return all of the inner questions as one object. Object.keys(question.options).reduce((sides, side) => { sides = {...sides, ...question.options[side].reduce((sideQuestions, sideQuestion) => { sideQuestions[sideQuestion.name] = sideQuestion.value; return sideQuestions; }, {})}; return sides; }, {}); return questions; }, {}); return obj; }, {}); // upload the data to the db db.ref().child("matches/" + matchStore.matchKey).set({[matchStore.teamID]: flatData}, error => { if (error) { alert(error); } else { // if upload was successful, go back to homepage settingStore.history.push("/"); } }); // upload individual game data to team history db.ref().child("teams/" + matchStore.teamID).push().set({matchID: matchStore.matchKey, ...flatData}); }; return ( <div className={style.form}> {Object.entries(store).map((section, sectionIndex) => ( <React.Fragment key={sectionIndex}> <section className={style.section}> <h2>{section[0]}</h2> <section className={style.inner}> {section[1].map((question, questionIndex) => ( <div className={style.question} key={questionIndex}> <h4>{question.name} {question.type === "multiple" ? <span className={style.gray}>(M)</span> : ""}</h4> {questionGen(question, section[0], questionIndex)} </div> ))} </section> </section> <hr className={style.divider}/> </React.Fragment> ))} <section className={style.section} id="validation"> <h2>Submission</h2> <h3>fix the following values to submit form:</h3> <section className={style.inner}> <pre className={style.validation}> {valid.map(el => el.test || `${el.section} - ${el.name}\n`)} </pre> <Question.Button disabled={valid.filter(el => !el.test).length !== 0} onClick={handleSubmit}> Submit </Question.Button> </section> </section> </div> ); }; export default Form;
const Product = require('./../models/Product') const Order = require('./../models/Order') const User = require('./../models/User') const axios = require('axios') exports.createOrder = async (req, res) => { console.log(req.body) try { const { products, buyer } = req.body const idProducts = products?.map(el => el._id) const newOrder = await Order.create({ products: products, buyer: buyer }) const UserOrder = await User.findByIdAndUpdate(buyer, { $push: { orders: newOrder._id } }) return res.json({ data: { order: newOrder } }) } catch (error) { console.log(error) } } exports.payment = async (req, res) => { const { items } = req.body try { const preference = { items, notification_url: 'https://webhook.site/282d1a97-269a-4778-ab6d-f21cc0e7a423', back_urls: { success: `${process.env.FRONTEND_ENDPOINT}/orden/exito`, failure: `${process.env.FRONTEND_ENDPOINT}/orden/declinado`, pending: `${process.env.FRONTEND_ENDPOINT}/orden/pendiente` } } const { data } = await axios.post('https://api.mercadopago.com/checkout/preferences', preference, { headers: { Authorization: `Bearer ${process.env.MP_TOKEN}` } }) console.log({ data }) return res.json({ data }) } catch (error) { console.log(error) } }
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import styled from 'styled-components'; class Album extends Component { render() { const { props: { album }, } = this; const { artistName, collectionName, collectionId, artworkUrl100 } = album; return ( <AlbumStyles> <div className="card-album"> <img src={ artworkUrl100 } alt="Capa do álbum" /> <div className="description"> <Link className="link" data-testid={ `link-to-album-${collectionId}` } to={ `/album/${collectionId}` } > <p>{ collectionName }</p> </Link> <p>{ artistName }</p> </div> </div> </AlbumStyles> ); } } Album.propTypes = { album: PropTypes.objectOf(PropTypes.any).isRequired, }; const AlbumStyles = styled.div` .card-album { width: 18rem; display: flex; flex-direction: column; gap: .5rem; border: 1px solid #E1E5EB; border-radius: 10px; box-shadow: 3px 3px 10px 2px rgba(0, 0, 0, 0.3); } .description { width: 80%; padding: 10px; } .link { text-decoration: none; color: #3D495C; font-weight: bold; } div img { border-top-left-radius: 10px; border-top-right-radius: 10px; } p { color: #3D495C; } `; export default Album;
var canvas var timer = 0 var newtimer = 0 var currentTimer var seed = 1234; //backing tracks loops var loop //essaie donc ! var berenger = new String(6669826978716982) var easteregg = new String var amplitudeA, amplitudeB, amplitudeD, amplitudeK, amplitudeF, amplitudeE, amplitudeG, amplitudeT, amplitudeV var soundAFFT, soundCFFT, soundTFFT, soundQFFT, soundHFFT var biscottes = [] var cordes = [] var cerclesConfiance = [] var pg, pgE, pgC //o var amppX = 50 var amppY = 100 //d var angleD = 20 //x var sizeX = 0 var sizeY = 0 //j let xtargetJ = [] let ytargetJ = [] var newOriginX var newOriginY //values set up in keyPressed() function //palettes de couleur var palette = [] var randomColor var lineColor = [] //random color values var redR = [] var greenR = [] var blueR = [] var couleurF, couleurG, couleurH, couleurI, couleurJ, couleurK, couleurM, couleurN, couleurP, couleurP, couleurT, couleurU, couleurV, couleurY //animA var colorsCircles = [] var randomColor = [] var orientationA = [] //directions var directionA = [] var directionG var directionJ //randoms for H, R & J var x1H = [] var x2H = [] var xR = [] var yR = [] //c & q var springs = [] var springQ = [] //f var Ycircle = [] function preload() { soundA = loadSound("assets/mannishboy.wav") soundZ = loadSound("assets/stevieRAY.wav") soundE = loadSound("assets/bbking_loop_jazzy.wav") soundR = loadSound("assets/rythm_wahwah1.wav") //sounds without backing tracks soundB = loadSound("assets/turnaround1.wav") soundC = loadSound("assets/merlin.wav") soundD = loadSound("assets/blues_lick_3.wav") soundF = loadSound("assets/feutre.wav") soundG = loadSound("assets/blues_double.wav") soundH = loadSound("assets/disco.wav") soundI = loadSound("assets/echo_micro.wav") soundJ = loadSound("assets/blueslick1.wav") soundK = loadSound("assets/gratte_cuillere.wav") soundL = loadSound("assets/harmonique.wav") soundM = loadSound("assets/jimi.wav") soundN = loadSound("assets/j.bonamassa_lick.wav") soundO = loadSound("assets/jump_wah_wah.wav") soundP = loadSound("assets/retour_lick.wav") soundQ = loadSound("assets/rebond_basse.wav") soundS = loadSound("assets/slide_317.wav") soundT = loadSound("assets/dumiel.wav") soundU = loadSound("assets/watchtower_lick.wav") soundV = loadSound("assets/western.wav") soundW = loadSound("assets/fin.wav") soundX = loadSound("assets/saute_de_veau.wav") soundY = loadSound("assets/andreas.wav") /* //sounds for A track soundB1 = loadSound("assets/soundsA/blueslick1.wav") soundC1 = loadSound("assets/soundsA/merlin.wav") soundD1 = loadSound("assets/soundsA/blues_lick_3.wav") soundF1 = loadSound("assets/soundsA/feutre.wav") soundG1 = loadSound("assets/soundsA/blues_double.wav") soundH1 = loadSound("assets/soundsA/disco.wav") soundI1 = loadSound("assets/soundsA/echo_micro.wav") soundJ1 = loadSound("assets/soundsA/funky.wav") soundK1 = loadSound("assets/soundsA/gratte_cuillere.wav") soundL1 = loadSound("assets/soundsA/harmonique.wav") soundM1 = loadSound("assets/soundsA/jimi.wav") soundN1 = loadSound("assets/soundsA/j.bonamassa_lick.wav") soundO1 = loadSound("assets/soundsA/jump_wah_wah.wav") soundP1 = loadSound("assets/soundsA/retour_lick.wav") soundQ1 = loadSound("assets/soundsA/rebond_basse.wav") soundS1 = loadSound("assets/soundsA/slide_317.wav") soundT1 = loadSound("assets/soundsA/dumiel.wav") soundU1 = loadSound("assets/soundsA/watchtower_lick.wav") soundV1 = loadSound("assets/soundsA/western.wav") soundW1 = loadSound("assets/soundsA/fin.wav") soundX1 = loadSound("assets/soundsA/saute_de_veau.wav") soundY1 = loadSound("assets/soundsA/tap_slide.wav") //sounds for Z track soundB2 = loadSound("assets/soundsZ/blueslick1.wav") soundC2 = loadSound("assets/soundsZ/merlin.wav") soundD2 = loadSound("assets/soundsZ/blues_lick_3.wav") soundF2 = loadSound("assets/soundsZ/feutre.wav") soundG2 = loadSound("assets/soundsZ/blues_double.wav") soundH2 = loadSound("assets/soundsZ/disco.wav") soundI2 = loadSound("assets/soundsZ/echo_micro.wav") soundJ2 = loadSound("assets/soundsZ/funky.wav") soundK2 = loadSound("assets/soundsZ/gratte_cuillere.wav") soundL2 = loadSound("assets/soundsZ/harmonique.wav") soundM2 = loadSound("assets/soundsZ/jimi.wav") soundN2 = loadSound("assets/soundsZ/j.bonamassa_lick.wav") soundO2 = loadSound("assets/soundsZ/jump_wah_wah.wav") soundP2 = loadSound("assets/soundsZ/retour_lick.wav") soundQ2 = loadSound("assets/soundsZ/rebond_basse.wav") soundS2 = loadSound("assets/soundsZ/slide_317.wav") soundT2 = loadSound("assets/soundsZ/dumiel.wav") soundU2 = loadSound("assets/soundsZ/watchtower_lick.wav") soundV2 = loadSound("assets/soundsZ/western.wav") soundW2 = loadSound("assets/soundsZ/fin.wav") soundX2 = loadSound("assets/soundsZ/saute_de_veau.wav") soundY2 = loadSound("assets/soundsZ/tap_slide.wav") //soundsfor E track soundB3 = loadSound("assets/soundsE/blueslick1.wav") soundC3 = loadSound("assets/soundsE/merlin.wav") soundD3 = loadSound("assets/soundsE/blues_lick_3.wav") soundF3 = loadSound("assets/soundsE/feutre.wav") soundG3 = loadSound("assets/soundsE/blues_double.wav") soundH3 = loadSound("assets/soundsE/disco.wav") soundI3 = loadSound("assets/soundsE/echo_micro.wav") soundJ3 = loadSound("assets/soundsE/funky.wav") soundK3 = loadSound("assets/soundsE/gratte_cuillere.wav") soundL3 = loadSound("assets/soundsE/harmonique.wav") soundM3 = loadSound("assets/soundsE/jimi.wav") soundN3 = loadSound("assets/soundsE/j.bonamassa_lick.wav") soundO3 = loadSound("assets/soundsE/jump_wah_wah.wav") soundP3 = loadSound("assets/soundsE/retour_lick.wav") soundQ3 = loadSound("assets/soundsE/rebond_basse.wav") soundS3 = loadSound("assets/soundsE/slide_317.wav") soundT3 = loadSound("assets/soundsE/dumiel.wav") soundU3 = loadSound("assets/soundsE/watchtower_lick.wav") soundV3 = loadSound("assets/soundsE/western.wav") soundW3 = loadSound("assets/soundsE/fin.wav") soundX3 = loadSound("assets/soundsE/saute_de_veau.wav") soundY3 = loadSound("assets/soundsE/tap_slide.wav") //sounds for R track soundB4 = loadSound("assets/soundsR/blueslick1.wav") soundC4 = loadSound("assets/soundsR/merlin.wav") soundD4 = loadSound("assets/soundsR/blues_lick_3.wav") soundF4 = loadSound("assets/soundsR/feutre.wav") soundG4 = loadSound("assets/soundsR/blues_double.wav") soundH4 = loadSound("assets/soundsR/disco.wav") soundI4 = loadSound("assets/soundsR/echo_micro.wav") soundJ4 = loadSound("assets/soundsR/funky.wav") soundK4 = loadSound("assets/soundsR/gratte_cuillere.wav") soundL4 = loadSound("assets/soundsR/harmonique.wav") soundM4 = loadSound("assets/soundsR/jimi.wav") soundN4 = loadSound("assets/soundsR/j.bonamassa_lick.wav") soundO4 = loadSound("assets/soundsR/jump_wah_wah.wav") soundP4 = loadSound("assets/soundsR/retour_lick.wav") soundQ4 = loadSound("assets/soundsR/rebond_basse.wav") soundS4 = loadSound("assets/soundsR/slide_317.wav") soundT4 = loadSound("assets/soundsR/dumiel.wav") soundU4 = loadSound("assets/soundsR/watchtower_lick.wav") soundV4 = loadSound("assets/soundsR/western.wav") soundW4 = loadSound("assets/soundsR/fin.wav") soundX4 = loadSound("assets/soundsR/saute_de_veau.wav") soundY4 = loadSound("assets/soundsR/tap_slide.wav")*/ } function setup() { canvas = createCanvas(windowWidth, windowHeight); //Capturer.start() background(0, 40); pixelDensity(1) //no loop of backing tracks loop = 0 //tous les analysers de son amplitudeA = new p5.Amplitude() amplitudeA.setInput(soundA) amplitudeB = new p5.Amplitude() amplitudeB.setInput(soundB) amplitudeD = new p5.Amplitude() amplitudeD.setInput(soundD) amplitudeF = new p5.Amplitude() amplitudeF.setInput(soundF) amplitudeO = new p5.Amplitude() amplitudeO.setInput(soundO) amplitudeI = new p5.Amplitude() amplitudeI.setInput(soundI) amplitudeE = new p5.Amplitude() amplitudeE.setInput(soundE) amplitudeG = new p5.Amplitude() amplitudeG.setInput(soundG) amplitudeT = new p5.Amplitude() amplitudeT.setInput(soundT) amplitudeV = new p5.Amplitude() amplitudeV.setInput(soundV) soundAFFT = new p5.FFT(0.8, 16) soundAFFT.setInput(soundA) soundCFFT = new p5.FFT(0.8, 16) soundCFFT.setInput(soundC) soundSFFT = new p5.FFT(0.8, 16) soundSFFT.setInput(soundS) soundTFFT = new p5.FFT(0.8, 16) soundTFFT.setInput(soundT) soundQFFT = new p5.FFT(0.8, 16) soundQFFT.setInput(soundQ) soundHFFT = new p5.FFT(0.8, 16) soundHFFT.setInput(soundH) //for color palette, helped by a sketch of @GotoLoop, sketch online at https://forum.processing.org/two/discussion/17621/array-of-colors#Item_1 palette[0] = color(154, 202, 42) palette[1] = color(151, 71, 140) palette[2] = color(212, 42, 41) palette[3] = color(202, 167, 46) palette[4] = color(74, 184, 219) palette[5] = color(255, 140, 231) palette[6] = color(30, 25, 86) palette[7] = color(241, 101, 39) lineColor[0] = color(232, 223, 205, 15) lineColor[1] = color(171, 4, 21, 15) xpos = 200 ypos = 7 * height / 8 /* a = 150 / height b = 70 / width */ //biscottes Xrect = 0.043 * width Yrect = 0.203804 * height pg = createGraphics(width, height) pgE = createGraphics(width, height) pgC = createGraphics(width, height) } function draw() { randomSeed(seed); background(0, 40) //backing tracks musicPlay(soundA, 65) //a musicPlay(soundZ, 90) //z musicPlay(soundE, 69) //e musicPlay(soundR, 82) //r //others musicPlay(soundB, 66) //b musicPlay(soundC, 67) //c musicPlay(soundD, 68) //d musicPlay(soundF, 70) //f musicPlay(soundG, 71) //g musicPlay(soundH, 72) ////h musicPlay(soundI, 73) //i musicPlay(soundJ, 74) //j musicPlay(soundK, 75) //k musicPlay(soundL, 76) //l musicPlay(soundM, 77) //m musicPlay(soundN, 78) //n musicPlay(soundO, 79) //o musicPlay(soundP, 80) //p musicPlay(soundQ, 81) //q musicPlay(soundS, 83) //s musicPlay(soundT, 84) //t musicPlay(soundU, 85) //u musicPlay(soundV, 86) //v musicPlay(soundW, 87) //w musicPlay(soundX, 88) //x musicPlay(soundY, 89) //y //to display instructions if no sounds have been played since 3sec //placé après musicPlay() qui reboote le timer, sans quoi la condition serait toujours valide car inchangée currentTimer = millis() //console.log("current = " + currentTimer + " timer = " + timer) if ((currentTimer > timer)) document.getElementById('instructions').style.display = "initial"; /* if (soundA.isPlaying() == true){ } if (soundZ.isPlaying() == true){ } if (soundE.isPlaying() == true){ } if (soundR.isPlaying() == true){ }*/ //is loop activated ? if (loop) { soundA.setLoop(true) soundZ.setLoop(true) soundE.setLoop(true) soundR.setLoop(true) } else { soundA.setLoop(false) soundZ.setLoop(false) soundE.setLoop(false) soundR.setLoop(false) } // first, in foreground, riffs wich can be repeated as sound background //only one except, because this animation change background color if (soundL.currentTime() < soundL.duration() - 0.1 && soundL.currentTime() > 0) { animL() } else background(0, 40) if (soundE.currentTime() < soundE.duration() - 0.1 && soundE.currentTime() > 0) { animE() } if (soundA.currentTime() < soundA.duration() - 0.1 && soundA.currentTime() > 0) { animA() } if (soundZ.currentTime() < soundZ.duration() - 0.1 && soundZ.currentTime() > 0) { animZ() } else { pg.clear() biscottes = [] transparence = 100 } if (soundR.currentTime() < soundR.duration() - 0.1 && soundR.currentTime() > 0) { animR() } //then short animations if (soundG.currentTime() < soundG.duration() - 0.1 && soundG.currentTime() > 0) { animG() } if (soundB.currentTime() < soundB.duration() - 0.1 && soundB.currentTime() > 0) { animB() } if (soundC.currentTime() < soundC.duration() - 0.1 && soundC.currentTime() > 0) { animC() } else springs = [] if (soundH.currentTime() < soundH.duration() - 0.1 && soundH.currentTime() > 0) { //h animH() } if (soundI.currentTime() < soundI.duration() - 0.1 && soundI.currentTime() > 0) { //i animI() } if (soundO.currentTime() < soundO.duration() - 0.1 && soundO.currentTime() > 0) { animO() } if (soundT.currentTime() < soundT.duration() - 0.1 && soundT.currentTime() > 0) { animT() } if (soundK.currentTime() < soundK.duration() - 0.1 && soundK.currentTime() > 0) { animK() } if (soundF.currentTime() < soundF.duration() - 0.1 && soundF.currentTime() > 0) { animF() } if (soundJ.currentTime() < soundJ.duration() - 0.1 && soundJ.currentTime() > 0) { animJ() } if (soundM.currentTime() < soundM.duration() - 0.1 && soundM.currentTime() > 0) { animM() } if (soundN.currentTime() < soundN.duration() - 0.1 && soundN.currentTime() > 0) { animN() } if (soundP.currentTime() < soundP.duration() - 0.1 && soundP.currentTime() > 0) { animP() } if (soundQ.currentTime() < soundQ.duration() - 0.1 && soundQ.currentTime() > 0) { animQ() } else springQ = [] if (soundS.currentTime() < soundS.duration() - 0.1 && soundS.currentTime() > 0) { animS() } if (soundU.currentTime() < soundU.duration() - 0.1 && soundU.currentTime() > 0) { animU() } if (soundV.currentTime() < soundV.duration() - 0.1 && soundV.currentTime() > 0) { animV() } if (soundW.currentTime() < soundW.duration() - 0.1 && soundW.currentTime() > 0) { //u animW() } if (soundX.currentTime() < soundX.duration() - 0.1 && soundX.currentTime() > 0) { animX() } if (soundY.currentTime() < soundY.duration() - 0.1 && soundY.currentTime() > 0) { animY() } if (soundD.currentTime() < soundD.duration() - 0.1 && soundD.currentTime() > 0) { animD() } } //loop //to avoid changes during the play of the sound due to use of random() method function keyPressed() { //hide instruction if a key is Pressed document.getElementById('instructions').style.display = "none"; // activate / desactivate loop condition for 4 backings tracks if (keyCode === ENTER) { if (loop) { console.log("loop désactivée") loop = 0 } else { console.log("loop activée") loop = 1 } } //saveframe to make the gif /* if (keyCode == 20) { // VER.MAJ Capturer.capture(canvas) console.log("screen capture start") } if (keyCode == 16) { // VER.MAJ Capturer.stop() Capturer.save() console.log("fin screen capture") }*/ //backing tracks animations if (keyIsDown(65) == true) { for (let i = 0; i < 4; i++) { colorsCircles[i] = random(palette) } //setup of the colors and rotations of forms for (let i = 0; i < 4; i++) { colorsCircles[i] = random(palette) } for (let j = 0; j < height / 2; j = j + 35) { randomColor[j] = random(colorsCircles) orientationA[j] = random(j) directionA[j] = int(random(0, 2) < 1) ? 1 : -1 } //only one backing track at the same time is available, because others sounds change depeding on it //ok there is a trick : if you press two of them or more at the same time, it slip throught this rule if ((soundZ.isPlaying() == true) || (soundE.isPlaying() == true) || (soundR.isPlaying() == true)) { //console.log("backingtrack") soundZ.stop() soundE.stop() soundR.stop() } } if (keyIsDown(69) == true) { //e //only one backing track at the same time is available, because others sounds change depeding on it if ((soundA.isPlaying() == true) || (soundZ.isPlaying() == true) || (soundR.isPlaying() == true)) { //console.log("backingtrack") soundA.stop() soundZ.stop() soundR.stop() } } if (keyIsDown(82) == true) { //r for (let i = 0; i < 25; i++) { redR[i] = random(80) greenR[i] = random(250) blueR[i] = random(255) xR[i] = random(width) yR[i] = random(height) } //only one backing track at the same time if ((soundZ.isPlaying() == true) || (soundE.isPlaying() == true) || (soundA.isPlaying() == true)) { //console.log("backingtrack") soundZ.stop() soundE.stop() soundA.stop() } } if (keyIsDown(90) == true) { if ((soundA.isPlaying() == true) || (soundE.isPlaying() == true) || (soundR.isPlaying() == true)) { //console.log("backingtrack") soundA.stop() soundE.stop() soundR.stop() } } //others animations if (keyIsDown(70) == true) { for (let i = 0; i < 30; i++) { //30 valeur arbitraire, mais sur mon écran 17", j'ai 13 cercles...prudence est mère de sureté ! Ycircle[i] = random(-75, 75) } } if (keyIsDown(70) == true) { couleurF = random(palette) } if (keyIsDown(71) == true) { couleurG = random(palette) directionG = int(random(0, 2) < 1) ? 1 : -1 } if (keyIsDown(72) == true) { for (let w = 0; w < width; w = w = w + 200) { x1H[w] = random(width) x2H[w] = random(width) } couleurH = random(palette) } if (keyIsDown(73) == true) { couleurI = random(palette) } if (keyIsDown(74) == true) { couleurJ = random(palette) directionJ = random(TWO_PI) newOriginX = random((width / 2) - 50, (width / 2) + 50) newOriginY = random((height / 2) + 50, (height / 2) - 50) for (let i = 0; i < 15; i++) { xtargetJ[i] = random(100, 500) ytargetJ[i] = random(-100, 100) } } if (keyIsDown(75) == true) { couleurK = random(palette) } if (keyIsDown(77) == true) { couleurM = random(palette) } if (keyIsDown(78) == true) { couleurN = random(lineColor) } if (keyIsDown(80) == true) { couleurP = random(palette) } if (keyIsDown(84) == true) { couleurT = random(palette) } if (keyIsDown(85) == true) { couleurU = random(palette) } if (keyIsDown(86) == true) { couleurV = random(palette) } if (keyIsDown(89) == true) { couleurY = random(palette) } //easter egg if (keyIsDown(66) == true) b = 1 } function musicPlay(sound, keyID) { if (keyIsDown(keyID) == true) { seed = random(9999) //to display instructions if no key is pressed for 5sec since the end of the last sound newtimer = millis() + 5000 + (sound.duration() * 1000) // temps actuel + 5 sec + durée du son if (newtimer > timer) { //pour s'assurer qu'une animation courte déclenchée après une longue ne vienne pas reset le timer timer = newtimer } if (sound.isPlaying() == true) { sound.stop() sound.play() } else sound.play() } //ifkeydown } function windowResized() { resizeCanvas(windowWidth, windowHeight) background(0) } function animA() { // multiples couches de cerlces qui pivotent dans un sens aléatoire en fonction du volume d'une plage de fréquence push() soundAFFT.analyze() let basses = soundAFFT.getEnergy("bass") // console.log(basses) translate(width / 2, height / 2) //select only 4 colors in the palette available let angle = TWO_PI / 80 //define one color + angle per circle, sometimes many side by side can be of the same color for (let j = 0; j < height / 2; j = j + 35) { //randomColor = random(colorsCircles) push() rotate(orientationA[j]) noFill() strokeWeight(4) strokeCap(SQUARE) stroke(randomColor[j]) //change their position proportionally to the bass freq with randomly direction push() if (basses > 225) rotate(map(basses, 0, 255, PI / 8, TWO_PI) * directionA[j]) //display circles beginShape() for (let i = 0; i < 72; i++) { let x = (cos(angle * i) * ((height / 2) - j)) let y = (sin(angle * i) * ((height / 2) - j)) vertex(x, y) } endShape() pop() pop() } pop() } //cercles de totem rectangulaires filaires, avec "vibrations" sur les notes appuyées function animB() { push() rectMode(CENTER) let levelB = amplitudeB.getLevel() //console.log(levelB) let seuil = map(levelB, 0, 0.08187300869102197, 0, 100) //retrecissement du rect interne par rapport à l'amp let miniX = map(levelB, 0, 0.08187300869102197, 50, 5) let miniY = map(levelB, 0, 0.08187300869102197, 180, 18) //grossissement du rect exterieur par rapport à l'amplitude let maxX = map(levelB, 0, 0.08187300869102197, 0, 50) let maxY = map(levelB, 0, 0.08187300869102197, 0, 180) let minicoin = map(levelB, 0, 0.08187300869102197, 0, 10) let totems = 6 let currentTotem = (map(soundB.currentTime(), 0, soundB.duration(), 0, totems + 1)) let posXgauche = 0 let posYgauche = 0 let posYdroite = 0 let posXdroite = 0 push() translate(width / 2, height / 2) for (let i = 0; i < currentTotem; i++) { posXdroite = (height / 4 * -cos(i * PI / 6 + PI / 2)) posYdroite = (height / 4 * -sin(i * PI / 6 + PI / 2)) posXgauche = height / 4 * cos(i * PI / 6 + PI / 2) posYgauche = height / 4 * -sin(i * PI / 6 + PI / 2) noFill() strokeWeight(2) stroke(255, 38 * i, 0) rect(posXdroite, posYdroite, 50 + maxX, 180 + maxY, 10) rect(posXgauche, posYgauche, 50 + maxX, 180 + maxY, 10) //display vibrating rectangles only f the sound exceed 60 % if (seuil > 50) { for (let i = 0; i < minicoin; i++) { rect(posXdroite, posYdroite, miniX, miniY, minicoin) rect(posXgauche, posYgauche, miniX, miniY, minicoin) } } } pop() pop() } //suite de boules tirées par un effet elastique proportionnel au son //try to launch it several times before the sound ends ! function animC() { push() soundCFFT.analyze() let middle = soundCFFT.getEnergy("mid") // console.log(middle) let middleSpring = map(middle, 105, 249, -(height / 4), height / 4) let timeline = map(soundC.currentTime(), 0, soundC.duration() * 0.65, 50, width - 50) //add new spring for each excess of the energy of the range of freq if (middle > 105) springs.push(new Spring(timeline, middle, middleSpring)) for (let i = 0; i < springs.length; i++) { springs[i].update(); springs[i].display(); } pop() } function animD() { //spirograph, try to keep the key down and drop it sometimes push() t = map(soundD.currentTime(), 0, soundD.duration(), 0, 20) angleD += 0.25 * t let sinval = sin(angleD) let cosval = cos(angleD) let x = (width / 2) + (cosval * 90) let y = (height / 2) + (sinval * 90) let x2 = x + cos(angleD * 30) * 90 / 2 let y2 = y + sin(angleD * 30) * 90 / 2 fill(235, 223, 89) noStroke() rect(x, y, 25, 25, 2) fill(94, 211, 83) rect(x2, y2, 25, 25, 2) pop() } //inspirée d'un sketch Pde tiré du bouquin "DEsign Generatif" de H. Bohnacker, B. Grob, J. Laub, et C. Lazzeroni publié par Pyramid function animE() { //polygone au nombre de faces changeant selon l'amplitude du son push() var levelE = amplitudeE.getLevel() //console.log(levelE) translate(width / 2, height / 2) let vertices = map(levelE, 0, 0.19, 2, 50) let nbcircles = 80 // map (soundE.currentTime(),0,soundE.duration(),0,200) let angle = TWO_PI / vertices noFill() strokeWeight(1) for (let j = 0; j < nbcircles; j++) { let radius //créer une différence dans les shapes selon leur taille if (j > 40) radius = j / 35 else radius = j / 10 stroke(74, 184, 219, nbcircles) beginShape() for (let i = 0; i < vertices; i++) { let x = (cos(angle * i) * ((height / 2) - 100)) / radius let y = (sin(angle * i) * ((height / 2) - 100)) / radius vertex(x, y) } endShape(CLOSE) } pop() } function animF() { //pulupulu un escargot qui en appelle un autre let levelF = amplitudeF.getLevel() let radius = map(levelF, 0, 0.1, 20, 150) //pour changer le radius des points let point = 12 let currentPoint = map(soundF.currentTime(), 0, soundF.duration(), 0, point + 1) push() noFill() strokeWeight(2) stroke(couleurF) translate(0, height / 2) for (let i = 1; i < currentPoint + 1; i++) { ellipse((i * width / 14), Ycircle[i], radius, radius) ellipse((i * width / 14), Ycircle[i], radius + 15, radius + 15) ellipse((i * width / 14), Ycircle[i], radius + 30, radius + 30) } pop() } function animG() { //droite verticale qui slide vers la droite push() var levelG = map(amplitudeG.getLevel(), 0, 0.08772784950665151, 0, 100) let posX = map(soundG.currentTime(), 0, soundG.duration(), 0, width) let posY = map(soundG.currentTime(), 0, soundG.duration(), 0, height) stroke(couleurG) strokeWeight(30) if (levelG > 60) { if (directionG == 1) { line(posX, 0, posX, height) line(posX - (width / 18), 0, posX - (width / 18), height) } else { line(0, posY, width, posY) line(0, posY - (height / 10), width, posY - (height / 10)) } } pop() } function animH() { //croisement de multiples barres avec différents angles bougeant un peu à la manière d'un noise, mais selon le volume d'une plage de fréquences push() noFill() strokeWeight(5) stroke(couleurH) soundHFFT.analyze() let middle = soundHFFT.getEnergy("highMid") // console.log(middle) let varX = map(middle, 0, 123.5, -100, 100) let posX = map(soundH.currentTime(), 0, soundH.duration(), 0, width) for (let w = 0; w < width; w = w = w + 200) { //change their position proportionally to the bass freq with randomly direction let direction = int(random(0, 2) < 1) ? 1 : -1 line(x1H[w] + (varX * direction), 0, x2H[w] + (varX * direction), height) } pop() } function animI() { //i //matéralisation de l'amplitude entre deux droites verticales let levelI = amplitudeI.getLevel() var length = map(levelI, 0, 0.042, 0, width / 10) push() noStroke() fill(couleurI) translate(width / 2, 0) //cacher la fin du son qui n'est plus audible if (soundI.currentTime() < soundI.duration()) { for (i = 0; i < height; i++) { ellipse(length, i, 10, 10) ellipse(-length, i, 10, 10) } pop() } } function animJ() { //j //jet de cocobilles let t = map(soundJ.currentTime(), 0, soundJ.duration() * 0.60, 0, 1) t = constrain(t, 0, 1) push() noStroke() fill(couleurJ) //placer le point d'origine dans un cercle de 50px autour du centre de l'écran translate(newOriginX, newOriginY) //angle de lancé alétoire rotate(directionJ) for (let i = 0; i < 15; i++) { let x = lerp(0, xtargetJ[i], t) let y = lerp(0, ytargetJ[i], t) ellipse(x, y, 20, 20) } pop() } //la course des pôles d'une ligne ! function animK() { push() let time = map(soundK.currentTime(), 0, soundK.duration() * 0.75, 0, 1) * 1.4 time = constrain(time, 0, 1) let before = lerp(width / 6, 5 * width / 6, time) let after = map(soundK.currentTime(), 0, soundK.duration(), width / 8, 5 * (width / 6)) // départ plus proche du bord pour éviter l'impression de décentrage stroke(couleurK) strokeWeight(height / 8) strokeCap(SQUARE) line(before, height / 2, after, height / 2) pop() } function animL() { //l let transp = map(soundL.currentTime(), 0, soundL.duration() - 0.2, 100, 0) background(59, 66, 86, transp) } function animM() { //interpolation du nombre de face d'un polygone push() let radius; if (width < height) radius = width / 3 else radius = height / 3 stroke(couleurM) strokeWeight(5) noFill() strokeJoin(ROUND) let mod = map(soundM.currentTime(), 0, soundM.duration(), TWO_PI, 0.001) translate(width / 2, height / 2) beginShape(); for (let i = 0; i < TWO_PI; i += mod) { let xpos = radius * cos(i); let ypos = radius * sin(i); vertex(xpos, ypos); } endShape(CLOSE); pop() } function animN() { //à partir du papillon de T.Fay, un peu lourde, ralentit le Patitap... push() translate(width / 2, height / 2) for (let i = 0; i <= 6000; i++) { // var angle = i * 24.0 * PI / 10000; var angle = map(soundN.currentTime(), 0, soundN.duration(), 2, TWO_PI * 2) * i / 4000 var x = cos(angle) * ((cos(angle)) - 10 * cos(4 * angle) - pow(sin(angle / 4), 15)) * 40 var y = sin(angle) * ((cos(angle)) - 10 * cos(4 * angle) - pow(sin(angle / 4), 15)) * 40 stroke(couleurN) strokeWeight(1) noFill() push() rotate(i / 210) line(x, y, x + 100, y + 100) pop() } pop() } function animO() { //circles morphing depending on amp of the sound ; w/ effect of dephasing between x and y axes push() noFill() strokeWeight(1.5) let levelO = amplitudeO.getLevel() amppY += 0.05 // pour déphaser les axes x et y des cercles amppX += 0.03 let radiusX = map(levelO, 0, 0.1, 30, 350) * cos(amppX) let radiusY = map(levelO, 0, 0.1, 30, 350) * cos(amppY) for (let i = 0; i < 25; i++) { let c = color(i * 4, 9, 154) stroke(c) ellipse((width / 2), (height / 2), radiusX + (i * 15), radiusY + (i * 15)) } pop() } function animP() { //petites lucioles qui se déplacent de gauche vers la droite push() let x = map(soundP.currentTime(), 0, soundP.duration(), 0, width) noStroke() fill(couleurP, 30) for (let i = height / 4; i < height; i = i + (height / 4)) { let y = i + (sin(x) * 20) ellipse(x, y, 20, 20) } pop() } function animQ() { //spring effect ; try to tap a lot of time on Q key and charge the spring ! push() springQ.push(new Spring(100, width - 200)) springQ[0].update(); springQ[0].displayQ(); pop() } function animR() { //rectangles qui tournent sur eux mêmeS push() rectMode(CENTER) for (let i = 0; i < 25; i++) { push() noFill() strokeWeight(2) stroke(redR[i], greenR[i], blueR[i]) translate(xR[i], yR[i]) rotate(frameCount / 10 + i) rect(0, 0, 200, 50, 10) pop() } pop() } function animS() { // un carré qui se fait la malle en tournicotant push() let g = map(soundS.currentTime(), 0, soundS.duration(), 0, 1) let x = lerp(0, width, g) //pour conserver plus ou moins la même vitesse de déplacement selon la taille de la fenetre let inconnue = width / 7 let y = -(((x * x) / inconnue) + x / inconnue) rectMode(CENTER) noFill() strokeWeight(2) stroke(176, 17, 65) push() translate(width / 4 + x, height + y) rotate(frameCount / 10) rect(0, 0, 50, 50) pop() pop() } function animT() { //cercle gigoteur push() let x = width / 2 let y = height / 2 let size = 80 + map(soundT.currentTime(), 0, soundT.duration(), 0, 80) soundTFFT.analyze() let aigu = soundTFFT.getEnergy("highMid") // console.log(aigu) let levelT = amplitudeT.getLevel() // console.log(levelT) if (soundT.currentTime() > soundT.duration() / 2.2) { //correspond au deuxième temps de la phrase size = 116 // fixer la taille atteinte à ce moment de l'anim x = map(aigu, 0, 250, 80, width - 200) y = map(levelT, 0, 0.2, 50, height) } noStroke() fill(couleurT) ellipse(x, y, size, size) pop() } //inspired by a sketch Pde from "DEsign Generatif" (p.357), written by H. Bohnacker, B. Grob, J. Laub, et C. Lazzeroni, published by Pyramid function animU() { //u //Lissajous curve push() translate(width / 2, height / 2) let nombrePoints = 1500 let apparition = map(soundU.currentTime(), 0, soundU.duration() * 0.76, 0, nombrePoints) stroke(couleurU) strokeWeight(1) noFill() for (let i = 0; i <= nombrePoints && apparition > i; i++) { push() let angle = map(i, 0, nombrePoints, 0, TWO_PI); // play w/ value of the Lissajous curve let x = (sin(angle * 2 + radians(30)) * cos(angle)) * (width / 2 - 25) let y = (sin(angle * 5) * cos(angle)) * (height / 2 - 25) translate(x, y) rotate(i) rect(0, 0, 15, 15) pop() } pop() } function animV() { //circle morph qui arrivent sur le dancefloor push() fill(couleurV) noStroke() var levelV = amplitudeV.getLevel() amppY += 0.05 // même effet de déphasage que animO amppX += 0.03 let radiusY = 120 let radiusX = 120 let posY = map(soundV.currentTime(), 0, soundV.duration() * 0.08, height, height / 2) let posYhaut = map(soundV.currentTime(), 0, soundV.duration() * 0.08, 0, height / 2) let diminue = 1 if (soundV.currentTime() > soundV.duration() * 0.08) { // fixer la position des cercles au centre diminue = map(soundV.currentTime(), soundV.duration() * 0.08, soundV.duration(), 1, 10) posY = height / 2 posYhaut = height / 2 radiusX = map(levelV, 0, 0.1, 30, 180) * cos(amppX) radiusY = map(levelV, 0, 0.1, 30, 180) * cos(amppY) } ellipse(width / 4, posYhaut, radiusX / diminue, radiusY / diminue) ellipse(width / 2, posY, radiusX / diminue, radiusY / diminue) ellipse(3 * width / 4, posYhaut, radiusX / diminue, radiusY / diminue) pop() } function animW() { //la chute molle var distX = 6 * width / 8 var distY = 6 * height / 7 let progress = map(soundW.currentTime(), 0, soundW.duration() - 1.5, 0, 1) fill(90, 100, 187); noStroke() if (progress < 1) { var x = (width / 8) + progress * distX; var y = (height / 7) + pow(progress, 8) * distY; } ellipse(x, y, 50, 50); } function animX() { //most satisphying circle morph, top views on YT ! sizeX += 0.05 sizeY += 0.07 //pour garder une animation smooth même sur écran grand let taillemax if (taillemax < 250) tailemax = (width / 2) else taillemax = 250 noFill() stroke(212, 42, 41) strokeWeight(2) ellipse(width / 2, height / 2, cos(sizeX) * taillemax, cos(sizeY) * taillemax) } function animY() { //la glissade infernale vers le centre du Patatap push() t = map(soundY.currentTime(), 0, 3.05, 4 * TWO_PI, 0) radiusY = map(soundY.currentTime(), 0, 3.05, (height / 2) - 50, 0) let sinval = +sin(t) let cosval = +cos(t) let x = (width / 2) + (cosval * radiusY) let y = (height / 2) + (sinval * radiusY) let taille = 15 //anim en deux temps : la glissade dans un premier temps (else), agrandissement ensuite lorsque le point atteint le centre de l'écran if (soundY.currentTime() > 3.1) { taille = map(soundY.currentTime(), 3.05, soundY.duration(), 15, 200) //h += 0.001 noise foireux à corriger x = (width / 2) y = (height / 2) //changement entre une forme pleine et un contour smooth stroke(couleurY) strokeWeight(map(soundY.currentTime(), 3.05, soundY.duration(), 2, 5)) noFill() } else { noStroke() fill(couleurY) } ellipse(x, y, taille, taille) pop() } function animZ() { //LES BISCOOOOTEEES !!!! pg.clear() if (frameCount % 24 == 0) { //almost the perfect tempo corresponding to the real tempo of the song biscottes.push(new biscotte()) } //console.log("length= " +biscottes.length) //plop le compteur de boucle du désespoir for (plop = 0; plop < biscottes.length; plop++) { // console.log("boucle for " + plop) biscottes[plop].update(); // update biscotte transparency biscottes[plop].display(pg); // draw new biscotte //erase biscotte if it's too much transparent if (biscottes[plop].transparence < 5) { biscottes = biscottes.splice(plop) } } image(pg, 0, 0, width, height) }
$(".toggleButton").hover(function() { $(this).css("background-color", "grey"); }, function(){ $(this).css("background-color", "grey"); });
'use strict'; var request = require('request'); module.exports = function(opts) { if(!opts.url) { throw new Error('url is required'); } if(!opts.logger) { throw new Error('logger is required'); } return function(message) { request.post( { url: opts.url, headers: { 'Content-Type': 'text/xml' }, body: message }, function(err/*, response, body*/) { opts.logger.info('Callback sent'); if(err) { opts.logger.error('Callback endpoint responded with: ' + err); } } ); }; };
/** * Created by levy on 2018/8/15. */ // 这里编写全局注册的filter import Vue from 'vue' import {isNull} from '@/utils' import dayjs from 'dayjs' // 千分位分隔符表示价格 // 123456 => 123,456 function price(val, cancelFixed) { if (isNull(val) || isNaN(val)) return let USPrice = Number.parseFloat(val).toLocaleString() let lastDot = USPrice.toString().indexOf('.') // 完全是整数, 需要添加小数点 if (lastDot === -1 && !cancelFixed) USPrice += '.00' // 返回数据是一位小数,用0补齐为两位小数 if (USPrice.toString().substring(lastDot + 1).length === 1 && !cancelFixed) USPrice += '0' return '¥ ' + USPrice } // 时间戳格式化 function formatDateTime(value, format = 'YYYY.MM.DD') { return dayjs(value).isValid() ? dayjs(value).format(format) : value } Vue.filter('price', price) Vue.filter('formatDateTime', formatDateTime)
import {ImmutablePropTypes, PropTypes} from 'src/App/helpers' import {immutableVideoPageTextModel, pageRequestParamsModel} from 'src/App/models' import {immutableVideoItemModel} from 'src/generic/VideoItem/models' const openGraphDataModelBuilder = process.env.NODE_ENV === 'production' ? null : isImmutable => { const exact = isImmutable ? ImmutablePropTypes.exact : PropTypes.exact, arrayOf = isImmutable ? ImmutablePropTypes.listOf : PropTypes.arrayOf, props = { id: PropTypes.number, title: PropTypes.string, thumb: PropTypes.string, tags: arrayOf(PropTypes.string), duration: PropTypes.number, swfPlugUrl: PropTypes.string, } return PropTypes.nullable(exact(props)) }, galleryModelBuilder = process.env.NODE_ENV === 'production' ? null : isImmutable => { const exact = isImmutable ? ImmutablePropTypes.exact : PropTypes.exact, arrayOf = isImmutable ? ImmutablePropTypes.listOf : PropTypes.arrayOf, props = { id: PropTypes.number, classId: PropTypes.number, title: PropTypes.string, urlForIframe: PropTypes.string, sponsorName: PropTypes.string, sponsorLink: PropTypes.string, sponsorUrl: PropTypes.string, published: PropTypes.string, thumb: PropTypes.string, thumbMask: PropTypes.string, thumbs: arrayOf(PropTypes.number), firstThumb: PropTypes.number, tags: arrayOf(PropTypes.string), tagsShort: arrayOf(PropTypes.string), duration: PropTypes.string, videoPageRef: PropTypes.number, } return PropTypes.nullable(exact(props)) }, immutableGalleryModel = process.env.NODE_ENV === 'production' ? null : galleryModelBuilder(true), immutableOpenGraphDataModel = process.env.NODE_ENV === 'production' ? null : openGraphDataModelBuilder(true) export const galleryModel = process.env.NODE_ENV === 'production' ? null : galleryModelBuilder(false), openGraphDataModel = process.env.NODE_ENV === 'production' ? null : openGraphDataModelBuilder(false), model = process.env.NODE_ENV === 'production' ? null : ImmutablePropTypes.exact({ isLoading: PropTypes.bool, isLoaded: PropTypes.bool, isFailed: PropTypes.bool, lastPageRequestParams: PropTypes.nullable(pageRequestParamsModel), inlineAdvertisementIsShowed: PropTypes.bool, pageText: PropTypes.nullable(immutableVideoPageTextModel), openGraphData: immutableOpenGraphDataModel, gallery: immutableGalleryModel, videoList: ImmutablePropTypes.listOf(immutableVideoItemModel), })
import React, { Component } from 'react'; import { connect } from 'react-redux'; import AggregateGraph from 'robTable/containers/AggregateGraph'; import RiskOfBiasForm from 'robTable/containers/RiskOfBiasForm'; import RiskOfBiasDisplay from 'robTable/containers/RiskOfBiasDisplay'; class RiskOfBias extends Component { render() { return ( this.props.isForm ? <RiskOfBiasForm /> : <div> <AggregateGraph /> <hr/> <RiskOfBiasDisplay /> </div> ); } } function mapStateToProps(state){ return { isForm: state.config.isForm, }; } export default connect(mapStateToProps)(RiskOfBias);
/*========================= ********** ********* ****** *** TECHWARE(PENMANSHIP - RE_EN^TW130) - Calendar ============================*/ jQuery(document).ready(function ($) { time_agenda(); //popup(); /* === Pre Load Time === */ var time =$(".slider-handle.min-slider-handle.round").attr('aria-valuetext'); $('.from_eventual_time').val(time); var time_asst =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuenow'); $('.from_eventual_asst').val(time_asst); }); /* === Booking Time Selection === */ function time_agenda(){ var bcChange = function () { $(".slider-handle").addClass("sl-hand-highlight"); var date =$(".acty-2.enter-fromdate").data('fromdate'); var month =$(".acty-1.enter-frommonth").data('frommonth'); var time =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); var time_asst =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuenow'); $('.from_eventual_asst').val(time_asst); $('.from_eventual_month').val(month); $('.from_eventual_date').val(date); $('.from_eventual_time').val(time); var to_month =$(".acty-1.enter-tomonth").data('tomonth'); var to_date =$(".acty-2.enter-todate").data('todate'); var to_time =$(".range-main-slider.tochrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); $('.to_eventual_month').val(to_month); $('.to_eventual_date').val(to_date); $('.to_eventual_time').val(to_time); }; /* === Slider Selection === */ if ($('#ex1').length) { $('#ex1').slider({ /* === Time Picker === */ formatter: function (value) { $("#num_ppl").val(value); $(".slider-handle").removeClass("sl-hand-highlight"); var hours1 = Math.floor(value / 60); var minutes1 = value - (hours1 * 60); if (hours1.length == 1) hours1 = '0' + hours1; if (minutes1.length == 1) minutes1 = '0' + minutes1; if (minutes1 == 0) minutes1 = '00'; if (hours1 >= 12) { if (hours1 == 12) { hours1 = hours1; minutes1 = minutes1 + " PM"; } else { hours1 = hours1 - 12; minutes1 = minutes1 + " PM"; } } else { hours1 = hours1; minutes1 = minutes1 + " AM"; } if (hours1 == 0) { hours1 = 12; minutes1 = minutes1; } return 'Time:' + hours1 + ':' + minutes1; } }).on('slide', bcChange) .data('slider'); } if ($('#ex2').length) { $('#ex2').slider({ formatter: function (value) { $("#num_ppl").val(value); $(".slider-handle").removeClass("sl-hand-highlight"); var hours1 = Math.floor(value / 60); var minutes1 = value - (hours1 * 60); if (hours1.length == 1) hours1 = '0' + hours1; if (minutes1.length == 1) minutes1 = '0' + minutes1; if (minutes1 == 0) minutes1 = '00'; if (hours1 >= 12) { if (hours1 == 12) { hours1 = hours1; minutes1 = minutes1 + " PM"; } else { hours1 = hours1 - 12; minutes1 = minutes1 + " PM"; } } else { hours1 = hours1; minutes1 = minutes1 + " AM"; } if (hours1 == 0) { hours1 = 12; minutes1 = minutes1; } return 'Time:' + hours1 + ':' + minutes1; } }).on('slide', bcChange) .data('slider'); } } /* === Booking Date Selection ===*/ function date_agenda(){ $('.content-ul-ride-main .carousel[data-type="multi"] .item').each(function () { var next = $(this).next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); for (var i = 0; i < 2; i++) { next = next.next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); } }); } /* === Booking Date's Month Picker ===*/ function getmonthdiary(thisvalue,value){ var month =$(thisvalue).data('frommonth'); $.ajax({ type: "POST", url: base_url+"Chronology/getFmonthagenda", data: "lastmsg="+value, cache: false, success: function(html){ $(".month_agenda").html(html); date_agenda(); time_agenda(); var date =$(".acty-2.enter-fromdate").data('fromdate'); var time =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); var time_asst =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuenow'); $('.from_eventual_asst').val(time_asst); $('.from_eventual_month').val(month); $('.from_eventual_date').val(date); $('.from_eventual_time').val(time); } }); } /* === From^Date Picker ===*/ function getdatediary(thisvalue,value){ var date =$(thisvalue).data('fromdate'); $.ajax({ type: "POST", url: base_url+"Chronology/getFdateagenda", data: "lastmsg="+value, cache: false, success: function(html){ $(".month_agenda").html(html); date_agenda(); time_agenda(); var month =$(".acty-1.enter-frommonth").data('frommonth'); var time =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); var time_asst =$(".range-main-slider.fromchrono .slider-handle.min-slider-handle.round").attr('aria-valuenow'); $('.from_eventual_month').val(month); $('.from_eventual_date').val(date); $('.from_eventual_time').val(time); $('.from_eventual_asst').val(time_asst); } }); } /* === Booking Calendar Popup ===*/ function popup(){ $(".ride-add-pop ul li").click(function(){ $(".ride-add-pop ul li").removeClass('pop-c-1-active'); $(this).addClass('pop-c-1-active'); id = $(this).attr('id'); $(".cnt-rides").addClass('hidden'); $("."+id).removeClass('hidden'); }); } /* === From^Month Picker ===*/ function FrommonthNext(){ var month = $('#month_prev').val(); var date = $('#date_prev').val(); var time = $('#time_prev').val(); var asst = $('#time_asst_prev').val(); $(".ride-add-pop ul li").removeClass('pop-c-1-active'); $('#cnt-ride-2').addClass('pop-c-1-active'); id = $('#cnt-ride-2').attr('id'); $(".cnt-rides").addClass('hidden'); $("."+id).removeClass('hidden'); $.ajax({ type: "POST", url: base_url+"Chronology/getprevagenda", data: "month="+month+"&date="+date+"&time="+time+"&timeasst="+asst, cache: false, success: function(html){ $(".next_month_agenda").html(html); date_agenda(); time_agenda(); var to_date =$(".acty-2.enter-todate").data('todate'); var to_month =$(".acty-1.enter-tomonth").data('tomonth'); var to_time =$(".range-main-slider.tochrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); $('.to_eventual_month').val(to_month); $('.to_eventual_date').val(to_date); $('.to_eventual_time').val(to_time); } }); } /* === To^Month Picker ===*/ function getfacingmonthdiary(thisvalue,value){ var month =$(".acty-1.enter-frommonth").data('frommonth'); var to_month =$(thisvalue).data('tomonth'); var date =$(".acty-2.enter-fromdate").data('fromdate'); var time = $('#time_prev').val(); var asst = $('#time_asst_prev').val(); $.ajax({ type: "POST", url: base_url+"Chronology/getTmonthagenda", data: "lastmsg="+value+"&month="+month+"&date="+date+"&time="+time+"&timeasst="+asst, cache: false, success: function(html){ $(".next_month_agenda").html(html); date_agenda(); time_agenda(); var to_date =$(".acty-2.enter-todate").data('todate'); var to_time =$(".range-main-slider.tochrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); $('.to_eventual_month').val(to_month); $('.to_eventual_date').val(to_date); $('.to_eventual_time').val(to_time); } }); } /* === To^Date Picker ===*/ function getfacingdatediary(thisvalue,value){ var to_date =$(thisvalue).data('todate'); var date =$(".acty-2.enter-fromdate").data('fromdate'); var month =$(".acty-1.enter-frommonth").data('frommonth'); var time = $('#time_prev').val(); var asst = $('#time_asst_prev').val(); $.ajax({ type: "POST", url: base_url+"Chronology/getTdateagenda", data: "lastmsg="+value+"&month="+month+"&date="+date+"&time="+time+"&timeasst="+asst, cache: false, success: function(html){ $(".next_month_agenda").html(html); date_agenda(); time_agenda(); var to_month =$(".acty-1.enter-tomonth").data('tomonth'); var to_time =$(".range-main-slider.tochrono .slider-handle.min-slider-handle.round").attr('aria-valuetext'); $('.to_eventual_month').val(to_month); $('.to_eventual_date').val(to_date); $('.to_eventual_time').val(to_time); } }); } /* === Next Page Picker ===*/ function TomonthNext(){ var month = $('#month_prev').val(); var date = $('#date_prev').val(); var time = $('#time_prev').val(); var to_date =$('#date_next').val(); var to_month =$('#month_next').val(); var to_time =$('#time_next').val(); $('.from_eventual_month_org').val(month); $('.from_eventual_date_org').val(date); $('.from_eventual_time_org').val(time); $('.to_eventual_month_org').val(to_month); $('.to_eventual_date_org').val(to_date); $('.to_eventual_time_org').val(to_time); $(".ride-add-pop ul li").removeClass('pop-c-1-active'); $('#cnt-ride-3').addClass('pop-c-1-active'); id = $('#cnt-ride-3').attr('id'); $(".cnt-rides").addClass('hidden'); $("."+id).removeClass('hidden'); }
window.onload = function() { var songList = []; var currentSongIndex = 0; var audio = document.getElementById('currentAudio'); var musicInfoText = document.getElementById('musicInfo'); function Jukebox(songList, currentSongIndex) { this.addSong = function(src, track, artist) { songList.push([src, track, artist]); }; this.QueenbeeJuke = function() { audio.innerHTML = "<source src=\"" + songList[0][0] + "\" type=\"audio/mp3\">"; musicInfoText.innerText = songList[0][1] + " - " + songList[0][2]; currentSongIndex = 0; }; //play button - use doc.getElementById("play").addEventListener("click", function() document.getElementById("play").addEventListener("click", function(){ audio.play(); }); // pause button - use doc.getElementById("pause").addEventListener("click", function() document.getElementById("pause").addEventListener("click", function(){ audio.pause(); }); //next button - use doc.getElementById("next").addEventListener("click", function() document.getElementById("next").addEventListener("click", function(){ if (songList[currentSongIndex+1] != null) { currentSongIndex++; musicInfoText.innerText = songList[currentSongIndex][1] + " - " + songList[currentSongIndex][2]; audio.innerHTML = "<source src=\"" + songList[currentSongIndex][0] + "\" type=\"audio/mp3\">"; audio.load(); audio.play(); } else { currentSongIndex = 0; audio.innerHTML = "<source src=\"" + songList[0][0] + "\" type=\"audio/mp3\">"; musicInfoText.innerText = songList[0][1] + " - " + songList[0][2]; audio.load(); audio.play(); } }); //Begin of back button- Use if/else, true/false document.getElementById("back").addEventListener("click", function(){ if (songList[currentSongIndex-1] != null) { currentSongIndex--; musicInfoText.innerText = songList[currentSongIndex][1] + " - " + songList[currentSongIndex][2]; audio.innerHTML = "<source src=\"" + songList[currentSongIndex][0] + "\" type=\"audio/mp3\">"; audio.load(); audio.play(); } else { currentSongIndex = songList.length-1; audio.innerHTML = "<source src=\"" + songList[songList.length-1][0] + "\" type=\"audio/mp3\">"; musicInfoText.innerText = songList[songList.length-1][1] + " - " + songList[songList.length-1][2]; console.log(currentSongIndex); audio.load(); audio.play(); } }); } //End of back button //Array must be last to function-----DO NOT MOVE THIS LIST! var juke = new Jukebox(songList); juke.addSong("audio/bensound-scifi.mp3", "sicifi", "n/a"); juke.addSong("audio/bensound-straight.mp3", "straight", "n/a"); juke.addSong("audio/bensound-goinghigher.mp3", "goinghigher", "n/a"); juke.addSong("audio/bensound-popdance.mp3", "popdance", "n/a"); juke.QueenbeeJuke(); }
const div = document.createElement('div'); document.body.appendChild(div); div.innerHTML = ` <div on:click="alert('xss')"></div> `; const div1 = document.createElement('div'); document.body.appendChild(div1); div1.innerHTML = ` <script>alert('xss')</script> `; const div2 = document.createElement('div'); document.body.appendChild(div2); div2.innerHTML = ` <img src="./404" onerror="alert('xss')" /> `;
import XLSX from 'xlsx'; import ExportJsonExcel from 'js-export-excel'; const excel = {}; // 导出excel excel.exportExcel = (cols, items, name) => { const option = { fileName: name, datas: [{ sheetFilter: cols.map(col => col.key), sheetHeader: cols.map(col => col.title), sheetData: items, }] }; new ExportJsonExcel(option).saveExcel(); }; const defaultConvert = (cols, arr) => { if (!arr.length) { return arr; } else { const colIndex = []; const result = []; for (let col of cols) { const index = arr[0].findIndex(title => title === col.title); if (index < 0) { return null; } else { colIndex.push(index); } } for (let i = 1; i < arr.length; i++) { const length = arr[i].length; const item = {}; result.push(item); for (let j = 0; j < cols.length; j++) { const index = colIndex[j]; if (index < length) { item[cols[j].key] = arr[i][index]; } } } return result; } }; // 导入excel excel.importExcel = (cols, callback, convert=defaultConvert) => { const input = document.createElement('input'); input.type = 'file'; input.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'; input.onchange = (e) => { if (e.target.files.length === 1) { const reader = new FileReader(); reader.onload = (e) => { const wb = XLSX.read(new Uint8Array(e.target.result), {type: 'array'}); const header = convert ? 1 : cols.map(col => col.key); const arr = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], {raw: false, header}); callback(convert ? convert(cols, arr) : arr); }; reader.readAsArrayBuffer(e.target.files[0]); } }; input.click(); }; export default excel;
define(["jquery"], function($) { function PPT($box) { //传入盒子的元素对象 this.box=$box; this.ulbox=$box.find(".pic"); this.img=$box.find(".pic li"); this.circle=$box.find("ol li"); this.left=$box.find(".left"); this.right=$box.find(".right"); this.onew =this.img.eq(1).width(); this.img.eq(this.circle.size() - 1).clone().prependTo(this.ulbox);//最后一张图片clone到第一张前面 this.img.eq(0).clone().appendTo(this.ulbox);//第一张图片clone到最后一张图片后面 this.ulbox.css({ width: this.onew * (this.img.size()+2), //盒子图片宽度 left: -this.onew }); this.num = 0; this.timer = null; this.init(); } PPT.prototype = { init() { this.banner();//鼠标移入移出 this.circleover();//按钮移入移出 this.rightclick();//右箭头点击 this.leftclick();//左箭头点击 this.autoplay();//自动播放 }, banner() { var that = this; this.box.hover(function() { that.left.show(); that.right.show(); clearInterval(that.timer); }, function() { that.left.hide(); that.right.hide(); that.timer = setInterval(function() { that.right.click(); }, 1500) }) }, circleover() { var that = this; this.circle.on("mouseover", function() { that.num=$(this).index(); $(this).addClass("active").siblings().removeClass("active"); that.ulbox.stop(true).animate({ left: -($(this).index() + 1) * that.onew }) }) }, rightclick() { var that = this; var ostop = true this.right.on("click", function() { if (ostop) { that.num++; ostop = false; if (that.num == that.circle.size()) { that.ulbox.animate({ left: -(that.num + 1) * that.onew }, function() { $(this).css("left", -that.onew); ostop = true; }); that.num = 0; that.circle.eq(that.num).addClass("active").siblings().removeClass("active"); } else { that.circle.eq(that.num).addClass("active").siblings().removeClass("active"); that.ulbox.animate({ left: -(that.num + 1) * that.onew }, function() { ostop = true; }) } } }) }, leftclick() { var that = this; var ostop = true; this.left.on("click", function() { if (ostop) { that.num--; ostop = false; if (that.num < 0) { that.ulbox.stop(true).animate({ left: -(that.num + 1) * that.onew }, function() { $(this).css("left", -that.circle.size() * that.onew) ostop = true; }); that.num = that.circle.size() - 1; that.circle.eq(that.num).addClass("active").siblings().removeClass("active"); } else { that.circle.eq(that.num).addClass("active").siblings().removeClass("active"); that.ulbox.animate({ left: -(that.num + 1) * that.onew }, function() { ostop = true; }) } } }) }, autoplay() { var that = this; this.timer = setInterval(function() { that.right.click(); }, 4000) } } var ppt = new PPT($(".lbbox2")); //三个对象都是ppt效果 var ppt2 =new PPT($(".book_em ._lunbo")); var ppt3 =new PPT($(".clothes_em ._lunbo")); return{ "ppt1":ppt, "ppt2":ppt2, "PPT3":ppt3 } })
const Category = require("../model/category_model") const constant = require("../constant/constant"); const Product = require("../model/product_model") exports.addCategory = (req,res)=>{ console.log(req.body); new Category(req.body).save().then(category=>{ return res.send({status:constant.SUCCESS_CODE,message:constant.ADDED_SUCCESS}) }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) } exports.getCategories =(req,res)=>{ const option={ page:req.params.page, limit: constant.POST_PER_PAGE } Category.paginate({},option).then(category=>{ return res.send({status:constant.SUCCESS_CODE,data:category}) }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) } exports.getAllCategories = (req,res)=>{ Category.find({}).then(category=>{ return res.send({status:constant.SUCCESS_CODE,data:category}) }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) } exports.getSingleCategory = (req,res)=>{ Category.findOne({_id:req.params.id}).then(category=>{ if(!category){ return res.send({status:constant.NOT_FOUND,message:constant.RECORD_NOT_FOUND}) }else{ return res.send({status:constant.SUCCESS_CODE,data:category}) } }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) } exports.deleteCategory = (req,res)=>{ Category.findByIdAndDelete({_id:req.params.id}).then(record=>{ Product.deleteMany({category_id:req.params.id}).then(product=>{ return res.send({status:constant.SUCCESS_CODE,message:constant.RECORD_DELETED}) }) }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) } exports.updateCategory = (req,res)=>{ Category.updateOne({_id:req.params.id},req.body).then(category=>{ return res.send({status:constant.SUCCESS_CODE,message:constant.RECORD_UPDATED}) }).catch(err=>{ return res.send({status:constant.ERROR_CODE,message:err.message || constant.DATABASE_ERROR}) }) }
$(document).ready(function(){ $(".student-details").DataTable(); $(document).on('click','.submitChanges', function(){ var fname = $(document).find('.first_name').val(); var lname = $(document).find('.last_name').val(); var birthday = $(document).find('.dob').val(); var phone = $(document).find('.phone').val(); var getId = $(document).find('.id').val(); var flag = 1; var getUrl = $(this).data('url'); $.ajax({ url : getUrl, method : 'POST', data :{ id : getId, first_name : fname, last_name : lname, dob : birthday, contact : phone, flagger : flag }, success : function(response){ // if(response != null) location.reload(); }, error : function(response){ console.error(response); } }); }); $(document).on('click','.deleteStudent', function(){ var getUrl = $(this).data('url'); var id = $(this).data('delete'); $.ajax({ url : getUrl, method : 'POST', data :{ delete : id, flagger : 2 }, success : function(response){ // if(response != null) location.reload(); }, error : function(response){ console.error(response); } }); }); $(document).on('click','.editstudent', function(){ var studentData = $('#student_' + $(this).data("update")); $(document).find('.id').val($(this).data("update")); $(document).find('.first_name').val (studentData.data('firstname')); $(document).find('.last_name').val(studentData.data('lastname')); $(document).find('.dob').val(studentData.data('dob')); $(document).find('.phone').val(studentData.data('contact')); $(document).find('#studentModal').modal('show'); }); });
/************ SHARED ************/ const projectName = 'project-name'; const databaseUrl = `mongodb://localhost:27017/${projectName}`; const port = 4000; const jwtSecret = '7612ca2ee54e1583a3281c5d22c5504df2862574fe28e3f86a8a736a5b4ea2cce560d5b8b0c6ab14d852a60e2fe38ab8' const userRoles = { CRISPY: 100, SUPERADMIN: 90, ADMIN: 80, USER: 70 }; /************ CONFIGURATIONS ************/ // TEST CONFIG const test = { port, database: { url: `${databaseUrl}-test`, name: `${projectName}-test` }, jwtSecret, userRoles, mailer: { nodemailerConf: { host: 'smtp.ethereal.email', port: 587, auth: { user: 'i6t2mlf4ld4pwqct@ethereal.email', pass: 'u8hR4an9ArfZ8aAtef' } }, from: 'noreply@crispybacon.it' }, address: `http://localhost:${port}` } // DEVELOPMENT CONFIG const development = { port, database: { url: `${databaseUrl}-development`, name: `${projectName}-development` }, jwtSecret, userRoles, mailer: { nodemailerConf: { host: 'smtp.ethereal.email', port: 587, auth: { user: 'i6t2mlf4ld4pwqct@ethereal.email', pass: 'u8hR4an9ArfZ8aAtef' } }, from: 'noreply@crispybacon.it' }, address: `http://localhost:${port}` } // PRODUCTION CONFIG const production = { port, database: { url: `${databaseUrl}-production`, name: `${projectName}-production` }, jwtSecret, userRoles, mailer: { nodemailerConf: { host: 'smtp.ethereal.email', port: 587, auth: { user: 'i6t2mlf4ld4pwqct@ethereal.email', pass: 'u8hR4an9ArfZ8aAtef' } }, from: 'noreply@crispybacon.it' }, address: `http://localhost:${port}` }; // STAGING CONFIG const staging = { port, database: { url: `${databaseUrl}-production`, name: `${projectName}-production` }, jwtSecret, userRoles, mailer: { nodemailerConf: { host: 'smtp.ethereal.email', port: 587, auth: { user: 'i6t2mlf4ld4pwqct@ethereal.email', pass: 'u8hR4an9ArfZ8aAtef' } }, from: 'noreply@crispybacon.it' }, address: `http://localhost:${port}` } module.exports = { test, development, staging, production };
import React from 'react'; import {StyleSheet, Text, View, Image} from 'react-native'; import moment from 'moment'; import {ms} from 'react-native-size-matters'; export default function WeatherCard({date, icName, metric, weather}) { let day = moment.unix(date).format('DD-MM-YYYY'); return ( <View style={styles.cover}> <Text style={{fontSize: ms(14)}}>{day}</Text> <Image style={styles.tinyLogo} source={{ uri: `http://openweathermap.org/img/wn/${icName}.png`, }} /> <Text style={{fontSize: ms(14)}}>{weather}</Text> <Text style={{fontSize: ms(14)}}>{metric} C</Text> </View> ); } const styles = StyleSheet.create({ cover: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, tinyLogo: { width: ms(50), height: ms(50), }, });
// jshint ignore: start // State argument is not application state, only the state this reducer is responsible for export default function(state = null, action) { // if state is undefined, set it to null switch (action.type) { case 'BOOK_SELECTED': return action.payload; } return state; }
({ answerMessage : function(component, event, helper) { var text=event.getParam("text"); component.set("v.text",text); } })
import './App.css'; import {useState} from "react"; const style = { 'textDecoration': 'line-through' } function Todo(props) { const {todo = {}, isFirst, isLast} = props; const {done} = todo; const [inputValue, setInputValue] = useState(todo.title) const [isEditMode, setIsEditMode] = useState(false) const deleteButtonHandler = () => { props.deleteTodoItem(todo.id) } const isDone = done ? style : {} const saveButtonHandler = () => { props.editTodo(todo.id, inputValue) setInputValue(todo.title) setIsEditMode(false) } return ( <div > <span style={isDone}>{todo.title}</span> <button onClick={deleteButtonHandler}>delete</button> <button onClick={() => props.updateTodo(todo.id)}>upd</button> <button disabled={isFirst} onClick={() => props.moveUp(props.index, props.index - 1)}>↑</button> <button disabled={isLast} onClick={() => props.moveUp(props.index, props.index + 1)}>↓</button> {!isEditMode && <button onClick={() => setIsEditMode(!isEditMode)}>edit</button>} {isEditMode && <> <label >new title:</label> <input type="text" onChange={(e) => setInputValue(e.target.value)} value={inputValue}/> <button onClick={saveButtonHandler}>save</button> <button onClick={() => setIsEditMode(!isEditMode)}>cancel</button> </>} </div> ); } export default Todo;
import React from 'react'; import { withNavigation } from 'react-navigation'; import { View, Text, TouchableOpacity, StatusBar, } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import AsyncStorage from '@react-native-community/async-storage'; import PropTypes from 'prop-types'; import styles from './styles'; const deleteRepositories = async () => { await AsyncStorage.clear(); }; const backToInitialPage = async () => { const { navigation } = this.props; navigation.navigate('Welcome'); }; const Header = ({ iconBack = false, iconDelete = false, title }) => ( <View style={styles.container}> <StatusBar barStyle="dark-content" /> {iconBack ? ( <TouchableOpacity onPress={backToInitialPage}> <Icon name="exchange" size={16} style={styles.iconBack} /> </TouchableOpacity> ) : ( <View style={styles.left} /> )} <Text style={styles.title}>{title}</Text> {iconDelete ? ( <TouchableOpacity onPress={deleteRepositories}> <Icon name="trash" size={16} style={styles.iconDelete} /> <Text style={styles.iconText}>All</Text> </TouchableOpacity> ) : ( <View style={styles.left} /> )} </View> ); Header.propTypes = { iconBack: PropTypes.bool.isRequired, iconDelete: PropTypes.bool.isRequired, navigation: PropTypes.shape({ navigate: PropTypes.func, }).isRequired, }; export default withNavigation(Header);
/* ======================================= CUSTOM JS ======================================= */ var works = [ { key: "arcos", title: "Instituto Arcos Create", year: "2016", client: "Instituto Arcos Create - Cultura y actualidad", designdetail: "Anuncios, Administración Facebook, Instagram y Twitter", images: [ "images/material_portafolio/create/cover_final.png", "images/material_portafolio/create/seleccionados_vina.png", "images/material_portafolio/create/Miercoles11_create.png" ] }, { key: "decomundo", title: "Decomundo Decoracíon", year: "2017", client: "Decomundo Decoracíon", designdetail: "Diseño soportes digitales: Renovación de imagen (portada, perfil) y contenido redes sociales", images: [ "images/material_portafolio/decomundo/logo.jpg", "images/material_portafolio/decomundo/banner_decomundo_2.png", "images/material_portafolio/decomundo/collar.png", "images/material_portafolio/decomundo/publicaion_decomundo.jpg" ] }, { key: "auriculoterapeuta", title: "Nutricionista Auriculoterapeuta", year: "2017", client: "Eyleen Quinteros – Nutricionista Auriculoterapeuta", designdetail: "Diseño tarjeta presentación. Imagen, composición, troquel y materialidad", images: [ "images/material_portafolio/nutricionista/tarjeta_1.jpg", "images/material_portafolio/nutricionista/tarjeta_2.jpg", "images/material_portafolio/nutricionista/tarjeta_3.jpg" ] }, { key: "facialup", title: "Facial Up", year: "2016", client: "Facial Up", designdetail: "Diseño y desarrollo de soportes digitales: Post, Mailing, publicidad instagram, Fb portada y diseño de infografías", images: [ "images/material_portafolio/facial_up/miercoles_24.png", "images/material_portafolio/facial_up/ABIFOODS.png", "images/material_portafolio/facial_up/bruxismo_3.png", "images/material_portafolio/facial_up/Instagram_asesoria img_2.png", "images/material_portafolio/facial_up/Instagram_receta.png", "images/material_portafolio/facial_up/Perfil_fp_facialup_5.png", "images/material_portafolio/facial_up/PSD_quinoa.png", "images/material_portafolio/facial_up/viernes_27.png", "images/material_portafolio/facial_up/MARTES 2_FacialUp.png" ] }, { key: "interfilm", title: "Interfilm Ltda.", year: "2016", client: "Interfilm Ltda.", designdetail: "Desarrollo de soportes digitales: Diseño y creación de post y contenido redes sociales. Anuncios, publicidad e infografías", images: [ "images/material_portafolio/interfilm/MARTES 2_interfilm.png", "images/material_portafolio/interfilm/MARTES 9_interfilm.png", "images/material_portafolio/interfilm/Martes 18_oct.png", "images/material_portafolio/interfilm/Martes-19_interfilm.jpg", "images/material_portafolio/interfilm/MIERCOLES 6_interfilm.png", "images/material_portafolio/interfilm/Miercoles 31_interfilm.png", "images/material_portafolio/interfilm/miercoles_28 Sept.png", "images/material_portafolio/interfilm/VIERNES 5_interfilm.png", "images/material_portafolio/interfilm/VIERNES_15-de-Julio.jpg" ] }, { key: "propiedades", title: "Corretaje de propiedades", year: "2015", client: "Nancy Romero - Corretaje de propiedades", designdetail: "Diseño de logotipo", images: [ "images/material_portafolio/propiedades/logotipo_propiedades.jpg" ] }, { key: "tome", title: "Comuna de Tomé 8vaR", year: "2014", client: "Comuna de Tomé 8vaR", designdetail: "Diseño de logotipo. Ganadora de Concurso a nivel comunal. Actual imagen de Municipalidad, Tomé Octava Región del Bío Bío", images: [ "images/material_portafolio/tome/logotipo_final.jpg" ] }, { key: "sanwor", title: "Sanwor Ltda.", year: "2015", client: "Sanwor Ltda.", designdetail: "Diseño de Logotipo y papelería básica", images: [ "images/material_portafolio/sanwor/pdf.jpg", "images/material_portafolio/sanwor/Sanwor_carta.jpg", "images/material_portafolio/sanwor/Sobre_sanword.png" ] }, { key: "silhouette", title: "Silhouette Chile", year: "2017", client: "Silhouette Chile", designdetail: "Desarrollo de soportes publicitarios (Diseño y composición de lateral revista Materia prima, Creación de Catálogo y Packaging). Desarrollo de soportes digital (Anuncios, post, mailing, concursos, redes sociales)", images: [ "images/material_portafolio/silhouette/conejo_huevos.jpg", "images/material_portafolio/silhouette/descuentos_cumpleanos.png", "images/material_portafolio/silhouette/flyer_materia prima.png", "images/material_portafolio/silhouette/Instagram_concurso.png", "images/material_portafolio/silhouette/Instagram_dia_de_la_mujer.png", "images/material_portafolio/silhouette/Lateral_medida_final.jpg", "images/material_portafolio/silhouette/Promocion_San_Valentin.png", "images/material_portafolio/silhouette/Taller.png" ] }, { key: "nutrymas", title: "Nutrymás", year: "2017", client: "Nutrymás – Clínica Nutrición y Dietética", designdetail: "Diseño de Logotipo", images: [ "images/material_portafolio/nutrymas/logotipo_final_nutrymas_rgb-01.jpg" ] }, { key: "ttihone", title: "TTihone", year: "2016", client: "TTihone", designdetail: "Desarrollo de soportes digital (Publicidad, Mailing, Diseño de portada, Anuncios y post)", images: [ "images/material_portafolio/ttihone/mailingblanco.jpg", "images/material_portafolio/ttihone/mailing.jpg", "images/material_portafolio/ttihone/perfilfutbolista.png" ] }, { key: "casitadeco", title: "Casita Deco", year: "2017", client: "Casita Deco", designdetail: "Diseño logotipo, imagen corporativa y administración de contenido en redes sociales. Proyecto personal, creado exclusivamente para comercializar artículos de decoración, vinilos, papelería, packaging, entre otros", images: [ "images/material_portafolio/casita_deco/logo.png", "images/material_portafolio/casita_deco/banner_casita.png", "images/material_portafolio/casita_deco/Anuncio_1_casita_deco.jpg" ] }, { key: "katho", title: "Katho Jerez SpA", year: "2016", client: "Katho Jerez SpA – Marketing Digital", designdetail: "Imagen Corporativa y Manejo de RRSS. Diseño y desarrollo de soportes gráficos (Pendón, tarjetas de presentación, planificador, separador de páginas, caluga soporte editorial). Desarrollo soportes digital (Anuncios promocionales, post, mailing, recursos gráficos y publicidad en redes sociales)", images: [ "images/material_portafolio/katho/Flyer_feria.jpg", "images/material_portafolio/katho/flyer_vestido.jpg", "images/material_portafolio/katho/Cover_2.png", "images/material_portafolio/katho/Instagram_docentes.png", "images/material_portafolio/katho/planificador_Noviembre_para-grupo.jpg", "images/material_portafolio/katho/promocion_final.jpg", "images/material_portafolio/katho/Promocion_15_noviembre.png", "images/material_portafolio/katho/Separador.jpg" ] }, { key: "revista", title: "Revista Viajero", year: "2011", client: "Transportes Línea Azul", designdetail: "Diseño y diagramación de revista", images: [ "images/material_portafolio/revista_viajero/revista.jpg", "images/material_portafolio/revista_viajero/revista2.jpg", "images/material_portafolio/revista_viajero/revista3.jpg", "images/material_portafolio/revista_viajero/revista4.jpg", "images/material_portafolio/revista_viajero/revista5.jpg", "images/material_portafolio/revista_viajero/revista6.jpg", "images/material_portafolio/revista_viajero/revista7.jpg", "images/material_portafolio/revista_viajero/revista8.jpg", "images/material_portafolio/revista_viajero/revista9.jpg", "images/material_portafolio/revista_viajero/revista10.jpg", "images/material_portafolio/revista_viajero/revista11.jpg", "images/material_portafolio/revista_viajero/revista12.jpg", "images/material_portafolio/revista_viajero/revista13.jpg", "images/material_portafolio/revista_viajero/revista14.jpg", "images/material_portafolio/revista_viajero/revista15.jpg", "images/material_portafolio/revista_viajero/revista16.jpg", "images/material_portafolio/revista_viajero/revista17.jpg", "images/material_portafolio/revista_viajero/revista18.jpg" ] } ]; function loadWorks() { var work = window.location.hash.split("=")[1]; var data = works.filter(function(item) { return item.key === work; })[0]; if (data && data.hasOwnProperty("key")) { $(".title").text(data.title); $(".year").text(data.year); $(".client").text(data.client); $(".design-detail").text(data.designdetail); for (var j = 0; j < data.images.length; j++) { var img = document.createElement("img"); img.setAttribute("class","work-img img-responsive"); img.setAttribute("src", data.images[j]); document.getElementById("work-images-grid").appendChild(img); } } }; $(".navbar").hide(); $("footer").hide(); $(".scrollToTop").hide(); $(".loading-circle").show(); new WOW().init(); $(".carousel").carousel(); $(function() { // Scrolling $('a.scroller').on('click', function(event) { $.scrollify.move($(this).attr("href")); }); $.scrollify({ section : ".scrollify", sectionName : "section-name", interstitialSection : "", easing: "easeOutExpo", scrollSpeed: 1300, offset : 0, setHeights: false, updateHash: true, }); // sidr config $("#mobile-menu-toggle").sidr({ side: "right", name: "sidr", onOpen: function() { // $("#mobile-menu-toggle").find(".icon").toggle(); $("#mobile-menu-toggle").toggleClass("is-open"); $(".wrapper").toggleClass("blur"); }, onClose: function() { // $("#mobile-menu-toggle").find(".icon").toggle(); $("#mobile-menu-toggle").toggleClass("is-open"); $(".wrapper").toggleClass("blur"); } }); // Close Sidr menu after click link or click outside $(document).on("click","#sidr",function(e) { if( $(e.target).is("a") ) { $.sidr("close", "sidr"); } }); $(document).bind("click", function () { $.sidr("close", "sidr"); }); // Navbar hide and show scroll // $(window).scroll(function () { // if ($(this).scrollTop() > 100) { // $(".navbar").fadeIn(); // } else { // $(".navbar").fadeOut(); // } // }); function resizeNav() { if($(document).scrollTop()>10){ $(".navbar").fadeIn(); } else{ $(".navbar").fadeOut(); } } resizeNav(); $(window).on('scroll',resizeNav); // Scroll totop $(window).scroll(function() { if($(this).scrollTop() != 0) { $(".scrollToTop").fadeIn(); } else { $(".scrollToTop").fadeOut(); } }); $(".scrollToTop").click(function() { $("body,html").animate({scrollTop:0},800); }); // Filter works gallery $(".filter-button").click(function(){ var value = $(this).attr("data-filter"); $(this).siblings().removeClass("active"); $(this).toggleClass("active"); if($(this).hasClass("active")) { $(".work-container").addClass("wow animated fadeIn"); } if(value == "all") { $(".filter").show("1000"); } else { $(".filter").not("."+value).hide("3000"); $(".filter").filter("."+value).show("3000"); } }); }); // Preload body overlay effect $(window).on("load", function () { $("body").addClass("is-loaded"); $(".loading-circle").addClass("hidden"); $("nav.navbar").removeClass("hidden"); $("footer").show(); loadWorks(); });
function dec2hex(s) { return (s < 15.5 ? '0' : '') + Math.round(s).toString(16); } function hex2dec(s) { return parseInt(s, 16); } function base32tohex(base32) { var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; var bits = ""; var hex = ""; for (var i = 0; i < base32.length; i++) { var val = base32chars.indexOf(base32.charAt(i).toUpperCase()); bits += leftpad(val.toString(2), 5, '0'); } for (var i = 0; i + 4 <= bits.length; i += 4) { var chunk = bits.substr(i, 4); hex = hex + parseInt(chunk, 2).toString(16); } return hex; } function leftpad(str, len, pad) { if (len + 1 >= str.length) { str = Array(len + 1 - str.length).join(pad) + str; } return str; } function updateOtp() { var key = base32tohex($('#secret').val()); var epoch = Math.round(new Date().getTime() / 1000.0); //console.log('epoch = ' + epoch); var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0'); //console.log('time = ' + time); // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/ var shaObj = new jsSHA("SHA-1", "HEX"); shaObj.setHMACKey(key, "HEX"); shaObj.update(time); var hmac = shaObj.getHMAC("HEX"); //console.log('hmac = ' + hmac); var url='https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=200x200&chld=M|0&cht=qr&chl=otpauth://totp/user@host.com%3Fsecret%3D' + $('#secret').val() $('#qrImg').attr('src', url); $('#secretHex').text(key); $('#secretHexLength').text((key.length * 4) + ' bits'); $('#epoch').text(time); $('#hmac').empty(); if (hmac == 'KEY MUST BE IN BYTE INCREMENTS') { $('#hmac').append($('<span/>').addClass('label important').append(hmac)); } else { var offset = hex2dec(hmac.substring(hmac.length - 1)); var part1 = hmac.substr(0, offset * 2); var part2 = hmac.substr(offset * 2, 8); var part3 = hmac.substr(offset * 2 + 8, hmac.length - offset); if (part1.length > 0) $('#hmac').append($('<span/>').addClass('label label-default').append(part1)); $('#hmac').append($('<span/>').addClass('label label-primary').append(part2)); if (part3.length > 0) $('#hmac').append($('<span/>').addClass('label label-default').append(part3)); } var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + ''; otp = (otp).substr(otp.length - 6, 6); $('#otp').text(otp); GetSevOTP(); GetQrUrls(url); } function timer() { var epoch = Math.round(new Date().getTime() / 1000.0); var countDown = 30 - (epoch % 30); if (epoch % 10 == 0) updateOtp(); $('#updatingIn').text(countDown); } function GetQrUrls(jsUrl) { var url = '/OneTimePass/GetQrURL'; $.get(url, function (data) { $('#jsUrl').text(jsUrl); $('#srvUrl').text(data); }); } function GetSevOTP() { console.log('GetSevOTP'); var url = '/OneTimePass/GetOTP'; $.get(url, function (data) { console.log(data); $('#txtSrvOtp').val(data); }); } function GeterateLocalQrCode() { var url = 'otpauth://totp/user@host.com?secret=JBSWY3DPEHPK3PXP'; var url1 = 'otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example'; $('#divQrCode').qrcode({ width: 200, height: 200, text: url }); } $(function () { GeterateLocalQrCode(); updateOtp(); $('#update').click(function (event) { updateOtp(); event.preventDefault(); }); $('#secret').keyup(function () { updateOtp(); }); $('#btnCheck').click(function (event) { var url = '/OneTimePass/CheckPass/' + $('#txtOtp').val(); $.get(url, function (data) { console.log("Done:" + data); }); }); //setInterval(timer, 1000); });
import React, { useState } from 'react'; import styled from 'styled-components'; import { useSelector } from 'react-redux'; import { useParams } from '@reach/router'; import ProfessionsSVG from './../../svg/professions.svg'; import { getUsersByName, getUsersByProfession } from '../../utils/filters.js'; import Profession from '../Profession'; import SectionBanner from '../Banners/SectionBanner'; import UsersList from '../User/UsersList.js'; import SearchInput from '../SearchInput.js'; import DataManager from '../DataManager'; export const ProfessionHeader = styled.div` background: white; position: sticky; top: 0; display: grid; grid-template-columns: 100%; row-gap: 13px; svg, section { justify-self: center; } `; const ProfessionsFinder = () => { let { name } = useParams(); const { users } = useSelector((state) => state.town); const [searchValue, setSearchValue] = useState(''); const usersByProfession = getUsersByProfession(users, name); const searchedUsers = getUsersByName(usersByProfession, searchValue); const search = (inputSearchValue) => { setSearchValue(inputSearchValue); }; return ( <section data-testid="ProfessionSite"> <ProfessionHeader> <SectionBanner /> <ProfessionsSVG width={49.83}> </ProfessionsSVG> <Profession name={name}> </Profession> <SearchInput onSearch={search} /> </ProfessionHeader> <DataManager> <UsersList users={searchedUsers} usersPerPage={15} /> </DataManager> </section> ); }; export default ProfessionsFinder;
/* Write a function that sorts array while keeping the array structure. Numbers should be first then letters both in ascending order. Examples numThenChar([ [1, 2, 4, 3, "a", "b"], [6, "c", 5], [7, "d"], ["f", "e", 8] ]) ➞ [ [1, 2, 3, 4, 5, 6], [7, 8, "a"], ["b", "c"], ["d", "e", "f"] ] numThenChar([ [1, 2, 4.4, "f", "a", "b"], [0], [0.5, "d","X",3,"s"], ["f", "e", 8], ["p","Y","Z"], [12,18] ]) ➞ [ [0, 0.5, 1, 2, 3, 4.4], [8], [12, 18, "X", "Y", "Z"], ["a", "b", "d"], ["e", "f", "f"], ["p", "s"] ] Notes Test cases will containg integer and float numbers and single letters. */ const numThenChar = arr => { let values = arr.flat(); values = [ ...values.filter(v => typeof v === "number").sort((a, b) => a - b), ...values.filter(v => typeof v === "string").sort() ]; return arr.map(a => a.map(b => values.shift())); }
var buttonRock = document.getElementById('rock'); var buttonScissors = document.getElementById('scissors'); var buttonPaper = document.getElementById('paper'); var buttonNewGame = document.getElementById('new-game'); var output = document.getElementById('output'); var result = document.getElementById('result'); var finalResult = document.getElementById('final-result'); var message = document.getElementById('message'); var roundNumber = 0; var roundWonByComputerNumber = 0; var roundWonByPlayerNumber = 0; var roundToWinNumber = 0; buttonNewGame.addEventListener ('click', function() { roundToWinNumber = window.prompt('Specify game distance (number of rounds to win)'); roundNumber = 0; roundWonByComputerNumber = 0; roundWonByPlayerNumber = 0; output.innerHTML = 'You started a New Game'; finalResult.innerHTML = ''; display(); }); function calculateWinner(playerMove) { if ((roundToWinNumber <= roundWonByComputerNumber) || (roundToWinNumber <= roundWonByPlayerNumber)) { pleasePressTheNewGameButton(); return; } var computerMove = getRandomIntInclusive(1, 3); if ((computerMove == 1 && playerMove == 2) || (computerMove == 2 && playerMove == 3) || (computerMove == 3 && playerMove == 1)) { output.innerHTML = 'ROUND LOST'; roundWonByComputerNumber++; } else if (computerMove == playerMove) { output.innerHTML = 'TIE'; } else { output.innerHTML = 'YOU WON'; roundWonByPlayerNumber++; } roundCount(); winnerWonEntireGameDisplay(); } buttonRock.addEventListener ('click', function() { calculateWinner(1); }); buttonScissors.addEventListener ('click', function() { calculateWinner(2); }); buttonPaper.addEventListener ('click', function() { calculateWinner(3); }); function pleasePressTheNewGameButton() { finalResult.innerHTML += 'Game over, please press the new game button !!!' + '<br>'; } function winnerWonEntireGameDisplay() { if (roundToWinNumber == roundWonByComputerNumber) { output.innerHTML += ', COMPUTER WON ENTIRE GAME !!!'; } if (roundToWinNumber == roundWonByPlayerNumber) { output.innerHTML += ', YOU WON ENTIRE GAME !!!'; } } function roundCount() { roundNumber++; display(); } function display() { result.innerHTML = '(You) ' + roundWonByPlayerNumber + ' - ' + roundWonByComputerNumber + ' (Computer)'; message.innerHTML = 'The first one who wins ' + roundToWinNumber + ' rounds is the entire game winner'; } function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Mixed = Schema.Types.Mixed; module.exports = function (connection, modelName) { let jobModel; try { jobModel = connection.model(modelName); } catch (ex) { if (ex.name === 'MissingSchemaError') { const jobSchema = new Schema({ name: { type: String, required: true }, worker: { type: String }, params: {}, queue: { type: String, required: true }, attempts: { type: Mixed, default: null }, timeout: { type: Number, default: null }, delay: Date, priority: Number, status: { type: String, required: true }, enqueued: { type: Date, required: true }, dequeued: Date, ended: Date, error: String, stack: String, result: Mixed }); jobSchema.index({ status: 1, queue: 1, priority: 1, _id: 1, delay: 1 }); jobModel = connection.model(modelName, jobSchema); } else { throw ex; } } return jobModel; };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import Loading from './Loading'; class Post extends Component { constructor(props) { super(props); } onPostClick = (e) => { this.context.router.push(`/posts/${this.props.post.id}/`) } onUserClick=(e)=>{ e.preventDefault() e.stopPropagation() this.context.router.push(`/users/${this.props.post.userId}/`) } render() { const { post } = this.props if (!post) { return ( <Loading/> ) } return ( <div className="post cursor"> <div onClick={this.onPostClick} > <h4 className="description"> <div className="avatar"> <span> {post.user.name[0]} </span> </div> <a href="#" onClick={this.onUserClick} > {post.user.name} </a> <br /> </h4> <h3> {post.title} </h3> <p> {post.body}</p> <span className="italic"> City: {post.user.address.city} </span> </div> </div> ) } } Post.contextTypes = { router: PropTypes.object.isRequired, }; export default Post;
// JavaScript Document window.onload=function(){ var tys=document.getElementById('ty-djs');//获取倒计时的ID var sp=tys.getElementsByTagName('span')[0];//获取倒计时中的span var spt=sp.innerHTML;//获取倒计时中span内容 //让span里的内容每秒减一 var timer=setInterval(function(){ spt--; if(spt<=0){ clearInterval(timer); window.location.href="http://www.gonet.cc/m/"; } sp.innerHTML=spt; },1000); }; $(function(){ //返回按钮代码 $('.pic').click(function(){ //window.location.href="index.html"; history.go(-1); }); //性别按钮效果代码 $(".xb input").click(function(){ var xp=$(".xb input").index(this); $(".xb input").removeClass("on").eq(xp).addClass("on"); }); $("#ty-lj").click(function(){ window.location.href="http://www.gonet.cc/m/"; }); });
/** * @class CQ.form.rte.plugins.SubSuperScriptPlugin * @extends CQ.form.rte.plugins.Plugin * <p>This class implements sub- and superscript as a plugin.</p> * <p>The plugin ID is "<b>subsuperscript</b>".</p> * <p><b>Features</b></p> * <ul> * <li><b>subscript</b> - adds a button to format the selected text with subscript</li> * <li><b>superscript</b> - adds a button to format the selected text with superscript * </li> * </ul> */ CQ.form.rte.plugins.CleanHtmlPlugin = CQ.Ext.extend(CQ.form.rte.plugins.Plugin, { /** * @private */ cleanupUI: null, constructor: function(editorKernel) { CQ.form.rte.plugins.CleanHtmlPlugin.superclass.constructor.call(this, editorKernel); }, getFeatures: function() { return [ "cleanup" ]; }, initializeUI: function(tbGenerator) { var plg = CQ.form.rte.plugins; var ui = CQ.form.rte.ui; if (this.isFeatureEnabled("cleanup")) { this.cleanupUI = new ui.TbElement("cleanup", this, true, this.getTooltip("cleanup")); tbGenerator.addElement("cleanup", plg.Plugin.SORT_FORMAT, this.cleanupUI, 150); } }, execute: function(id) { this.editorKernel.relayCmd("cleanhtml"); }, updateState: function(selDef) { // var hasSubscript = this.editorKernel.queryState("subscript", selDef); // var hasSuperscript = this.editorKernel.queryState("superscript", selDef); // if (this.subscriptUI != null) { // this.subscriptUI.getExtUI().setDisabled(!selDef.isSelection); // this.subscriptUI.getExtUI().toggle(hasSubscript); // } // if (this.superscriptUI != null) { // this.superscriptUI.getExtUI().setDisabled(!selDef.isSelection); // this.superscriptUI.getExtUI().toggle(hasSuperscript); // } }, notifyPluginConfig: function(pluginConfig) { // configuring "special characters" dialog pluginConfig = pluginConfig || { }; var defaults = { "tooltips": { "cleanup": { "title": "Clean Up", "text": "Plain text" } } }; CQ.Util.applyDefaults(pluginConfig, defaults); this.config = pluginConfig; } }); // register plugin CQ.form.rte.plugins.PluginRegistry.register("cleanhtml", CQ.form.rte.plugins.CleanHtmlPlugin);
import * as previewApi from './preview'; export const storiesOf = previewApi.storiesOf; export const setAddon = previewApi.setAddon; export const addDecorator = previewApi.addDecorator; export const configure = previewApi.configure; export const getStorybook = previewApi.getStorybook; // NOTE export these to keep backwards compatibility // export { action } from '@kadira/storybook-addon-actions'; export { linkTo } from '@kadira/storybook-addon-links';
export const required = value => { if (value) return undefined; return 'Field is required'; } export const lenghtCreator = (length) => (value) => { if (value && value.length > length) return `Length more than ${length} symbols`; if (value && value.length < length) return `Length less than ${length} symbols`; return undefined }
const { EventEmitter } = require('events'); const Terminal = new class Terminal extends EventEmitter { // TTY utils RESET = '\x1B[0m'; BOLD = '\x1B[1m'; /** Returns ANSI coloring symbols sequence */ ansi (color, isBG = false) { return `\x1B[${color + (isBG ? 40 : 30)}m`; } clearLine (lines = 0) { process.stdout.write('\r'); process.stdout.moveCursor(0, -lines); readline.clearScreenDown(process.stdout); } /** Just prints text to stdout with new line symbol */ print (line) { process.stdout.write(line + '\n'); } // CLI utils _actions = []; registerAction (action) { this._actions.push(action); } /** Parse CLI input and call matched action */ dispatch () { switch (process.argv[2]) { case '-v': case '--version': process.stdout.write(require('./package').version); process.stdout.isTTY && process.stdout.write('\n'); break; case '-h': case '--help': case '--usage': case 'help': case 'usage': require('./pages/help').full(); break; default: for (const action of this._actions) { if (action.name == process.argv[2]) { try { return action.handler(this._parse(action)); } catch (err) { if (err.length) log.error(...err); else log.error('Unexpected error', err); } } } this.print('No action matching this arguments found\n'); require('./pages/help').header(); break; } } invokeAction (name, opts) { for (const action of this._actions) { if (action.name == name) { return action.handler(opts); } } } _parseError (text) { log.error(text); process.exit(-1); } _parse (action) { const argvLength = process.argv.length; let currentArg; let currentParam = 0; const parsed = {}; args_loop: for (let i = 3; i < argvLength; i++) { const part = process.argv[i]; if (part[0] == '-') { if (action.args) { const isShort = part[1] != '-'; for (const argProp in action.args) { const argInfo = action.args[argProp]; if (isShort ? (argInfo.short == part.slice(1)) : (argInfo.name == part.slice(2))) { currentArg = argProp; continue args_loop; } } this._parseError(`This action has no "${part}" argument`); } else { this._parseError('This action takes no argument'); } } else if (currentArg) { switch (action.args[currentArg].type) { case String: parsed[currentArg] = part; break; case Number: parsed[currentArg] = Number(part); break; case Boolean: if (part == 'true' || part == '1') { parsed[currentArg] = true; } else if (part == 'false' || part == '0') { parsed[currentArg] = false; } break; } currentArg = null; } else { if (action.params) { const [paramProp, paramInfo] = Object.entries(action.params)[currentParam++]; parsed[paramProp] = part; } else { this._parseError('This action has no parameters'); } } } for (const argProp in action.args) { if (argProp in parsed) continue; const argInfo = action.args[argProp]; if (argInfo.default === undefined) { this._parseError(`The "--${argInfo.name}"${argsInfo.short ? ` or "-${argsInfo.short}"` : ''} argument is required for current action`); } else { parsed[argProp] = argInfo.default; } } for (const paramProp in action.params) { if (paramProp in parsed) continue; const paramInfo = action.params[paramProp]; if (paramInfo.default === undefined) { this._parseError(`The "${paramInfo.name}" parameter is required for current action`); } else { parsed[paramProp] = paramInfo.default; } } return parsed; } } module.exports = { Terminal }; const readline = require('readline'); const log = require('./log'); readline.emitKeypressEvents(process.stdin); if (process.stdin.setRawMode) process.stdin.setRawMode(true); let input = ''; process.stdin.on('keypress', (str, key) => { if (key.ctrl && key.name == 'c') return process.exit(0); if (key.name == 'return') { Terminal.emit('line', input); input = ''; } else if (!str || str == ' ') { Terminal.emit('key', key); } else { if (key.name == 'backspace') { input = input.slice(0, -1); Terminal.emit('key', key); } else { input += str; Terminal.emit('symbol', str); } } });
$(function(){ $("#selcate").change(function(){ var cate_id = $(this).val(); $.ajax({ type:'get', url: '/admin.php/member/order/ajax_cate?cate_id='+cate_id, dataType: 'json', success:function(data){ var html = '<option value="">----请选择产品----</option>'; var l = data.length; var i = 0; for(i = 0; i < l; i++) { html += '<option value="'+data[i]["goods_id"]+'">'+data[i]['goods_name']+'</option>'; } $("#selprod").html(html); $("#selprod").show(); $("#seltons").html(""); } }); }); $("#selprod").change(function(){ var goods_id = $(this).val(); $.ajax({ type:'get', url: '/admin.php/member/order/ajax_tons?goods_id='+goods_id, dataType: 'json', success:function(data){ var html = '<option value="0">----请选择规格----</option>'; var l = data.length; var i = 0; for(i = 0; i < l; i++) { html += '<option value="'+data[i]["id"]+'">'+data[i]['prod_spec']+'</option>'; } $("#seltons").html(html); $("#seltons").show(); } }); }); $("#seltons").change(function(){ var tons_id = $(this).val(); $.ajax({ type:'get', url: '/admin.php/member/order/ajax_tons_info?tons_id='+tons_id, dataType: 'json', success:function(data){ $("#spec_ku_tonsid").val(data["id"]); $("#spec_ku_tons").val(data["prod_spec"]); $("#spec_ku_smishu").val(data["stand_height"]); $("#spec_ku_sprice").val(data["price"]); $("#spec_ku_sjiacha").val(data["each_price"]); if(data["stand_height"]){ $("#spec_mishu_show1").show(); $("#spec_mishu_show2").show(); $("#add_mishu").val(data["stand_height"]); } } }); }); $("#user_name").change(function(){ var user_id = $(this).val(); $.ajax({ type:'get', url: '/admin.php/member/order/ajax_user_address?user_id='+user_id, dataType: 'json', success:function(data){ var html = ''; var l = data.length; var i = 0; for(i = 0; i < l; i++) { html += '<li><label><input type="radio" value="'+data[i]["address_id"]+'" name="user_address" />'+data[i]['area_info']+'&nbsp;&nbsp;'+data[i]['address']+'&nbsp;('+data[i]['true_name']+')&nbsp;</label></li>'; } $("#user_address_html").html(html); } }); }); $("#count_order_sel").change(function(){ var tag_id = $(this).val(); $.ajax({ type:'get', url: '/admin.php/member/order/ajax_count_total?tag_id='+tag_id, dataType: 'json', success:function(data){ $("#count_order_val").html(data["goods_amount"]+"元"); } }); }); }); /*手动输入数量控制----产品下单*/ function numchange2(){ var goodsnum = parseInt($("#add_numbs").val()); if(goodsnum <= 1 || goodsnum == null || goodsnum=="" || isNaN(goodsnum)){ goodsnum = 1; } $("#add_numbs").val(goodsnum); }
const mongoose = require("mongoose") const routeSchema = mongoose.Schema({ fecha:{type : String}, idVendedor:{type: String, required: true}, route:[{ latitude: {type: Number, required: true}, longitude: {type: Number, required: true}, date:{type:Date,default: Date.now} }] },{ timestamps:true } ) module.exports = mongoose.model("Route", routeSchema)
function format(state) { if (!state.id) return state.text; return "<img class='flag' src='../assets/img/flags/" + state.id.toLowerCase() + ".png'/> &nbsp;" + state.text; } var placeholder = "Select a State"; $('.select2, .select2-multiple').select2({ theme: "bootstrap", placeholder: placeholder, }); $("#selitemIcon").select2({ theme: "bootstrap", templateResult: format, formatSelection: format, escapeMarkup: function(m) { return m; } }); $('.select2-allow-clear').select2({ theme: "bootstrap", allowClear: true, placeholder: placeholder }); $( "button[data-select2-open]" ).click( function() { $( "#" + $( this ).data( "select2-open" ) ).select2( "open" ); }); $( ":checkbox" ).on( "click", function() { $( this ).parent().nextAll( "select" ).prop( "disabled", !this.checked ); });
/* 新增:【新促銷】促銷免運 add by shuangshuang0420j 20150727 15:07 修改1: 修改2: */ var currentRecord = { data: {} }; var pageSize = 25; Ext.Loader.setConfig({ enabled: true }); var freightStore = Ext.create('Ext.data.Store', { fields: ['parameterName', 'ParameterCode'], data: [ { 'parameterName': '全部', 'ParameterCode': '0' }, { 'parameterName': '常溫', 'ParameterCode': '1' }, { 'parameterName': '冷凍', 'ParameterCode': '2' }, ] }); //簡訊查詢Model Ext.define('gigade.Ipo', { extend: 'Ext.data.Model', fields: [ { name: "row_id", type: "int" }, { name: "po_id", type: "string" }, { name: "vend_id", type: "string" }, { name: "buyer", type: "string" }, { name: "sched_rcpt_dt", type: "string" }, { name: "po_type", type: "string" }, { name: "po_type_desc", type: "string" }, { name: "cancel_dt", type: "string" }, { name: "msg1", type: "string" }, { name: "msg2", type: "string" }, { name: "msg3", type: "string" }, { name: "create_user", type: "string" }, { name: "create_dtim", type: "string" },//user_username { name: "status", type: "int" }, { name: "user_username", type: "string" } ] }); var IpoStore = Ext.create('Ext.data.Store', { pageSize: pageSize, model: 'gigade.Ipo', proxy: { type: 'ajax', url: '/WareHouse/GetIpoList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); Ext.define("gigade.parameter", { extend: 'Ext.data.Model', fields: [ { name: "ParameterCode", type: "string" }, { name: "parameterName", type: "string" } ] }); var PoTypeStore = Ext.create('Ext.data.Store', { model: 'gigade.parameter', autoLoad: true, proxy: { type: 'ajax', url: "/WareHouse/GetPromoInvsFlgList?Type=po_type", // actionMethods: 'post', reader: { type: 'json', root: 'data' } } }); Ext.define('gigade.Ipod', { extend: 'Ext.data.Model', fields: [ { name: "row_id", type: "int" }, { name: "po_id", type: "string" }, { name: "pod_id", type: "int" }, { name: "ParameterCode", type: "string" }, { name: "bkord_allow", type: "string" }, { name: "cde_dt_incr", type: "int" }, { name: "cde_dt_var", type: "int" }, { name: "cde_dt_shp", type: "int" }, { name: "pwy_dte_ctl", type: "string" }, { name: "qty_ord", type: "int" }, { name: "qty_damaged", type: "int" }, { name: "qty_claimed", type: "int" }, { name: "promo_invs_flg", type: "string" }, { name: "req_cost", type: "string" }, { name: "off_invoice", type: "string" }, { name: "new_cost", type: "string" }, { name: "freight_price", type: "int" }, { name: "prod_id", type: "string" }, { name: "product_id", type: "int" }, { name: "product_name", type: "string" }, { name: "create_user", type: "string" }, { name: "user_username", type: "string" }, { name: "create_dtim", type: "string" }, { name: "change_dtim", type: "string" }, { name: "user_username", type: "string" }, { name: "parameterName", type: "string" }, { name: "plst_id", type: "string" }, { name: "spec", type: "string" }, { name: "item_stock", type: "string" },//庫存 { name: 'cde_dt', type: "string" }, { name: 'made_date', type: "string" }, ] }); // //採購單單身store var IpodStore = Ext.create('Ext.data.Store', { autoDestroy: true, pageSize: pageSize, model: 'gigade.Ipod', proxy: { type: 'ajax', url: '/WareHouse/GetIpodCheck', reader: { type: 'json', root: 'data' } }, //listeners: { //update: function (store, record) { // //如果編輯的是轉移數量 // //var row_id = e.record.data.row_id; // var qty_damaged = record.get("qty_damaged"); // var qty_claimed = record.get("qty_claimed"); // var qty_ord = record.get("qty_ord"); // if (parseInt(qty_claimed) == 0 && parseInt(qty_damaged) == 0) // { // ; // } // else if (parseInt(qty_claimed) > parseInt(qty_ord) ) // { // Ext.Msg.alert("錯誤提示", "允收數量不能大於下單採購量,保存失敗!"); // return false; // } // if (record.isModified('qty_damaged') || record.isModified('qty_claimed')) { // Ext.Ajax.request({ // url: '/WareHouse/UpdateIpodCheck', // params: { // row_id: record.get("row_id"), // qty_damaged: record.get("qty_damaged"), // qty_claimed: record.get("qty_claimed"), // item_stock: parseInt(record.get("item_stock")) + parseInt(qty_claimed), // plst_id:"F" // }, // success: function (response) // { // var res = Ext.decode(response.responseText); // if (res.success) // { // Ext.Msg.alert("提示信息", "驗收成功!"); // IpodStore.load(); // } // else // { // Ext.Msg.alert("提示信息", "驗收失敗!"); // IpodStore.load(); // } // }, // failure: function () { // Ext.Msg.alert("提示信息", "驗收失敗!"); // } // }); // } // } //} }); IpoStore.on("beforeload", function () { Ext.apply(IpoStore.proxy.extraParams, { Poid: Ext.getCmp("po_id").getValue(), Potype: Ext.getCmp('Poty').getValue(), start_time : Ext.getCmp('start_time').getValue() == null ? null : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('start_time').getValue()), 'Y-m-d 00:00:00')), end_time : Ext.getCmp('end_time').getValue() == null ? null : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('end_time').getValue()), 'Y-m-d 23:59:59')), freight:Ext.getCmp("freight").getValue() }) }) IpodStore.on("beforeload", function () { Ext.apply(IpodStore.proxy.extraParams, { ipod: Ext.getCmp("ipod") ? Ext.getCmp("ipod").getValue() : '' }) }) /************************編輯*********************************/ onEditClick = function () { var row = Ext.getCmp("detailist").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { if (row[0].data.plst_id == "已驗收") { Ext.Msg.alert(INFORMATION, "請選擇未驗收的商品!"); } else { CheckEditFunction(row[0], IpodStore); } } } //左邊活動列表 var ipoList = Ext.create('Ext.grid.Panel', { id: ' ipoList', autoScroll: true, layout: 'anchor', height: document.documentElement.clientHeight - 12, border: false, frame: false, store: IpoStore, dockedItems: [{ id: 'dockedItem', xtype: 'toolbar', layout: 'column', dock: 'top', items: [ { xtype: 'datefield', margin: '5 0 0 0', fieldLabel: "創建時間", labelWidth: 70, id: 'start_time', format: 'Y-m-d', value: "", //value: Tomorrow(1 - new Date().getDate()), editable: false, listeners: { select: function (a, b, c) { var start = Ext.getCmp("start_time"); var end = Ext.getCmp("end_time"); var s_date = new Date(start.getValue()); end.setValue(new Date(s_date.setMonth(s_date.getMonth() + 1))); }, specialkey: function (field, e) { if (e.getKey() == Ext.EventObject.ENTER) { Search(); } } } }, { xtype: 'displayfield', margin: '5 0 0 0', value: '~' }, { xtype: 'datefield', id: 'end_time', format: 'Y-m-d', margin: '5 0 0 0', value: "", //value: Tomorrow(0), editable: false, listeners: { select: function (a, b, c) { var start = Ext.getCmp("start_time"); var end = Ext.getCmp("end_time"); var s_date = new Date(start.getValue()); if (end.getValue() < start.getValue()) { Ext.Msg.alert("提示", "開始時間不能大於結束時間!"); end.setValue(new Date(s_date.setMonth(s_date.getMonth() + 1))); } }, specialkey: function (field, e) { if (e.getKey() == Ext.EventObject.ENTER) { Search(); } } } }, { xtype: 'textfield', fieldLabel: '採購單單號', id: 'po_id', name: 'po_id', margin: '5 0 0 0', width: 210, labelWidth: 70, listeners: { specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Search(); } } } }, { xtype: 'combobox', //類型 editable: false, id: 'freight', fieldLabel: "溫層", name: 'freight', width: 160, labelWidth: 35, margin: '5 0 5 15', store: freightStore, displayField: 'parameterName', valueField: 'ParameterCode', emptyText: "请选择溫層", value: '0' }, { xtype: 'combobox', //類型 editable: false, id: 'Poty', fieldLabel: "採購單類別", name: 'Poty', width: 210, labelWidth: 70, margin: '5 0 0 0', store: PoTypeStore, // margin: '20 0 0 0', lastQuery: '', displayField: 'parameterName', valueField: 'ParameterCode', emptyText: "请选择採購單類別", value: '' }, { xtype: 'button', text: '查詢', id: 'grid_btn_search', iconCls: 'ui-icon ui-icon-search', margin: ' 5 0 10 0', width: 70, handler: Search }, { xtype: 'button', text: "打印採購單", margin: ' 5 0 5 0', width: 90, id: 'ExportEnter', icon: '../../../Content/img/icons/excel.gif', handler: onExportEnter }, ] }], columns: [ { header: '採購單單號', dataIndex: 'po_id', align: 'center', width: 120, menuDisabled: true, sortable: false }, { header: '採購單別描述', dataIndex: 'po_type_desc', align: 'center', width: 120, menuDisabled: true, sortable: false, flex: 1 }, { header: "廠商代號", dataIndex: 'vend_id', width: 100, align: 'center', menuDisabled: true, sortable: false }, { header: '創建時間', dataIndex: 'create_dtim', align: 'center', menuDisabled: true, sortable: false } ], bbar: Ext.create('Ext.PagingToolbar', { store: IpoStore, dock: 'bottom', pageSize: pageSize, displayInfo: true }), listeners: { itemclick: function (view, record, item, index, e) { LoadDetail(currentRecord = record); }, resize: function () { this.doLayout(); } } }) var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', { clicksToMoveEditor: 1, autoCancel: false, clicksToEdit: 1, errorSummary: false, listeners: { beforeedit: function (e, eOpts) { if (e.colIdx == 0) { e.hide(); } if (e.record.data.plst_id == "已驗收") { return false; } }, edit: function (e, eOpts) { Ext.Msg.confirm("提示信息", "確認是否保存?", function (btn) { if (btn == "yes") { //如果編輯的是轉移數量 //var row_id = e.record.data.row_id; var qty_damaged = e.record.data.qty_damaged; e.record.data.item_stock var qty_claimed = e.record.data.qty_claimed; var qty_ord = e.record.data.qty_ord; if (parseInt(qty_claimed) == 0 && parseInt(qty_damaged) == 0) { ; } else if (parseInt(qty_claimed) > parseInt(qty_ord)) { Ext.Msg.alert("錯誤提示", "允收數量不能大於下單採購量,保存失敗!"); IpodStore.load(); return false; } //Ext.Msg.alert("提示", e.originalValues); return false; //if (record.isModified('qty_damaged') || record.isModified('qty_claimed')) { Ext.Ajax.request({ url: '/WareHouse/UpdateIpodCheck', params: { row_id: e.record.data.row_id, qty_damaged: e.record.data.qty_damaged, qty_claimed: e.record.data.qty_claimed, item_stock: parseInt(e.record.data.item_stock) + parseInt(qty_claimed), plst_id: "F" }, success: function (response) { var res = Ext.decode(response.responseText); if (res.success) { Ext.Msg.alert("提示信息", "驗收成功!"); IpodStore.load(); } else { Ext.Msg.alert("提示信息", "驗收失敗!"); IpodStore.load(); } }, failure: function () { Ext.Msg.alert("提示信息", "驗收失敗!"); IpodStore.load(); } }); } } else { IpodStore.load(); } }); }, } }); Ext.grid.RowEditor.prototype.saveBtnText = "保存"; Ext.grid.RowEditor.prototype.cancelBtnText = "取消"; var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { Ext.getCmp("center").down('#edit').setDisabled(selections.length == 0); } } }); var center = Ext.create('Ext.form.Panel', { id: 'center', autoScroll: true, border: false, frame: false, layout: { type: 'vbox', align: 'stretch' }, defaults: { margin: '2 2 2 2' }, items: [ { id: 'ipod', xtype: 'textfield', fieldLabel: "ipod", maxLength:18, labelWidth: 70, //regex: /^\d+$/, //regexText: '请输入正確的編號,訂單編號,行動電話進行查詢', name: 'ipod', allowBlank: true, hidden: true, }, { title: '採購單內容', xtype: 'gridpanel', id: 'detailist', autoScroll: true, frame: false, height: document.documentElement.clientHeight-15, store: IpodStore, //plugins: [rowEditing], columns: [ { header: "驗收狀態", dataIndex: 'plst_id', width: 80, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value=="已驗收") { return '<span style="color:red">'+ value +'</span> '; } else { return '<span style="color:green">' +value + '</span> '; } } }, { header: "商品編號", dataIndex: 'product_id', width: 80, align: 'center' }, { header: "商品名稱", dataIndex: 'product_name', width: 200, align: 'center' }, { header: "商品細項編號", dataIndex: 'prod_id', width: 80, align: 'center' }, { header: "規格", dataIndex: 'spec', width: 80, align: 'center' }, //{ header: "收貨狀態", dataIndex: 'parameterName', width: 100, align: 'center' }, //{ header: "收貨狀態", dataIndex: 'ParameterCode', width: 100, align: 'center', hidden: true }, { header: "下單採購量", dataIndex: 'qty_ord', width: 80, align: 'center' }, { header: "前台庫存", dataIndex: 'item_stock', width: 80, align: 'center' }, //{ header: "是否允許多次收貨", dataIndex: 'bkord_allow', width: 120, align: 'center' }, { header: "不允收的量", dataIndex: 'qty_damaged', flex: 1, align: 'center', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, maxValue: 99999, allowDecimals: false } }, { header: "允收數量", dataIndex: 'qty_claimed', flex: 1, align: 'center', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, maxValue: 99999, allowDecimals: false } }, { header: "製造日期", dataIndex: 'made_date', flex: 1, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value == "0001-01-01") { return ''; } else { return value; } } }, { header: "有效日期", dataIndex: 'cde_dt', flex: 1, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value == "0001-01-01") { return ''; } else { return value; } } }, //{ header: "品項庫存用途", dataIndex: 'promo_invs_flg', flex: 1, align: 'center' }, //{ header: "訂貨價格", dataIndex: 'new_cost', flex: 1, align: 'center' }, //{ header: "運費", dataIndex: 'freight_price', flex: 1, align: 'center' }, //{ header: "是否有效期控管", dataIndex: 'pwy_dte_ctl', flex: 1, align: 'center' }, //{ header: "有效期天數", dataIndex: 'cde_dt_incr', flex: 1, align: 'center' }, //{ header: "允收天數", dataIndex: 'cde_dt_var', flex: 1, align: 'center' }, //{ header: "允出天數", dataIndex: 'cde_dt_shp', flex: 1, align: 'center' }, //{ header: "創建人", dataIndex: 'user_username', flex: 1, align: 'center' }, //{ header: "創建時間", dataIndex: 'create_dtim', flex: 1, align: 'center' }, { header: "修改人", dataIndex: 'user_username', flex: 1, align: 'center' }, { header: "修改時間", dataIndex: 'change_dtim', flex: 1, align: 'center' } ], tbar: [ { xtype: 'button', text: "驗收", id: 'edit', iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }, // { xtype: 'button', text: "刪除", id: 'delete', iconCls: 'icon-user-remove', disabled: true, }//handler: onDeleteClick ], listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } }, }, selModel: sm } ], //bbar: Ext.create('Ext.PagingToolbar', { // store: IpodStore, // pageSize: pageSize, // displayInfo: true, // displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', // emptyMsg: NOTHING_DISPLAY //}), }) Ext.onReady(function () { Ext.QuickTips.init(); Ext.create('Ext.Viewport', { id: "index", autoScroll: true, width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, layout: 'border', items: [{ region: 'west',//左西 xtype: 'panel', autoScroll: true, frame: false, width: 420, margins: '5 4 5 5', id: 'west-region-container', layout: 'anchor', items: ipoList } , { region: 'center',//中間 id: 'center-region-container', xtype: 'panel', frame: false, layout: 'fit', width: 480, margins: '5 4 5 5', items: center } ], listeners: { resize: function () { Ext.getCmp("index").width = document.documentElement.clientWidth; Ext.getCmp("index").height = document.documentElement.clientHeight; this.doLayout(); }, scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, renderTo: Ext.getBody() }); }); function LoadDetail(record) { if (record.data.row_id == undefined || record.data.row_id == 0) { Ext.getCmp('center').getForm().reset(); IpodStore.removeAll(); } else { Ext.getCmp("ipod").setValue(record.data.po_id); center.getForm().loadRecord(record); IpodStore.load(); //alert(Ext.getCmp("ipod").getValue()); } } function Search() { var Poid = Ext.getCmp("po_id").getValue(); var Potype= Ext.getCmp('Poty').getValue(); var start_time = Ext.getCmp('start_time').getValue() == null ? null : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('start_time').getValue()), 'Y-m-d 00:00:00')); var end_time = Ext.getCmp('end_time').getValue() == null ? null : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('end_time').getValue()), 'Y-m-d 23:59:59')); var freight=Ext.getCmp("freight").getValue(); if (Poid.trim() == "" && Potype.trim() == "" && start_time == null && end_time == null && freight == "0") { Ext.Msg.alert("提示", "請輸入查詢條件!"); return; } //Ext.Msg.alert("提示", Poid+Potype+start_time +end_time+freight); IpoStore.removeAll(); IpoStore.loadPage(1); } function Tomorrow(s) { var d; d = new Date(); // 创建 Date 对象。 // 返回日期。 d.setDate(d.getDate() + s); return d; } /************************匯入 匯出**************************/ function onExportEnter() { var potys = Ext.getCmp('Poty').getValue(); var Poid = Ext.getCmp('po_id').getValue(); var start_time = Ext.getCmp('start_time').getValue() == null ? "" : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('start_time').getValue()), 'Y-m-d 00:00:00')); var end_time = Ext.getCmp('end_time').getValue() == null ? "" : Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('end_time').getValue()), 'Y-m-d 23:59:59')); var freight = Ext.getCmp("freight").getValue(); if (Poid.trim() == "" && potys.trim() == "" && start_time == "" && end_time == "" && freight == "0") { Ext.Msg.alert("提示", "請輸入查詢條件!"); return; } else { var Potype = Ext.getCmp('Poty').getValue(); window.open("/WareHouse/WritePdf?Poid=" + Poid + "&Potype=" + Potype + "&start_time=" + start_time + "&end_time=" + end_time + "&freight=" + freight); } }
describe("TaskModel", function () { var task; beforeEach(function () { task = new TaskModel(); }); it("should be initialized with default values", function () { expect(task.get("id")).toEqual(null); expect(task.get("title")).toEqual(""); }); it("should contain tags when initialized with tags", function () { var json = { id: 100, title: "Sample Task", tags: [ { id: 101, title: "Sample Tag A" }, { id: 102, title: "Sample Tag B" } ] }; var task = new TaskModel(json); expect(task.get("id")).toEqual(100); expect(task.get("title")).toEqual("Sample Task"); expect(task.get("tags").length).toEqual(2); expect(task.get("tags").at(0).get("id")).toEqual(101); expect(task.get("tags").at(0).get("title")).toEqual("Sample Tag A"); expect(task.get("tags").at(1).get("id")).toEqual(102); expect(task.get("tags").at(1).get("title")).toEqual("Sample Tag B"); }); it("should be able to determine if tag is selected", function () { var json = { id: 100, title: "Sample Task", tags: [ { id: 101, title: "Sample Tag A" }, { id: 102, title: "Sample Tag B" } ] }; var task = new TaskModel(json); expect(task.tagSelected(105)).toEqual(false); var tag = new TagModel({ id: 105, title: "Sample Tag C" }); task.get("tags").add(tag); expect(task.tagSelected(105)).toEqual(true); }); });
console.log(7 / 0) // Retorna um Valor Infinito console.log("10" / 2) // Ele valida se é possivel fazer a conversão da string da para valor numerico e faz o caculo console.log("Show!" * 2) // Retorna Not-A-Number (não é um número) console.log(0.1 + 0.7) // Gera uma empresição //console.log(10.ToString()) Não é possivel fazer conversão de um numero para string direto console.log((10.345).toFixed(2)) // é possivel chamar o literal com o valor dentro de parenteses var teste = 'abc.'
import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; import axios from 'axios'; import { ApiFeed } from '../../api/feed'; import { ApiProfile } from '../../api/profile'; import ProfileDisplayTop from '../../components/ProfileDisplayTop'; import ProfilePostList from '../../components/ProfilePostList'; import ProfileFollowers from '../../components/ProfileFollowers'; import ProfileFollowing from '../../components/ProfileFollowing'; import FollowButton from '../../components/FollowButton'; import { defaultMenu, defaultPostState, defaultFollowingState } from '../ProfilePrivate/default'; import { StyledSection, StyledMenuSection, StyledMenuButton, StyledBottomSection } from '../ProfilePrivate/styles'; const ProfilePublic = ({ match }) => { const { uuid } = match.params; const [menu, setMenu] = useState('Posts'); const [post, setPost] = useState(defaultPostState); const [following, setFollowing] = useState(defaultFollowingState); const [myFollowing, setMyFollowing] = useState(defaultFollowingState); const counts = { Posts: post.length || 0, Followers: following.follower.length || 0, Following: following.following.length || 0 }; const UnfollowFunc = followed => { // unfollowing the person I followed ApiProfile( axios, 'delete', '/api/following', { followed }, myFollowing, setMyFollowing, null ); }; const FollowFunc = followed => { ApiProfile( axios, 'post', '/api/following', { followed }, myFollowing, setMyFollowing, null ); }; useEffect(() => { // retrieving list of posts ApiFeed( axios, 'get', `/api/listPost/${uuid}`, null, null, post, setPost, null, null ); // retrieving list of followers and following ApiProfile( axios, 'get', `/api/following/${uuid}`, null, following, setFollowing, null ); // retrieving list of followers and following ApiProfile( axios, 'get', '/api/following/me', null, myFollowing, setMyFollowing, null ); }, [uuid]); let bottomSection; switch (menu) { case 'Posts': bottomSection = ( <ProfilePostList postList={post} publicProfile={true} /> ); break; case 'Followers': bottomSection = ( <ProfileFollowers follower={following.follower} following={myFollowing.following} UnfollowFunc={UnfollowFunc} FollowFunc={FollowFunc} /> ); break; case 'Following': bottomSection = ( <ProfileFollowing groupA={myFollowing.following} following={following.following} UnfollowFunc={UnfollowFunc} FollowFunc={FollowFunc} /> ); break; default: bottomSection = null; break; } const changeMenu = e => { // changing menu setMenu(e); }; return ( <StyledSection> <ProfileDisplayTop publicProfile={true} publicUUID={uuid} /> <StyledMenuSection> {defaultMenu.map(oneMenu => ( <StyledMenuButton type="button" key={oneMenu} att={menu} name={oneMenu} onClick={() => changeMenu(oneMenu)} > {`${oneMenu} : ${counts[oneMenu]}`} </StyledMenuButton> ))} <FollowButton groupA={myFollowing.following} publicUUID={uuid} UnfollowFunc={UnfollowFunc} FollowFunc={FollowFunc} /> </StyledMenuSection> <StyledBottomSection>{bottomSection}</StyledBottomSection> </StyledSection> ); }; export default withRouter(ProfilePublic);
import axios from "axios"; const getChapters = () => async (dispatch) => { try { dispatch({ type: "chapters/loading", payload: [] }); const { data } = await axios.get("http://localhost:5000/api/questions"); dispatch({ type: "chapters/success", payload: data }); } catch (err) { dispatch({ type: "chapters/error", payload: err }); } }; export { getChapters };
import React, { useState, useContext } from 'react' import WatchListContext from '../../../components/contexts/WatchListContext' import { TextInput, Textarea } from '../../../components/utilities/inputs' const WatchListForm = () => { const { dispatch } = useContext(WatchListContext) const [market, setMarket] = useState('') const [context, setContext] = useState('') const [buyAreas, setBuyAreas] = useState('') const [sellAreas, setSellAreas] = useState('') const addItem = (e) => { e.preventDefault() dispatch({ type: 'ADD_ITEM', market, context, buyAreas, sellAreas, }) setMarket('') setContext('') setBuyAreas('') setSellAreas('') } return ( <form onSubmit={addItem}> <TextInput value={market} placeholder="market" onChange={(e) => setMarket(e.target.value)} /> <br /> <Textarea value={context} placeholder="context" onChange={(e) => setContext(e.target.value)} /> <br /> <TextInput value={buyAreas} placeholder="buy areas" onChange={(e) => setBuyAreas(e.target.value)} /> <TextInput value={sellAreas} placeholder="sell areas" onChange={(e) => setSellAreas(e.target.value)} /> <br /> <button>Add</button> </form> ) } export default WatchListForm
const { Router } = require('express'); const { validator } = require('../shared/openapi'); const router = new Router(); router.get('/', validator.validate('get', '/health'), (req, res, next) => { res.json({ status: 'ok' }); }); module.exports = router;
import PropTypes from 'prop-types' import React, { Fragment } from 'react' const Input = (props) => { const { onChange, onBlur, name, id, disabled, className, placeholder, type, value, checked, inputMode, tabIndex, } = props return ( <Fragment> <input type={ type } id={ id } disabled={ disabled } name={ name } onChange={ onChange } onBlur={ onBlur } value={ value } placeholder={ placeholder } className={ className } checked={ checked } inputMode={ inputMode } tabIndex={ tabIndex } /> </Fragment> ) } Input.propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, onChange: PropTypes.func, onBlur: PropTypes.func, value: PropTypes.any, placeholder: PropTypes.string, disabled: PropTypes.bool, className: PropTypes.string, type: PropTypes.string, checked: PropTypes.any, inputMode: PropTypes.string, tabIndex: PropTypes.number, } Input.defaultProps = { onChange: null, onBlur: null, value: '', placeholder: '', disabled: false, className: '', type: 'text', checked: false, inputMode: 'text', tabIndex: null, } export default Input
#!/usr/bin/env node const { app } = require("../src/app"); const { program } = require("commander"); const fs = require('fs'); const DEFAULT_FILE = "query_params.csv" const DEFAULT_WORKERS = 1; program .option('-f, --file <name>', 'please enter the csv file name to be used from within the /data folder', DEFAULT_FILE) .option('-w, --workers <number>', 'please enter the number of workers you want to use concurrently', DEFAULT_WORKERS) program.parse(process.argv); let { file, workers } = program.opts(); if (workers) { workers = Number(workers); if (isNaN(workers) || workers <= 0) { workers = DEFAULT_WORKERS; } if (workers > 20) { throw new Error(`${workers} is too many. Please enter a number between 1 and 20.`); } } let filePath = __dirname + "/../data/" + file; if (!fs.existsSync(filePath)) { throw new Error(`The file ${file} does not exist at the path ${filePath}.`); } app(filePath, workers)
// Main script & template 'use strict'; angular.module('services', []) .factory('globalVar', function() { return { IPAddress: 'http://sgntupc0008:3000/', } }) .factory('globalFunction', function(){ var page; return{ removeFilterEmpty: function(val){ var key = Object.keys(val); for(var i in key){ if(typeof val[key[i]]=="undefined" || val[key[i]]===""){ delete val[key[i]]; } } return val; }, } });
import { dispatch, } from '../state/state-manager.js'; import { toggleFilterPanelAction, resetStoreTypesAction, actionWithLoading, } from '../state/actions.js'; import './filter-btn.js'; class FilterPanel extends HTMLElement { constructor() { super(); this.toggleBtn = this.querySelector('.filter-panel_toggleBtn'); this.resetBtn = this.querySelector('.filter-panel_resetBtn'); this.panel = this.querySelector('collapsable-tab'); this.list = this.querySelector('ul'); // this.filterBtns = []; } connectedCallback() { this.toggleBtn.addEventListener('click', this.handleToggleBtn.bind(this)); this.resetBtn.addEventListener('click', this.handleReset.bind(this)); } static get observedAttributes() { return ['filters', 'open', 'filters-applied']; } attributeChangedCallback(name, oldValue, newValue) { switch (name) { case 'filters': this.handleFilters(JSON.parse(newValue)); break; case 'open': this.handleOpen(newValue === 'true' ? true : false); break; case 'filters-applied': this.handleFiltersApplied(newValue); } }; get filters() { return this.getAttribute('filters'); } set filters(newValue) { this.handleFilters(newValue); } get open() { return this.getAttribute('open'); } set open(newValue) { this.setAttribute('open', newValue ? 'true' : 'false'); } get filtersApplied() { return this.getAttribute('filters-applied'); } set filtersApplied(newValue) { this.handleFiltersApplied(newValue); } handleOpen(newValue) { if (this.panel) { this.panel.setAttribute('open', newValue); } } handleToggleBtn() { dispatch(toggleFilterPanelAction()); } handleReset() { dispatch(actionWithLoading(resetStoreTypesAction())); } handleFilters(filters) { this.filterBtns = filters.map((filter) => { const filterBtn = document.createElement('filter-btn'); this.list.appendChild(filterBtn); filterBtn.filter = filter; filterBtn.applied = false; return filterBtn; }); } handleFiltersApplied(filtersApplied) { this.filterBtns.forEach((filterBtn) => { filterBtn.applied = filtersApplied.includes(filterBtn.filterId) }); } } window.customElements.define('filter-panel', FilterPanel);
/** * */ $(document).ready(function() {menu.getMenu(0); menu.getListBody();}); var font = "广告位管理"; var valids = ["广告位名称", "尺寸", "最后修改时间", "最后修改人"]; var sizes = [100, 100, 100, 100]; var contents = ["广告位名称", "尺寸", "最后修改时间", "最后修改人"]; var keys = ["advert_name", "advert_size", "last_update_time", "last_update_by"];
// novo recurso do ES2015 const pessoa = { nome: 'Pedro', idade: 29, peso: 95, endereco: { logradouro: 'Rua bacana', numero: 126 } } const {nome, idade} = pessoa //Tire do objeto os atributos nome, idade console.log(nome, idade) const {nome: n, idade: i} = pessoa //Tire do objeto os atributos nome, idade console.log(n, i) const {sobrenome, bemHumorada = true} = pessoa //Permite atribuir valores padrão a atributos console.log(sobrenome, bemHumorada) const{endereco: {logradouro, numero, cep}} = pessoa //Extraindo atraibutos do endereço console.log(logradouro, numero, cep)
import React, {PureComponent} from 'react'; import Bind from 'lodash-decorators/bind'; import {Row, Col, Form, Input, Select, Icon, Button, InputNumber, DatePicker} from 'antd'; import styles from './Filter.less' const FormItem = Form.Item; const {Option} = Select; const ROW_PROPS = {md: 8, lg: 24, xl: 48}; const COL_PROPS = {md: 8, sm: 24} @Form.create() export default class ManagementDepartmentFilter extends PureComponent { state = { expandForm: false, }; @Bind() handleFormReset() { const {form, handleSearch} = this.props; form.resetFields(); handleSearch && handleSearch({}) } toggleForm = () => { this.setState({ expandForm: !this.state.expandForm, }); } handleSearch = (e) => { e.preventDefault(); const {handleSearch, form} = this.props; form.validateFields((err, fieldsValue) => { if (err) return; handleSearch && handleSearch(fieldsValue) }); } renderSimpleForm() { const {form} = this.props const {getFieldDecorator} = form; return ( <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={ROW_PROPS}> <Col md={8} sm={24}> <FormItem label="部门名称"> {getFieldDecorator('name')( <Input placeholder="请输入"/> )} </FormItem> </Col> <Col {...COL_PROPS}> <span className={styles.submitButtons}> <Button type="primary" htmlType="submit">查询</Button> <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</Button> {/* <a style={{marginLeft: 8}} onClick={this.toggleForm}> 展开 <Icon type="down"/> </a> */} </span> </Col> </Row> </Form> ); } renderAdvancedForm() { const {getFieldDecorator} = this.props.form; return ( <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={ROW_PROPS}> <Col {...COL_PROPS}> <FormItem label="服务商名称"> {getFieldDecorator('name')( <Input placeholder="请输入"/> )} </FormItem> </Col> <Col {...COL_PROPS}> <FormItem label="使用状态"> {getFieldDecorator('status')( <Select placeholder="请选择" style={{width: '100%'}}> <Option value="0">关闭</Option> <Option value="1">运行中</Option> </Select> )} </FormItem> </Col> <Col {...COL_PROPS}> <FormItem label="调用次数"> {getFieldDecorator('number')( <InputNumber style={{width: '100%'}}/> )} </FormItem> </Col> </Row> <Row gutter={ROW_PROPS}> <Col {...COL_PROPS}> <FormItem label="更新日期"> {getFieldDecorator('date')( <DatePicker style={{width: '100%'}} placeholder="请输入更新日期"/> )} </FormItem> </Col> <Col {...COL_PROPS}> <FormItem label="使用状态"> {getFieldDecorator('status3')( <Select placeholder="请选择" style={{width: '100%'}}> <Option value="0">关闭</Option> <Option value="1">运行中</Option> </Select> )} </FormItem> </Col> <Col {...COL_PROPS}> <FormItem label="使用状态"> {getFieldDecorator('status4')( <Select placeholder="请选择" style={{width: '100%'}}> <Option value="0">关闭</Option> <Option value="1">运行中</Option> </Select> )} </FormItem> </Col> </Row> <div style={{overflow: 'hidden'}}> <span style={{float: 'right', marginBottom: 24}}> <Button type="primary" htmlType="submit">查询</Button> <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</Button> <a style={{marginLeft: 8}} onClick={this.toggleForm}> 收起 <Icon type="up"/> </a> </span> </div> </Form> ); } renderForm() { return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm(); } render() { return ( <div className={styles.tableListForm}> {this.renderForm()} </div> ); } }
import Header from '../../components/Header'; import AllAboutCancer from '../../components/AllAboutCancer'; import WhatNeedKnow from '../../components/WhatNeedKnow'; import OnlineTest from '../../components/OnlineTest'; import UsefulInformation from '../../components/UsefulInformation'; import Specialists from '../../components/Specialists'; import WhereToApply from '../../components/WhereToApply'; import Footer from '../../components/Footer'; const Home = () => { return ( <div> <Header /> <AllAboutCancer /> <WhatNeedKnow /> <OnlineTest /> <UsefulInformation /> <Specialists /> <WhereToApply /> <Footer /> </div> ) } export default Home;
import React, { Component } from 'react'; import ChatRooms from './chatRooms'; import DirectMessage from './directMessage'; import Favorited from './favorited'; import UserPanel from './userPanel'; import './sideStyles.css'; class SidePanel extends Component { render() { return ( <div className="sidePanel"> <UserPanel /> <Favorited /> <ChatRooms /> <DirectMessage /> </div> ); } } export default SidePanel;
import React, {Component} from 'react'; import GoogleMap from 'google-map-react'; import Marker from '../marker'; import {isExistObj} from '../../utils/functions'; let c = 0; class NonPremiumCourse extends Component{ constructor(props,context){ super(props,context); this.state={classname:"" } } OnUnfollow(){ if(this.props.OnUnfollow){ this.props.OnUnfollow(); } } componentDidMount(){ $('#nonPremium').show(); } // leftViewToggle(){ // alert("from nonPremium"); // let width = window.innerWidth; // if(width<992){ // $('.lftPart').fadeIn(); // $('#nonPremium').hide(); // this.state.classname="nonPremium"; // if(this.props.append){ // //alert(this.state.classname); // this.props.append(this.state.classname); // //$('.nonPremium').show(); // } // } // } render(){ return( <div>{ ((_.size(this.props.courseDetails)>0)?(<div id="nonPremium"><div className="col-sm-12 col-md-8 nonPremium bgfff pdlftryt0px col-xs-12"> { /* <span className="glyphicon glyphicon-chevron-left float-left" ></span> <div className="col-sm-12 pdlftryt0px col-xs-12 courseSelRspns"> </div>*/ } <div className="col-sm-12 zeroPad"> <div className="col-sm-12 zeroPad hgt180px"> <div className="imgGolf col-sm-12 zeroPad"><img src="/assets/img/nonPremBanner.jpg" className="col-sm-12"/></div> <div className="col-sm-12"> <div className="following nonPrefollowing"> {((_.size(this.props.courseDetails)>0 && isExistObj(this.props.courseDetails.course_user_details) && this.props.courseDetails.course_user_details.is_following)?(<span><span className="OrangeDot"><img src="/assets/img/icons/eclipse.png"/></span>Following</span>):(<span className="clrTrnsparnt">following</span>))}</div> <div className="NonPremiumPlayed">{((_.size(this.props.courseDetails)>0 && isExistObj(this.props.courseDetails.course_user_details) && this.props.courseDetails.course_user_details.is_played)?(<span>Played</span>):(<span className="clrTrnsparnt">following</span>))} </div> </div> {isExistObj(this.props.courseDetails.course) && <div className="col-sm-12 top35pc"><div className="coursesTitle">{this.props.courseDetails.course.name}</div></div>} {isExistObj(this.props.courseDetails.course) && <div className="courseAdd">{this.props.courseDetails.course.address1}</div>} <div className="col-sm-6 mt5pc txtcenter mt1pc"> </div> <div className="col-sm-6 mt1pc zeroPad courseMobileNum"> {isExistObj(this.props.courseDetails.course) && <span className="coursePhone col-sm-12 txtRyt">{this.props.courseDetails.course.phone}</span>} </div> </div> <div className="col-sm-12"> <div className="col-sm-3 zeroPad"> <button onClick={this.OnUnfollow.bind(this)} className="btn_followCourse"> {(_.size(this.props.courseDetails)>0 && isExistObj(this.props.courseDetails.course_user_details) && this.props.courseDetails.course_user_details.is_following)?'Unfollow Course':'Follow Course'}</button> </div> </div> <div className="col-sm-12 map NonPremiumMap"> <GoogleMap center={{lat: (_.size(this.props.courseDetails)>0 && isExistObj(this.props.courseDetails.course))?this.props.courseDetails.course.lat:0, lng: (_.size(this.props.courseDetails)>0)?this.props.courseDetails.course.lon:0}} defaultZoom={14}> <Marker lat={(_.size(this.props.courseDetails)>0 && isExistObj(this.props.courseDetails.course))?this.props.courseDetails.course.lat:0} lng={(_.size(this.props.courseDetails)>0)?this.props.courseDetails.course.lon:0}/> </GoogleMap> </div> <div className="col-sm-12 nonPremiumModal"> <button className="upgradeToPremium" data-toggle="modal" data-target="#myModal">Upgrade to Premium</button> <div className="modal fade" id="myModal" role="dialog"> <div className="modal-dialog wd100pc "> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal">&times;</button> <span className="modal-title nonPrem">Have your course upgrade and become a premium course</span> </div> <div className="modal-body"> {isExistObj(this.props.courseDetails.course) && <p className="fnt17px">Have your course contact Golf Connectx by sending an email to <a href={"mailto:" + this.props.courseDetails.course.email}>{this.props.courseDetails.course.email}</a> to get more information.</p>} <center className="FtrBnfit">Features and Benefits</center> <ul className="featureList"> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">Ability to customize your content and photos.</span></li> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">Ability to organize and manage groups that play outof your course + Men's, Women's, Jr's Sr's, etc ALL ON ONE PAGE.</span></li> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">Ability to organize and manage course events includingcharity, corporate, member member, member guest, etc ALL ON ONE PAGE.</span></li> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">Premier page Ads to generate income.</span></li> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">See GolfConnectx users and get reports for users who follow your course and have your course as a favorite.</span></li> <li className="fnt20px clr44b54a"><span className="fnt15px clrBlack">Have access to View all the groups and events that select your course as home course or event course.</span></li> </ul> </div> <div className="modal-footer"> <button type="button" className="ModalClose" data-dismiss="modal">CLOSE</button> </div> </div> </div> </div></div> </div> </div> </div>):(<div></div>))}</div> ); } } export default NonPremiumCourse;
juke.directive('player', function() { return { restrict: 'E', controller: 'PlayerCtrl', templateUrl: '/js/player/templates/player.html' }; }); juke.directive('updateTime', function() { return { restrict: 'A', scope: { }, link: function(scope, element, attr) { var clicked = false; element.on('mousedown', function() { clicked = true; }); element.on('mousemove', function() { if (clicked) { var clickX = event.clientX - element[0].offsetLeft; var barWidth = element[0].clientWidth; var position = clickX / barWidth; var root = scope.$root; root.setProgress(position); } }); element.on('mouseup', function(event) { clicked = false; }); } }; });
var Group = require('../models/groupModel'); var groupRoute = function(route){ route .post('/group',function(req,res){ Group.create(req.body,function(err,data){ if(err){ res.status(500).send(err); }else{ res.status(200).send(data); } }) }) .get('/group/:groupId',function(req,res){ Group.read(req.params.groupId,function(err,data){ if(err){ res.status(500).send(err); }else{ res.status(200).send(data); } }) }) .put('/group/:groupId',function(req,res){ Group.update(req.params.groupId,req.body,function(err,data){ if(err){ res.status(500).send(err); }else{ res.status(200).send(data); } }) }) .delete('/group/:groupId',function(req,res){ Group.delete(req.params.groupId,function(err,data){ if(err){ res.status(500).send(err); }else{ res.status(200).send(data); } }) }) } module.exports = groupRoute;
// @flow import React from "react"; import { useState } from "react"; import Select from "../Select/Select.jsx"; import { OPERATION_SAVE_ENTITY } from "lk/operations.js"; import { getLKQuery } from "lk/redux/actions.js"; import { FileUpload } from "lk/components/FileUpload/FileUpload.jsx"; const addFileComponentView = ( { addFileOnClick } ) => <div className="b-upload__container-add" onClick={ addFileOnClick }></div>; function singleFileContainer( props ): React.Node { const onChange = ( field: string, value: any ) => props.onChange( { ...props.data, [field]: value } ); const onChangeString = ( event ) => onChange( event.target.name, event.target.value ); let StatusBlock = (): React.Node => null; if( props.__isError ) StatusBlock = (): React.Node => <div className="b-upload__error-block"></div>; else if( !props.__isUploaded ) StatusBlock = (): React.Node => <div className="b-upload__container-progress-bar"><div><span></span></div></div>; const data = props.data; return ( <div><StatusBlock />{ props.__file ? "Файл загружен" : "Выберите файл" }</div> ); } const addButton = <button className="offers-download__button">Выберите файл</button>; const removeButton = <span className="b-upload__button-remove"></span>; const componentContainer = ( props ) => <div className="row array-item-list">{ props.addButton }{ props.childs }{ props.fileInput }</div> //const componentContainer = ( props ) => <div className="row array-item-list">{ props.childs }</div> function sendForm( data, onOfferImportStarted, onOfferImportFinished ) { let dataWithOperation = { operation: OPERATION_SAVE_ENTITY, entity: "OffersImport", data: data }; getLKQuery( dataWithOperation, () => onOfferImportFinished( "Оферты загружены на сервер и будут импортироваться в фоновом режиме. Через некоторое время обновите журнал загрузок." ), () => onOfferImportFinished( "Произошла ошибка при загрузке оферт, обратитесь к Администратору" ) ); onOfferImportStarted(); } export function ImportForm( props ) { const [ segment, setSegment ] = useState( null ); const [ operationType, setOperationType ] = useState( null ); const [ source, setSource ] = useState( null ); const [ file, setFile ] = useState( null ); const [ message, setMessage ] = useState( "" ); const [ isOfferImportStarted, setIsOfferImportStarted2 ] = useState( false ); const setIsOfferImportStarted = ( value ) => { console.log( value ); setIsOfferImportStarted2( value ); } const onOfferImportStarted = () => setIsOfferImportStarted( true ); const onOfferImportFinished = ( message ) => { setSegment( null ); setOperationType( null ); setSource( null ); setIsOfferImportStarted( false ); setMessage( message ); }; const uploadProps = { files: file, filenameField: "file", actionURL: "/upload_files", onChange: setFile, singleFileContainer: singleFileContainer, limitFiles: 1, autoupload: true, multiselect: false, componentContainer: componentContainer, addButton: addButton, removeButton: removeButton, defaultFileProps: { id: 0, order: 0, file: null } }; // Чтобы включилась кнопка импорта оферт, необходимо, чтобы все поля формы были заполнены const isUploadAllowed = segment && operationType && source ; const isImportAllowed = isUploadAllowed && file; const buttonClass = "offers-download__button" + ( isImportAllowed ? "" : " disabled" ); const importOffer = () => { const data = { segment: segment, operationType: operationType, source: source, file: file }; sendForm( data, onOfferImportStarted, onOfferImportFinished ); }; const waiterBlock = ( <div className="b-section__fadeout"> <div className="centering__yes"> <div className="spinner spinner_size_l spinner_progress_yes"></div> <p className="offers-download__service-messages">Идет загрузка оферт...</p> </div> </div> ); return( <article className="b-section__form" id="offers-download"> <section className="b-section__article-container offers-download__select-block-wrapper active"> <div className="offers-download__select-block">Сегмент <Select entity="Segments" value={ segment } onChange={ setSegment } /> </div> <div className="offers-download__select-block">Тип операции <Select entity="TypesOfEconomicOperations" value={ operationType } onChange={ setOperationType } /> </div> <div className="offers-download__select-block">Источник <Select entity="EconomicOperationsSourceTypes" value={ source } onChange={ setSource } /> </div> <div className="offers-download__select-block"> { isUploadAllowed ? <FileUpload { ...uploadProps } /> : null } <button className={ buttonClass } disabled={ !isImportAllowed } onClick={ importOffer }>Загрузить оферты</button> { message } </div> { isOfferImportStarted ? waiterBlock : null } </section> </article> ); }
const { SetWindowPos, HWND_BOTTOM, HWND_TOPMOST, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOMOVE } = require('win-setwindowpos'); exports.onWindow = win => { const hwnd = win.getNativeWindowHandle(); win.setMinimizable(false); win.setMaximizable(false); const setBottom = () => { SetWindowPos( hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE ); }; win.on('show', function() { setBottom(); }); win.on('focus', function() { setBottom(); }); };
const isProd = false; const localConfif = { user: "root", password: "", //password: "root", database: "exotic", //port: "8889" port: "3306" }; if (isProd) { module.exports = { user: "*****", password: "*****", database: "*****", port: "*****" }; } else { module.exports = localConfif; } module.exports.isProd = isProd;
const { Command } = require('discord.js-commando'); const { oneLine, stripIndents } = require('common-tags'); const { MessageEmbed } = require('discord.js'); const moment = require('moment'); require('moment-duration-format'); module.exports = class QuoteCommand extends Command { constructor(client) { super(client, { name: 'quote', group: 'info', hidden: true, memberName: 'quote', description: 'Quotes a specified user.', details: oneLine` Quote the last messages of a user. `, examples: ['quote @Bob#1234'], args: [{ key: 'user', label: 'user', prompt: 'What user would you like to quote? Please specify one only.', type: 'user', infinite: false }], guarded: true }); } async run(message, {user}) { const quoteUser = user; const messages = await message.channel.messages.fetch({ limit: 100 }); const collected = messages.array().filter(fetchedMsg => fetchedMsg.author.id === user.id); const msgs = collected.map((m) => { return `**${user.username}#${user.discriminator}:** ${m.content}`; }); // if (msgs.size < 10) return message.reply('This user does not have enough recent messages!'); // TODO Use a loop to generate this const quotes = msgs.join("\n"); // const embed = new MessageEmbed() // .setTitle('**Quotes**') // .setAuthor(quoteUser.username, quoteUser.avatarURL) // .setColor(0x00CCFF) // .setDescription() // .setTimestamp(); message.channel.send(quotes, { split: true }); } };
export const reducer = (state, action) =>{ switch(action.type){ case "SignIn": state.userId = action.payload.userId return {...state} default: return state } }
class Cachorro { constructor(nome, raca) { this.raca = raca; this.nome = nome; } latir() { console.log("AU AU"); } falaNome() { console.log(`Meu nome é ${this.nome}`); } } module.exports = Cachorro;
import * as R from 'ramda' export default function getAccessibleText ({ r, g, b }) { return R.pipe( R.reduce(R.add, 0), R.divide(R.__, 1000), R.ifElse( R.gte(R.__, 125), R.always({ r: 0, g: 0, b: 0 }), R.always({ r: 255, g: 255, b: 255 }) ) )([ R.multiply(r, 299), R.multiply(g, 587), R.multiply(b, 114) ]) }
import React from "react"; import { Link } from "react-router-dom"; import logo from "../../assets/logo_grey.png"; import fb from "../../assets/icons/facebook.png"; import tw from "../../assets/icons/twitter.png"; import yt from "../../assets/icons/youtube.png"; import "./style.scss"; const sc_links = [ { img: tw, link: "", }, { img: fb, link: "", }, { img: yt, link: "", }, ]; const links = [ { title: "About Us", link: "/about" }, { title: "Ministries", link: "/ministries" }, { title: "Blog", link: "#" }, { title: "Membership Form", link: "/membership" }, ]; const extras = [ "17, Baptist Church Street, Gbagada Estate Phase 2, Lagos.", "+234 802 737 5656", "info@gebcgbagada.org", ]; const Footer = () => { return ( <section className="ft_sx flex-col"> <div className="ft_con container flex-row"> <div className="contents flex-row card j-space al-start"> <div className="logo"> <img src={logo} alt="" className="contain" /> </div> <div className="na_gt flex-col al-start"> <h3>Quick Navigation</h3> {links.map((link, i) => ( <Link key={`ft_sublink_${i}`} to={link.link} className="links"> {link.title} </Link> ))} </div> <div className="na_gt flex-col al-start"> <h3>Locate Us</h3> {extras.map((extra, i) => ( <p key={`ft_sublink_${i}`} className="links"> {extra} </p> ))} </div> <div className="cn_us flex-row"> {sc_links.map((link, i) => ( <Link to={link.link} key={`social_link_${i}`}> <img src={link.img} alt="" className="img contain" /> </Link> ))} </div> </div> </div> </section> ); }; export default Footer;
import { createApp } from 'vue' import App from './App.vue' import './main.css' import { registerSW } from 'virtual:pwa-register' const theme = `hsl(${Math.floor(Math.random() * 36) * 10},50%,50%)`; document.body.style.setProperty('--theme', theme); document.querySelector('link[rel=icon]').href = `data:image/svg+xml,%3Csvg width='120' height='120' viewBox='0 0 120 120' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M61 30c11.046 0 20-8.954 20-20h20c5.523 0 10 4.477 10 10v80c0 5.523-4.477 10-10 10H81c0-11.046-8.954-20-20-20s-20 8.954-20 20H21c-5.523 0-10-4.477-10-10V20c0-5.523 4.477-10 10-10h20c0 11.046 8.954 20 20 20zm0 40c5.523 0 10-4.477 10-10s-4.477-10-10-10-10 4.477-10 10 4.477 10 10 10z' fill='${theme}'/%3E%3C/svg%3E` createApp(App).mount('#app') const updateSW = registerSW({ onNeedRefresh() { console.log('[sdsd]'); // show a prompt to user }, onOfflineReady() { console.log('[w]'); // show a ready to work offline to user }, }) updateSW()
let mix = require("laravel-mix") mix.js("source/app.js", "build") mix.sass("source/app.scss", "build")
import {ADD_ITEM, REMOVE_ITEM, CHANGE_AMOUNT} from '../actionTypes'; const initialState = { items: [] }; export function basketReducer(state = initialState, action) { switch (action.type) { case ADD_ITEM: { const {item} = action.payload; // TODO Prob best to do this in a side effect or have an extra reducer const itemsCopy = [...state.items]; const itemIndex = itemsCopy.findIndex(({id}) => id === item.id); if (itemIndex === -1) { return { ...state, items: [...state.items, {...item, amount: 1}] } } itemsCopy[itemIndex].amount++; return { ...state, items: itemsCopy } } case REMOVE_ITEM: { const {id} = action.payload; const items = state.items.filter(item => item.id !== id); return { ...state, items } } case CHANGE_AMOUNT: { const {id, amount} = action.payload; const itemsCopy = [...state.items]; const itemIndex = itemsCopy.findIndex((item) => id === item.id); itemsCopy[itemIndex].amount = amount; return { ...state, items: itemsCopy } } default: return state; } }
function growDiv(id) { var growDiv = document.getElementById(id); growDiv.className += " hidden"; } function goToLink(html) { $("#main-content").load(html + ".html"); } function birdClick(id) { var scoreElement = document.getElementById('bird-score'); var score = document.getElementById('bird-score').innerHTML; var scoreLabelElement = document.getElementById('score-label'); var intScore = parseInt(score); if(intScore === 0) { scoreElement.style.display = "block" scoreLabelElement.style.display = "block" } document.getElementById('bird-score').innerHTML = intScore + 1; var sound = document.getElementById("audio-shot"); sound.src = "/media/Click.wav"; sound.play(); showHide(id) } function showHide(id) { var x = document.getElementById(id); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
import Link from 'next/link' import Meta from '../components/Meta' import Navbar from '../components/nav/Navbar' import { LeftNav, RightNav } from '../components/nav/Navbar' import NavLink from '../components/nav/Link' import MainContainer from '../components/Container' import ProjectContainer from '../components/ProjectContainer' const Main = ({ children, project }) => { const Container = project ? ProjectContainer : MainContainer return ( <div> <Navbar> <LeftNav> <Link href="/" passHref> <NavLink first>Home</NavLink> </Link> <Link href="/about" passHref> <NavLink>About</NavLink> </Link> <Link href="/projects" passHref> <NavLink>Projects</NavLink> </Link> <Link href="/posts" passHref> <NavLink>Posts</NavLink> </Link> </LeftNav> <RightNav> <NavLink href="https://github.com/dongy7/" newTab> <i className="fab fa-github fa-lg" /> </NavLink> <NavLink href="https://www.linkedin.com/in/dongy7/" newTab> <i className="fab fa-linkedin fa-lg" /> </NavLink> <NavLink href="mailto:dongy7@gmail.com" newTab> <i className="fas fa-envelope fa-lg" /> </NavLink> </RightNav> </Navbar> <Container> {children} <Meta /> </Container> </div> ) } export default Main
import { Router } from 'express' import multer from 'multer' import uploadsConfig from '../config/uploadConfig' import productController from '../Controllers/productController' const routes = new Router() const upload = multer(uploadsConfig) const productRouteList = [ routes.get('/', productController.getAll), routes.get('/products/:id', productController.getById), routes.post('/post', upload.single('image'), productController.create), routes.put('/products/update/:id', productController.update), routes.delete('/products/del/:id', productController.removerProduto), ] export default productRouteList
import React from "react" import styled from "styled-components" import { above } from "../../styles/Theme" const BasicBulletListCard = ({ headline, bullets }) => { return ( <CardContainer> <CardHeadline>{headline}</CardHeadline> <BulletList dangerouslySetInnerHTML={{ __html: bullets }} /> </CardContainer> ) } export default BasicBulletListCard const CardContainer = styled.div` padding: 30px; display: flex; flex-direction: column; align-items: flex-start; background: #1e1f2b; border-radius: 10px; box-shadow: 0 4px 18px -8px rgba(0, 0, 0, 0.4); ` const CardHeadline = styled.h3` margin: 0; padding: 0; font-size: 26px; color: ${props => props.theme.bodyText}; font-weight: 600; ` const BulletList = styled.div` margin: 20px 0 0 0; padding: 0; list-style: none; & ul { margin: 0 0 0 10px; padding: 0; } & li { position: relative; margin-bottom: 22px; font-weight: 400; color: ${props => props.theme.bodyText}; &:last-child { margin-bottom: 0; } &::before { position: absolute; content: ""; top: 0; left: 0; background: ${props => props.theme.secondaryAccentColor}; border-radius: 50%; width: 12px; height: 12px; transform: translate(-180%, 70%); } } ${above.mobile` & ul { margin: 0 0 0 30px; } `} `
addButtonEvent() function addButtonEvent() { document.getElementById ( "submitBtn" ) .addEventListener ( "click", addPost ) } function addPost() { let textBox = document.getElementById ('blog-container') let textInput = document.getElementById ('user-input') let paragraph = document.createElement("p") textBox.appendChild(paragraph) paragraph.innerText = textInput.value } c
function Visita(fecha, lugar) { this.fecha = fecha; this.lugar = lugar; } Visita.prototype.getLugar = function(){ return this.lugar; }
import React from 'react' import {Text} from 'react-native' export default () => { return ( <Text>news detail pages</Text> ) }
import React, { useEffect } from 'react'; import { Alert, Container, Progress } from 'reactstrap'; const Prices = ({ loadConcerts, request, concerts }) => { useEffect(() => { loadConcerts(); },[]); if (request.pending) return <Progress animated color="primary" value={50} />; else if (request.error) return <Alert color="warning">{request.error}</Alert>; else if (!request.success || !concerts.length) return <Alert color="info">No concerts</Alert>; else if (request.success) return ( <Container> <h1>Prices</h1> <p>Prices may differ according the day of the festival. Remember that ticket includes not only the star performance, but also 10+ workshops. We gathered several genre teachers to help you increase your vocal skills, as well as self confidence.</p> <Alert color="info"> Attention! <strong>Children under 4 can go freely with you without any other fee!</strong> </Alert> { concerts.sort((c1, c2) => (c1.day - c2.day)).map(({id, day, price, workshops}) => ( <div key={id}> <h2>Day {day}</h2> <p>Price: {price}$</p> <p>Workshops: "{workshops.map(ws => ws.name).join('", ')}"</p> </div> )) } </Container> ) }; export default Prices;
const mongo = require("mongoose"); module.exports = async () => { try { await mongo.connect("mongodb://localhost:27017/dinamica_teste", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); console.log("connected to mongodb"); } catch (error) { console.log("error on mongodb connection:", error.message); } };