text
stringlengths
7
3.69M
var mongoose = require('mongoose') var Message = mongoose.model('Message') var Comment = mongoose.model('Comment') module.exports = { create:function(req, res) { Message.findOne({_id: req.params.id}, function(err, msg) { if(err) console.log(err) else { var comment = new Comment(req.body) comment._message = msg._id msg.comments.push(comment) comment.save(function(err) { if(err) console.log(err) else { msg.save(function(err) { if(err) console.log(err) else res.redirect('/') }) } }) } }) } }
const Manager = require("./lib/Manager"); const Engineer = require("./lib/Engineer"); const Intern = require("./lib/Intern"); const Employee = require("./lib/Employee"); const inquirer = require("inquirer"); const path = require("path"); const fs = require("fs"); const render = require("./lib/htmlRenderer"); let employeeList = ["Manager", "Engineer", "Intern", "I don't want to add anymore employees"]; const employees = []; const employeeID = []; //user asked for input on which employee type to create function chooseEmployee() { inquirer.prompt({ name: "employeeType", message: "Which type of employee would you like to add?", type: "rawlist", choices: employeeList }) .then(({employeeType}) => { switch (employeeType) { case "Manager": return createManager(); case "Engineer": return createEngineer(); case "Intern": return createIntern(); case "I don't want to add anymore employees": return createTeam(); } }); }; function createManager(){ inquirer.prompt([{ name: "name", type: "input", message: "What is your manager's name?" }, { name: "managerID", type: "input", message: "What is your manager's ID?", validate: validateID }, { name: "email", type: "input", message: "What is your manager's email?", validate: validateEmail }, { name: "officeNumber", type: "input", message: "What is your manager's office number?", validate: validateOfficeNumber }]).then((answer) => { console.log(answer); const newManager = new Manager(answer.name, answer.managerID, answer.email, answer.officeNumber); employees.push(newManager); employeeID.push(answer.managerID); //ensure only one manager is created for( var i = 0; i < employeeList.length; i++){ if (employeeList[i] === "Manager") { employeeList.splice(i, 1); } }; chooseEmployee(); }); }; function createEngineer(){ inquirer.prompt([{ name: "name", type: "input", message: "What is your engineers's name?" }, { name: "engineerID", type: "input", message: "What is your engineer's ID?", validate: validateID }, { name: "email", type: "input", message: "What is your engineer's email?", validate: validateEmail }, { name: "gitHubUsername", type: "input", message: "What is your engineer's GitHub username?" }]).then((answer) => { console.log(answer); const newEngineer = new Engineer(answer.name, answer.engineerID, answer.email, answer.gitHubUsername); employees.push(newEngineer); employeeID.push(answer.engineerID); chooseEmployee(); }); }; function createIntern(){ inquirer.prompt([{ name: "name", type: "input", message: "What is your intern's name?" }, { name: "internID", type: "input", message: "What is your intern's ID?", validate: validateID }, { name: "email", type: "input", message: "What is your intern's email?", validate: validateEmail }, { name: "school", type: "input", message: "Where does your intern go to school?" }]).then((answer) => { console.log(answer); const newIntern = new Intern(answer.name, answer.internID, answer.email, answer.school); employees.push(newIntern); employeeID.push(answer.internID); chooseEmployee(); }); }; function createTeam(){ const outputPath = path.resolve(__dirname, "output", "team.html"); fs.writeFile(outputPath, render(employees) ,function(err){ if(err) throw err; console.log("Team successfully created!"); }); }; // Ensure id is a number and that it is not already in use by another employee function validateID(id){ if(isNaN(id)){ return "Invalid ID. Please enter a valid number for employee ID"; } for (i = 0; i < employeeID.length; i++) { if (id === employeeID[i]) { return "Invalid ID. Please enter a unique employee ID"; } } return true; }; // Ensure email address contains @ and . function validateEmail(email){ if(email.indexOf("@") != -1 && email.indexOf(".") != -1){ return true; }else{ return "Please enter a valid email address"; } }; // Ensure office number is a number function validateOfficeNumber(officeNumber){ if(isNaN(officeNumber)){ return "Please enter a valid number for manager office number"; } return true; }; chooseEmployee();
//ele = 차트를 그릴 canvas id //chart = 차트 타입 bar, line, pie //data = 안의 데이터 //chartTitle = 차트의 제목 //chartTitleTF = 차트 제목 사용 true, false var chartComponent = new Object(); var makeChart = { make: function (ele, chart, data, chartTitle, chartTitleTF) { ctx = document.getElementById(ele).getContext("2d"); var config = { type: chart, data: data, options: { // indexAxis: "y", responsive: true, legend: { position: "top", fullWidth: true, }, title: { display: chartTitleTF, //true, false text: chartTitle, //제목 }, scales: { yAxes: [ { ticks: { min: 0, max: 100, beginAtZero: true, fontSize: 14, }, }, ], }, }, }; if (chartComponent[ele] == null) { chartComponent[ele] = new Chart(ctx, config); } else { chartComponent[ele].ctx = ctx; chartComponent[ele].config = config; chartComponent[ele].update(); } }, }; // var makeChart_h = { // make: function (ele1, chart1, data1, chartTitle1, chartTitleTF1) { // var ctx1 = document.getElementById(ele1).getContext("2d"); // new Chart(ctx1, { // type: chart1, // data: data1, // options: { // indexAxis: "y", // // responsive: true, // legend: { // position: "top", // fullWidth: true, // }, // title: { // display: chartTitleTF1, //true, false // text: chartTitle1, //제목 // }, // scales: { // yAxes: [ // { // ticks: { // //min : 0 // //max : 20 // beginAtZero: true, // fontSize: 14, // }, // }, // ], // }, // }, // }); // }, // }; function callFunc(url, parameter, callback, async) { var boolAsync = true; if (arguments.length == 5 && new Boolean(async)) { boolAsync = async; } $.ajax({ url: url, type: "get", dataType: "json", data: parameter, async: boolAsync, success: function (data, status, xhr) { callback(status, data); }, error: function (xhr, status, error) { callback(status, xhr); }, }); } function callFuncView(url, parameter, callback) { $.ajax({ url: url, dataType: "html", data: parameter, async: false, success: function (data, status, xhr) { callback(status, data); }, error: function (xhr, status, error) { callback(status, xhr); }, }); } // callFunc(url, 'post', JSON.stringify(param), function(status, data){ // if(status == 'success'){ // returnData = data.resultList; // } else { // swAlertToast('데이터 가져오기 실패'); // returnData = null; // } // }, false);
// https://github.com/diegohaz/arc/wiki/Storybook import React from 'react' import { storiesOf } from '@kadira/storybook' import Chart from '.' storiesOf('Chart', module) .add('default', () => ( <Chart /> ))
import React, { Component } from 'react' import MainFooter from '../component/footer' import { List, Checkbox, Icon } from 'antd' import { connect } from 'react-redux' import { completeData, deleteData } from '../redux/actions/action' @connect( state => ({add: state.add}), {completeData, deleteData} ) class Active extends Component{ constructor(props){ super(props) this.handleCheck = this.handleCheck.bind(this) } handleCheck(id){ this.props.completeData(id) } render() { const allData = this.props.add.slice(1).filter(v => v.checked === false) return ( <div> <List bordered='true' split='true'> {allData.length < 1 ? null : allData.map(v => { if(v.id === 0) return null return ( <List.Item key={v.id}> <Icon type='close' onClick={() => this.props.deleteData(v.id) }></Icon> <Checkbox checked={v.checked} onChange={() => this.handleCheck(v.id)}></Checkbox> <List.Item.Meta title='' description={v.value}/> </List.Item> ) })} </List> <MainFooter/> </div> ) } } export default Active
const team = [ {method:"Email", number: "petassistant@sample.com" }, {method:"Cell" , number: "123-456-7890" }, {method:"Fax" , number: "123-456-7890" } ] Template.contactus.helpers({ contactusData: team, })
(function() { const hamburger = document.querySelector('[data-plugin="toggle"]'); const nav = document.querySelector('.nav__list'); hamburger.addEventListener('click', function(e) { e.preventDefault(); this.classList.toggle('open'); nav.classList.toggle('nav__list--show'); }); })();
import { api_key } from '../../config/config.json' export const getPlacePhotoUrl = (photo_reference, width, height) => { const photoReference = photo_reference; const url = new URL('https://maps.googleapis.com/maps/api/place/photo'); url.searchParams.append('key', api_key); url.searchParams.append('photoreference', photoReference); url.searchParams.append('maxwidth', width); url.searchParams.append('maxheight', height); return url; }
import React, { Component } from "react" import Form from '../../components/DynamicForm/Index' import { connect } from 'react-redux'; import axios from "../../axios-orders" import Currency from "../Upgrade/Currency" import general from '../../store/actions/general'; import ReactDOMServer from "react-dom/server" import Validator from '../../validators'; import Router from "next/router" import Translate from "../../components/Translate/Index"; import swal from 'sweetalert' import dynamic from 'next/dynamic' const Gateways = dynamic(() => import("../Gateways/Index"), { ssr: false, }); class Balance extends Component { constructor(props) { super(props) this.state = { title: "Withdraw Balance", success: false, error: null, loading: true, member: props.member, monetization_threshold_amount:props.monetization_threshold_amount, submitting: false, firstLoaded: true, user:props.pageInfoData.user ? true : false, adsPaymentStatus: props.pageData.adsPaymentStatus, gateways:null } this.myRef = React.createRef(); } componentDidMount(){ var that = this $(document).on("click",'.open_withdraw',function(e) { e.preventDefault(); let user = that.props.pageInfoData.user ? `&user=${that.props.pageInfoData.user}` : ""; let userAs = that.props.pageInfoData.user ? `?user=${that.props.pageInfoData.user}` : ""; Router.push( `/dashboard?type=withdraw${user}`, `/dashboard/withdraw${userAs}`, ) }) if (this.state.adsPaymentStatus) { if (this.state.adsPaymentStatus == "success") { swal("Success", Translate(this.props, "Wallet recharge successfully.", "success")); } else if (this.state.adsPaymentStatus == "fail") { swal("Error", Translate(this.props, "Something went wrong, please try again later", "error")); } else if (this.state.adsPaymentStatus == "cancel") { swal("Error", Translate(this.props, "You have cancelled the payment.", "error")); } } } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} } else if (nextProps.pageInfoData.member != prevState.member) { return { success: false, error: null, loading: true, member: nextProps.pageInfoData.member, monetization_threshold_amount:nextProps.monetization_threshold_amount, submitting: false, firstLoaded: true, user:nextProps.pageInfoData.user ? true : false, adsPaymentStatus: nextProps.pageData.adsPaymentStatus, gateways:null } } else{ return null } } onSubmit = model => { if (this.state.submitting) { return } var that = this; let user = that.props.pageInfoData.user ? `&user=${that.props.pageInfoData.user}` : ""; let userAs = that.props.pageInfoData.user ? `?user=${that.props.pageInfoData.user}` : ""; let price = this.props.pageInfoData.levelPermissions['member.monetization_threshold_amount'] if(this.state.monetization_threshold_amount){ price = this.state.monetization_threshold_amount } if(parseFloat(this.state.member.balance) >= parseFloat(model['amount']) && parseFloat(price) <= parseFloat(model['amount'])){ let formData = new FormData(); for (var key in model) { if (model[key]) formData.append(key, model[key]); } formData.append("owner_id", this.state.member.user_id) const config = { headers: { 'Content-Type': 'multipart/form-data', } }; let url = '/members/balance-withdraw'; this.setState({ submitting: true, error: null }); axios.post(url, formData, config) .then(response => { if (response.data.error) { window.scrollTo(0, this.myRef.current.offsetTop); this.setState({ error: response.data.error, submitting: false }); } else { this.setState({ submitting: false }); this.props.openToast(Translate(this.props,response.data.message), "success"); setTimeout(() => { Router.push( `/dashboard?type=withdraw${user}`, `/dashboard/withdraw${userAs}`, ) },1000); } }).catch(err => { this.setState({ submitting: false, error: err }); }); }else{ if(parseFloat(this.state.member.balance) < parseFloat(model['amount'])){ this.setState({ error: [{"field":"amount","message":"Enter amount must be less than available balance."}], submitting: false }); }else if( parseFloat(price) > parseFloat(model['amount'])){ this.setState({ error: [{"field":"amount","message":"Enter amount must be greater than minimum withdraw amount."}], submitting: false }); } } }; recharge = (e) => { this.setState({localUpdate:true, adsWallet: true }) } walletFormSubmit = (e) => { e.preventDefault() if (!this.state.walletAmount) { return } this.setState({localUpdate:true, adsWallet: false,gatewaysURL:"/ads/recharge?fromBalance=1&amount=" + encodeURI(this.state.walletAmount),gateways:true }) // swal("Success", Translate(this.props, "Redirecting you to payment gateway...", "success")); // window.location.href = "/ads/recharge?fromBalance=1&amount=" + encodeURI(this.state.walletAmount) } closeWalletPopup = (e) => { this.setState({localUpdate:true, adsWallet: false, walletAmount: 0 }) } walletValue = (e) => { if (isNaN(e.target.value) || e.target.value < 1) { this.setState({localUpdate:true, walletAmount: parseFloat(e.target.value) }) } else { this.setState({localUpdate:true, walletAmount: e.target.value }) } } render() { let adsWallet = null if (this.state.adsWallet && !this.state.user) { adsWallet = <div className="popup_wrapper_cnt"> <div className="popup_cnt"> <div className="comments"> <div className="VideoDetails-commentWrap"> <div className="popup_wrapper_cnt_header"> <h2>{Translate(this.props, "Recharge Wallet")}</h2> <a onClick={this.closeWalletPopup} className="_close"><i></i></a> </div> <div className="user_wallet"> <div className="row"> <form onSubmit={this.walletFormSubmit}> <div className="form-group"> <label htmlFor="name" className="control-label">{Translate(this.props, "Enter Amount :")}</label> <input type="text" className="form-control" value={this.state.walletAmount ? this.state.walletAmount : ""} onChange={this.walletValue} /> </div> <div className="form-group"> <label htmlFor="name" className="control-label"></label> <button type="submit">{Translate(this.props, "Submit")}</button> </div> </form> </div> </div> </div> </div> </div> </div> } let validator = [ { key: "paypal_email", validations: [ { "validator": Validator.required, "message": "Paypal Email is required field" } ] }, { key: "paypal_email", validations: [ { "validator": Validator.email, "message": "Please provide valid email" } ] }, { key: "amount", validations: [ { "validator": Validator.required, "message": "Amount is required field" } ] }, { key: "amount", validations: [ { "validator": Validator.price, "message": "Please provide valid amount" } ] } ] let perclick = {} let price = this.props.pageInfoData.levelPermissions['member.monetization_threshold_amount'] if(this.state.monetization_threshold_amount){ price = this.state.monetization_threshold_amount } perclick['package'] = { price: parseFloat(price) } let wallet = {} wallet['package'] = { price: this.state.member ? this.state.member.wallet : this.props.pageInfoData.loggedInUserDetails.wallet } let userBalance = {} userBalance['package'] = { price: parseFloat(this.state.member.balance ? this.state.member.balance : 0) } let priceData = ReactDOMServer.renderToString(<Currency { ...this.props } { ...perclick} />) let formFields = [ { key: "wallet", label: "Wallet Total",props: { readOnly: true }, value: ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...wallet} />) }, { key: "balance", label: "Available Balance",props: { readOnly: true }, value: ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...userBalance} />) }, { key: "paypal_email", label: "Paypal Email", value: this.state.member.email,isRequired:true }, { key: "amount", label: "Amount", type: "text", value: "", placeholder:"00.00",isRequired:true }, { key: "res_type_1", type: "content", content: '<h6 class="custom-control minimum_amount_cnt">'+this.props.t("Minimum withdraw amount should be greater than or equal to {{data}}.",{data:`(${priceData})`})+'</h6>' } ] let initalValues = {} //get current values of fields formFields.forEach(item => { initalValues[item.key] = item.value }) let gatewaysHTML = "" if(this.state.gateways){ gatewaysHTML = <Gateways {...this.props} success={() => { this.props.openToast(Translate(this.props, "Payment done successfully."), "success"); setTimeout(() => { Router.push(`/dashboard?type=balance`, `/dashboard/balance`) },1000); }} successBank={() => { this.props.openToast(Translate(this.props, "Your bank request has been successfully sent, you will get notified once it's approved"), "success"); this.setState({localUpdate:true,gateways:null}) }} bank_price={this.state.walletAmount} bank_type="recharge_wallet" bank_resource_type="user" bank_resource_id={this.props.pageInfoData.loggedInUserDetails.username} tokenURL={`ads/successulPayment?fromBalance=1&amount=${encodeURI(this.state.walletAmount)}`} closePopup={() => this.setState({localUpdate:true,gateways:false})} gatewaysUrl={this.state.gatewaysURL} /> } return ( <React.Fragment> { adsWallet } { gatewaysHTML } <button className="custom-control open_withdraw floatR" href="#">{this.props.t("Withdrawal Requests")}</button> <button className="floatR balance_recharge" onClick={this.recharge.bind(this)}>{Translate(this.props, "Recharge Wallet")}</button> <div ref={this.myRef}> <Form className="form" title={this.state.title} initalValues={initalValues} defaultValues={initalValues} validators={validator} submitText={!this.state.submitting ? "Submit Request" : "Submitting Request..."} model={formFields} {...this.props} generalError={this.state.error} onSubmit={model => { this.onSubmit(model); }} /> </div> </React.Fragment> ) } } const mapDispatchToProps = dispatch => { return { openToast: (message, typeMessage) => dispatch(general.openToast(message, typeMessage)), }; }; export default connect(null, mapDispatchToProps)(Balance);
import React, { useState, useEffect } from 'react'; import { Transition, animated } from 'react-spring/renderprops'; import MSG from 'get-message'; const getMessage = MSG('education'); const defaultStyles = { overflow: 'hidden', width: '100%', color: 'white', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '2em', textTransform: 'uppercase' }; let t1, t2, t3; const time = 200; const ListTransition = () => { const eduList = [ getMessage('edu'), getMessage('study1'), getMessage('boot'), getMessage('study2'), getMessage('school1') ]; const [items, setItems] = useState(eduList.slice(0, 1)); const [isOpen, toggle] = useState(false); const clear = () => { t1 && clearTimeout(t1); t2 && clearTimeout(t2); t3 && clearTimeout(t3); }; const open = () => { clear(); toggle(true); setItems(eduList.slice(0, 2)); t1 = setTimeout(() => setItems(eduList.slice(0, 3)), time); t2 = setTimeout(() => setItems(eduList.slice(0, 4)), 2 * time); t3 = setTimeout(() => setItems(eduList), 3 * time); }; const close = () => { clear(); toggle(false); t1 = setTimeout(() => setItems(eduList.slice(0, 3)), time); t2 = setTimeout(() => setItems(eduList.slice(0, 2)), 2 * time); t3 = setTimeout(() => setItems(eduList.slice(0, 1)), 3 * time); }; useEffect(() => clear(), []); return ( <div style={{ backgroundColor: 'rgba(29, 20, 15, 0.47)', overflow: 'hidden', cursor: 'pointer', margin: 0, padding: 0, width: '100%' }} onClick={() => (isOpen ? close() : open())}> <Transition items={items} from={{ overflow: 'hidden', height: 0, opacity: 0 }} enter={{ height: 100, opacity: 1, background: 'rgba(10, 6, 5, 0.51)' }} leave={{ height: 0, opacity: 0.7, background: '#4d000355' }} update={{ background: 'rgba(29, 20, 15, 0.47)' }} trail={200}> {(item) => (styles) => <animated.div style={{ ...defaultStyles, ...styles }}>{item}</animated.div>} </Transition> </div> ); }; export default ListTransition;
import React, { Component } from 'react'; class Plane extends Component { render() { return ( <div className="plane-container"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1131.53px" height="379.304px" viewBox="0 0 1131.53 379.304" enableBackground="new 0 0 1131.53 379.304" xmlSpace="preserve" className="plane"> <polygon fill="#D8D8D8" points="72.008,0 274.113,140.173 274.113,301.804 390.796,221.102 601.682,367.302 1131.53,0.223 "/> <polygon fill="#C4C4C3" points="1131.53,0.223 274.113,140.173 274.113,301.804 390.796,221.102 "/> </svg> </div> ) } } export default Plane;
var mongoose = require('mongoose'), passport = require('passport'), router = require('express').Router() var auth = require('../auth') var User = mongoose.model('User') // Registration router.post('/users', (req, res, next) => { var user = new User() user.username = req.body.user.username user.setPassword(req.body.user.password) user.save().then(() => { return res.json({ user: user.toAuthJSON() }) }).catch(next) }) // Authentication router.post('/users/login', (req, res, next) => { if(!req.body.user.username){ return res.status(422).json({ errors: { username: "can't be blank" } }) } if(!req.body.user.password){ return res.status(422).json({ errors: { password: "can't be blank" } }) } passport.authenticate('local', { session: false }, (err, user, info) => { if(err){ return next(err) } if(user){ return res.json({ user: user.toAuthJSON() }) }else{ return res.status(422).json(info) } })(req, res, next) }) // Get Current User router.get('/user', auth.required, (req, res, next) => { User.findById(req.payload.id).then(user => { if(!user){ return res.sendStatus(401) } return res.json({ user: user.toAuthJSON() }) }).catch(next) }) // Update User router.put('/user', auth.required, (req, res, next) => { User.findById(req.payload.id).then(user => { if(!user){ return res.sendStatus(401) } if(typeof req.body.user.username !== 'undefined' && req.payload.username !== auth.admin){ user.username = req.body.user.username } if(typeof req.body.user.proPic !== 'undefined'){ user.proPic = req.body.user.proPic } if(typeof req.body.user.password !== 'undefined'){ user.setPassword(req.body.user.password) } return user.save().then(() => { res.json({ user: user.toAuthJSON() }) }) }).catch(next) }) module.exports = router
/* eslint-disable react/jsx-one-expression-per-line */ import React from 'react' import * as Story from '_story' import Toggle, { toggleTypes, Checkbox, Radio } from '.' const Demo = () => ( <> <h1>Toggle</h1> <p> The <em>Toggle</em> component provides checkbox and radio input functionality with a themed presentation. other than{' '} <code>type=&quot;checkbox&quot;</code> It provides no additional behavior beyond what native HTML checkboxes and radios provide, e.g. toggle logic. </p> <Checkbox id="toggle-checkbox-0" name="toggle-checkbox-0" /> <Radio id="toggle-radio-0" name="toggle-radio-0" /> <Story.Grid> {toggleTypes.map(type => ( <div> <Story.Label>{type}</Story.Label> <Toggle id={`toggle-${type}-1`} name={`example-${type}`} type={type} /> <Toggle id={`toggle-${type}-2`} name={`example-${type}`} type={type} /> <Toggle id={`toggle-${type}-3`} name={`example-${type}`} type={type} /> </div> ))} </Story.Grid> </> ) Demo.story = { name: 'Toggle', } export default Demo
import React, { useEffect } from "react" import { Link, graphql } from "gatsby" import Layout from "../components/layout" const BlogPage = ({ data }) => { useEffect(() => { if (document) { document.title = `Home | HUBCAP Guides` } }) return ( <Layout> <div className="blog"> <h1 className="blog__heading">Guides</h1> {data.allMarkdownRemark.edges.map(post => ( <div className="blog__item" key={post.node.id}> <Link className="blog__item__link" to={post.node.frontmatter.path}> <h3>{post.node.frontmatter.title}</h3> </Link> <hr /> </div> ))} </div> </Layout> ) } export const pageQuery = graphql` query BlogIndexQuery { allMarkdownRemark(sort: { fields: [frontmatter___guideNo], order: ASC }) { edges { node { id frontmatter { title path guideNo } } } } } ` export default BlogPage
function getLCS(a, b) { let count = 0; let current = 0; let arrA = a.split(''); let arrB = b.split(''); for (let i = 0;i<a.length;i++) { if (arrA[i] == arrB[i]) { current++; } else { if (current > count) { count = current; } current = 0; } } return count; }
//Piedra, papel o tijera let ganadorUno = "Ganó el Usuario 1" let ganadorDos = "Ganó el Usuario 2" let sinGanador = "Empataron" let invalida = "No ingresaste una opción válida. Se acabó el juego " let puntajeGanadorUno = 0 let puntajeGanadorDos = 0 for (i = 0; i = puntajeGanadorUno < 2 && puntajeGanadorDos < 2; i++) { let respuestaPrimerUsuario = prompt("Usuario 1: ¿Piedra, papel o tijera?"); if (respuestaPrimerUsuario === "piedra") { let respuestaSegundoUsuario = prompt("Usuario 2: ¿Piedra, papel o tijera?"); if (respuestaSegundoUsuario === "piedra") { alert(sinGanador) } else if (respuestaSegundoUsuario === "papel") { alert(ganadorDos) puntajeGanadorDos++ } else if (respuestaSegundoUsuario === "tijera") { alert(ganadorUno) puntajeGanadorUno++ } else { alert("No ingresaste una opcion valida") } } else if (respuestaPrimerUsuario === "tijera") { let respuestaSegundoUsuario = prompt("Usuario 2: ¿Piedra, papel o tijera?"); if (respuestaSegundoUsuario === "piedra") { alert(ganadorDos) puntajeGanadorDos++ } else if (respuestaSegundoUsuario === "papel") { alert(ganadorUno) puntajeGanadorUno++ } else if (respuestaSegundoUsuario === "tijera") { alert(sinGanador) } else { alert("No ingresaste una opcion valida") } } else if (respuestaPrimerUsuario === "papel") { let respuestaSegundoUsuario = prompt("Usuario 2: ¿Piedra, papel o tijera?"); if (respuestaSegundoUsuario === "piedra") { alert(ganadorUno) puntajeGanadorUno++ } else if (respuestaSegundoUsuario === "papel") { alert(sinGanador) } else if (respuestaSegundoUsuario === "tijera") { alert(ganadorDos) puntajeGanadorDos++ } else { alert("No ingresaste una opcion valida") } } else { alert("No ingresaste una opcion valida") } }
import React, { Component } from "react"; // import PropTypes from "prop-types"; import { StyleSheet } from "react-native"; import { Footer, FooterTab, Button, Text } from "native-base"; import Colors from "../constants/Colors"; import Icon from "react-native-vector-icons/MaterialIcons"; import NavigationService from "../services/nav.service"; const styles = StyleSheet.create({ footer: { backgroundColor: Colors.secondary, // backgroundColor: "#FFFFFF", }, text: { color: Colors.primary, }, }); const ListIcon = () => <Icon name="list" size={30} color={Colors.primary} />; const GraphIcon = () => ( <Icon name="show-chart" size={30} color={Colors.primary} /> ); const ExportIcon = () => ( <Icon name="cloud-download" size={30} color={Colors.primary} /> ); class BottomTabNav extends Component { render() { return ( <Footer style={styles.footer}> <FooterTab style={styles.footer}> <Button vertical onPress={() => NavigationService.navigate("Value")}> <ListIcon /> <Text style={styles.text}>Liste</Text> </Button> <Button vertical onPress={() => NavigationService.navigate("Graph")}> <GraphIcon /> <Text style={styles.text}>Graphs</Text> </Button> <Button vertical onPress={() => NavigationService.navigate("Export")}> <ExportIcon /> <Text style={styles.text}>Export</Text> </Button> </FooterTab> </Footer> ); } } BottomTabNav.propTypes = {}; export default BottomTabNav;
import * as d3 from 'd3'; export const countiesStoreUtil = { colorScale: d3 .scaleSequential() .domain([0, 100]) .interpolator(d3.interpolateRainbow), sortIntoArraysByCounty: (data, field = 'CountyName') => { // data in = [{galway},{galway},{longford}] // want data out = [[{galway},{galway}],[{longford}]] const usedCountyNames = []; const newData = []; data.forEach((d) => { // new county if (!usedCountyNames.includes(d[field])) { usedCountyNames.push(d[field]); newData.push([d]); } else { // find county in array of arrays and push new one in const correctArray = newData.filter((n) => n[0][field] === d[field])[0]; correctArray.push(d); } }); return newData; }, getLatestOrSelectedDateDataForCounty: (county, selectedDate) => { let dateToUse = selectedDate; if (!dateToUse) { // const dates = county.stats.map((s) => s.TimeStampDate); const dates = county.stats.map((s) => s.TimeStamp); dateToUse = Math.max(...dates.map((d) => d)); } const newestData = county.stats.filter( // (s) => s.TimeStampDate === dateToUse (s) => s.TimeStamp=== dateToUse ); return newestData[0]; }, turnArraysIntoNiceObjects: (data) => { const createManagableObjectAndSetFirstCountyToSelected = (n, i) => { const obj = {}; obj.name = n[0].CountyName; // should add reg obj.selected = false; obj.stats = [...n]; obj['color'] = countiesStoreUtil.colorScale(n[0].PopulationCensus16); if (i === 0) { obj['selected'] = true; } return obj; }; return data.map((n, i) => createManagableObjectAndSetFirstCountyToSelected(n, i) ); }, selectAttributeWithThisFieldName: (attributes, fieldName) => { return attributes.map((a) => { if (a.fieldName === fieldName) { a.selected = true; } else { a.selected = false; } return a; }); }, }; export const sharedUtil = { getLatestDate: (county) => { //const dates = county.stats.map((s) => s.TimeStampDate); const dates = county.stats.map((s) => s.TimeStamp); // renamed seventh july const newestDate = Math.max(...dates.map((d) => d)); return newestDate; // const dates = removeFromNestedAttributes(county, 'stats') }, getDataByFieldName: (data, fieldName, fieldValue) => { return data.filter((s) => s[fieldName] === fieldValue); }, removeFromNestedAttributes: (data, attr = 'attributes') => { return data.map((d) => { let obj = {}; for (const key in d[attr]) { obj[key] = d[attr][key]; } return obj; }); }, maxDate: (specificDate, data, specificDateFieldName) => { let dateToUse = specificDate; if (!dateToUse) { const dates = data.map((s) => s[specificDateFieldName]); dateToUse = Math.max(...dates.map((d) => d)); } return dateToUse; }, getLatestDataOrDataOnSpecificDate: ( data, specificDate, specificDateFieldName ) => { const dateToUse = sharedUtil.maxDate( specificDate, data, specificDateFieldName ); const newestData = sharedUtil.getDataByFieldName( data, specificDateFieldName, dateToUse ); return newestData[0]; }, prepArrayToShowInTextBox: graph => { return graph.selectedAttributeNames.map((name) => { const title = graph.avail.filter((a) => a.fieldName === name)[0].name; const color = graph.avail.filter((a) => a.fieldName === name)[0].color; const ans = {}; ans[name] = graph.selectedDateData[name]; ans.color = color; ans.title = title; ans.fieldName = name; ans.value = graph.selectedDateData[name]; return ans; }); } }; export const contactUtil = { isProbablyEmail: (str) => { var re = /\S+@\S+\.\S+/; if (str.length < 50) { return re.test(str); } return false; }, // function from netlify docs encode: (data) => { return Object.keys(data) .map( (key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) ) .join('&'); }, validate: (val, rules) => { let isValid = true; if (rules.required) { isValid = val.trim() !== '' && isValid; } if (rules.min) { isValid = val.length >= rules.min && isValid; } if (rules.max) { isValid = val.length <= rules.max && isValid; } if (rules.isProbablyEmail) { isValid = contactUtil.isProbablyEmail(val) && isValid; } return isValid; }, };
var searchData= [ ['mensagem',['Mensagem',['../client_8h.html#a13d6eab42ea1147a3b4b74bbec7a336b',1,'client.h']]] ];
import React, { Component } from 'react'; import { View, Text, SafeAreaView, StatusBar } from 'react-native'; import AboutPage from '../customer/AboutPage'; import ServicesPage from '../customer/ServicesPage'; import ReviewsPage from '../customer/ReviewsPage'; import styles from '../../styles/customer/Style_BusinessScreen'; import colors from '../../constants/Colors'; import ImagesSwiper from 'react-native-image-swiper'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import Layout from '../../constants/Layout'; import { Button } from 'react-native-elements'; import { connect } from "react-redux"; import * as Actions_Customer from '../../redux/actions/Actions_Customer'; import Menu, { MenuItem, MenuDivider } from 'react-native-material-menu'; import { MaterialCommunityIcons, MaterialIcons, FontAwesome, FontAwesome5, Ionicons, Octicons, Entypo } from '@expo/vector-icons'; import route from '../../routeConfig'; class BusinessScreen extends Component { constructor(props) { super(props); this.state = { businessData: this.props.route.params.businessData, carousel: [], hideAddToFavoritesButton: false, menu: null } this.renderBusinessInfo = this.renderBusinessInfo.bind(this); this.renderAddToFavoritesButton = this.renderAddToFavoritesButton.bind(this); this.fetchAddToFavorites = this.fetchAddToFavorites.bind(this); this.fetchRemoveFromFavorites = this.fetchRemoveFromFavorites.bind(this); this.handleRemoveFromFavorites = this.handleRemoveFromFavorites.bind(this); } componentDidMount() { this.props.navigation.setOptions({ title: 'Business', headerRight: () => ( <Entypo name={'dots-three-vertical'} size={26} color={colors.lightBlack} onPress={this.showMenu} style={{}} /> ), headerLeft: () => ( <MaterialIcons name={'keyboard-arrow-left'} size={45} color={colors.lightBlack} onPress={() => this.props.navigation.goBack()} /> ), }); } setMenuRef = ref => { this.menu = ref; }; hideMenu = () => { this.menu.hide(); }; showMenu = () => { this.menu.show(); }; handleRemoveFromFavorites() { // console.log(this.state.businessData.businessDetails.business.businessid) this.hideMenu(); this.props.dispatch(Actions_Customer.removeFromFavoritesList(this.state.businessData.businessDetails.business.businessid)); this.fetchRemoveFromFavorites(); } renderBusinessInfo() { const { businessData } = this.state; return ( <ScrollableTabView initialPage={0} locked={true} tabBarUnderlineStyle={styles.tabBarUnderline} tabBarBackgroundColor={'#FEFDFF'} tabBarActiveTextColor={colors.red} tabBarInactiveTextColor={'grey'} tabBarTextStyle={styles.tabBarText} > <AboutPage tabLabel="About" businessData={businessData} /> <ServicesPage tabLabel="Services" businessData={businessData} navigation={this.props.navigation} /> <ReviewsPage tabLabel="Reviews" businessData={businessData} /> </ScrollableTabView> ) } renderAddToFavoritesButton() { return ( <View style={styles.askToJoinContainer}> <View style={styles.askToJoinInsideContainer}> <Text style={styles.joinText}>Add to your favorites</Text> <Button type="outline" containerStyle={styles.joinButtonContainer} buttonStyle={styles.joinButton} titleStyle={styles.joinButtonTitle} icon={<MaterialIcons name={'favorite-border'} size={25} color={colors.white}/>} onPress={() => { alert(`${this.state.businessData.businessDetails.business.name} added to favorites!`); this.setState({ hideAddToFavoritesButton: true }); this.props.dispatch(Actions_Customer.addToFavoritesList(this.state.businessData)); this.fetchAddToFavorites(); }} /> </View> </View> ) } async fetchAddToFavorites() { const url = `${route}/customer/addBusinessToFavorites`; const options = { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ userID: this.props.currentUser.userid, businessID: this.state.businessData.businessDetails.business.businessid }) }; const request = new Request(url, options) await fetch(request) .then(response => response.json()) .then(data => { console.log(data) }) .catch(error => console.log(error)) } async fetchRemoveFromFavorites() { const url = `${route}/customer/removeBusinessFromFavorites`; const options = { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ userID: this.props.currentUser.userid, businessID: this.state.businessData.businessDetails.business.businessid }) }; const request = new Request(url, options) await fetch(request) .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.log(error)) } render() { return ( <View style={styles.flexContainer}> <StatusBar barStyle="dark-content"/> <View style={{width: 200, position: 'absolute', right: 0}}> <Menu ref={this.setMenuRef} style={{flex: 1}}> <MenuItem onPress={this.handleRemoveFromFavorites} textStyle={{color: 'red'}}>Remove from favorites</MenuItem> </Menu> </View> <View style={styles.ImagesSwiperContainer}> <ImagesSwiper autoplay={true} autoplayTimeout={5} showsPagination width={Layout.window.width} height={200} images={this.state.businessData.businessDetails.photos.carousel.map((item) => item.imagelink)} /> </View> {this.renderBusinessInfo()} {this.props.route.params.isInFavorites || this.state.hideAddToFavoritesButton ? null : this.renderAddToFavoritesButton()} </View> ) } } const mapStateToProps = ({ App, User, Customer, Business }) => { return { hasBusiness: User.hasBusiness, currentUser: User.currentUser, favoritesList: Customer.favoritesList, view: User.view, categoriesList: App.categoriesList, currentBusiness: Business.currentBusiness } } export default connect(mapStateToProps)(BusinessScreen);
$('.regionInput').on('click', function() { $('.region__wrapper').toggleClass('closed'); $('.category__wrapper').addClass('closed'); }); $('.regionInput').on('input', function() { var text = $(this).val(); if (text.length > 2) { var selector = '.region-first-level:contains(' + '"' + text + '"' + ')'; $('.region-first-level').hide(); $(selector).show(); } else { $('.region-first-level').show(); } }); $('.region-first-level').on('click', function() { $('.region-items-item').remove(); var newRegText = $(this).text(); $('.region-empty').addClass('have-select-region'); var newReg = $('<div class="region-items-item"></div>'); newReg.text(newRegText); $('.regionInput').val(newRegText); $('.region-items').prepend(newReg); $('.region-items').removeClass('dnthave-select-region'); $('.region-first-level').show(); }); $('.clear-regions').on('click', function() { $('.region-items-item').remove(); $('.region-empty').removeClass('have-select-region'); $('.region-items').addClass('dnthave-select-region'); $('.regionInput').val(''); }); $('.close__btn-reg').on('click', function() { $('.region__wrapper').toggleClass('closed'); }); $('.first-level span').on('click', function() { if ($(this).parent().parent().parent().parent().parent().parent().find('.category-items-item').length) { newElem(); $('.category__wrapper').addClass('closed'); $(this).parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); } else { $(this).parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); var catText = $(this).text(); var newCat = $('<div class="category-items-item"></div>') newCat.text(catText); $(this).parent().parent().parent().parent().parent().parent().find('.category-items').prepend(newCat); $(this).parent().parent().parent().parent().parent().parent().find('.category-empty').addClass('have-select-category'); $(this).parent().parent().parent().parent().parent().parent().find('.category-items').removeClass('dnthave-select-category'); $(this).parent().parent().parent().parent().parent().parent().parent().find('.catInput').val(catText); } }); $('.second-level span').on('click', function() { if ($(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').length) { newElem(); $('.category__wrapper').addClass('closed'); $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); } else { $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); var catText = $(this).text(); var newCat = $('<div class="category-items-item"></div>') newCat.text(catText); $(this).parent().parent().parent().parent().parent().parent().parent().find('.category-items').prepend(newCat); $(this).parent().parent().parent().parent().parent().parent().parent().find('.category-empty').addClass('have-select-category'); $(this).parent().parent().parent().parent().parent().parent().parent().find('.category-items').removeClass('dnthave-select-category'); $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.catInput').val(catText); } }); $('.third-level').on('click', function() { if ($(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').length) { newElem(); $('.category__wrapper').addClass('closed'); $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); } else { $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items-item').remove(); var catText = $(this).text(); var newCat = $('<div class="category-items-item"></div>') newCat.text(catText); $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items').prepend(newCat); $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-empty').addClass('have-select-category'); $(this).parent().parent().parent().parent().parent().parent().parent().parent().find('.category-items').removeClass('dnthave-select-category'); $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.catInput').val(catText); } }); $('.first-level .ico').on('click', function() { $(this).parent().parent().children('.category__content-item-ul').toggleClass('off'); $(this).parent().toggleClass('selected'); }); $('.second-level .ico').on('click', function() { $(this).parent().parent().children('.category__content-item-ul-li-ul').toggleClass('off'); $(this).parent().toggleClass('selected'); }); $('.clear-category').on('click', function() { $(this).parent().parent().parent().find('.category-empty').removeClass('have-select-category'); $(this).parent().parent().parent().find('.category-items').addClass('dnthave-select-category'); $(this).parent().parent().parent().find('.selected').removeClass('selected'); $(this).parent().parent().parent().find('.category__content-item-ul').addClass('off'); $(this).parent().parent().parent().find('.category__content-item-ul-li-ul').addClass('off'); $(this).parent().parent().parent().parent().find('.catInput').val(''); }); $('.catInput').on('click', function() { $('.region__wrapper').addClass('closed'); $('.category__wrapper').addClass('closed'); $(this).parent().children('.category__wrapper').toggleClass('closed'); }); $('.category__header .close__btn').on('click', function() { $(this).parent().parent().addClass('closed'); });
import React from 'react'; import SidebarInfo from '../../../util/SidebarInfo/SidebarInfo'; import DetailsBlock from '../../../util/DetailsBlock/DetailsBlock'; const PositionDetails = ({ geo }) => ( <div className='sidebar'> <div className='sidebar-wrap'> {geo ? ( <DetailsBlock title='Your coordinates' latitude={geo.latitude.toFixed(6)} longitude={geo.longitude.toFixed(6)} accuracy={geo.accuracy} /> ) : null} <SidebarInfo list='React, React Hooks, Geolocation API' /> </div> </div> ); export default PositionDetails;
'use strict' angular.module('sharedServices').directive('customSummary', function () { return { link: function (scope, elm, attrs, ctrl) { scope.$watch("modelErrors['summaryerrors']", function (newValue, oldValue) { if (newValue) { elm.empty(); for (var i = 0; i < newValue.length; i++) { var error_message = newValue[i]; elm.append('<li class="help-block">' + error_message + '</li>'); } } }); } }; });
$(document).ready(function () { // Método para pular campos teclando ENTER $('.pula').on('keypress', function(e){ var tecla = (e.keyCode?e.keyCode:e.which); if(tecla == 13){ campo = $('.pula'); indice = campo.index(this); if(campo[indice+1] != null){ proximo = campo[indice + 1]; proximo.focus(); e.preventDefault(e); } } }); // Inseri máscara no CEP $("#cepfunc").inputmask({ mask: ["99999-999",], keepStatic: true }); // $("#cpf").inputmask({ // mask: ["999.999.999-99",], // keepStatic: true // }); // Método para consultar o CEP $('#cepfunc').on('blur', function(){ if($.trim($("#cepfunc").val()) != ""){ $("#mensagem").html('(Aguarde, consultando CEP ...)'); $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cepfunc").val(), function(){ if(resultadoCEP["resultado"]){ $("#logradourofunc").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"])); $("#bairrofunc").val(unescape(resultadoCEP["bairrofunc"])); $("#cidadefunc").val(unescape(resultadoCEP["cidade"])); $("#uffunc").val(unescape(resultadoCEP["uffunc"])); } }); } }); }); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $(document).ready(function () { // Método para pular campos teclando ENTER $('.pula').on('keypress', function(e){ var tecla = (e.keyCode?e.keyCode:e.which); if(tecla == 13){ campo = $('.pula'); indice = campo.index(this); if(campo[indice+1] != null){ proximo = campo[indice + 1]; proximo.focus(); e.preventDefault(e); } } }); // Inseri máscara no CEP $("#cepaluno").inputmask({ mask: ["99999-999",], keepStatic: true }); // $("#cpf").inputmask({ // mask: ["999.999.999-99",], // keepStatic: true // }); // Método para consultar o CEP $('#cepaluno').on('blur', function(){ if($.trim($("#cepaluno").val()) != ""){ $("#mensagem").html('(Aguarde, consultando CEP ...)'); $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cepaluno").val(), function(){ if(resultadoCEP["resultado"]){ $("#logradouroaluno").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"])); $("#bairroaluno").val(unescape(resultadoCEP["bairroaluno"])); $("#cidadealuno").val(unescape(resultadoCEP["cidade"])); $("#ufaluno").val(unescape(resultadoCEP["ufaluno"])); } }); } }); });
const cron = require('cron') const CronJob = cron.CronJob const test = () => { new CronJob('*/10 * * * * *', () => { console.log('aaa') }).start() new CronJob('*/10 * * * * *', () => { console.log('bbb') }).start() } test()
/** * An example data layer for the repo. Just stores the information in memory and * gets updates from authenticated nodes via a file. */ var config = require('config') var fs = require('fs') var Q = require('q') var loc = './../head.txt' var head = '0000000000000000000000000000000000000000' if (!fs.existsSync(loc)) { fs.writeFileSync(loc, '0000000000000000000000000000000000000000') } var head = fs.readFileSync(loc).toString() fs.watchFile(loc, function () { head = fs.readFileSync(loc).toString() }) module.exports.head = function () { return Q(head) }
window.onload = function() { var flag = 1; var main18 = document.getElementById('main18'); main18.onclick = function() { if (flag == 1) { main7.style.transition = '-webkit-transform 1.5s'; main7.style.transform = 'rotate(-60deg)'; main6.style.transition = '-webkit-transform 1.5s'; main6.style.transform = 'rotate(-40deg)'; main5.style.transition = '-webkit-transform 1.5s'; main5.style.transform = 'rotate(-20deg)'; main4.style.transition = '-webkit-transform 1.5s'; main4.style.transform = 'rotate(0deg)'; main3.style.transition = '-webkit-transform 1.5s'; main3.style.transform = 'rotate(20deg)'; main2.style.transition = '-webkit-transform 1.5s'; main2.style.transform = 'rotate(40deg)'; main1.style.transition = '-webkit-transform 1.5s'; main1.style.transform = 'rotate(60deg)'; flag = 0; } else if (flag == 0) { main7.style.transition = '-webkit-transform 1.5s'; main7.style.transform = 'rotate(0deg)'; main6.style.transition = '-webkit-transform 1.5s'; main6.style.transform = 'rotate(0deg)'; main5.style.transition = '-webkit-transform 1.5s'; main5.style.transform = 'rotate(0deg)'; main4.style.transition = '-webkit-transform 1.5s'; main4.style.transform = 'rotate(0deg)'; main3.style.transition = '-webkit-transform 1.5s'; main3.style.transform = 'rotate(0deg)'; main2.style.transition = '-webkit-transform 1.5s'; main2.style.transform = 'rotate(0deg)'; main1.style.transition = '-webkit-transform 1.5s'; main1.style.transform = 'rotate(0deg)'; flag = 1; } } } function doce(fn, wait) { let timer = null wait = wait || 500; return function () { clearTimeout(timer) timer = setTimeout(() => { fn.call(this, ...arguments)//保证this执行 和参数的传递 }, wait) } } function throttle(fn, wait) { var flag = true; return function () { if (!flag) return setTimeout(() => { flag = true; fn.call(this, ...arguments) }, wait) } } function black1(id) { let $bigDiv = $(id); console.log($bigDiv); // $mask = $bigDiv.find('.solide_mask') // console.log($mask); $bigDiv.on('mouseenter', throttle(function (e) { // if (e.target!==this) { // return // } // e.stopPropagation() $(this).find('h1').css({ transform: 'translateY(0px)',opacity:'1'}) let $mask = $(this).find('.mask').eq(0) $mask.css({ opacity:'0.98' },300) var e = e || window.event var target = $bigDiv[0] //获取鼠标x,y坐标 var x = e.pageX var y = e.pageY //获取图片距离浏览器位置 var t = $bigDiv.offset().top var b = t + target.offsetHeight var l = $bigDiv.offset().left var r = l + target.offsetWidth //获取鼠标与图片距离浏览器位置的差值(注意有负值,需要绝对值 Math.abs) var chaYT = Math.abs(y - t) var chaYB = Math.abs(y - b) var chaXL = Math.abs(x - l) var chaXR = Math.abs(x - r) //取得最小值 var min = Math.min(chaYT, chaYB, chaXL, chaXR) let boxT = $bigDiv[0].clientHeight let boxW = $bigDiv[0].clientWidth switch (min) { case chaYT: //上 $mask.css({ top: -boxT + 'px', left: '0' }).animate({ top: 0, left: 0 }, 250) break; case chaYB://下 $mask.css({ top: boxT + 'px', left: '0' }).animate({ top: 0, left: 0 }, 250) break; case chaXL://左 $mask.css({ top: 0, left: -boxW + 'px' }).animate({ top: 0, left: 0 }, 250) break; case chaXR://右 $mask.css({ top: 0, left: boxW + 'px' }).animate({ top: 0, left: 0 }, 250) break; } }, wait = 10)) $bigDiv.on('mouseleave', throttle(function (e) { // if (e.target!==this) { // return // } $(this).find('h1').css({ transform: 'translateY(-80px)',opacity:'0'}) // e.stopPropagation() let $mask = $(this).find('.mask') var e = e || window.event var target = $(this)[0] //获取鼠标x,y坐标 var x = e.pageX var y = e.pageY //获取图片距离浏览器位置 var t = $(this).offset().top var b = t + target.offsetHeight var l = $(this).offset().left var r = l + target.offsetWidth //获取鼠标与图片距离浏览器位置的差值(注意有负值,需要绝对值 Math.abs) var chaYT = Math.abs(y - t) var chaYB = Math.abs(y - b) var chaXL = Math.abs(x - l) var chaXR = Math.abs(x - r) //取得最小值 var min = Math.min(chaYT, chaYB, chaXL, chaXR) $mask.hide() let boxT = $(this)[0].clientHeight let boxW = $(this)[0].clientWidth $mask.show() switch (min) { case chaYT: //上 $mask.animate({ top: -boxT + 'px', left: 0 }, 250) break; case chaYB://下 $mask.animate({ top: boxT + 'px', left: 0 }, 250) break; case chaXL://左 $mask.animate({ top: 0, left: -boxW + 'px' }, 250) break; case chaXR://右 $mask.animate({ top: 0, left: boxW + 'px' }, 250) break; } }, wait = 10)) } black1('.pic1') black1('.pic2') black1('.pic3') black1('.pic4') // $(function(){ // let $oDiv=$('.characteritic div') // let $h1=$('.characteritic h1') // $oDiv.on('mouseenter',function (){ // $(this).find('h1').css({ transform: 'translateY(0px)',opacity:'1'}) // }) // $oDiv.on('mouseleave',function (){ // }) // })
/** * PostController * * @description :: Server-side logic for managing Posts * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { // Carrega a view de feed do usuario view_feed: function(req, res) { return res.view('post/feed'); }, // Cria um novo post api_create: function(req, res) { req.body.owner = req.params.uid; Post .create(req.body) .exec(function(err, post) { if (err || !post) { console.log(err); return res.status(400).json({}); } return res.json(post) }); }, // Altera um post api_edit: function(req, res) { var _post; Post .findOne({ id : req.params.id }) .then(function(post) { if (!post) { return res.status(401).json({}); } else { if (req.body.title) post.title = req.body.title; if (req.body.text) post.text = req.body.text; _post = post; return post.save(); } }) .then(function() { return res.json(_post); }) .catch(function(err) { console.log(err); return res.status(401).json({}); }); }, // Remove um post api_delete: function(req, res) { Post .destroy({ id : req.params.id }) .then(function() { return res.json({}); }) .catch(function(err) { console.log(err); return res.status(401).json({}); }); }, // Carrega os posts do usuario api_feed: function(req, res) { Post .find({ owner : req.params.uid }) .populate('owner') .populate('likes') .populate('dislikes') .populate('shares') .exec(function(err, posts) { if (err || !posts) { console.log(err); return res.status(400).json({}); } return res.json(posts) }); }, // Compartilha um post de um usuário api_share: function(req, res) { var _post; Post .findOne({ id : req.params.pid }) .exec(function(err, post) { if (err || !post) { return res.status(400).json({}); } post.shares.add(req.params.uid); _post = { originalId : post.id, title : post.title, text : post.text, owner : req.params.uid } post.save(function(err, post) { Post .create(_post) .exec(function(err, post) { if (err || !post) { console.log(err); return res.status(400).json({}); } return res.json(post) }); }); }); }, // Da um like no post api_like: function(req, res) { var _post; Post .findOne({ id : req.params.pid }) .exec(function(err, post) { if (err || !post) { console.log(err); return res.status(400).json({}); } post.likes.add(req.params.uid); post.save(function(err) { return res.json(post) }); }); }, // Da um dislike no post api_dislike: function(req, res) { var _post; Post .findOne({ id : req.params.pid }) .exec(function(err, post) { if (err || !post) { return res.status(400).json({}); } post.dislikes.add(req.params.uid); post.save(function(err) { return res.json(post) }); }); } };
import React, { useContext, useEffect } from 'react' import { Link ,withRouter } from 'react-router-dom'; import { Fragment } from 'react/cjs/react.production.min'; import MyContext from '../context/Context'; const Links = (props) => { const context = useContext(MyContext) const { TodoList,logoutApp,usernameLogin } = context useEffect(() => { if(usernameLogin == ""){ localStorage.clear() props.history.replace("/") } }, []) return ( <Fragment> <div className="userlayout position-absolute "> <div className={"wellcoming"}>سلام <span className="text-success">"{usernameLogin} "</span> </div> </div> <nav className="nay-p d-flex justify-content-start position-absolute"> <button type="button" className={(TodoList.length<3 ? ("btn btn-success px-2 py-0"):("btn btn-primary px-2 py-0"))} > <span className="badge badge-light " style={{fontSize:"1.3rem"}}>{TodoList.length}</span>: تعداد </button> <Link className="btn btn-info mx-2" to={"/about-app"} >درباره برنامه</Link> <Link className="btn btn-danger " to={"/login"} onClick={logoutApp} >خروج</Link> </nav> </Fragment> ); } export default withRouter(Links) ;
'use strict'; import * as chai from 'chai'; import { respond } from './action'; import * as sinon from 'sinon'; import * as sinonAsPromised from 'sinon-as-promised'; import { RecipientsCounterService } from '../../lib/recipients_counter_service'; import * as event from './event.json' const expect = chai.expect; describe('recipientsCounter', () => { const recipientsCounterService = sinon.createStubInstance(RecipientsCounterService); describe('#respond()', () => { beforeEach(() => { sinon.stub(RecipientsCounterService, 'create').returns(recipientsCounterService); recipientsCounterService.updateCounters.resolves({}); }); it('calls to the update counters service', (done) => { respond(event, (err, result) => { expect(recipientsCounterService.updateCounters).calledOnce; done(); }); }); afterEach(() => { recipientsCounterService.updateCounters.restore(); }); }); });
// Config vue-head import prefetchedThirdPartyDomains from './prefetchedThirdPartyDomains' export default { title: 'nuxt', meta: [ { charset: 'utf-8' }, // check with designer if this should be removed for better lighthouse score { name: 'viewport', content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' }, { hid: 'robots', name: 'robots', content: 'INDEX,FOLLOW' }, { hid: 'site', property: 'og:site_name', content: 'vidaxl' } ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }, ...prefetchedThirdPartyDomains ], script: [ // For Zendesk prefill user data { innerHTML: 'window.adaSettings = { metaFields: {} }' } ] }
// function returns fibbonacci series // reference taken from the odin project git repo const fibonacci = function (count) { if (count < 0) return "OOPS"; if (count === 0) return 0; let a = 0; let b = 1; for (let i = 1; i < count; i++) { const temp = b; b = a + b; a = temp; } return b; // code in the comment works same // num = parseInt(count); // let array = []; // array[0] = 1; // array[1] = 1; // for (let i = 2; i <= count; i++) { // array[i] = array[i - 2] + array[i - 1]; // } // return count < 0 ? "OOPS" : array[count - 1]; }; module.exports = fibonacci;
const grid_module = require('../grid'); describe('Grid', function() { let grid, config; beforeEach(function() { config = { width: 2, height: 3, seedValue: 'x' }; grid = grid_module(config); }); describe('built with a config object', function() { it('should return two-dimensional array when called', function() { let result = grid(); expect(Array.isArray(result)).toBe(true); result.forEach(function(row) { expect(Array.isArray(row)).toBe(true); }); }); it('should initialize all its values to the given "seedValue" key', function() { grid().forEach(function(row) { row.forEach(function(el) { expect(el).toEqual(config.seedValue); }); }); }); it('should return the correct width', function() { expect(grid.width()).toEqual(config.width); }); it('should return the correct height', function() { expect(grid.height()).toEqual(config.height); }); }); describe('getCell()', function() { it('should get a value at a cell', function() { let p = [0,2]; let expected = grid()[p[1]][p[0]]; let result = grid.getCell(p); expect(result).toEqual(expected); }); }); describe('setCell()', function() { it('should set the value of a cell', function() { let p = [0,2]; let value = 'test'; let result = grid.setCell(p).to(value); expect(result.getCell(p)).toEqual(value); }); }); });
// const myArray = [12, 4, 26, 44, 1043, 2]; // for (let i = 0; i < myArray.length; i++) { // console.log(myArray[i]); // } //OR // for (number of myArray) { // console.log(number); // } // // // myArray.forEach((item) => { // console.log(item); // }); //OR // const print = (number) => { // console.log(number); // } // myArray.forEach(print); // const nology = [ // ["Jonny", "Sunny", "Annika", "Sophie"], // ["Andy", "Nasir", "Sonia", "Sam"] // ]; // nology [0] [2] //Loop through the state and replace all the i's iwth 1s // 1. Loop through the string // const state = "mississippi"; // // Loop through the state and replace all the i's with 1s // // 1. Loop through the string // const newState = [...state]; // for (let i = 0; i < newState.length; i++) { // if (newState[i] === "i") { // newState[i] = 1; // } // } // console.log(newState); // 2. If the letter is i, replace with it with 1 //3. console.log the new string // Fizzbuzz // Fizzbuzz // 1. console.log all numbers to 1000 // 2. If the number is divisible by 3, replace it with fizz // 2. If the number is divisible by 5, replace it with buzz // 3. divisible by both, fizzbuzz!!!!!! // loop if console log // for (let i = 0; i <= 100; i++) { // if ((i % 3 === 0)&& ) // if (i % 3 === 0) { // console.log("fizz") // } else (i % 5 === 0); { // console.log("buzz"); // } else // } // const loom = (thread, dye) => { // const cloth = "Cloth of color " + dye + " made with " + thread + " thread"; // return cloth; // } // const result = loom("cotton", "red"); // console.log(result); // write a function that returns the square root of a number const squareRoot = (number) => { return Math.sqrt(number); } // write a function that checks if a number is an integer const checkIsInteger = (number) => { return Number.IsInteger(number); } const result = squareRoot (16); console.log(checkIsInteger(result)); const squareRoot = squareTheNumber(16); const IsInteger = checkIsInteger(squareRoot); // small functions first
// # 请半小时后将答案以邮件形式回复HR // 1. 简单说一下对函数式编程的理解,50字左右即可 // 2. 请实现下面两个函数使其通过测试,以最简洁的方式完成,并保证代码质量 module.exports.test1 = (inpu) => {} module.exports.test2 = (input) => {}
/** * Created by beetle on 2016/4/30. */ (function () { 'use strict'; angular .module('app') .controller('addCtrl', addCtrl); addCtrl.$inject = ['$scope', 'frameworkService']; function addCtrl($scope, frameworkService) { $scope.addMode = true; $scope.editMode = false; $scope.save = save; //提交框架 function save() { var parma = JSON.stringify($scope.fw) frameworkService.save(parma).$promise.then(function (result) { $scope.respondMessage = result.message; }) } $scope.reset = reset; //重置表单数据 function reset() { $scope.newFramework = {}; } } })();
module.exports = { userCache: { }, ipCache: { } };
var canLogin = false; $(document).ready(function(){ }); //checkUser = function(){ // var resno1 = $("#resno1").val(); // var resno2 = $("#resno2").val(); // // if(resno1.length == 6 && resno2.length == 7){ // var j_username = resno1 + resno2; // $.ajax({ // dataType: 'json', // type : 'POST', // url : _requestPath + '/login/checkUser', // timeout : 5000, // data : {j_username : j_username}, // beforeSubmit : function(){ // // }, // success : function(result){ // var needPwInsert = result.needPwInsert; // var success = result.success; // var errorOccur = result.errorOccur; // // if(success){ // canLogin = true; // $("#j_username").val(j_username); // $("#j_password").attr("disabled",false); // }else{ // if(needPwInsert){ // $("#j_username").val(j_username); // $("#j_password").attr("disabled",false); // $("#j_password").focus(); // passwordSetting(); // }else if(errorOccur){ // var msg = result.msg; // alert(msg); // $("#resno1").val(""); // $("#resno2").val(""); // } // } // }, // error : function(response, status, err){ // alert(err); // $("#resno1").val(""); // $("#resno2").val(""); // } // }); //Ajax로 호출한다. // } //}; checkUser = function(){ var patno = $("#patno").val(); var name = $("#name").val(); if(patno.length > 0 && name.length > 0){ var j_username = patno; $.ajax({ dataType: 'json', type : 'POST', url : _requestPath + '/login/checkUser', timeout : 5000, data : {j_username : j_username, patName : name}, beforeSubmit : function(){ }, success : function(result){ var needPwInsert = result.needPwInsert; var success = result.success; var errorOccur = result.errorOccur; if(success){ canLogin = true; $("#j_username").val(j_username); $("#name").attr("readonly",true); $("#j_password").attr("disabled",false); }else{ if(needPwInsert){ $("#j_username").val(j_username); $("#j_password").attr("disabled",false); $("#j_password").focus(); passwordSetting(); }else if(errorOccur){ var msg = result.msg; alert(msg); $("#j_username").val(""); $("#patno").val(""); $("#name").val(""); $("#name").attr("readonly",false); } } }, error : function(response, status, err){ alert(err); $("#patno").val(""); $("#j_username").val(""); $("#patno").val(""); $("#name").val(""); $("#name").attr("readonly",false); } }); //Ajax로 호출한다. } }; passwordSetting = function(){ hideLogin(); $.fancybox.open({ href : "#password-popup",type : 'inline', modal : 'true', openEffect : 'elastic',closeEffect : 'elastic', width : 500, height :300, helpers : { title : {type : 'float'} } }); }; submitPassword = function(){ var j_username = $("#j_username").val(); var nPassword = $("#nPassword").val(); var rPassword = $("#rPassword").val(); //TODO 비밀번호 규칙 필요? if(nPassword == null || nPassword.length == 0){ alert("비밀번호를 입력하세요."); return; } if(nPassword.length < 4){ alert("비밀번호를 최소 4자리이상 입력하세요."); return; } if(nPassword != rPassword){ alert("비밀번호가 서로 다릅니다."); return; } $.ajax({ dataType: 'json', type : 'POST', url : _requestPath + '/login/insertPassword', timeout : 5000, data : {j_username : j_username, j_password : nPassword}, beforeSubmit : function(){ }, success : function(result){ if(result.success){ //alert("비밀번호 설정이 완료되었습니다.로그인하세요."); $("#j_password").val(nPassword); _login(); $.fancybox.close(); }else{ alert(result.msg); } }, error : function(response, status, err){ alert(err); } }); //Ajax로 호출한다. }; _login = function(){ var loginId = $("#j_username").val(); var password = $("#j_password").val(); if(loginId == null || loginId.length == 0){ var patno = $("#patno").val(); if(patno == null || patno.length == 0){ alert("수진자번호를 입력하세요"); return; }else{ $("#j_username").val(patno); } } if(password == null || password.length == 0){ alert("비밀번호를 입력하세요."); return; } $("#loginForm").submit(); }; searchPatno = function(){ if(!$("#agree").is(':checked')){ alert("'개인정보이용동의'에 체크하셔야 수진자번호를 부여 받으실 수 있습니다."); return; } var resno1 = $("#resno1").val(); var resno2 = $("#resno2").val(); if(resno1.length == 6 && resno2.length == 7){ $.ajax({ dataType: 'json', type : 'POST', url : _requestPath + '/login/findPatno', timeout : 5000, data : {resno : resno1+resno2}, beforeSubmit : function(){ }, success : function(result){ if(result.success){ var patno = result.patno; alert("수진자번호는 " + patno + "입니다."); $.fancybox.close(); }else{ alert(result.msg); } }, error : function(response, status, err){ alert(err); } }); //Ajax로 호출한다. }else{ alert("주민등록번호를 전부 입력하세요."); } };
import React from "react" export default function ripple() { return <div className="ripple" /> }
import { makeStyles } from "@material-ui/core"; import React from "react"; import Fifty from "../../components/Fifty"; import LoginForm from "../../components/LoginForm"; import Header from "../../components/shared/Header"; const useStyles = makeStyles((theme) => ({ welcome: { display: "flex", flexFlow: "column nowrap", width: "100vw", height: "100%", textAlign: "center", alignItems: "center", justifyContent: "center", }, blurb: { margin: "10vh 0 10vh 0 ", fontFamily: "Helvetica", }, logo: { position: "absolute", right: 5, bottom: 2, width: "20vw", }, })); export default function Welcome({ loginGuest, setCurrentGuest }) { const classes = useStyles(); return ( <> <Header /> <div className={classes.welcome}> <LoginForm loginGuest={loginGuest} /> </div> <Fifty /> </> ); }
import Ember from 'ember'; export default Ember.Mixin.create({ bindSidebar: function() { var onSidebar, _this = this; onSidebar = function(){ try { return _this.sidebarred(); } catch(err){} }; Ember.$('#main-content').bind('openSidebar', onSidebar); Ember.$('#main-content').bind('closeSidebar', onSidebar); }, unbindSidebar: function() { Ember.$('#main-content').unbind('openSidebar'); Ember.$('#main-content').unbind('closeSidebar'); } });
var mh_8c = [ [ "mh_mkstemp", "mh_8c.html#ac05f97c3d2b14c1e952032b5c624fd29", null ], [ "mh_already_notified", "mh_8c.html#ac355ba6e8c9b1ab7fa886e52ac6f5d4e", null ], [ "mh_valid_message", "mh_8c.html#a5fb13b8e28f2517db9e35b6a0f4d809e", null ], [ "mh_check_empty", "mh_8c.html#a0bc1f221906f8f540fa7a98e81f0dc31", null ], [ "mh_mbox_check_stats", "mh_8c.html#a6e79a0be615b804703affa841d14c992", null ], [ "mh_update_maildir", "mh_8c.html#a77bdd8a27e35d9feaa1b128307caf80a", null ], [ "mh_commit_msg", "mh_8c.html#a7d1a12ff9d7a670232f772da4f090bc8", null ], [ "mh_rewrite_message", "mh_8c.html#ab449581b7e9a8cbdca031bb0d80573d2", null ], [ "mh_sync_message", "mh_8c.html#a165a4e742c432037d9063fbe8afa97ce", null ], [ "mh_update_mtime", "mh_8c.html#a2a7cfed3c9ddff88c51d36c49c8b3e02", null ], [ "mh_parse_dir", "mh_8c.html#aec94a56b213ec14d2043468f41785ed1", null ], [ "mh_cmp_path", "mh_8c.html#ad6a01e2383ee6ae084516d844375eb7b", null ], [ "mh_parse_message", "mh_8c.html#a07e65bb55fabf32fcdff84b8e6668d65", null ], [ "mh_delayed_parsing", "mh_8c.html#a3d2701c591b243c3ff1bd487f808987b", null ], [ "mh_read_dir", "mh_8c.html#a137d15a2837f85d27c140171be272f10", null ], [ "mh_sync_mailbox_message", "mh_8c.html#a233a7a0d01e5a50160e42219674f2e16", null ], [ "mh_open_message", "mh_8c.html#a162aba0c0982eef8baca0955c817df28", null ], [ "mh_msg_save_hcache", "mh_8c.html#af2af0145d20c54226fa0d46c4979e7a6", null ], [ "mh_ac_find", "mh_8c.html#ae9793c87e77b2eb37ebf7ad8fc0ae984", null ], [ "mh_ac_add", "mh_8c.html#a504b173b18164b2b7849a8cf1a1af052", null ], [ "mh_mbox_open", "mh_8c.html#abdf02885d1d741a84e8ebd99aef8cf10", null ], [ "mh_mbox_open_append", "mh_8c.html#a6683ee55cc11fb9430cb51cd110c7254", null ], [ "mh_mbox_check", "mh_8c.html#a2a2f83814f45a1f1364bae22ed6240af", null ], [ "mh_mbox_sync", "mh_8c.html#a5b0d82f90208aa4da82905602d3b321a", null ], [ "mh_mbox_close", "mh_8c.html#a1beb9bdd072c82f832b832762957ed72", null ], [ "mh_msg_open", "mh_8c.html#a37a59f0a2d3e560ef149608d36160b14", null ], [ "mh_msg_open_new", "mh_8c.html#a3373a131c1c4ed67367da08682521553", null ], [ "mh_msg_commit", "mh_8c.html#ab7cdabd2411f9704a83e58359212256a", null ], [ "mh_msg_close", "mh_8c.html#a41ed62b3e2b71b6c945d6abfe8a2a142", null ], [ "mh_path_canon", "mh_8c.html#a92b95118a48740439ca375d6fd797f8e", null ], [ "mh_path_parent", "mh_8c.html#a8fe234adfa21a07311f485e8199ad96f", null ], [ "mh_path_pretty", "mh_8c.html#a3558dab49e1616e07a97e7ac8aa0e088", null ], [ "mh_path_probe", "mh_8c.html#a6d5988bb4154475a9d8cb94a4c7c77d4", null ], [ "MxMhOps", "mh_8c.html#a1c6613efa24f50ed6d0c077738937838", null ] ];
// Write a program that, given a word, computes the scrabble score for that word. // 1. split word into individual characters // 2. run each character against the value table // 3. add to final score // 4. output final score var scrabbleTable = { "A":1, "E":1, "I":1, "O":1, "U":1, "L":1, "N":1, "R":1, "S":1, "T":1, "D":2, "G":2, "B":3, "C":3, "M":3, "P":3, "F":4, "H":4, "V":4, "W":4, "Y":4, "K":5, "J":8, "X":8, "Q":10, "Z":10 }; console.log('Scrabble Score'); function ScrabbleScore(word) { var cleaned_word = word.replace(/[^\w\s]|_/g, "").replace(/\s+/g, "").toUpperCase(); var length = cleaned_word.length; var split = cleaned_word.split(''); var score = 0; for (var i = 0; i < length; i++) { score += (scrabbleTable[split[i]]); } return score; }
/** * Base class for canvas objects * @namespace * @constructor */ vonline.Base = function() { // data and object needs to be always in sync this.data = vonline.Base.defaultData; this.obj = null; // overwrite in subclass for connections and annotations this.resizeable = true; this.rotationCircle = null; this.rotationHandle = null; this.connectionHandle = null; this.annotationHandle = null; this.inlineTextHandle = null; this.connectionPath = null; } /** default values and json format specification */ vonline.Base.defaultData = { /** unique identifier */ id: 0, /** 'rectangle', 'circle', 'path', 'image', 'annotation', 'connection' */ type: null, /** SVG path or further differentation of type, e.g. 'arrow', 'line' */ path: null, x: 0, y: 0, width: 50, height: 50, rotation: 0, /** see: http://raphaeljs.com/reference.html#colour */ color: '90-#ddd-#fff', text: null, /** [width, color] */ border: null, /** [id, id] */ connect: [] }; vonline.Base.prototype.getId = function() { return this.data.id; } vonline.Base.prototype.isResizeable = function() { return this.resizeable; } /** * Displays the element on the canvas * @param {vonline.Canvas} canvas */ vonline.Base.prototype.setCanvas = function(canvas) { if (!canvas && this.obj) { // remove this.obj.remove(); if (this.text) { this.text.remove(); } return; } this.canvas = canvas; this.obj = this.createObject(canvas).initZoom(); this.setPosition(this.data.x, this.data.y); this.setRotation(this.data.rotation); this.setColor(this.data.color); this.setBorder(); this.createText(canvas); this.setClickEventMode(true); this.setDragEventMode(this); this.obj.node.id = this.createObjectId(); } /** * returns the object id */ vonline.Base.prototype.createObjectId = function() { return 'object_'+this.data.id; } /** * Set the position of the component * Note that this function sets the absolute position by the top-left corner of the bounding box * @param {integer} x * @param {integer} y */ vonline.Base.prototype.setPosition = function(x, y) { var bbox = this.obj.getBBox(), currentX = bbox.x, currentY = bbox.y; this.obj.translate(x - currentX, y - currentY); this.data.x = x; this.data.y = y; } /** * Translates the object by the given values * @param {integer} x * @param {integer} y */ vonline.Base.prototype.setTranslation = function(x, y) { this.obj.translate(x, y); this.data.x += x; this.data.y += y; $(this.obj.node).trigger('changed'); //$(this.obj.node).trigger('textchanged'); } /** * @param {float} x * @param {float} y * @param {number} origX * @param {number} origY */ vonline.Base.prototype.setScale = function(x, y, origX, origY) { throw 'vonline.Base.setScale must be implemented in subclass'; } /** * @param {int} deg Degree between 0...360° */ vonline.Base.prototype.setRotation = function(deg) { this.obj.rotate(deg, true); this.data.rotation = deg; $(this.obj.node).trigger('changed'); } /** * @param {string} color * @see http://raphaeljs.com/reference.html#colour */ vonline.Base.prototype.setColor = function(color) { this.obj.attr({fill: color}); this.data.color = color; } vonline.Base.prototype.setBorder = function() { this.obj.setAttr('stroke-width', 1); this.obj.setAttr('stroke', 'black'); } /** * creates a text within the object */ vonline.Base.prototype.createText = function() { var that = this; if (this.data.text) { this.text = this.canvas.getPaper().text(this.data.x, this.data.y, this.data.text).initZoom(); this.text.setAttr('font-size', 10); // redirect events to object $(this.text.node).click(function(event) { $(that.obj.node).trigger(event); }); $(this.text.node).dblclick(function(event) { $(that.obj.node).trigger(event); }); $(this.text.node).mousedown(function(event) { $(that.obj.node).trigger(event); }); $(this.text.node).mousemove(function(event) { // fix for connection-path event.target = that.obj.node; $(that.obj.node).trigger(event); }); // reposition on change this.adjustText(); $(this.obj.node).bind('changed', function() { that.adjustText(); }); $(vonline.events).bind('zoom', function() { that.adjustText(); }); $(this.obj.node).trigger('textchanged'); } } /** * @param {string} text */ vonline.Base.prototype.changeText = function(text) { this.data.text = text; if (this.text) { this.text.remove(); } this.createText(); } /** * sets the correct position of the inlined text */ vonline.Base.prototype.adjustText = function() { var bbox = this.obj.getBBox(); this.text.attr('x', bbox.x + bbox.width / 2); this.text.attr('y', bbox.y + bbox.height / 2); this.text.rotate(this.data.rotation, true); } /** * Returns the JSON representation of the object * @return {json} this.data */ vonline.Base.prototype.toJSON = function() { // clean up (remove default values) var json = {}; for (var property in this.data) { if (this.data[property] != vonline.Base.defaultData[property]) { json[property] = this.data[property]; } } return json; } /** * @param {boolean} active * @param {number} selected Number of selected objects */ vonline.Base.prototype.setSelection = function(active, selected) { if (active) { this.obj.attr('stroke', 'red'); this.selected = true; $(this.obj.node).trigger('select'); this.updateSelection(selected == 1); var that = this; } else { this.obj.attr('stroke', 'black'); this.selected = false; $(this.obj.node).trigger('unselect'); this.updateSelection(); } if (!this.selectionHandler) { this.selectionHandler = vonline.events.bind('selection_changed', function(event, number) { that.updateSelection(number == 1); }); } } /** * @param {boolean} controls Show controls */ vonline.Base.prototype.updateSelection = function(controls) { if (this.selected && controls) { this.setRotationMode(true); this.setConnectionMode(true); this.setAnnotationMode(true); this.setTextMode(true); } else { this.setRotationMode(false); this.setConnectionMode(false); this.setAnnotationMode(false); this.setTextMode(false); } } /** * @param {vonline.Base / array} objects * @param {function} ondrag (optional) is executed on drag (e.g. for updating interface) */ vonline.Base.prototype.setDragEventMode = function(objects, ondrag) { if (!$.isArray(objects)) { objects = [objects]; } var that = this; this.obj.attr('cursor', 'pointer'); if (this.dragEventHandler) { $(this.obj.node).unbind('mousedown', this.dragEventHandler); } /** * catches the mouse events */ this.dragEventHandler = function(event) { that.obj.attr('cursor', 'move'); $.each(objects, function(i, object) { object.setRotationMode(false); object.setConnectionMode(false); object.setAnnotationMode(false); object.setTextMode(false); }); // prevent selecting text event.preventDefault(); event.stopPropagation(); var origX = x = event.pageX, origY = y = event.pageY; var moveEvent = function(event) { // distinguish between click and drag-event, see setClickHandler that.wasDragging = true; that.setClickEventMode(false); event.preventDefault(); event.stopPropagation(); var deltaX = event.pageX - x, deltaY = event.pageY - y; if (event.altKey) { $.each(objects, function(i, object) { var bbox = object.obj.getBBox(); // adjust object object.obj.translate((Raphael.snapTo(vonline.GRIDSIZE, bbox.x) - bbox.x), (Raphael.snapTo(vonline.GRIDSIZE, bbox.y) - bbox.y)); }); event.pageX = Raphael.snapTo(vonline.GRIDSIZE, event.pageX); deltaX = Raphael.snapTo(vonline.GRIDSIZE, event.pageX - x); event.pageY = Raphael.snapTo(vonline.GRIDSIZE, event.pageY); deltaY = Raphael.snapTo(vonline.GRIDSIZE, event.pageY - y); } $.each(objects, function(i, object) { object.setTranslation(deltaX, deltaY); }); x = event.pageX; y = event.pageY; if (ondrag) { ondrag(); } } $(window).mousemove(moveEvent); $(window).one('mouseup', function(event) { event.preventDefault(); event.stopPropagation(); $(window).unbind('mousemove', moveEvent); if (that.wasDragging) { var translateX = (x - origX), translateY = (y - origY); vonline.events.trigger('commandexec', new vonline.TranslateCommand(objects, translateX, translateY)); that.wasDragging = false; window.setTimeout(function() { that.setClickEventMode(true); }, 0); } that.obj.attr('cursor', 'pointer'); $.each(objects, function(i, object) { if (object.selected) { object.updateSelection(objects.length == 1); $(object.obj.node).trigger('changed'); } }); }); }; $(this.obj.node).mousedown(this.dragEventHandler); } /** * @param {boolean} active */ vonline.Base.prototype.setClickEventMode = function(active) { var that = this; if (active) { this.clickEventHandler = function(event) { event.preventDefault(); event.stopPropagation(); if (event.shiftKey) { vonline.document.canvas.selection.toggle(that); } else { vonline.document.canvas.selection.clear(); vonline.document.canvas.selection.add(that); } } $(this.obj.node).click(this.clickEventHandler); } else { $(this.obj.node).unbind('click', this.clickEventHandler); } } /** * @param {boolean} active */ vonline.Base.prototype.setRotationMode = function(active) { var bbox = this.obj.getBBox(), radius = Math.sqrt(Math.pow(bbox.width / 2, 2) + Math.pow(bbox.height / 2, 2)) + 20, centerX = bbox.x + bbox.width / 2, centerY = bbox.y + bbox.height / 2, that = this; if (this.rotationCircle || this.rotationHandle) { $(this.obj.node).unbind('changed', this.updateRotationHandles); if (this.rotationCircle) { this.rotationCircle.remove(); this.rotationCircle = null; } if (this.rotationHandle) { this.rotationHandle.remove(); this.rotationHandle = null; } } if (active) { /** * updates rotation-circle and rotation-handle on object changes */ this.updateRotationHandles = function() { var newBBox = that.obj.getBBox(), newRadius = Math.sqrt(Math.pow(newBBox.width / 2, 2) + Math.pow(newBBox.height / 2, 2)) + 20, newCenterX = newBBox.x + newBBox.width / 2, newCenterY = newBBox.y + newBBox.height / 2; if (that.rotationCircle) { if (radius != newRadius) { that.rotationCircle.scale(newRadius/radius, newRadius/radius); that.rotationCircle.resetScale(); that.rotationCircle.translate(newCenterX - centerX, newCenterY - centerY); that.rotationHandle.rotate(0, centerX, centerY); that.rotationHandle.translate(newCenterX - centerX, newCenterY - newRadius - (centerY - radius)); that.rotationHandle.rotate(that.data.rotation, newCenterX, newCenterY); radius = newRadius; centerX = newCenterX; centerY = newCenterY; } else if (centerX != newCenterX || centerY != newCenterY) { that.rotationCircle.translate(newCenterX - centerX, newCenterY - centerY); that.rotationHandle.translate(newCenterX - centerX, newCenterY - newRadius - (centerY - radius)); centerX = newCenterX; centerY = newCenterY; } } } $(this.obj.node).bind('changed', this.updateRotationHandles); this.rotationCircle = this.canvas.getPaper().circle(centerX, centerY, radius).attr('stroke', 'orange').attr('stroke-width', '1'); this.rotationHandle = this.canvas.getPaper().circle(centerX, centerY - radius, 5.5).attr('stroke', 'none').attr('fill', 'orange').attr('cursor', 'pointer').rotate(this.data.rotation, centerX, centerY); this.rotationInfo = this.canvas.getPaper().text(0, 0, "").attr('font-size', 16).attr('font-weight', 'bold').attr('fill', 'orangered').hide(); $(this.rotationHandle.node).mousedown(function(event) { event.stopPropagation(); // disable/hide everything, but the rotation controls that.setConnectionMode(false); that.setAnnotationMode(false); that.setTextMode(false); that.canvas.selection.setSelectionMode(false); that.rotationInfo.show(); that.rotationCircle.attr('stroke-width', '2'); var deg = that.data.rotation, origDeg = that.data.rotation; function rotationEvent(event) { event = that.canvas.normalizeEvent(event); deg = Raphael.angle(centerX, centerY, event.offsetX, event.offsetY); deg -= 90; deg = deg < 0 ? 360 + deg : deg; if (!event.altKey) { deg = Raphael.snapTo(45, deg, 20); } if (deg == 360) { deg = 0; } that.rotationHandle.rotate(deg, centerX, centerY); that.obj.rotate(deg, true); that.rotationHandle.attr({fill: 'yellow'}); var angle = -deg * Math.PI/180; var infoPos = { x: -(radius+25)*Math.sin(angle), y: -(radius+25)*Math.cos(angle) }; that.rotationInfo.attr({text: Math.round(deg)+'°', x: centerX+infoPos.x, y: centerY+infoPos.y}); } $(window).mousemove(rotationEvent); $(window).one('mouseup', function() { $(window).unbind('mousemove', rotationEvent); if (deg != origDeg) { var command = new vonline.RotateCommand(that, deg); command.execute(); vonline.events.trigger('commandexec', command); } // enable/show everything again that.setConnectionMode(true); that.setAnnotationMode(true); that.setTextMode(true); that.canvas.selection.setSelectionMode(true); that.rotationHandle.attr({fill: 'orange'}); that.rotationInfo.hide(); that.rotationCircle.attr('stroke-width', '1'); }); }) .mouseover(function(event) { that.rotationHandle.attr({fill: 'yellow'}); }) .mouseout(function(event) { that.rotationHandle.attr({fill: 'orange'}); }); } } /** * show connection handles */ vonline.Base.prototype.setConnectionMode = function(active) { var that = this; if (this.connectionHandle) { $(this.obj.node).unbind('changed', this.updateConnectionHandles); this.connectionHandle.remove(); this.connectionHandle = null; } if (active) { var bbox = this.obj.getBBox(); this.updateConnectionHandles = function() { if (that.connectionHandle) { var newBBox = that.obj.getBBox(); that.connectionHandle.translate(newBBox.x - bbox.x + newBBox.width - bbox.width, newBBox.y - bbox.y + newBBox.height - bbox.height); that.connectionHandle.rotate(that.data.rotation, newBBox.x + newBBox.width/2, newBBox.y + newBBox.height/2); bbox = newBBox; } } $(this.obj.node).bind('changed', this.updateConnectionHandles); // create connection handle this.connectionHandle = this.canvas.getPaper().image('images/canvas/connect.png', 0, 0, 22, 22).attr('cursor', 'pointer'); var handleBBox = this.connectionHandle.getBBox(); this.connectionHandle.translate(bbox.x + bbox.width + 20, bbox.y + 38); this.connectionHandle.rotate(this.data.rotation, bbox.x + bbox.width/2, bbox.y + bbox.height/2); // handles events if(this.connectionPath == null) { this.connectionPath = this.canvas.getPaper().path('M0,0').toBack(); } this.connectionPath.attr('path', 'M0,0').hide(); var targetObj = null, targetStrokeColor = null, targetStrokeWidth = null; var restoreTargetObj = function() { if(targetObj) { targetObj.obj.attr('stroke', (targetStrokeColor ? targetStrokeColor : '#000')); targetObj.obj.attr('stroke-width', (targetStrokeWidth ? targetStrokeWidth : '1')); targetObj = null, targetStrokeColor = null, targetStrokeWidth = null; } } var connectionMoveEvent = function(event) { event.preventDefault(); event.stopPropagation(); event = that.canvas.normalizeEvent(event); that.connectionPath.show(); if ($(event.target).is('tspan')) { // fix for wrong connection when mousepointer over test return; } // highlight target object if (event.target.id && event.target.id.substr(0, 7) == 'object_' && that.obj.node.id != event.target.id) { var newTargetObj = that.canvas.getObjectById(event.target.id.replace(/object_/, '')); if (newTargetObj != targetObj) { // if an old target object exists, restore old values restoreTargetObj(); targetObj = newTargetObj; targetStrokeColor = targetObj.obj.attr('stroke'); targetStrokeWidth = targetObj.obj.attr('stroke-width'); } targetObj.obj.attr('stroke', 'red').attr('stroke-width', '2'); // update path var targetBBox = targetObj.obj.getBBox(); that.connectionPath.attr('path', vonline.Connection.computePath(bbox.x+bbox.width/2, bbox.y+bbox.height/2, targetBBox.x+targetBBox.width/2, targetBBox.y+targetBBox.height/2)); } else { restoreTargetObj(); // update path that.connectionPath.attr('path', vonline.Connection.computePath(bbox.x+bbox.width/2, bbox.y+bbox.height/2, event.offsetX, event.offsetY)); } } $(this.connectionHandle.node).mousedown(function(event) { event.stopPropagation(); $(window).bind('mousemove', connectionMoveEvent); }); $(this.connectionHandle.node).click(function(event) { event.stopPropagation(); that.canvas.selection.setConnectionMode(true); that.canvas.container.one('click', function(event) { $(window).unbind('mousemove', connectionMoveEvent); that.connectionPath.hide(); restoreTargetObj(); // if a target object exists, restore old values that.canvas.selection.setConnectionMode(false); // abort if user clicks on canvas or the same object if (event.target.id && event.target.id.substr(0, 7) == 'object_' && that.obj.node.id != event.target.id) { // see vonline.Document vonline.events.trigger('drop', {type:'connection', connect: [that.obj.node.id.replace(/object_/, ''), event.target.id.replace(/object_/, '')]}); } }); }); } } /** * show annotation handles */ vonline.Base.prototype.setAnnotationMode = function(active) { var that = this if(this.annotationHandle) { $(this.obj.node).unbind('changed', this.updateAnnotationHandle); this.annotationHandle.remove(); this.annotationHandle = null; } if (active) { var bbox = this.obj.getBBox(); this.updateAnnotationHandle = function() { if (that.annotationHandle) { var newBBox = that.obj.getBBox(); that.annotationHandle.translate(newBBox.x - bbox.x + newBBox.width - bbox.width, newBBox.y - bbox.y + newBBox.height - bbox.height); that.annotationHandle.rotate(that.data.rotation, newBBox.x + newBBox.width/2, newBBox.y + newBBox.height/2); bbox = newBBox; } } $(this.obj.node).bind('changed', this.updateAnnotationHandle); // create connection handle this.annotationHandle = this.canvas.getPaper().image('images/canvas/annotate.png', 0, 0, 22, 22).attr('cursor', 'pointer'); var handleBBox = this.annotationHandle.getBBox(); this.annotationHandle.translate(bbox.x + bbox.width + 20, bbox.y - 10); this.annotationHandle.rotate(this.data.rotation, bbox.x + bbox.width/2, bbox.y + bbox.height/2); // handles events $(this.annotationHandle.node).mousedown(function(event) { event.stopPropagation(); }); $(this.annotationHandle.node).click(function(event) { event.stopPropagation(); new vonline.InputDialog({text: 'Enter an annotation:', confirm: function(annotation) { if (annotation != '') { // see vonline.Document vonline.events.trigger('drop', {type:'annotation', text: annotation, connect: [that.data.id], x: that.data.width + 20, y: 0}); } }}); }); } } /** * enables/disables the object text show/hide event */ vonline.Base.prototype.setTextMode = function(active) { var that = this if (this.inlineTextHandle) { $(this.obj.node).unbind('changed', this.updateInlineTextHandle); this.inlineTextHandle.remove(); this.inlineTextHandle = null; } if (active) { var bbox = this.obj.getBBox(); this.updateInlineTextHandle = function() { if (that.inlineTextHandle) { var newBBox = that.obj.getBBox(); that.inlineTextHandle.translate(newBBox.x - bbox.x + newBBox.width - bbox.width, newBBox.y - bbox.y + newBBox.height - bbox.height); that.inlineTextHandle.rotate(that.data.rotation, newBBox.x + newBBox.width/2, newBBox.y + newBBox.height/2); bbox = newBBox; } } $(this.obj.node).bind('changed', this.updateInlineTextHandle); // create connection handle this.inlineTextHandle = this.canvas.getPaper().image('images/canvas/inline_text.png', 0, 0, 22, 22).attr('cursor', 'pointer'); var handleBBox = this.inlineTextHandle.getBBox(); this.inlineTextHandle.translate(bbox.x + bbox.width + 20, bbox.y + 14); this.inlineTextHandle.rotate(this.data.rotation, bbox.x + bbox.width/2, bbox.y + bbox.height/2); // handles events $(this.inlineTextHandle.node).mousedown(function(event) { event.stopPropagation(); }); $(this.inlineTextHandle.node).click(function(event) { event.stopPropagation(); new vonline.InputDialog({text: 'Enter a new inline text:', confirm: function(inlinetext) { var command = new vonline.TextChangeCommand(that, inlinetext); command.execute(); vonline.events.trigger('commandexec', command); }}); }); } } /** * Checks if bounding contains the current object * @param {object} bounding Specified by (x, y, width, height) */ vonline.Base.prototype.fitsIn = function(bounding) { var bbox = this.obj.getBBox(); return (bbox.x >= bounding.x && bbox.y >= bounding.y && bbox.x + bbox.width <= bounding.x + bounding.width && bbox.y + bbox.height <= bounding.y + bounding.height); } /** * tests if an object with given id is connected to the current object * @param {vonline.Base} obj */ vonline.Base.prototype.isConnectedTo = function(obj) { for (var i = 0, len = this.data.connect.length; i < len; i++) { if (this.data.connect[i] == obj.getId()) { return true; } } return false; }
var Twit = require('twit') var T = new Twit({ consumer_key: 'uyduDUdKiGdvorxesaewyAbQa', consumer_secret: 'eGtFUBOamliPnvDRSXujpODprAjBHMRrmmiBwrAv0AJNHk9jTr', access_token: '19531723-ljijUu8Bxld08aXH7zUzM3yt6K6l40cmFo0VnnPv3', access_token_secret: 'VIFz8n4CCBdnYKMkCumsVjuKe8PDTCpJRRsi6bwxZQRJo' }) // post 'ebook test tweet' T.post('statuses/update', { status: 'ebook test tweet' }, function(err, data, response) { console.log("data: " + data) console.log("err: " + err) console.log("response: " + response) } )
// @flow import commitAnalyzer from '@semantic-release/commit-analyzer'; import composeExternal from '../../external'; import composeCommon from '../../common'; import composeCommits from '../../commits'; import composeAnalyzeCommits from './analyzeCommits'; export default () => { const external = composeExternal(); let deps = { userConfig: {}, external, }; const common = composeCommon(deps); deps.userConfig = common.config.getUserConfig(); deps = { ...deps, common, }; const commits = composeCommits(deps); deps = { ...deps, commits, }; const analyzeCommits = composeAnalyzeCommits( deps.common.log, deps.commits.filterValidCommits, commitAnalyzer, ); return analyzeCommits; };
/* eslint-disable react/prop-types */ import React, { useRef } from 'react'; function Product(props) { const ref = useRef(); const mouseEnter = () => { ref.current.classList.add('hovered'); }; const mouseOut = () => { ref.current.classList.remove('hovered'); }; return ( <div ref={ref} onMouseEnter={mouseEnter} onMouseLeave={mouseOut} className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${ props.outOfStock ? 'prd-outstock' : '' }`} > <div className="prd-inside"> <div className="prd-img-area"> <a href="products/" className="prd-img image-hover-scale image-container" style={{ paddingBottom: '128.48%' }} > <img src={props.images[props.primary_image]} alt={props.name} className="js-prd-img fade-up ls-is-cached lazyloaded" /> <div className="prd-big-squared-labels"></div> </a> <div className="prd-circle-labels"> <a href="/" className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0" title="Add To Wishlist" > <i className="icon-heart-stroke"></i> </a> <a href="/" className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0" title="Remove From Wishlist" > <i className="icon-heart-hover"></i> </a> <a href="/" className="circle-label-qview js-prd-quickview prd-hide-mobile" data-src="ajax/ajax-quickview.html" > <i className="icon-eye"></i> <span>QUICK VIEW</span> </a> {props.colors.length ? ( <div className="colorswatch-label colorswatch-label--variants js-prd-colorswatch"> <i className="icon-palette"> <span className="path1"></span> <span className="path2"></span> <span className="path3"></span> <span className="path4"></span> <span className="path5"></span> <span className="path6"></span> <span className="path7"></span> <span className="path8"></span> <span className="path9"></span> <span className="path10"></span> </i> <ul> {props.colors.map((c) => ( <li key={props.id + c} data-image="images/skins/fashion/products/product-02-1.webp" > <a className="js-color-toggle" data-toggle="tooltip" data-placement="left" title={c} > <img src={`images/colorswatch/color-${c}.webp`} alt="" /> </a> </li> ))} </ul> </div> ) : null} </div> <ul className="list-options color-swatch"> {props.images.map((img, i) => ( <li key={'sub' + props.id + i} className={i === parseInt(props.primary_image) ? 'active' : ''} > <a href="/" className="js-color-toggle" data-toggle="tooltip" data-placement="right" title="" data-original-title="Color Name" > <img src={img} className="fade-up ls-is-cached lazyloaded" alt="Image Name" /> </a> </li> ))} </ul> </div> <div className="prd-info"> <div className="prd-info-wrap"> <div className="prd-info-top"></div> <div className="prd-rating justify-content-center"> <i className="icon-star-fill fill"></i> <i className="icon-star-fill fill"></i> <i className="icon-star-fill fill"></i> <i className="icon-star-fill"></i> <i className="icon-star-fill"></i> </div> <div className="prd-tag"> <a href="/">{props.brand}</a> </div> <h2 className="prd-title"> <a href="product.html">{props.name}</a> </h2> <div className="prd-description"> Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante sed lacinia. </div> <div className="prd-action"> <form action="#"> <button className="btn js-prd-addtocart" data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}' > Add To Cart </button> </form> </div> </div> <div className="prd-hovers"> <div className="prd-circle-labels"> <div> <a href="/" className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0" title="Add To Wishlist" > <i className="icon-heart-stroke"></i> </a> <a href="/" className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0" title="Remove From Wishlist" > <i className="icon-heart-hover"></i> </a> </div> <div className="prd-hide-mobile"> <a href="/" className="circle-label-qview js-prd-quickview" data-src="ajax/ajax-quickview.html" > <i className="icon-eye"></i> <span>QUICK VIEW</span> </a> </div> </div> <div className="prd-price"> <div className="price-new">$ {props.price.usd}</div> </div> <div className="prd-action"> <div className="prd-action-left"> <form action="#"> <button className="btn js-prd-addtocart" data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}' > Add To Cart </button> </form> </div> </div> </div> </div> </div> </div> ); } export default Product; // For multiple refs // const elementrefs = useRef([]); // const handle = i => { // elementrefs.current[i].classList.add('otherclass'); // }; // <div ref={(el) => (elementrefs.current[0] = el)} onClick={() => handle(0)} className="myclass"></div>;
import React from 'react' import './Footer.css' import { UNIMEMO_LOGO } from '../../../constants' const Footer = () => { return ( <div className="footer"> <div>Powered by UniMemo</div> <a href="https://github.com/xemexpress/UniMemo" target="_blank" rel="noopener noreferrer"> <img className="unimemo-logo" src={UNIMEMO_LOGO} height="14px" alt="UniMemo" /> </a> <div className="unimemo-manifesto"> 我們認爲,每個人都能夠發展出他們擅長並熱愛的事業。<br/> 人唯有在這狀態,才能自覺、勇敢地克服問題,成就卓越。<br/> 社會亦唯有隨着這狀態的普及,才能免於政治上的龐大花費和無扭轉意義的拖延。<br/> 因此,爲了人類整體福祉,社會應創造條件讓更多人自我覺醒。<br/> <br/> 「自我覺醒」需要時間和資源。而當前社會資本當道,人才和科技亦漸趨普及。<br/> 作爲社會一員,我們必須把握優勢——<br/> 集衆人之智,建立「時、地、人資訊流通」的環境;<br/> 合一己之順便,創造額外可利用的時間和資源。<br/> <br/> 爲社會的美好將來,我們願意付出我們的順便、能力和資源,貫徹使命,實現目標。 </div> </div> ) } export default Footer
/** * CREATE NEW SYMBOL TO POLYLINE DECORATOR */ L.Symbol.LongArrowHead = L.Class.extend({ isZoomDependant: true, options: { polygon: true, pixelSize: 10, headAngle: 60, pathOptions: { stroke: false, weight: 2 } }, initialize: function (options) { L.Util.setOptions(this, options); this.options.pathOptions.clickable = false; }, buildSymbol: function(dirPoint, latLngs, map, index, total) { var opts = this.options; var path; if(opts.polygon) { path = new L.Polygon(this._buildArrowPath(dirPoint, map), opts.pathOptions); } else { path = new L.Polyline(this._buildArrowPath(dirPoint, map), opts.pathOptions); } return path; }, _buildArrowPath: function (dirPoint, map) { var d2r = Math.PI / 180; var tipPoint = map.project(dirPoint.latLng); var direction = (-(dirPoint.heading - 90)) * d2r; var radianArrowAngle = this.options.headAngle / 2 * d2r; var headAngle1 = direction + radianArrowAngle, headAngle2 = direction - radianArrowAngle; headAngle3 = direction + 0; headAngle4 = direction - 0; headAngle5 = direction - radianArrowAngle; var arrowHead1 = new L.Point( tipPoint.x - this.options.pixelSize * Math.cos(headAngle1), tipPoint.y + this.options.pixelSize * Math.sin(headAngle1)), arrowHead2 = new L.Point( tipPoint.x - this.options.pixelSize * Math.cos(headAngle2), tipPoint.y + this.options.pixelSize * Math.sin(headAngle2)), arrowBack1 = new L.Point( arrowHead1.x - (this.options.pixelSize*1.5) * Math.cos(headAngle3), arrowHead1.y + (this.options.pixelSize*1.5) * Math.sin(headAngle3)), arrowBack2 = new L.Point( arrowHead2.x - (this.options.pixelSize * 1.5) * Math.cos(headAngle4), arrowHead2.y + (this.options.pixelSize * 1.5) * Math.sin(headAngle4)), arrowBackCenter = new L.Point( arrowBack2.x + this.options.pixelSize * Math.cos(headAngle5), arrowBack2.y - this.options.pixelSize * Math.sin(headAngle5)); return [ map.unproject(arrowBack1), map.unproject(arrowHead1), dirPoint.latLng, map.unproject(arrowHead2), map.unproject(arrowBack2), map.unproject(arrowBackCenter), ]; } }); L.Symbol.longArrowHead = function (options) { return new L.Symbol.LongArrowHead(options); };
export const CATEGORY_TYPE = "category"; export const SUBCATEGORY_TYPE = "subcategory"; export const SEARCH_PRODUCT_TYPE = "searchProductType";
// @ts-check export default class InputTag { constructor(type, value) { this.type = type; this.value = value; } render() { return `<input type="${this.type}" value="${this.value}">`; } toString() { return this.render(); } }
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' /* 两种方法引入组件 一、先引入home组件,再在routes里面注册 二、about是在component里面使用箭头函数引入about组件 区别:第一个是直接引入,不管有没有访问都把组件引进来了 第二个是只有你访问的的时候才加载组件 好处:项目比较大,页面比较多,vue是单页面应用,一次性加载这么多内容, 加载会很慢,体验不好,所以在项目中使用第二种方法比较好 */ Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/get', name: 'get', component: () => import('../views/get.vue') }, { path: '/concurrence', name: 'concurrence', component: () => import('../views/concurrence.vue') }, { path: '/contactlist', name: '联系人了列表', component: () => import('../views/contactlist.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
jQuery(function($){ /** 真实姓名验证 **/ $('#name').blur(function(){ var reg = /^[\u4e00-\u9fa5]+$/i; //验证只能输入汉字的正则表达式 var _name = $(this).val(); var d = "<h5>2-5个中文字符</h5>"; var c = "icon_error"; if($.trim(_name)==""){ d = '<h5>真实姓名不能为空</h5>'; }else if(!reg.test(_name)){ d = '<h5>请输入中文名字</h5>'; }else if(_name.length<2 || _name.length>5){ d = '<h5>2-5个中文字符</h5>'; }else{ c="icon_ok"; d=""; } $('#nameTip').html('<span class="'+c+'"></span>'+d).show(); }); /** 所在学校验证 **/ $('#school').blur(function(){ var _school = $(this).val(); var d = "<h5>请输入所在学校名称</h5>"; var c = "icon_error"; if($.trim(_school)!=""){ if(_school.length<4 || _school.length>50){ d = '<h5>学校名称不正确</h5>'; }else{ c="icon_ok"; d=""; } } $('#schoolTip').html('<span class="'+c+'"></span>'+d).show(); }); /** 验证QQ号码 **/ $('#qq').blur(function(){ var _qq = $(this).val(); var d = "<h5>请填写QQ号码,找回密码需用的QQ邮箱。</h5>"; var c = "icon_error"; if($.trim(_qq)!=""){ if(_qq.length<5 || _qq.length>12 || isNaN(_qq) ){ d = '<h5>QQ号码不正确</h5>'; }else{ c="icon_ok"; d=""; } } $('#qqTip').html('<span class="'+c+'"></span>'+d).show(); }); /** 家庭地址验证 **/ $('#address').blur(function(){ var _address = $(this).val(); var d = '<h5 >请准确填写,保证能准时收到学习资料</h5>'; var c = "icon_error"; if($.trim(_address)!="" && _address.length>8){ c="icon_ok"; d=""; } $('#addressTip').html('<span class="'+c+'"></span>'+d).show; }); /** 家庭电话验证 **/ $('#telephone').blur(function(){ var _input = $(this).val(); var d = '<h5 >请输入家庭联系电话,区号和电话号码连着填写</h5>'; var c = "icon_error"; if($.trim(_input)!="" && _input.length>7 && !isNaN(_input)){ c="icon_ok"; d=""; } $('#telephoneTip').html('<span class="'+c+'"></span>'+d).show; }); /** 家庭电话验证 **/ $('#mobile').blur(function(){ var _input = $(this).val(); var d = '<h5 >请输入手机号码</h5>'; var c = "icon_error"; if($.trim(_input)!=""){ if(/^13\d{9}$/g.test(_input) || (/^15[0-35-9]\d{8}$/g.test(_input)) || (/^18[05-9]\d{8}$/g.test(_input))){ c="icon_ok"; d=""; } } $('#mobileTip').html('<span class="'+c+'"></span>'+d).show; }); /** 邮政编码验证 **/ $('#postcode').blur(function(){ var _input = $(this).val(); var d = '<h5 >请准确填写,保证能准时收到学习资料</h5>'; var c = "icon_error"; var reg=/^\d{6}$/; if($.trim(_input)!="" && reg.test(_input)){ c="icon_ok"; d=""; } $('#postcodeTip').html('<span class="'+c+'"></span>'+d).show; }); /** 注册提交 **/ $('#g_btn').click(function(){ $('#name').blur(); $('#school').blur(); $('#qq').blur(); $('#address').blur(); $('#telephone').blur(); $('#mobile').blur(); $('#postcode').blur(); var err = $(".icon_error"); if(err.length==0){//不存在错误图标 $("#regform").submit(); }else{ alert(err.length+"个选项填写错误!"); } }); this.init = function(){ $('#nameTip').html('<h5>2-5个中文字符</h5>'); $('#schoolTip').html('<h5>请输入所在学校名称</h5>'); $('#qqTip').html('<h5>请填写QQ号码,找回密码需用的QQ邮箱。</h5>'); $('#addressTip').html('<h5 >请准确填写,保证能准时收到学习资料</h5>'); $('#telephoneTip').html('<h5 >请输入家庭联系电话</h5>'); $('#mobileTip').html('<h5 >请输入手机号码</h5>'); $('#postcodeTip').html('<h5 >请准确填写,保证能准时收到学习资料</h5>'); } this.init(); });
class Vertex { static rad(){return 0.017453292519943295};//Math.PI / 180}; constructor(x, y, z) { if (typeof (y) === 'undefined') { if (typeof (x.x) === 'undefined') { // testib, et pole punktiga notatsioon -> pole objekt this.x = x[0],//[0], this.y = x[1],//[1], this.z = x[2];//[2]; } else { this.x = x.x,//[0], this.y = x.y,//[1], this.z = x.z;//[2]; } } else { this.x = x, this.y = y, this.z = z }; } static custom(P) { if (typeof(P.x) === 'undefined') { return {x:P[0], y:P[1], z:P[2]}; } else { return P; } } static add(v1, v2) { let V1 = Vertex.custom(v1), V2 = Vertex.custom(v2); //return new Vertex(V1.x + V2.x, V1.y + V2.y, V1.z + V2.z); return {x: V1.x + V2.x, y: V1.y + V2.y, z: V1.z + V2.z}; } static divide(V1, V2) { let A = Vertex.custom(V1), B = Vertex.custom(V2); return {x: A.x / B.x, y: A.y / B.y, z: A.z / B.z}; } static vector(beginP,endP) { let a = Vertex.custom(beginP), b = Vertex.custom(endP); return {x: b.x - a.x ,y: b.y - a.y ,z: b.z - a.z}; } static translateEnd(V) { /* let B = []; let v = new Vertex(V[V.length-1].x, V[V.length-1].y,V[V.length-1].z); let transX = v.x; let transY = v.y; let transZ = v.z; for (i = 0; i < V.length - 1; i++){ B[i] = new Vertex(V[i].x - transX, V[i].y - transY, V[i].z - transZ); } B[V.length -1] = new Vertex(0,0,0); return B; */ } static cAngle(p1, p2) // static tähendab, saab kõikide objektide pea. statickul pole individuaalset parameetrit { let v = Vertex.scale(0.5,Vertex.vector(p1, p2)); let ll = v.x * v.x + v.y * v.y + v.z * v.z; return 2 * Math.atan(Math.sqrt(ll / 3)); } static scale(a, p) { let P = Vertex.custom(p); return new Vertex(P.x * a, P.y * a, P.z * a); } static midpoint(PolyV) // leiab polygonide keskpunkti { let x = PolyV[0].x, y = PolyV[0].y, z = PolyV[0].z; let i; for(i = 1; i < PolyV.length; i++) { x += PolyV[i].x, y += PolyV[i].y, z += PolyV[i].z; } //return {x : x / i, y : y / i, z : z / i}; return new Vertex(x / i, y / i, z / i); } static shift2(Parr, Pref) { let convey = []; for(let i = 0; i < Parr.length; i++) { convey[i] = {x : Parr[i].x - Pref.x, y : Parr[i].y - Pref.y, z : Parr[i].z - Pref.z}; } return convey; } static monoscale(Arr, x) { let convey = []; for(let i = 0; i < Arr.length; i++) { convey[i] = {x : Arr[i].x * x, y : Arr[i].y * x, z : Arr[i].z * x}; } return convey; } monoscale(x) { this.x = this.x * x; this.y = this.y * x; this.z = this.z * x; } static dist(A, B) { let V; if(typeof(B) === 'undefined') { V = Vertex.custom(A); } else { V = Vertex.vector(A, B); } return Math.sqrt(V.x * V.x + V.y * V.y + V.z * V.z); } static normal(v1,v2)// Kahele vektorile normaalvektori leidmine { //third point is 0,0,0 - both vectors there let a = v1.y * v2.z - v1.z * v2.y; let b = -(v1.x * v2.z - v1.z * v2.x); let c = v1.x * v2.y - v1.y * v2.x; return {x:a,y:b,z:c}; } static plane(p1, p2, p3)// PLANE parameters by 3 points { // tagastab normaalvektori – kolm punkti sisendiks let V1 = Vertex.vector(p1, p2);//{x:p2.x - p1.x, y:p2.y - p1.y, z:p2.z - p1.z}; let V2 = Vertex.vector(p1, p3);//{x:p3.x - p1.x, y:p3.y - p1.y, z:p3.z - p1.z}; let N = Vertex.normal(V1, V2); return N; } static tangent(N, p1, l1) { let num = N.x * p1.x + N.y * p1.y + N.z * p1.z; let den = N.x * l1.x + N.y * l1.y + N.z * l1.z; let t = num / den; return t; } static planeInt(Plane, A, B)//INTERSECTION line parametric form { let beam = Vertex.vector(A,B); let num = Plane.x * A.x + Plane.y * A.y + Plane.z * A.z; let den = Plane.x * beam.x + Plane.y * beam.y + Plane.z * beam.z; let t = num / (-den); let point = [A.x + t * beam.x, A.y + t * beam.y, A.z + t * beam.z]; return point; } set(x, y, z) { this.x = x, this.y = y, this.z = z; } shift(P) // punkt mille suhtes kujundit nihutada { return new Vertex(this.x - P.x, this.y - P.y, this.z - P.z); } pan(x, y, z) { this.set(this.x + x, this.y + y, this.z + z); } add(V) // annad ette vektori objektina { x:, y:, z: }, pmst sama mis pan, kuid saab vertex objektina sisestada { this.set(this.x + V.x, this.y + V.y, this.z + V.z); } subtract(V) { this.set(this.x - V.x, this.y - V.y, this.z - V.z); } scalar(x, y, z) // korrutab läbi { return new Vertex( x * this.x, y * this.y, z * this.z ); } /* scalar(v){ this.set(this.x * v, this.y * v, this.z * v); }*/ rotX(theta) { var x = this.x; var y = this.y; var z = this.z; return new Vertex( x, Math.cos(theta) * y - Math.sin(theta) * z, Math.sin(theta) * y + Math.cos(theta) * z ); } rotY(theta) { var x = this.x; var y = this.y; var z = this.z; return new Vertex( Math.cos(theta) * x - Math.sin(theta) * z, y, Math.sin(theta) * x + Math.cos(theta) * z ); } rotZ(theta){ var x = this.x; var y = this.y; var z = this.z; return new Vertex( Math.cos(theta) * x - Math.sin(theta) * y, Math.sin(theta) * x + Math.cos(theta) * y, z ); } project(depth){ // input for z coordinate return new Verticle(this.x/depth,this.y/depth); } // minu lisatud shiftPlus(P) // punkt mille suhtes kujundit { return new Vertex(this.x + P.x, this.y + P.y, this.z + P.z); } }
var moment = require("moment"); var axios = require("axios"); var punycode = require("punycode"); window.onload = function() { var hostArr = window.location.host.split("."); const host = punycode.toUnicode(window.location.host); if (host.length > 1) document.title = host; var when = "2017-02-14T13:57:07.631Z"; var computeTime = function() { var formated = "YYYY-MM-DD HH:mm:ss"; var startTime = moment(new Date(when)).format(formated); var now = moment().format(formated); var ms = moment(now).diff(moment(startTime)); var duration = moment.duration(ms); // var y = duration.years(); var d = Math.floor(duration.asDays()); var h = duration.hours(); var m = duration.minutes(); var s = duration.seconds(); // document.querySelector(".year").innerText = y; document.querySelector(".day").innerText = d < 10 ? `0${d}` : d; document.querySelector(".hour").innerText = h < 10 ? `0${h}` : h; document.querySelector(".minute").innerText = m < 10 ? `0${m}` : m; document.querySelector(".second").innerText = s < 10 ? `0${s}` : s; requestAnimationFrame(computeTime); }; var catchError = function() { document.querySelector(".prompt").style.display = "block"; }; var onSuccess = function(res) { when = res.data.when; document.querySelector(".prompt").style.display = "none"; document.querySelector(".content").style.display = "block"; requestAnimationFrame(computeTime); var manifesto = document.querySelector(".manifesto"); manifesto.style.display = "block"; manifesto.innerText = res.data.manifesto; if (res.data.from) { document.querySelector(".info span").innerText = res.data.from; } }; axios .get(`/ido/${hostArr[0]}.json`) .then(function(res) { if (!res || res.status < 200 || res.status >= 300 || !res.data) { throw "error"; } onSuccess(res); }) .catch(catchError); // onSuccess({ data: { when: "2018-1-1" } }); };
const Sequelize = require('sequelize'); const databaseManager = require('../user_modules/database-manager'); const attributeEnumMap = require('./maps/attribute-enum.map'); const AttributeEnumValue = require('./attribute-enum-value.model'); module.exports = {}; const AttributeEnum = databaseManager.context.define('attributeEnum', { Id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, Name: { unique: true, allowNull: false, type: Sequelize.STRING }, Description: { allowNull: false, type: Sequelize.STRING }, Question: { allowNull: false, type: Sequelize.STRING }, ForType: { allowNull: false, type: Sequelize.ENUM("STUDENT", "HOST", "BOTH") }, MaxSelect: { allowNull: true, type: Sequelize.INTEGER }, MinSelect: { allowNull: true, type: Sequelize.INTEGER }, SelectType: { allowNull: false, type: Sequelize.ENUM("DROPDOWN", "RADIO") }, Options: { allowNull: false, type: Sequelize.TEXT }, Required: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true } },{ instanceMethods: { getMap: function() { return AttributeEnum.getMap(); } }, }); AttributeEnum.Values = AttributeEnum.hasMany(AttributeEnumValue, { foreignKey: { name: 'AttributeId', allowNull: false }, as: 'Values' }); /** * Figures out how to serialize and deserialize this model * @returns {Object} */ AttributeEnum.getMap = function () { return attributeEnumMap; }; module.exports = AttributeEnum;
(function($) { /*--------------------------------------------------- / Style Switcher ---------------------------------------------------*/ 'use strict'; $(function() { var isTouchDevice = 'ontouchstart' in document.documentElement; //set 'touch' for touch devices if (isTouchDevice) { styleSwitcher('touchend'); } else { styleSwitcher('mouseup'); } function styleSwitcher(action) { /* Global variables */ var active = 'active', body = $('body'), /* Preloader */ pageWrap = $('#page-wrap'), preloader = $('#preloader'), spinner = $('.spinner'), /* Navbar */ navbarID = $('#navbarSettings'), navbarSpace = $('#navbarSpaceBottom'), navbarIsFixed = navbarID.hasClass('navbar-fixed-top'), navbarTrn = $('.navbar-trn'), navbar = $('.navbar'), nav = document.getElementById('nav'), topOffset, navToggle = $('.navbar-toggle'), navOpen = 'navbar-open', /* Style switcher */ sBtn = $('.switcher-icon'), sBody = $('.style-switcher'), icon = 'fa-gears', //set a name of class from all Font Awesome package /* Owl Carousel reinit */ owlCarousel = 'owlCarousel', owl1 = $('#skillsSlider').data(owlCarousel), owl2 = $('#teamSlider').data(owlCarousel), owl3 = $('#testimonialsSlider').data(owlCarousel), owl4 = $('#twitterSlider').data(owlCarousel), /* boxed / wide version of container */ wide = $('#wide'), boxed = $('#boxed'); /*--------------------------------- * Reset some plugins ---------------------------------*/ //reset certain plugins after changing window width and so on function pluginsReset(time) { setTimeout(function(time) { /* Refresh Owl carousel */ owl1.reinit({ autoPlay: true, //Set AutoPlay to 3 seconds items: 4, lazyLoad: true, itemsDesktop: [1200, 2], itemsDesktopSmall: [992, 3], itemsTablet: [768, 3], itemsMobile: [650, 1] }); owl2.reinit({ autoPlay: false, //Set AutoPlay to 3 seconds items: 4, lazyLoad: true, stopOnHover: true, itemsDesktop: [1200, 3], itemsDesktopSmall: [992, 2], itemsTablet: [768, 2], itemsMobile: [650, 1] }); owl3.reinit({ autoPlay: false, //Set AutoPlay to 3 seconds items: 2, lazyLoad: true, itemsDesktop: [1200, 2], itemsDesktopSmall: [992, 1], itemsTablet: [768, 1], itemsMobile: [480, 1] }); owl4.reinit({ autoPlay: true, //Set AutoPlay to 3 seconds items: 1, lazyLoad: true, stopOnHover: true, itemsDesktop: [1920, 1], itemsDesktopSmall: [992, 1], itemsTablet: [768, 1], itemsMobile: [480, 1] }); /* Refresh the slider Revolution */ $('.tp-banner').revolution({ delay: 11000, startheight: 1000, startwidth: 1170, hideThumbs: 10, navigationType: "none", navigationStyle: "preview4", touchenabled: "on", onHoverStop: "on", keyboardNavigation: "on", lazyLoad: "on", shadow: 0, fullWidth: "on", fullScreen: "off", spinner: "spinner4", autoHeight: "off", forceFullWidth: "on", hideArrowsOnMobile: "on" }); $('.tp-banner-container').css({ 'position': 'relative', 'overflow': 'hidden', 'max-height': '80vh', 'max-width': '100%', 'left': 0 }); /* Refresh stellar plugin - parallax images */ $.stellar('refresh'); }, time); //set time when the transition is finished!!! } $('#page-wrap').resize(function() { pluginsReset(100); }); /*--------------------------------- * Show / hide the style switcher ---------------------------------*/ /* Show style switcher after scrolling down (offset is set on 800px from the top) */ function showStyleSwitcher() { if ($(window).scrollTop() > 800) { sBtn.addClass(icon).addClass('show-it i-close').removeClass(icon); sBody.addClass(active); } } /* Close Style switcher */ function closeSwitcher() { sBody.removeClass(active); sBtn.removeClass('i-close').addClass(icon); $(window).off('scroll', showStyleSwitcher); } $('.md-trigger').on(action, function() { closeSwitcher(); }); $('.btn.trigger').on(action, function() { closeSwitcher(); }); $(window).on('scroll', showStyleSwitcher); if (isTouchDevice) { closeSwitcher(); sBtn.addClass(icon).addClass('show-it').on(action, function() { if (sBody.hasClass(active)) { sBody.removeClass(active); sBtn.removeClass('i-close').addClass(icon); } else { sBody.addClass(active); sBtn.removeClass(icon).addClass('i-close'); } }); } else { sBtn.on(action, function() { sBody.removeClass(active); sBtn.removeClass('i-close').addClass(icon); $(window).off('scroll', showStyleSwitcher); }); if (!sBody.hasClass(active)) { sBtn.mouseenter(function() { sBody.addClass(active); sBtn.removeClass(icon).addClass('i-close'); }); } } /*--------------------------------- * Change a navbar style ---------------------------------*/ function navbarStyle(navbarType) { function checkNavbarPosition() { if (navbarIsFixed) { navbarSpace.addClass(active); } else { navbarSpace.removeClass(active); } } $(navbarType).on(action, function() { if (navbarType === '#navDark') { navbarID.removeClass('nav-trn-style navbar-default navbar-trn').addClass('navbar-inverse'); checkNavbarPosition(); } if (navbarType === '#navLight') { navbarID.removeClass('nav-trn-style navbar-inverse navbar-trn').addClass('navbar-default'); checkNavbarPosition(); } if (navbarType === '#navTrn') { navbarSpace.removeClass(active); navbarID.removeClass('navbar-inverse navbar-default').addClass('navbar-trn'); } }); } if (matchMedia('(max-width: 767px)').matches) { navbarSpace.addClass('active'); } navbarStyle('#navDark'); navbarStyle('#navLight'); navbarStyle('#navTrn'); /*--------------------------------- * Change a color theme ---------------------------------*/ function changeTheme(theme, hex) { $('#' + theme + '').on(action, function() { $('h1.welcome').hide(); pageWrap.css('opacity', '0'); preloader.show(); spinner.show(); setTimeout(function() { spinner.hide(); setTimeout(function() { preloader.hide(); spinner.fadeOut(); pageWrap.css('opacity', '1'); }, 500); }, 2000); $('.tp-banner').revolution(); $('#mainTheme').attr('href', 'assets/css/main-theme/themes/' + theme + '-m.css'); $('#bootstrapTheme').attr('href', 'assets/css/bootstrap/themes/' + theme + '-b.css'); return false; }); /*-------------------------------------------------- * Change a style of knobs (Our skills seciton) ----------------------------------------------------*/ $("#" + theme).on(action, function(event) { event.preventDefault(); $(".lbKnob").trigger( "configure", { "fgColor": hex } ); }); } changeTheme("red", "#EF5350"); changeTheme("pink", "#EC407A"); changeTheme("deepPurple", "#7E57C2"); changeTheme("indigo", "#5C6BC0"); changeTheme("blue", "#42A5F5"); changeTheme("lightBlue", "#03A9F4"); changeTheme("cyan", "#26C6DA"); changeTheme("teal", "#009688"); changeTheme("green", "#4CAF50"); changeTheme("lightGreen", "#8BC34A"); changeTheme("lime", "#C0CA33"); changeTheme("yellow", "#FBC02D"); changeTheme("amber", "#FFC107"); changeTheme("orange", "#FF9800"); changeTheme("deepOrange", "#FF7043"); /*-------------------------------------------------- * Change a style of container (boxed/wide version) ----------------------------------------------------*/ //boxed boxed.on(action, function() { body.addClass('wrap-width'); pluginsReset(2501); }); //wide wide.on(action, function() { body.removeClass('wrap-width'); pluginsReset(2501); }); /*--------------------------------- * Set a background image ---------------------------------*/ //name = folder name have to be same as file name //type = png or jpg function changeBackground(id, name, type) { $('.bg-icon-' + id + '').on(action, function() { body.addClass('wrap-width'); $('.wrap-width').css('background', 'url("assets/img/patterns/' + name + '/' + name + '.' + type + '")'); pluginsReset(2501); }); } changeBackground('1', 'footer_lodyas', 'png'); changeBackground('2', 'sativa', 'png'); changeBackground('3', 'crossword', 'png'); changeBackground('4', 'geometry2', 'png'); changeBackground('5', 'greyzz', 'png'); changeBackground('6', 'subtle_white_feathers', 'png'); changeBackground('7', 'brickwall', 'png'); changeBackground('8', 'geometry', 'png'); changeBackground('9', 'pattern1', 'png'); changeBackground('10', 'pattern2', 'jpg'); } }); })(jQuery);
import React from 'react'; import { NavLink } from 'react-router-dom'; import { withRouter } from 'react-router-dom'; const FilterRadio = withRouter(({ filter, children, history, match }) => { return ( <label className="filter"> <input type="radio" checked={(match.params.filter || 'all') === filter} name="filter" className="filter__radio" onChange={(e) => history.push('/' + (filter === 'all' ? '' : filter)) } /> <span className={`filter__label--${children.toLowerCase()}`}>{children}</span> </label> ); }); export default FilterRadio;
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var app = express(); var indexRouter = require('./routes/index'); var starRouter = require('./routes/star'); var rickRouter = require('./routes/rick'); var pokemonRouter = require('./routes/poke'); app.use('/', indexRouter); app.use('/star', starRouter); app.use('/rick', rickRouter); app.use('/poke', pokemonRouter); const hbs = require('express-handlebars')({ defaultLayout: "main", extname: '.hbs' }); app.engine('hbs', hbs); app.set('view engine', 'hbs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); // Serve static content for the app from the "public" directory in the application directory. // var favicon = require('serve-favicon'); // app.use(favicon(path.join(__dirname, 'public/assets/img', 'favicon.ico'))); app.use('/public', express.static('public')); app.use('/img', express.static('public/img')); app.use('/stylesheets', express.static('public/stylesheets')); app.use('/css', express.static('public/css')); app.use('/lib', express.static('public/lib')); app.use('/js', express.static('public/js')); // app.use(express.static(path.join(__dirname, 'public'))); // // catch 404 and forward to error handler // app.use(function(req, res, next) { // next(createError(404)); // }); // // error handler // app.use(function(err, req, res, next) { // // set locals, only providing error in development // res.locals.message = err.message; // res.locals.error = req.app.get('env') === 'development' ? err : {}; // // render the error page // res.status(err.status || 500); // res.render('error'); // }); // Start the server and log the port var PORT = 8000; app.listen(process.env.PORT||PORT, () => { console.log(`Server started on ${PORT}`); }); module.exports = app;
export const SOCKET_DID_MOUNT = 'socket/SOCKET_DID_MOUNT' export const SOCKET_DID_CONNECT = 'socket/SOCKET_DID_CONNECT'
process.env.NODE_ENV = "test"; process.env.PORT = "0"; process.env.MONGODB_URI = "mongodb://db:27017/dig_test"; process.env.APP_ENV = "test"; process.env.JWT_SECRET = "segredo"; process.env.CONTACT_EMAIL = ""; process.env.SG_API_KEY = "SG."; module.exports = { globals: { "ts-jest": { tsConfig: "<rootDir>/../../tsconfig.json", // diagnostics: { // warnOnly: true // } diagnostics: false, }, }, moduleFileExtensions: ["ts", "js", "json"], transform: { "^.+\\.(ts|tsx)$": "ts-jest", }, testMatch: ["**/*.test.(ts|js)"], testEnvironment: "node", setupFilesAfterEnv: ["./jest.setup.ts"], };
gsap.registerPlugin(ScrollTrigger) gsap.to('.square',{ x:700, duration: 3, scrollTrigger: ".square2" }) gsap.to('.square3',{ x:700, duration: 3, scrollTrigger:{ trigger: '.square3', // start: 'top center', start: 'top 30%', // markers:{ // startColor: 'purple', // endColor:'fuchsia', // fontSize: '4rem', // indent: 200 // } // markers: true, } }) gsap.to('.square4',{ duration: 3, scrollTrigger: { trigger: '.square4', start: 'top 30%', // end: 'center 20%', end: ()=>`+=${document.querySelector('.square').offsetHeight}`, // markers: true, toggleClass: 'red' } }) gsap.to('.square5',{ x: 700, duration: 3, scrollTrigger: { trigger: '.square5', start: 'top 60%', end: 'top 40%', // onEnter, onLeave, onEnterBack, onLeaveBack toggleActions: 'restart pause resume complete', // markers:{ // startColor: 'purple', // endColor:'fuchsia', // fontSize: '3rem', // } } }) gsap.to('.square6',{ x: 1000, duration: 8, scrollTrigger: { trigger: '.square6', start: 'top 80%', end: 'top 30%', scrub: 4, toggleActions: 'restart none none none', // markers:{ // startColor: 'purple', // endColor:'fuchsia', // fontSize: '3rem', // } } }) gsap.to('.square7',{ x: 1000, duration: 8, scrollTrigger: { trigger: '.square8', start: 'top 80%', end: 'top 30%', scrub: 4, pin: '.square7', pinSpacing: false, toggleActions: 'restart none none none', // markers:{ // startColor: 'purple', // endColor:'fuchsia', // fontSize: '3rem', // } } }) // gsap.to('.box',{x:500, duration: 5}) // gsap.to('.box',{y:500, duration: 3, delay: 2}) // gsap.to('.box',{x:0, duration: 2, delay: 5}) const tl= gsap.timeline({ scrollTrigger: { trigger: '.box', markers: true, start: 'top 80%', end : 'top 30%', scrub: 1 } }) tl .to('.box',{x:500, duration: 5}) .to('.box',{y:200, duration: 3}) .to('.box',{x:0, duration: 2}) ScrollTrigger.create({ trigger:'.box2', start: 'top 80%', end: 'top 50%', markers: true, toggleClass: 'box2-red' })
var ammo = new BABYLON.GUI.TextBlock(); var health = new BABYLON.GUI.TextBlock(); var killsCount = new BABYLON.GUI.TextBlock(); var menuControlsPanel = new BABYLON.GUI.Rectangle(); var respawnPanel = new BABYLON.GUI.Rectangle(); var respawnCounterText = new BABYLON.GUI.TextBlock(); var controlInstructionsPanel = new BABYLON.GUI.StackPanel(); var advancedTexture; var levels = ["Can I play daddy?", "Don't hurt me!", "Bring 'em on!", "Suicidal"]; var mouse = ["Slow", "Slow", "Fast", "Fast"]; var createDomMenu = function () { var playButtonElement = document.getElementById("play_button"); var respawnButtonElement = document.getElementById("respawn"); var keepButtonElement = document.getElementById("keep"); if (typeof (playButtonElement) != 'undefined' && playButtonElement != null) { playButtonElement.style.display = "block"; respawnButtonElement.style.display = "block"; keepButtonElement.style.display = "block"; return; } var respawnButton = document.createElement("button"); respawnButton.innerHTML = "Respawn: NO"; respawnButton.style.bottom = "5%"; respawnButton.style.left = "5%"; respawnButton.setAttribute('id', 'respawn'); respawnButton.onclick = (event) => { respawn = !respawn; if (respawn) { respawnButton.innerHTML = "Respawn: YES"; } else { respawnButton.innerHTML = "Respawn: NO"; } } document.body.appendChild(respawnButton); var keepButton = document.createElement("button"); keepButton.innerHTML = "Keep 'em coming: NO"; keepButton.style.bottom = "5%"; keepButton.style.right = "5%"; keepButton.setAttribute('id', 'keep'); keepButton.onclick = (event) => { infiniteMode = !infiniteMode; if (infiniteMode) { keepButton.innerHTML = "Keep 'em coming: YES"; } else { keepButton.innerHTML = "Keep 'em coming: NO"; } } document.body.appendChild(keepButton); var play = document.createElement('IMG'); play.setAttribute('id', 'play_button'); play.setAttribute('src', '../images/play.png'); play.style.position = "absolute"; play.style.zIndex = 10; play.style.bottom = "20%" play.style.left = "50%" play.style.marginLeft = "-50px"; play.style.marginTop = "-50px"; play.style.width = "100px"; play.style.height = "100px"; play.style.borderRadius = "30%"; play.style.border = "thick solid orange"; play.onmousedown = () => { camera.inputs.clear(); camera.attachControl(canvas); camera.inputs.addVirtualJoystick(); document.body.requestFullscreen(); startPlaying(); play.style.display = "none"; respawnButton.style.display = "none"; keepButton.style.display = "none"; var playButtonElement = document.getElementById("play_button1"); if (typeof (playButtonElement) != 'undefined' && playButtonElement != null) { return; } createInGameButtons(); } document.body.appendChild(play); } var createInGameButtons = function () { var shoot1 = document.createElement('IMG'); shoot1.setAttribute('id', 'play_button1'); shoot1.setAttribute('src', '../../images/bullet.png'); shoot1.style.position = "absolute"; shoot1.style.zIndex = 10; shoot1.style.bottom = "20%" shoot1.style.right = "5%" shoot1.style.width = "60px"; shoot1.style.height = "60px"; shoot1.style.transform = "rotate(270deg)"; shoot1.style.borderRadius = "20%"; shoot1.style.border = "thick solid #000000"; shoot1.style.padding = "2px"; shoot1.draggable = false; shoot1.onmousedown = (event) => { if (!playerDied) { player.shoot(); player.fireButtonOn = true; } event.preventDefault(); } shoot1.ontouchstart = (event) => { if (!playerDied) { player.shoot(); player.fireButtonOn = true; } event.preventDefault(); } shoot1.ontouchend = () => { player.fireButtonOn = false; } shoot1.onmouseup = () => { player.fireButtonOn = false; } shoot1.onmouseout = () => { player.fireButtonOn = false; } document.body.appendChild(shoot1); var shoot2 = document.createElement('IMG'); shoot2.setAttribute('id', 'play_button2'); shoot2.setAttribute('src', '../../images/bullet.png'); shoot2.style.position = "absolute"; shoot2.style.zIndex = 10; shoot2.style.bottom = "20%" shoot2.style.left = "5%" shoot2.style.width = "60px"; shoot2.style.height = "60px"; shoot2.style.borderRadius = "20%"; shoot2.style.border = "thick solid #000000"; shoot2.style.padding = "2px"; shoot2.onmousedown = (event) => { if (!playerDied) { player.shoot(); player.fireButtonOn = true; } event.preventDefault(); } shoot2.ontouchstart = (event) => { if (!playerDied) { player.shoot(); player.fireButtonOn = true; } event.preventDefault(); } shoot2.ontouchend = () => { player.fireButtonOn = false; } shoot2.onmouseup = () => { player.fireButtonOn = false; } shoot2.onmouseout = () => { player.fireButtonOn = false; } document.body.appendChild(shoot2); var reloadButton = document.createElement('IMG'); reloadButton.setAttribute('id', 'play_button2'); reloadButton.setAttribute('src', '../../images/gun_reload.png'); reloadButton.style.position = "absolute"; reloadButton.style.zIndex = 10; reloadButton.style.bottom = "50%" reloadButton.style.left = "2%" reloadButton.style.width = "30px"; reloadButton.style.height = "30px"; reloadButton.style.borderRadius = "20%"; reloadButton.style.border = "thick solid #000000"; reloadButton.style.padding = "1px"; reloadButton.onmousedown = (event) => { if (!playerDied) { player.shoot(); player.fireButtonOn = true; } event.preventDefault(); } reloadButton.ontouchstart = (event) => { if (!playerDied) { player.reload(); } event.preventDefault(); } reloadButton.onmouseup = () => { player.reload(); } document.body.appendChild(reloadButton); advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI"); var style = advancedTexture.createStyle(); style.fontSize = 26; style.fontStyle = "bold"; var verticalPadding = "10px"; // style.fontStyle = "italic"; // style.fontFamily = "Verdana"; var smallTextStyle = advancedTexture.createStyle(); smallTextStyle.fontSize = 10; smallTextStyle.fontStyle = "bold"; ammo.text = "30| 100"; ammo.width = "170px" ammo.height = "50px"; ammo.color = "orange"; ammo.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; ammo.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; ammo.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; ammo.paddingRight = "60px"; ammo.paddingTop = verticalPadding; ammo.style = style; advancedTexture.addControl(ammo); killsCount.text = "Kills " + kills; killsCount.width = "570px" killsCount.height = "50px"; killsCount.color = "orange"; killsCount.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER; killsCount.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; killsCount.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER; killsCount.paddingTop = verticalPadding; killsCount.style = style; advancedTexture.addControl(killsCount); health.text = "100"; health.width = "150px" health.height = "50px"; health.color = "orange"; health.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; health.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; health.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; health.paddingLeft = "60px"; health.paddingTop = verticalPadding; health.style = style; advancedTexture.addControl(health); var healthSign = new BABYLON.GUI.Image("health", "images/health.png"); healthSign.width = "50px"; healthSign.height = "50px"; healthSign.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; healthSign.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; healthSign.paddingLeft = "10px"; healthSign.paddingTop = verticalPadding; advancedTexture.addControl(healthSign); var bullet = new BABYLON.GUI.Image("health", "images/bullet.png"); bullet.width = "50px"; bullet.height = "50px"; bullet.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; bullet.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; bullet.paddingRight = "20px"; bullet.paddingTop = verticalPadding; advancedTexture.addControl(bullet); advancedTexture.addControl(createRespawnPanel(advancedTexture)); } var createMainMenu = function () { var pause = BABYLON.GUI.Button.CreateImageOnlyButton("health", "images/pause.png"); pause.width = "50px"; pause.height = "100px"; pause.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; pause.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; pause.paddingRight = "10px"; pause.paddingTop = "50px"; pause.thickness = 0; pause.onPointerUpObservable.add(function () { if (!gameStarted) return; paused = !paused; if (paused) { killsCount.color = "black"; killsCount.text = "Game Paused"; setTimeout(function () { engine.stopRenderLoop(); }, 200); } else { killsCount.color = "orange"; killsCount.text = "Kills " + kills; engine.runRenderLoop(function () { globalScene.render(); divFps.innerHTML = engine.getFps().toFixed() + " fps"; }); } }); advancedTexture.addControl(pause); var pauseKB = new BABYLON.GUI.TextBlock(); pauseKB.text = "CTL + P"; pauseKB.width = "110px" pauseKB.height = "50px"; pauseKB.color = "orange"; pauseKB.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; pauseKB.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; pauseKB.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; pauseKB.paddingRight = "50px"; pauseKB.paddingTop = "100px"; pauseKB.style = smallTextStyle; advancedTexture.addControl(pauseKB); var fullScreenButton = new BABYLON.GUI.Image("health", "images/fullscreen.png"); fullScreenButton.width = "40px"; fullScreenButton.height = "120px"; fullScreenButton.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; fullScreenButton.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; fullScreenButton.paddingRight = "20px"; fullScreenButton.paddingTop = "100px"; fullScreenButton.thickness = 0; fullScreenButton.onPointerUpObservable.add(function () { if (!gameStarted) return; fullScreen = !fullScreen; if (fullScreen) { BABYLON.Tools.RequestFullscreen(canvas); } else { BABYLON.Tools.ExitFullscreen(); } }); advancedTexture.addControl(fullScreenButton); var fullScreenKB = new BABYLON.GUI.TextBlock(); fullScreenKB.text = "CTL + F"; fullScreenKB.width = "110px" fullScreenKB.height = "50px"; fullScreenKB.color = "orange"; fullScreenKB.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; fullScreenKB.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; fullScreenKB.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT; fullScreenKB.paddingRight = "50px"; fullScreenKB.paddingTop = "170px"; fullScreenKB.style = smallTextStyle; advancedTexture.addControl(fullScreenKB); var restartButton = new BABYLON.GUI.Image("restart", "images/restart.png"); restartButton.width = "52px"; restartButton.height = "100px"; restartButton.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; restartButton.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; restartButton.paddingLeft = "12px"; restartButton.paddingTop = "60px"; restartButton.thickness = 0; restartButton.onPointerUpObservable.add(function () { if (!gameStarted) return; location.reload(); globalScene.dispose(); engine.dispose(); loadIt(); canvas.blur(); }); advancedTexture.addControl(restartButton); var restartKB = new BABYLON.GUI.TextBlock(); restartKB.text = "CTL + N"; restartKB.width = "110px" restartKB.height = "50px"; restartKB.color = "orange"; restartKB.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; restartKB.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; restartKB.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; restartKB.paddingLeft = "60px"; restartKB.paddingTop = "110px"; restartKB.style = smallTextStyle; advancedTexture.addControl(restartKB); var audioButton = new BABYLON.GUI.Image("audio", "images/audio.png"); audioButton.width = "56px"; audioButton.height = "150px"; audioButton.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; audioButton.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; audioButton.paddingLeft = "16px"; audioButton.paddingTop = "110px"; audioButton.thickness = 0; audioButton.onPointerUpObservable.add(function () { if (!gameStarted) return; toggleAudio(); }); advancedTexture.addControl(audioButton); var audiotKB = new BABYLON.GUI.TextBlock(); audiotKB.text = "CTL + A"; audiotKB.width = "110px" audiotKB.height = "50px"; audiotKB.color = "orange"; audiotKB.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; audiotKB.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; audiotKB.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; audiotKB.paddingLeft = "60px"; audiotKB.paddingTop = "210px"; audiotKB.style = smallTextStyle; advancedTexture.addControl(audiotKB); var replayButton = BABYLON.GUI.Button.CreateSimpleButton("replay button", "PLAY"); replayButton.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER; replayButton.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM; replayButton.width = "190px" replayButton.height = "80px"; replayButton.color = "orange"; replayButton.background = "black"; replayButton.style = style; replayButton.style.zIndex = 1000; replayButton.paddingBottom = "10px"; replayButton.onPointerUpObservable.add(function () { startPlaying(); menuControlsPanel.isVisible = false; }); // menuControlsPanel.adaptWidthToChildren = true; menuControlsPanel.height = "300px"; menuControlsPanel.width = "300px"; menuControlsPanel.color = "orange"; menuControlsPanel.thickness = 5; menuControlsPanel.background = "orange"; menuControlsPanel.alpha = .9; menuControlsPanel.addControl(replayButton); var panel = new BABYLON.GUI.StackPanel(); panel.width = "500px"; panel.isVertical = true; panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; panel.addControl(createRespawnCheckbox()); panel.addControl(createInfiniteCheckbox()); panel.addControl(createLevelSlider()); panel.addControl(createMouseSlider()); panel.addControl(createControlInstructions()); menuControlsPanel.addControl(panel); advancedTexture.addControl(menuControlsPanel); advancedTexture.isForeground = true; advancedTexture.addControl(createRespawnPanel(advancedTexture)); // gameStarted = true; // menuControlsPanel.isVisible=false; } var createRespawnPanel = function (advancedTexture) { var style = advancedTexture.createStyle(); style.fontSize = 26; style.fontStyle = "bold"; var verticalPadding = "10px"; respawnPanel.height = "100px"; respawnPanel.width = "200px"; respawnPanel.color = "orange"; respawnPanel.thickness = 5; respawnPanel.background = "orange"; respawnPanel.alpha = .9; respawnCounterText.text = "" + respawnCounter; respawnCounterText.width = "190px"; respawnCounterText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER; respawnCounterText.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; respawnCounterText.color = "black"; respawnCounterText.paddingLeft = "3"; respawnCounterText.paddingTop = "80"; respawnCounterText.height = "30px"; respawnCounterText.style = style; respawnPanel.addControl(respawnCounterText); respawnPanel.isVisible = false; return respawnPanel; } var createRespawnCheckbox = function () { var respawnCb = new BABYLON.GUI.Checkbox(); respawnCb.width = "20px"; respawnCb.height = "20px"; respawnCb.isChecked = respawn; respawnCb.color = "orange"; respawnCb.onIsCheckedChangedObservable.add(function (value) { respawn = !respawn; }); var respawnCbText = new BABYLON.GUI.TextBlock(); respawnCbText.text = "Respawn"; respawnCbText.width = "180px"; respawnCbText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; respawnCbText.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; respawnCbText.color = "black"; respawnCbText.paddingLeft = "3"; respawnCbText.height = "30px"; var panel = new BABYLON.GUI.StackPanel(); panel.width = "200px"; panel.isVertical = false; panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; panel.addControl(respawnCb); panel.addControl(respawnCbText); panel.adaptHeightToChildren = true; return panel; } var createInfiniteCheckbox = function () { var infiniteCb = new BABYLON.GUI.Checkbox(); infiniteCb.width = "20px"; infiniteCb.height = "20px"; infiniteCb.isChecked = infiniteMode; infiniteCb.color = "orange"; infiniteCb.onIsCheckedChangedObservable.add(function (value) { infiniteMode = !infiniteMode; }); var infiniteCbText = new BABYLON.GUI.TextBlock(); infiniteCbText.text = "Keep 'em comming"; infiniteCbText.width = "180px"; infiniteCbText.height = "30px"; infiniteCbText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; infiniteCbText.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; infiniteCbText.color = "black"; infiniteCbText.paddingLeft = "3"; var panel = new BABYLON.GUI.StackPanel(); panel.width = "200px"; panel.isVertical = false; panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; panel.addControl(infiniteCb); panel.addControl(infiniteCbText); panel.adaptHeightToChildren = true; return panel; } var startPlaying = function () { gameStarted = true; audioEnabled = false; toggleAudio(); if (playerDied) { var cellIndex = Math.floor((Math.random() * randomAmmoLocations.length)); var cell = randomAmmoLocations[cellIndex]; var playerPos = new BABYLON.Vector3(cell.x * unit - 1650, camera.position.y, cell.y * unit - 1650); camera.position = playerPos; camera.setTarget(new BABYLON.Vector3(0, 25, 0)); camera.inputs.addMouse(); camera.inputs.addKeyboard(); player.leftArm.isVisible = true; player.rightArm.isVisible = true; player.weapon.isVisible = true; player.crosshairTop.isVisible = true; player.crosshairBottom.isVisible = true; player.crosshairLeft.isVisible = true; player.crosshairRight.isVisible = true; player.muzzleFlash.isVisible = true; player.health = 100; player.bullets = 100; player.ammo = 30; player.shouldJump = false; player.shouldDuck = false; ammo.text = player.ammo + "| " + player.bullets; health.text = Math.floor(player.health) + ""; playerDied = false; player.toggleDuck(); camera.keysUp = [87]; // W camera.keysDown = [83]; // S camera.keysLeft = [65]; // A camera.keysRight = [68]; // D if (!respawn) { kills = 0; killsCount.text = "Kills " + kills; lastEnemyId = 0; for (var i = enemies.length - 1; i >= 0; i--) { enemies[i].remove(false); } createFirstRoundEnemies(globalScene); } } else if (newEnemiesRound) { kills = 0; killsCount.text = "Kills " + kills; lastEnemyId = 0; createFirstRoundEnemies(globalScene); newEnemiesRound = false; camera.inputs.addMouse(); camera.inputs.addKeyboard(); player.health = 100; player.bullets = 100; player.ammo = 30; player.shouldJump = false; player.shouldDuck = false; player.toggleDuck(); ammo.text = player.ammo + "| " + player.bullets; health.text = Math.floor(player.health) + ""; camera.keysUp = [87]; // W camera.keysDown = [83]; // S camera.keysLeft = [65]; // A camera.keysRight = [68]; // D } } var createLevelSlider = function () { var smallTextStyle = advancedTexture.createStyle(); smallTextStyle.fontSize = 12; smallTextStyle.fontStyle = "bold"; var header = new BABYLON.GUI.TextBlock(); header.text = "Level: " + levels[0]; header.height = "30px"; header.color = "black"; header.style = smallTextStyle; var slider = new BABYLON.GUI.Slider(); slider.minimum = 0; slider.maximum = 7; slider.value = 0; slider.step = 5; slider.height = "20px"; slider.width = "150px"; slider.background = "black"; slider.onValueChangedObservable.add(function (value) { var level = Math.floor(value / 2); header.text = "Level: " + levels[level]; difficulty = level + 1; }); var panel = new BABYLON.GUI.StackPanel(); panel.width = "300px"; panel.isVertical = true; panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; panel.addControl(createInstructionLine(" ")); panel.addControl(header); panel.addControl(slider); return panel; } var createMouseSlider = function () { var smallTextStyle = advancedTexture.createStyle(); smallTextStyle.fontSize = 12; smallTextStyle.fontStyle = "bold"; var header = new BABYLON.GUI.TextBlock(); header.text = "Mouse Sensitivity: " + mouse[3]; header.height = "30px"; header.color = "black"; header.style = smallTextStyle; var slider = new BABYLON.GUI.Slider(); slider.minimum = 0; slider.maximum = 7; slider.value = 7; slider.step = 5; slider.height = "20px"; slider.width = "150px"; slider.background = "black"; slider.onValueChangedObservable.add(function (value) { var mouseValue = Math.floor(value / 2); header.text = "Mouse Sensitivity: " + mouse[mouseValue]; mouseSensitivity = 2000 + (1000 * (1 - (value / 7))); camera.angularSensibility = mouseSensitivity; }); var panel = new BABYLON.GUI.StackPanel(); panel.width = "300px"; panel.isVertical = true; panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP; panel.addControl(createInstructionLine(" ")); panel.addControl(header); panel.addControl(slider); return panel; } var createControlInstructions = function () { controlInstructionsPanel.width = "500px"; controlInstructionsPanel.isVertical = true; controlInstructionsPanel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; controlInstructionsPanel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM; controlInstructionsPanel.isVisible = true; return controlInstructionsPanel; } var createInstructionLine = function (text) { var smallTextStyle = advancedTexture.createStyle(); smallTextStyle.fontSize = 14; smallTextStyle.fontStyle = "bold"; var line = new BABYLON.GUI.TextBlock(); line.style = smallTextStyle; line.text = text; line.width = "500px"; line.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; line.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER; line.color = "black"; line.paddingLeft = "3"; line.height = "15px"; return line; }
module.exports = async (data, method) => { return new Promise((resolve, reject) => { const Joi = require('joi') const schema = Joi.object({ name: method == 'PUT' ? Joi.string().max(40).min(3) : Joi.string().max(40).min(3).required(), email: method == 'PUT' ? Joi.string().max(50).min(8).regex(/.+@.+\..+/) : Joi.string().max(50).min(8).regex(/.+@.+\..+/).required(), password: method == 'PUT' ? Joi.string().max(255).min(8) : Joi.string().max(255).min(8).required(), telephone: method == 'PUT' ? Joi.number().integer() : Joi.number().integer().required(), address: { street: method == 'PUT' ? Joi.string() : Joi.string().required(), number: method == 'PUT' ? Joi.number() : Joi.number().required(), city: method == 'PUT' ? Joi.string() : Joi.string().required(), state: method == 'PUT' ? Joi.string() : Joi.string().required(), country: method == 'PUT' ? Joi.string() : Joi.string().required(), } }) const { error } = schema.validate(data) if (error) return reject({ validatingError: error.message.replace(/"+/g, '') }) return resolve() }) }
const fs = require('fs'); const path = require('path'); function checkProjectExists(cmdPath, name) { return fs.existsSync(path.resolve(cmdPath, name)) }; exports.checkProjectExists = checkProjectExists;
import Load from './Load' export { Load, }
/** * Created by nicholas on 4/21/17. */ import { FETCH_WEATHER } from '../actions/index'; export default function (state = [], action) { switch (action.type) { case FETCH_WEATHER: // Add to end // return state.concat([action.payload.data]); // Add to beginning return [ action.payload.data, ...state]; // [city, city, city] } return state; }
import user from './components/user.vue'; import New from './components/New.vue'; import Author from './components/Author.vue'; import UserStart from './components/UserStart.vue'; import UserDetail from './components/UserDetail.vue'; import UserEdit from './components/UserEdit.vue'; import Header from './components/Header.vue'; export const routes =[ { path: '', name :'user', components:{ default: user, 'header-top':Header } }, { path: '/New', components: { default: New, 'header-bottom':Header }, children:[ { path:'', component:UserStart }, { path:':id', component:UserDetail, beforeEnter: (to,from,next) => { console.log('inside route setup'); next(); } }, { path:':id/edit', component:UserEdit, name: 'userEdit' } ] }, { path:'/Author', component:Author }, { path: '/redirect-me', redirect: { name: 'user' } }, { path:'*', redirect: { name: 'user' } } ];
(function () { 'use strict'; var app = angular.module('Events', []); })();
var AppDispatcher = require('../dispatcher/dispatcher.js'); var Store = require('flux/utils').Store; var UserAndPostConstants = require('../constants/user_and_post_constants'); var UserStore = new Store(AppDispatcher); var _users = []; var replaceWithMatchedUsers = function(matchedResults) { _users = matchedResults; }; UserStore.all = function() { return _users; }; UserStore.topSeven = function() { // sort by length var matches = []; for (var i = 0; i < _users.length; i++) { var name = _users[i].username || _users[i].hashtag; var length = name.length; // move the hashtags further back in the line if ( _users[i].hashtag ) { length = length * 2; } if ( matches[length] ) { matches[length].push( _users[i] ); } else { matches[length] = [ _users[i] ]; } } // take top seven var topSeven = []; var counter = 0; for (var j = 0; j < matches.length; j++) { if ( matches[j] ) { for (var k = 0; k < matches[j].length; k++) { topSeven.push(matches[j][k]); counter++; if (counter >= 7) { return topSeven; } } } } return topSeven; }; UserStore.__onDispatch = function(payload) { switch(payload.actionType) { case UserAndPostConstants.BRING_DOWN_MATCHED_USERS_AND_HASHTAGS: var matchedResults = payload.matchedResults; replaceWithMatchedUsers(matchedResults); UserStore.__emitChange(); break; } }; module.exports = UserStore;
import React from 'react'; import CommentForm from './CommentForm'; import CommentListBox from './CommentListBox'; const WeatherBox = ({ id, name, icon, feelslike_c, text, comments, removeWeather, addComment, removeComment }) => ( <div className="weather"> <div className="weather__box"> <div className="weather__icon-box"> <img className="weather__icon" src={icon} alt={text} /> </div> <div className="weather__info-box"> <p>{name}</p> <p>{text} - {feelslike_c} | C</p> </div> <div className="weather__icon-box weather--right"> <i onClick={() => { removeWeather(id); }} className="fa fa-2x fa-trash"></i> </div> </div> <div className="weather__box"> <CommentForm id={id} addComment={addComment} /> </div> <div className="weather__box"> <CommentListBox removeComment={removeComment} weatherId={id} comments={comments} /> </div> </div> ); export default WeatherBox;
import React from "react"; import { connect } from "react-redux"; import { createStructuredSelector } from "reselect"; import { CheckoutContainer, CheckoutItemsContainer, CheckoutFormContainer, CheckoutItemsHeader, CheckoutItemsHeaderBlock, } from "./checkout.styles"; import { selectCartItems, selectTotalToPay, } from "../../redux/cart/cart.selectors"; import { selectShowCheckoutModal } from "../../redux/checkout/checkout.selectors"; import CheckoutForm from "../../components/checkout-page-components/checkout-form/checkout-form.component"; import CheckoutItem from "../../components/checkout-page-components/checkout-item/checkout-item.component"; import CheckoutModal from "../../components/checkout-page-components/checkout-modal/checkout-modal.component"; import CustomTextSpan from "../../components/custom-text-span/custom-text-span.component"; const Checkout = ({ cartItems, showCheckoutModal, totalToPay }) => { const titles = ["Product", "Description", "Quantity", "Price", "Remove"]; return ( <CheckoutContainer> <CheckoutFormContainer> <CheckoutForm /> </CheckoutFormContainer> <CheckoutItemsContainer> <CheckoutItemsHeader> {titles.map((title, idx) => ( <CheckoutItemsHeaderBlock key={idx}> {title} </CheckoutItemsHeaderBlock> ))} </CheckoutItemsHeader> {cartItems.map((cartItem, idx) => ( <CheckoutItem item={cartItem} key={idx} /> ))} <CustomTextSpan text={`Total: $${totalToPay}`} size={24} /> </CheckoutItemsContainer> {showCheckoutModal ? <CheckoutModal /> : null} </CheckoutContainer> ); }; const mapStateToProps = createStructuredSelector({ cartItems: selectCartItems, totalToPay: selectTotalToPay, showCheckoutModal: selectShowCheckoutModal, }); export default connect(mapStateToProps)(Checkout);
var TarjetaArticuloCtrl = function($parent, carrito, articulo) { this.$parent = $parent; this.carrito = carrito; this.articulo = articulo; this.$elem = TarjetaArticuloCtrl.$PLANTILLA.clone().removeAttr('id'); }; TarjetaArticuloCtrl.$PLANTILLA = $('#plantillaTarjetaArticulo'); TarjetaArticuloCtrl.prototype.inicializar = function() { this.$elem.find('.card-image img').attr('src', this.articulo.imagen); this.$elem.find('.card-title').text(this.articulo.nombre + ' ¡solo ' + this.articulo.precio + '€!'); this.$elem.find('.card-action a').click(function(evt) { evt.preventDefault(); var accion = evt.currentTarget.getAttribute('data-accion'); // evt.target puede ser un elemento incluído en el botón if (accion === 'ELIMINAR') { this.eliminarDeCarrito(); } else { this.agregarTallaACarrito(accion); } }.bind(this)); this.$elem.appendTo(this.$parent); this.$elem.removeAttr('style'); }; TarjetaArticuloCtrl.prototype.actualizarTarjeta = function() { var mensaje; var articuloComprado = this.carrito.articulosComprados[this.articulo.nombre]; if (articuloComprado === undefined) { mensaje = 'No has comprado ninguna camiseta de este modelo.'; } else { var numeroArticulosComprados = articuloComprado.numeroArticulos(); if (numeroArticulosComprados === 0) { mensaje = 'No has comprado ninguna camiseta de este modelo.'; } else { mensaje = 'Camistas compradas: '; for (var talla in articuloComprado.tallasCompradas) { var unidadesCompradasDeTallaActual = articuloComprado.tallasCompradas[talla]; if (unidadesCompradasDeTallaActual > 0) { mensaje = mensaje + talla + ': ' + unidadesCompradasDeTallaActual + ', '; } } mensaje = mensaje.substring(0, mensaje.length- ', '.length) + '.'; } } this.$elem.find('.card-content p') .fadeOut(function() { this.innerHTML = mensaje; }).fadeIn(); }; TarjetaArticuloCtrl.prototype.eliminarDeCarrito = function() { this.carrito.eliminarArticulo(this.articulo); this.actualizarTarjeta(); }; TarjetaArticuloCtrl.prototype.agregarTallaACarrito = function(talla) { try { this.carrito.registrarCompra(this.articulo, talla); this.actualizarTarjeta(); } catch (error) { error.stack Materialize.toast(error.message, 3000, 'rounded'); } };
import React from 'react'; import { connect } from 'react-redux'; import Star from '../components/Star'; import { triggerReRender } from '../store/regionMap/actions'; import { selectStarDisplay, selectDefaultStarDisplay } from '../store/regionMap/selectors'; import { selectStarById } from '../store/stars/selectors'; const mapStateToProps = (state, ownProps) => { return { display: selectStarDisplay(state), defaultDisplay: selectDefaultStarDisplay(state), // data: selectStarById(state, ownProps.id), data: ownProps.data, }; }; const mapDispatchToProps = dispatch => { return { onTriggerReRender: data => dispatch(triggerReRender()), }; }; export default connect(mapStateToProps, mapDispatchToProps)(Star);
/** * Main action * * You can invoke this function via: * aio rt:action:invoke <action_path> -p tenant '<tenant_id>' -p apiKey '<api_key>' -p token '<access_token>' * * To find your <action_path>, run this command: * aio rt:ls * * To show debug logging for this function, you can add the LOG_LEVEL parameter as well: * aio rt:action:invoke <action_path> -p tenant '<tenant_id>' -p apiKey '<api_key>' -p token '<access_token>' -p LOG_LEVEL '<log_level>' * ... where LOG_LEVEL can be one of [ error, warn, info, verbose, debug, silly ] * * Then, you can view your app logs: * aio app:logs */ const { Core, Target } = require('@adobe/aio-sdk') async function main (params) { // create a Logger const myAppLogger = Core.Logger('MyApp', { level: params.LOG_LEVEL }) // 'info' is the default level if not set myAppLogger.info('Calling the main action') // log levels are cumulative: 'debug' will include 'info' as well (levels are in order of verbosity: error, warn, info, verbose, debug, silly) myAppLogger.debug(`params: ${JSON.stringify(params, null, 2)}`) try { // initialize the sdk const targetClient = await Target.init(params.tenant, params.apiKey, params.token) // get activities from Target api const activities = await targetClient.getActivities({ limit: 5, offset: 0 }) myAppLogger.debug(`profiles = ${JSON.stringify(activities, null, 2)}`) return activities } catch (error) { myAppLogger.error(error) } } exports.main = main
$(document).ready(function () { $.ajax({ type: "GET", url: "http://localhost:8081/suppliers/allorders", dataType: "json", beforeSend: function(xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS : ", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; row += "<td>" + data[i]['id'] + "</td>"; row += "<td>" + data[i]['adminEmail'] + "</td>"; row += "<td>" + data[i]['pharmacyName'] + "</td>"; row += "<td>" + data[i]['pharmacyAddress'] + "</td>"; row += "<td>" + data[i]['dateDeadline'] + "</td>"; row += "<td>" + data[i]['statusSupplier'] + "</td>"; row += "<td>" + data[i]['offer'] + "</td>"; if(data[i]['statusSupplier']==='odobrena'){ var btn = "<button disabled>Ponuda je obradjena</button>"; } else if(data[i]['statusSupplier']==='odbijena'){ var btn = "<button disabled>Ponuda je obradjena</button>"; } else if ( data[i]['offer']==0) { var btn = "<button class='btnGiveOffer' id = " + data[i]['id'] + ">Kreiraj ponudu</button>"; } else { var btn = "<button class='btnChangeOffer' id = " + data[i]['id'] + ">Izmeni ponudu</button>"; } row += "<td>" + btn + "</td>"; $('#orders').append(row); } }, error: function (data) { console.log("ERROR : ", data); } }); }); $(document).on('click', '.btnGiveOffer', function () { var pharmacyDiv = $(".orderall"); pharmacyDiv.hide(); var formaDiv=$(".orderForm"); formaDiv.show(); var orderID=this.id; $(document).on("submit", "form", function (event) { event.preventDefault(); var offer = $("#offer").val(); var deliveryDate = $("#date").val(); var offerJSON = formToJSON(offer,deliveryDate,orderID); $.ajax({ type: "POST", url: "http://localhost:8081/suppliers/addOffer", dataType: "json", contentType: "application/json", data: offerJSON, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function () { alert("success"); window.location.href = "supplier.html"; }, error: function (error) { alert(error); } }); }); }); $(document).on('click', '.btnChangeOffer', function () { var pharmacyDiv = $(".orderall"); pharmacyDiv.hide(); var formaDiv=$(".orderChangeForm"); formaDiv.show(); var orderID=this.id; $(document).on("submit", "form", function (event) { event.preventDefault(); var offer = $("#offer1").val(); var deliveryDate = $("#date1").val(); var offerJSON = formToJSON(offer,deliveryDate,orderID); $.ajax({ type: "POST", url: "http://localhost:8081/suppliers/changeoffer", dataType: "json", contentType: "application/json", data: offerJSON, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function () { alert("success"); window.location.href = "supplier.html"; }, error: function (error) { alert(error); } }); }); }); $(document).on('click', '.btnFilter', function () { //var s = document.getElementById('selection'); //var status=s.value; var status=$("#selection").val(); var statusJSON=formToJSON1(status); $('#orders tbody').empty(); $.ajax({ type: "POST", url: "http://localhost:8081/suppliers/filter", dataType: "json", contentType: "application/json", data: statusJSON, beforeSend: function(xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS : ", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; row += "<td>" + data[i]['id'] + "</td>"; row += "<td>" + data[i]['adminEmail'] + "</td>"; row += "<td>" + data[i]['pharmacyName'] + "</td>"; row += "<td>" + data[i]['pharmacyAddress'] + "</td>"; row += "<td>" + data[i]['dateDeadline'] + "</td>"; row += "<td>" + data[i]['statusSupplier'] + "</td>"; row += "<td>" + data[i]['offer'] + "</td>"; if(data[i]['statusSupplier']==='odobrena'){ var btn = "<button disabled>Ponuda je obradjena</button>"; } else if(data[i]['statusSupplier']==='odbijena'){ var btn = "<button disabled>Ponuda je obradjena</button>"; } else if ( data[i]['offer']==0) { var btn = "<button class='btnGiveOffer' id = " + data[i]['id'] + ">Kreiraj ponudu</button>"; } else { var btn = "<button class='btnChangeOffer' id = " + data[i]['id'] + ">Izmeni ponudu</button>"; } row += "<td>" + btn + "</td>"; $('#orders').append(row); } }, error: function (data) { console.log("ERROR : ", data); } }); }); function formToJSON1(status) { return JSON.stringify( { "status": status } ); }; function formToJSON(offerPrice,deliveryDate,orderID,supplier) { return JSON.stringify( { "offerPrice": offerPrice, "deliveryDate": deliveryDate, "orderID": orderID, } ); };
import React from 'react'; import { Route,IndexRoute } from 'react-router'; let Inicio = require('./page/Inicio/inicio.jsx'); let Equipo = require('./page/equipo/indexAlta.jsx'); let Site = require('./page/site/altaSite.jsx'); let Posicion = require('./page/posicion/indexAlta.jsx'); let Index = require("./index.jsx"); module.exports = ( <Route path="/" component={Index}> <IndexRoute component={Inicio} /> <Route path="equipo" component={Equipo} /> <Route path="site" component={Site} /> <Route path="posicion" component={Posicion} /> </Route> );
/* * @Description: 时间格式化 * @version: 0.1.0 * @Author: wsw * @Date: 2018-12-25 22:12:22 * @LastEditors: wsw * @LastEditTime: 2019-03-18 15:54:19 */ function formatDate (date, fmt) { // author: meizz var zArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'] var o = { 'M+': date.getMonth() + 1, // 月份 'd+': date.getDate(), // 日 'h+': date.getHours(), // 小时 'm+': date.getMinutes(), // 分 's+': date.getSeconds(), // 秒 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 'S': date.getMilliseconds(), // 毫秒 'z': zArr[date.getDay()] // 周 } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } } return fmt } function toDotNetString (date) { var str = `/Date(${date.getTime()}+0800)/` return str } function convertDotNetString2Date (dateStr) { var T, tz, off var dobj = dateStr.match(/(\d+)|([+-])|(\d{4})/g) T = parseInt(dobj[0]) tz = dobj[1] off = dobj[2] if (off) { off = parseInt(off.substring(0, 2), 10) * 3600000 + parseInt(off.substring(2), 10) * 600000 if (tz === '-') off *= -1 } else { off = 0 } return new Date(T) } function convertDbDate (date, fmt) { if (!date) return '' if (typeof date === 'string') { date = date.replace(new RegExp(/-/gm), '/') } let time = new Date(date) return formatDate(time, fmt) } function convertCurrentDate (fmt) { if (!fmt) return '' let time = new Date() return formatDate(time, fmt) } function AddDays (date, value) { date.setDate(date.getDate() + value) return date } function AddMonths (date, value) { date.setMonth(date.getMonth() + value) return date } function AddYears (date, value) { date.setFullYear(date.getFullYear() + value) return date } export default { formatDate, convertDbDate, toDotNetString, convertDotNetString2Date, convertCurrentDate, AddDays, AddMonths, AddYears }
//Utils const mongoHandler = require('../utils/mongo-handler'); import { initAdminRole, initOperatorRole, initOperatorUser, initPermissions, initRoles, initRootUser, initSupervisorRole, initSupervisorUser } from "../../src/services/InitService"; describe("InitService", () => { beforeAll(async () => { await mongoHandler.connect() }); afterAll(async () => { await mongoHandler.clearDatabase(); await mongoHandler.closeDatabase(); }) test('InitRoles', async () => { await initPermissions() let result = await initRoles() expect(result).toHaveProperty('rolesCreated') expect(result).toHaveProperty('rolesUpdated') }); })
const initState = { team: {squad: []}, isLoading: true, } const detailReducer = (state=initState, action) => { switch(action.type){ case "GET_DETAIL": return {...state, team: action.payload.team, isLoading: false } case "LOADING_DETAIL": return { ...state, isLoading: true, } default: return {...state} } } export default detailReducer;
import React, { Component } from 'react'; import axios from 'axios'; import { FlexContainer, SecondaryTitle, FormElm, InputElm, SmallText, ErrorText } from '../styledComponents/styledComponents'; import SubmitBtn from '../components/SubmitBtn/SubmitBtn'; class FibPage extends Component { state = { seenIndexes: [], values: {}, index: '', errorMsg: '' }; componentDidMount = () => { this.fetchValues(); this.fetchIndexes(); }; fetchValues = async () => { const values = await axios.get('/api/values/current'); this.setState({ values: values.data }); }; fetchIndexes = async () => { const seenIndexes = await axios.get('/api/values/all'); this.setState({ seenIndexes: seenIndexes.data, }); }; handleSubmit = e => { e.preventDefault(); const indexToCheck = this.state.index; const submittedIndexs = Object.keys(this.state.values); if (!indexToCheck) { return this.setState({ errorMsg: 'Missing index, please submit a value.'}); } else if (submittedIndexs.includes(indexToCheck)) { return this.setState({ index: '', errorMsg: 'Please see previous results.'}); } else if (indexToCheck > 40) { return this.setState({ index: '', errorMsg: 'Max allowed index is 40.'}); } else if (indexToCheck <= 40) { return this.addIndex(indexToCheck); } else { return this.setState({ errorMsg: 'Missing information please try again.'}); } }; addIndex = async (index) => { try { await axios.post('/api/values/add', { index: index, }); this.setState({ index: '', errorMsg: '' }); this.fetchValues(); this.fetchIndexes(); } catch (err) { console.log(err) if (err.response && err.response.data) { console.log(err.response.data) this.setState({ errorMsg: err.response.data.message }) } else { this.setState({ errorMsg: err.message }) } } }; renderSeenIndexes = () => { return this.state.seenIndexes.length ? this.state.seenIndexes.map(({ number }) => number).join(', ') : 'Submit your first index to start'; }; renderValues = () => { const entries = []; for (let key in this.state.values) { entries.push( <p key={key}> For index {key} I calculated {this.state.values[key]} </p> ); } return entries; }; renderError =() => { return this.state.errorMsg ? <ErrorText>{ this.state.errorMsg }</ErrorText> : null; }; render() { return ( <FlexContainer> <SecondaryTitle>Enter your index</SecondaryTitle> <FormElm onSubmit={this.handleSubmit} > <InputElm type='text' label='enter index' value={ this.state.index } onChange={e => this.setState({index: e.target.value })} /> {this.renderError()} <SmallText>( Max 40 )</SmallText> <SubmitBtn>Submit</SubmitBtn> </FormElm> <section> <SecondaryTitle>Submitted so far:</SecondaryTitle> <p>{this.renderSeenIndexes()}</p> </section> <section> <SecondaryTitle>Previous results:</SecondaryTitle> {this.renderValues()} </section> </FlexContainer> ) } }; export default FibPage;
i18n_es_texts = { "values": { "server_current_state": "Estado", "connections": "Conexiones", "uptime": "uptime", "start_time": "Online desde", "received_messages": "Mensajes recibidos", "received_messages_per_second": "Mensajes recibidos (por seg.)", "sent_messages": "Mensajes enviados", "sent_messages_per_second": "Mensajes enviados (por seg.)", "commands_waiting": "Órdenes en cola", "queries_waiting": "Preguntas en cola", "go_routines": "Go routines activas", "system_memory": "Memoria de sistema", "allocated_memory": "Memoria alojada", "heap_allocated_memory": "Memoria alojada en la pila", "secs": "segundos", "payload_to_send":"Mensaje a enviar", "send_as_command":"Enviar como órden", "send_as_query":"Enviar como pregunta", "responses": "Respuestas", "system_status": "Estado del sistema", "connected_devices": "Dispositivos conectados", "device_status": "Estado del dispositivo", "device_control": "Control del dispositivo", "last_connection": "Última conexión", "sse_subscribers": "Suscritos a SSE", "view_device": "Ver", "actions": "Acciones", "name": "Nombre", } };
/* * @Author: anchen * @Date: 2017-06-26 16:17:17 * @Last Modified by: anchen * @Last Modified time: 2017-06-30 09:51:26 */ document.getElementsByTagName("html")[0].style.fontSize=document.documentElement.clientWidth/30+"px";
import { createAction } from 'helpers/saga'; import * as types from './types'; import { authService } from 'services'; export const authenticationActions = { login: (user) => createAction(types.LOGIN_ASYNC.PENDING, { user }), loginSuccess: (user) => createAction(types.LOGIN_ASYNC.SUCCESS, { user }), loginError: (error) => createAction(types.LOGIN_ASYNC.ERROR, { error }), currentUser: () => createAction(types.CURRENT_USER_ASYNC.PENDING), currentUserSuccess: (user) => createAction(types.CURRENT_USER_ASYNC.SUCCESS, { user }), currentUserError: (error) => createAction(types.CURRENT_USER_ASYNC.ERROR, { error }), logout: logout } function logout() { authService.logout(); return { type: types.LOGOUT.REQUEST }; }
import React, { useEffect } from 'react'; import { useDispatch, shallowEqual, useSelector } from 'react-redux'; import { SET_API_STATE } from '../actions/file'; import { GetSettings } from '../utils/db'; const selector = (state) => { return { dataApi: state.file.dataApi, apiState: state.file.apiState, }; }; export const AutoLogin = () => { const { dataApi, apiState } = useSelector(selector, shallowEqual); const dispatch = useDispatch(); const doLogin = async () => { const settings = await GetSettings(); let loginResult; if (settings) { if (settings.token) { // already has token loginResult = await dataApi.LoginWithToken(settings.token); } if ( (!loginResult || !loginResult.ok) && settings.user && settings.password ) { console.log(`auto login with ${settings.user}, ${settings.password}`); loginResult = await dataApi.Login(settings.user, settings.password); } } if (loginResult && loginResult.ok) { dispatch({ type: SET_API_STATE, apiState: 'initialized', }); } }; useEffect(() => { if (apiState === 'login-needed') { doLogin(); } }, [apiState]); return null; }; export default AutoLogin;
import React from 'react'; import {Link} from 'react-router-dom'; import {deleteSubject, getAllSubjects} from '../../../services/ref-data/subject'; import './style.css'; import {SubjectTableHeaderRow,SubjectTableBodyRow} from './subject-table-row'; export default class SubjectComponent extends React.Component{ state={ message:'', isError:false, subjects:[], } componentDidMount = ()=>{ getAllSubjects() .then((data)=>{ this.setState({subjects:data.subjects}); }); } onDoubleClick = (id)=>{ this.props.history.push(`${this.props.match.url}/edit-subject/`+id); } onDelete = (id)=>{ deleteSubject(id).then((data)=>{ this.setState({message:data.message}); }) .catch(error =>{ this.setState({isError:true,message:error.message}); }); } render(){ window.scrollTo(0,0); return <div className="container-fluid subject-manager-component"> <div className="row heading-row"> <div> <Link className="btn btn-primary" to={`${this.props.match.url}/add-subject`}>Add New</Link> </div> <div className="flex-grow-1 text-center"> Subject Manager </div> </div> <div className="row justify-content-center"> <div className="text-center"> {this.state.message? <div className={"alert "+ (this.state.isError?' alert-danger':'alert-success') }> {this.state.message} </div>:''} </div> </div> <div className="row subject-manager-table"> <div className="col"> <table className="table table-hover"> <thead> <SubjectTableHeaderRow /> </thead> <tbody> {Array.isArray(this.state.subjects)?this.state.subjects.map((subject,index)=>{ return <SubjectTableBodyRow key={index} subject={subject} onDelete = {this.onDelete} onDoubleClick={this.onDoubleClick} />; }):<tr><td></td></tr>} </tbody> </table> </div> </div> </div>; } }
const minimatch = require('minimatch') const loaderUtils = require('loader-utils') const path = require('path') const fs = require('fs') function isArray (variable) { return variable instanceof Array } function isObject (variable) { return typeof variable === 'object' && !isArray(variable) } module.exports = function (source) { if (this.cacheable) { this.cacheable() } const options = loaderUtils.getOptions(this) const template = options.template if (template === undefined) return source const includes = options.includes || [] const symbols = options.symbols || {} symbols.source = options.source || source const absolutePath = this.resourcePath const relativePath = path.relative(this.rootContext, absolutePath) if (minimatch(relativePath, '*.js')) { source = template.replace('$_source', source) } includes.forEach(include => { if (minimatch(relativePath, include) || minimatch(absolutePath, include)) { let reArr = [] Object.keys(symbols).forEach(symbol => { const symbolValue = symbols[symbol] reArr.push(`(\\$_${symbol})`) if (isObject(symbolValue)) { let path = symbolValue.path symbols[symbol] = fs.readFileSync(path).toString() } }) let re = new RegExp(reArr.join('|'), 'g') source = template.replace(re, match => { return symbols[match.substr(2)] }) } }) return source }
const data = [ { country: "AR", sum: 80, __typename: "SessionsByCountry" }, { country: "BR", sum: 50, __typename: "SessionsByCountry" }, { country: "UY", sum: 25, __typename: "SessionsByCountry" } ] export default data
const { arrayBinarySearch } = require('../challenges/arrayBinarySearch/array-binary-search'); describe('arrayBinarySearch', () => { it('should find the index of a value in an array or return -1', () => { expect(arrayBinarySearch([4, 8, 15, 16, 23, 42], 15)) .toEqual(2); expect(arrayBinarySearch([11, 22, 33, 44, 55, 66, 77], 90)) .toEqual(-1); const bigArray = []; for(let i = 0; i < 100; i++){ bigArray[i] = i; } expect(arrayBinarySearch(bigArray, 12)) .toEqual(12); const biggerArray = []; for(let i = 0; i < 1000; i++){ biggerArray[i] = i; } expect(arrayBinarySearch(biggerArray, 900)) .toEqual(900); const biglyArray = []; for(let i = 0; i < 10000; i++){ biglyArray[i] = i; } expect(arrayBinarySearch(biglyArray, 9000)) .toEqual(9000); const chonkingArray = []; for(let i = 0; i < 100000; i++){ chonkingArray[i] = i; } expect(arrayBinarySearch(chonkingArray, 90000)) .toEqual(90000); expect(arrayBinarySearch(chonkingArray, 999999999999)) .toEqual(-1); }); });
var username; var myname = "Bazil Farooq"; var message ="Hello World" alert(message); var name = "Bazil Farooq" var age = "I am 20 years old." var bio = "Student in University." alert(name) alert(age) alert(bio) var food = "Pizza" alert(food+"\n"+food[0]+food[1]+food[2]+food[3]+"\n"+food[0]+food[1]+food[2]+"\n"+food[0]+food[1]+"\n"+food[0]) var email = "mianbazil21@gmail.com" alert("My email is "+email) var book = "A smarter way to learn JavaScript" alert("I am trying to learn from the book "+book) var str = "▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬" alert(str)
/** * Created by Amine on 27/11/2016. */ $(document).ready(function () { $('button').click(function () { if($('#commentaire').val() === "Idiot" || $('#commentaire').val() === "Débile" ||$('#commentaire').val() === "Ignare" ){ alert("Restez tranquille sinon vous serez supprimer, merci") } }) })
import React from "react"; import { StyledUserProfile } from "./UserProfile.styled"; import UserProfileForm from "../Form/UserProfileForm"; import PasswordResetForm from "../Form/PasswordResetForm"; export default function UserProfile() { return ( <StyledUserProfile> <div className="user-detail"> <UserProfileForm /> </div> <div className="user-password"> <PasswordResetForm /> </div> </StyledUserProfile> ); }
import React, { Component } from 'react'; import { Layout } from 'antd'; const { Header } = Layout; export default class Headers extends Component { render() { return (<Header> <h2 className="_app_name">Agent管理平台</h2> </Header> ); } }
/** * Created by Adam on 2016-03-25. */ (function (){ "use strict"; angular.module('blog') .controller('BlogController', BlogController); function BlogController($http,$scope, $routeParams, $timeout, $log, $location, $q, $rootScope, Notification){ var bc = this; bc.getWelcomePost = function(){ $http.get("api/blogs/" + $routeParams.username + "/welcome") .then(function(response) { bc.post = response.data; $timeout( function() { //$log.info('content loaded'); ckeditorElementsInlineScan(); },0); }, function (reason){ $location.url('/404'); }); }; //if (angular.isDefined($routeParams.username)) //bc.greeting = {id: $routeParams.username, content: 'Hello World!'}; if (angular.isDefined($routeParams.username)) bc.getWelcomePost(); bc.ckeditorSaveBlogChanges =function(data,type){ if(type == "blogTitle"){ bc.post.title = data; }else if(type == "blogSubTitle"){ bc.post.subtitle = data; }else if(type == "blogAbout1"){ bc.post.about1 = data; }else if(type == "blogAbout2"){ bc.post.about2 = data; } //console.log(JSON.stringify($rootScope.username)); if($rootScope.username ==$routeParams.username ) $http.put('api/action/update/' + $routeParams.username, bc.post) .then( function(response){ if(response.status != 304){ Notification.success('Welcome Post has been updated!'); } return response.data; }, function(errResponse){ if(errResponse.status != 304) Notification.error('Error while updating the welcome post. Please log in or try again.'); return $q.reject(errResponse); } ); else Notification.error('Error while updating the welcome post. Please log in and try again.'); //alert(JSON.stringify(bc.post)); //console.log(JSON.stringify($routeParams.username)); } bc.submitForm =function(){ if(bc.form.name == null || bc.form.email == null || bc.form.message == null){ $(".errorNg").css('color', 'red'); }else{ Notification.primary('Please wait. Sending your E-Mail...'); $http.put('api/mail/' + $routeParams.username, bc.form) .then( function(response){ Notification.success('E-Mail has been sent!!'); }, function(errResponse){ Notification.error('E-Mail server does not respond. Please try again later.'); } ); } } } })();
import React, {useState} from 'react'; const ErrorExample = () => { const [title,setTitle] = useState('Hello World'); const changeText = () => { // title = "Hello World\n"; ( title === "Hello World" ) ? setTitle("Random Title") : setTitle("Hello World"); // console.log( title ); }; return( <React.Fragment> <h2>{title}</h2> <button type="button" className="btn" onClick={changeText}>Change Text</button> </React.Fragment> ) }; export default ErrorExample;
import React from 'react' import { Router, Route, Switch } from 'dva/router' import All from './routes/all/all' import Active from './routes/active/active' import Completed from './routes/completed/completed' function RouterConfig ({ history }) { return ( <Router history={history}> <Switch> <Route path="/all" exact component={All} /> <Route path="/active" exact component={Active} /> <Route path="/completed" exact component={Completed} /> <Route component={All} /> </Switch> </Router> ) } export default RouterConfig
'use strict'; var HomeKitGenericService = require('./HomeKitGenericService.js').HomeKitGenericService; var util = require("util"); var sat; var curLevel=0; var lastLevel=0; var onc; function HomeMaticHomeKitRGBWService(log,platform, id ,name, type ,adress,special, cfg, Service, Characteristic) { HomeMaticHomeKitRGBWService.super_.apply(this, arguments); } util.inherits(HomeMaticHomeKitRGBWService, HomeKitGenericService); HomeMaticHomeKitRGBWService.prototype.createDeviceService = function(Service, Characteristic) { var that = this; var lightbulb = new Service.Lightbulb(this.name); this.services.push(lightbulb); this.onc = lightbulb.getCharacteristic(Characteristic.On) .on('get', function(callback) { that.query("1:LEVEL",function(value) { if (value==undefined) { value = 0; } that.state["LAST"] = value; if (callback) callback(null,value>0); }); }.bind(this)) .on('set', function(value, callback) { var lastLevel = that.state["LAST"]; if (lastLevel == undefined) { lastLevel = -1; } if (((value==true) || ((value==1))) && ((lastLevel<1))) { that.state["LAST"]=100; that.command("set","1:LEVEL" , 100); } else if ((value==0) || (value==false)) { that.state["LAST"]=0; that.command("set","1:LEVEL" , 0); } else if (((value==true) || ((value==1))) && ((lastLevel>0))) { // Do Nothing just skip the ON Command cause the Dimmer is on } else { that.delayed("set","1:LEVEL" , lastLevel,2); } callback(); }.bind(this)); var brightness = lightbulb.getCharacteristic(Characteristic.Brightness) .on('get', function(callback) { that.query("1:LEVEL",function(value){ that.state["LAST"] = (value*100); if (callback) callback(null,value); }); }.bind(this)) .on('set', function(value, callback) { var lastLevel = that.state["LAST"]; if (value!=lastLevel) { if (value==0){ // set On State if ((that.onc!=undefined) && (that.onc.updateValue!=undefined)) {this.onc.updateValue(false,null);} } else { if ((that.onc!=undefined) && (that.onc.updateValue!=undefined)) {this.onc.updateValue(true,null);} } that.state["LAST"] = value; that.isWorking = true; that.delayed("set","1:LEVEL" , value,5); } if (callback) callback(); }.bind(this)); that.currentStateCharacteristic["1:LEVEL"] = brightness; brightness.eventEnabled = true; this.remoteGetValue("1:LEVEL"); var color = lightbulb.addCharacteristic(Characteristic.Hue) .on('get', function(callback) { that.query("2:COLOR",function(value){ if (callback) callback(null,value); }); }.bind(this)) .on('set', function(value, callback) { if (that.sat < 10) { value = 361.809045226; } that.delayed("set","2:COLOR" ,value,100); callback(); }.bind(this)); that.currentStateCharacteristic["2:COLOR"] = color; color.eventEnabled = true; lightbulb.addCharacteristic(Characteristic.Saturation) .on('get', function(callback) { that.query("2:COLOR",function(value){ var ret = (value==200)?0:100; callback(null,ret); }); }) .on('set', function(value, callback) { that.sat = value; if (value<10) { that.delayed("set","2:COLOR" ,361.809045226,100); } callback(); }) this.remoteGetValue("2:COLOR"); } HomeMaticHomeKitRGBWService.prototype.endWorking=function() { this.remoteGetValue("1:LEVEL"); } module.exports = HomeMaticHomeKitRGBWService;
export default { API_HOST: 'https://qa.example.com/' };
export default [ { prop: 'name', label: '消息名称', render(h) { return <i-input> v-model={this.model}></i-input> } }, { prop: 'status', label: '状态', render(h) { const options = [ <i-option>使用中</i-option>, <i-option>停止使用</i-option> ] return <i-select>{options}</i-select> } }, { prop: 'deviceId', label: '执行运营号', render(h) { return <i-input> v-model={this.model}></i-input> } } ]
const editEl = document.body.querySelector(".fa-edit"); const deleteEl = document.body.querySelector(".fa-trash-alt"); const textCreate = document.body.querySelector("#notes-create"); const btnCreateEl = document.body.querySelector(".btn-create"); const notesContainer = document.body.querySelector(".notes-container"); const container = document.createElement("div"); container.setAttribute("class", "notes-container-wrapper"); const getNotesLs = () => { const res = JSON.parse(localStorage.getItem("notes")); return res == null ? [] : res; }; const editMode = (id) => { const btnSave = document.querySelectorAll(".btn-save"); const textUpdate = document.body.querySelectorAll("#notes-update"); btnSave[id - 1].classList.toggle("hidden"); textUpdate[id - 1].toggleAttribute("disabled"); }; const deleteMode = (id) => { const newData = getNotesLs().filter((item) => item.id !== id); localStorage.setItem("notes", JSON.stringify(newData)); showNotes(getNotesLs()); }; const updateMode = (id) => { const btnSave = document.querySelectorAll(".btn-save"); const currentNotes = getNotesLs(); const index = getNotesLs().findIndex((item) => item.id == id); const textUpdate = document.body.querySelectorAll("#notes-update"); const newData = { id, value: textUpdate[id - 1].value, }; currentNotes.splice(index, 1, newData); textUpdate[id - 1].setAttribute("disabled", "true"); btnSave[id - 1].classList.add("hidden"); localStorage.setItem("notes", JSON.stringify(currentNotes)); }; const showNotes = (data) => { let HTMLnotes = ""; if (data.length > 0) { data.map((item) => { HTMLnotes += ` <div class="notes-container"> <div> <i onclick=editMode(${item.id}) class="fas fa-edit"></i> <i onclick=deleteMode(${item.id}) class="fas fa-trash-alt"></i> </div> <textarea name="notes" disabled id="notes-update">${item.value}</textarea> <button onclick=updateMode(${item.id}) class="btn-save hidden" type="submit">Save</button> </div>`; }); } else { HTMLnotes = `<div class="notes-container"> <p class="placeholder">No notes found </p> </div>`; } container.innerHTML = HTMLnotes; }; document.body.appendChild(container); btnCreateEl.addEventListener("click", () => { let notesData = getNotesLs(); const data = { id: notesData.length + 1, value: textCreate.value, }; localStorage.setItem("notes", JSON.stringify([...notesData, data])); showNotes(getNotesLs()); textCreate.value = ""; }); showNotes(getNotesLs());