text
stringlengths
7
3.69M
"use strict"; var EVEoj = require("../../src/EVEoj.js"); describe("core", function() { it("has expected version", function() { expect(EVEoj.VERSION).toEqual("0.2.0"); }); });
function BoardWall(boardSize) { this.parts = []; this.size = boardSize; this.init(); }; BoardWall.prototype.init = function () { for(var i = -1; i < this.size + 1; i++){ for(var j = -1; j < this.size + 1; j++){ if(j == -1 || j == this.size){ this.parts.push({x : i, y : j}) }else if(i == -1 || i == this.size){ this.parts.push({x : i, y : j}) } } } }; module.exports = BoardWall;
const chalk = require("chalk"); const redUnderline = chalk.red.underline; const handleNotFound = (router) => { router.use((req, res, next) => { res.status(404).json({ errors: [ { msg: `Couldn't find the specified route ${req.url}`, status: "404", }, ], }); next(); }); }; const handlerServerError = (router) => { router.use((err, req, res, next) => { res.statusCode = 500; console.error(redUnderline(`${err}`)); res.json({ errors: [ { msg: "Oops, Something went wrong from our end.", status: "500", }, ], }); next(err); }); }; module.exports = [handleNotFound, handlerServerError];
'use strict' const path = require('path') const {invokeMap} = require('lodash') const shouldPurgeOnStart = {force: require('../../config').db.shouldPurgeOnStart} const {DB_HOST, DB_PORT, DB_BASE, DB_USER, DB_PASS} = process.env const Sequelize = require('sequelize') const sequelize = new Sequelize(DB_BASE, DB_USER, DB_PASS, { dialect: 'postgres', host: DB_HOST, port: DB_PORT, }) require('pg').defaults.parseInt8 = true const models = { Transaction: sequelize.import(path.join(__dirname, 'transaction')), Account: sequelize.import(path.join(__dirname, 'account')), } invokeMap(models, 'associate', models) models.sequelize = sequelize module.exports = (async () => { await sequelize.sync(shouldPurgeOnStart) Object.assign(module.exports, models) return models })()
// replace movies array with real list of titles from csv // var movies = ["Reservoir Dogs","Lord of the Rings","The Room","Jurassic Park","Jaws"]; var movies = []; var movieIndices = {}; const numInputs = 5; d3.text("static/movie_titles.csv",(e,r)=>{ if (e) console.log(e); var data = d3.csvParseRows(r) console.log(data[0]); movies = data.map(d=>d[2]) data.forEach(d=>{movieIndices[d[2]] = +d[0]}); for (var i=1; i<=numInputs; i++){ autocomplete(document.getElementById(`movieInput${i}`), movies); } }) function formHtml(num){ return `<div class="autocomplete"> <input id="movieInput${num}" type="text" name="movie${num}" placeholder="Type a Movie"> </div> Your Rating: <select class="custom-select" id="rating${num}"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br>` } var $form = d3.select("#movieRatingsForm"); for (var i=1; i<=numInputs; i++){ $form.append("div").html(formHtml(i)); } var $responseText = d3.select("#textResponse"); var $responseList = d3.select("#listResponse"); d3.select("#moviesSubmit").on("click",function(event){ d3.event.preventDefault(); titles = []; ratings = []; for (var i=1; i<=numInputs; i++){ titles.push(d3.select(`#movieInput${i}`).node().value.trim()); ratings.push(+d3.select(`#rating${i}`).node().value); } console.log(titles); // dummyResponse($responseText, titles, ratings); recommend($responseText, $responseList, titles, ratings); }) function recommend($div, $uldiv, tList, rList){ console.log(`'/predict/${getEndPoint(tList,rList)}'`) $div.text(`Calculating movies...`); // Assuming the Flask endpoint returns a JSON array of titles d3.json(`/predict/${getEndPoint(tList,rList)}`,(e,d)=>{ if (e) console.warn(e); console.log(d); $div.text(`Based on your input, we recommend the movies:`); recList($uldiv, d); }) } function recList($div, mList){ // console.log($div.attr("id")) $div.html("").append("ul").selectAll("li").data(mList).enter().append("li").text(d=>movies[d-1]); } function getEndPoint(tList, rList){ var endpoint = "" // console.log(tList.map((d,i)=>[movieIndices[d],rList[i]])); tList.forEach((d,i)=>{ var mi = movieIndices[d]; // Currently this returns -1 for an unknown movie input. if (!mi) { mi = -1; console.log(`Didn't recognize movie "${d}"`); } endpoint+=`${mi}:${rList[i]},`; }) return endpoint } function dummyResponse($div, tList, rList){ arr = []; tList.forEach(d=>{arr.push(...d.split(" "))}); // console.log(movieIndices[list[0]]); arr = arr.sort(d=>(Math.random()-0.5)); output = ""; arr.forEach(d=>{output += d + " "}) // console.log(arr) $div.text(`Based on your input, we think you'll like "${output}". Siskel and Ebert gave it ${d3.mean(rList)} thumbs up.`) console.log(`I'ma scrape some datums from '/predict/${getEndPoint(tList,rList)}'!`); }
var net = require('net'); var util = require('util'); var client = net.connect(1337, function() { console.log('client connected'); var msg = { action: 'hello', platform: 'iphone' } client.write(JSON.stringify(msg)); }); client.on('data', function(data) { var jss =JSON.parse(data.toString()); console.log(util.inspect(jss.data)); }); client.on('end', function() { console.log('client disconnected'); });
/*$("#main").append("Gayle James");*/ /*var name = "Gayle James"; var formattedName = HTMLheaderName.replace("%data%", name); $("#header").prepend(formattedName); var role = "Front End Web Developer"; var formattedRole = HTMLheaderRole.replace("%data%", role); $("#header").prepend(formattedRole);*/ /*var mobile = "972-999-9999"; var formattedMobile = HTMLmobile.replace("%data%", mobile); $("#header").append(formattedMobile); var email = "gayleajames@sbcglobal.net"; var formattedEmail = HTMLemail.replace("%data%", email); $("#header").append(formattedEmail);*/ var bio = { "name" : "Gayle James", "role" : "Front End Web Developer", "contacts" :{ "mobile": "972-999-9999", "email": "gayle@gmail.com", "github": "gjam", "twitter": "@gjam", "location": "Plano" }, "welcomeMessage": "Great to have an interactive resume", "skills": [ "web developer", "Quality Assurance", "Application Support" ], "bioPic": "gayle122614.jpg" }; var formattedName = HTMLheaderName.replace("%data%", bio.name); var formattedRole = HTMLheaderRole.replace("%data%", bio.role); $("#header").prepend(formattedRole); $("#header").prepend(formattedName); var formattedMobile = HTMLmobile.replace("%data%",bio.contacts.mobile); $("#topContacts").append(formattedMobile); var formattedEmail = HTMLemail.replace("%data%",bio.contacts.email); $("#topContacts").append(formattedEmail); var formattedGitHub = HTMLgithub.replace("%data%", bio.contacts.github); $("#topContacts").append(formattedGitHub); var formattedTwitter = HTMLtwitter.replace("%data%", bio.contacts.twitter); $("#topContacts").append(formattedTwitter); var formattedLocation= HTMLlocation.replace("%data%", bio.contacts.location); $("#topContacts").append(formattedLocation); var formattedPic = HTMLbioPic.replace("%data%", bio.bioPic); var formattedWelcome = HTMLWelcomeMsg.replace("%data%", bio.welcomeMessage); var formattedfooterMobile = HTMLmobile.replace("%data%",bio.contacts.mobile); $("#footerContacts").append(formattedfooterMobile); var formattedfooterEmail = HTMLemail.replace("%data%",bio.contacts.email); $("#footerContacts").append(formattedfooterEmail); var formattedfooterGitHub = HTMLgithub.replace("%data%", bio.contacts.github); $("#footerContacts").append(formattedfooterGitHub); var formattedfooterTwitter = HTMLtwitter.replace("%data%", bio.contacts.twitter); $("#footerContacts").append(formattedfooterTwitter); var formattedfooterLocation= HTMLlocation.replace("%data%", bio.contacts.location); $("#footerContacts").append(formattedfooterLocation); var formattedPic = HTMLbioPic.replace("%data%", bio.bioPic); var formattedWelcome = HTMLWelcomeMsg.replace("%data%", bio.welcomeMessage); $("#header").append(formattedPic); $("#header").append(formattedWelcome) /*$("#main").append(funThoughts); var bio { "name": "Gayle" "role": "Front end web developer" "contactinfo": 9729657451 "URL":"myphotourl" } */ var education ={ "schools":[ { "name": "University of Texas El Paso", "location": "El Paso", "degree": "BBA", "major":["Computer Information Systems"] }, { "name": "University of Phoenix", "location": "Phoenix", "degree": "Masters", "major": ["Information Systems"] } ] } var work = { "jobs": [ { "employer": "Southwestern Bell Telephone", "title": "Analyst", "location":"St Louis", "dates":"1990-1996", "description": "Supported and coded an Error Correction System running on Mainframe. I utilized COBOL and JCL to run jobs, write code and trouble-shoot" }, { "employer": "Cingular Wireless", "title": "Production support Analyst", "location":"Richardson", "dates":"2001-2006", "description": "I supported the billing system using Unix and ORACLE to access file. Wrote quick and dirty shell scripts to manipulate files . Used ORACLE to obtain and fix billing error. This in turn enabled the calls to be billed and revenue brought into the company, preventing revenue loss" } ] } if (bio.skills.length > 0) { $("#header").append(HTMLskillsStart)}; var formattedSkill = HTMLskills.replace("%data%", bio.skills[0]); $("#skills").append(formattedSkill); formattedSkill = HTMLskills.replace("%data%", bio.skills[1]); $("#skills").append(formattedSkill); formattedSkill = HTMLskills.replace("%data%", bio.skills[2]); $("#skills").append(formattedSkill); function displayWork() { for (job in work.jobs) { $("#workExperience").append(HTMLworkStart); var formattedEmployer = HTMLworkEmployer.replace ("%data%",work.jobs[job].employer); var formattedTitle = HTMLworkTitle.replace ("%data%",work.jobs[job].title); var formattedEmployerTitle = formattedEmployer + formattedTitle; $(".work-entry:last").append(formattedEmployerTitle); var formattedDates = HTMLworkDates.replace ("%data%",work.jobs[job].dates); $(".work-entry:last").append(formattedDates); var formattedDescription = HTMLworkDescription.replace ("%data%",work.jobs[job].description); $(".work-entry:last").append(formattedDescription); } } displayWork(); function displayEducation() { for (school in education.schools) { $("#education").append(HTMLschoolStart); var formattedschoolName= HTMLschoolName.replace ("%data%",education.schools[school].name); $(".education-entry:last").append(formattedschoolName); var formattedschoolLocation= HTMLschoolLocation.replace ("%data%",education.schools[school].location); $(".education-entry:last").append(formattedschoolLocation);} } displayEducation(); //for ( $("#mapDiv").append(googleMap); /*$(document).click(function(loc) { // your code goes here });*/
import { withRouter } from 'react-router'; const MainContentContainer = BaseComponent => withRouter(BaseComponent); export default MainContentContainer;
const config = { port: 80, proxy: { common: 'http:localhost:3000', }, cookie: { prefix: 'xxx_', domain: '.xxx.com', }, cdn: '', }; config.api = {}; const path = require('path'); Object.keys(config.proxy || {}).forEach((key) => { config.api[key] = path.join(config.root || '/', 'api', key); }); module.exports = Object.freeze(config);
import User from '../models/user.js' import Conversation from '../models/conversation.js' import mongoose from 'mongoose' const ObjectId = mongoose.Types.ObjectId export default () =>({ userConnection: async function(socket,connected=true){ console.log(`user ${connected?'connection':'disconnection'}`,socket.user.name) await User.findByIdAndUpdate(socket.user.id,{isActive:connected}).catch(err => console.log(err)) const convs = await Conversation.find({users:ObjectId(socket.user.id)},'_id').catch(err => console.log(err)) socket.to([...convs.map(conv=>conv._id+"")]).emit('user-state-change',socket.user.id,connected) }, })
import React from 'react'; import { shallow } from 'enzyme'; import Event from '../Event'; describe('<Event /> component', () => { let EventWrapper; const events = { created: 1564129835000, duration: 7200000, id: 'qbmqfryznbjc', name: 'Shut Up & Write!™ Munich', rsvp_limit: 15, date_in_series_pattern: false, status: 'upcoming', time: 1572075000000, local_date: '2019-10-26', local_time: '09:30', rsvp_open_offset: 'PT163H30M', updated: 1564129835000, utc_offset: 7200000, waitlist_count: 11, yes_rsvp_count: 15, venue: { id: 25966475, name: 'Bellevue München', lat: 48.160736083984375, lon: 11.563915252685547, repinned: false, address_1: 'Schleißheimer Str. 142a', city: 'München', country: 'de', localized_country_name: 'Germany' }, } test('click on details should reveal details', () => { let EventWrapper = shallow(<Event event={events}/>); EventWrapper.setState({ showDetails: false }); EventWrapper.find('.details').simulate('click'); expect(EventWrapper.state('showDetails')).toBe(true); }) })
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; class ListItemView extends Component { componentDidMount() { const { viewItem, match } = this.props; viewItem(match.params.name); } render() { const { item } = this.props; if (!item) { return (<div>Loading...</div>); } return ( <div className="view_item"> <Link to="/"> <button type="button">Back</button> </Link> <h2>{ item.name }</h2> <p>{ item.description }</p> </div> ); } } ListItemView.propTypes = { viewItem: PropTypes.func.isRequired, match: PropTypes.object.isRequired, item: PropTypes.object, }; ListItemView.defaultProps = { item: null, }; export default ListItemView;
export default function attendeeProfileService() { const messages = { httpFailure: 'HTTP 요청 실패', }; return { getProfile(attendeeId) { return fetch('http://conference.com/profile').then(function onSuccess(res) { if (res.ok) { return Promise.resolve(res); } else { return Promise.reject(new Error(messages.httpFailure)); } }); }, }; }
import React from 'react'; import { TouchableOpacity,Image,View,Text } from 'react-native'; import styles from './styles'; import props from './props'; const RadioButton=({ containerStyle, checked, onPress, iconSize, iconColor, label, labelSize, labelColor }) => { return ( <View style={styles.root(containerStyle)}> <TouchableOpacity activeOpacity={0.5} style={styles.radioContent()} onPress={onPress}> <Image style={styles.imageRadioButton(iconSize,iconColor)} source={ checked? require('../../Assets/Images/radio.png') : require('../../Assets/Images/unRadio.png') } /> <Text style={styles.label(labelSize,labelColor)}>{label}</Text> </TouchableOpacity> </View> ); }; export default RadioButton; props(RadioButton)
$(function() { var $menu = $(".pure-menu"); var $menuHide = $("#menu-hide"); var $menuShow = $("#menu-show"); var $menuList = $(".pure-menu-list"); $menu.on('mouseover', function() { $menu.css('opacity', 1); }); $menu.on('mouseout', function() { $menu.css('opacity', 0.3); }); $menuHide.click(function() { document.cookie = "hide=1; path=/"; $menuHide.hide(); $menuShow.show(); $menuList.hide(); }); $menuShow.click(function() { document.cookie = "hide=0; path=/"; $menuHide.show(); $menuShow.hide(); $menuList.show(); }); if (document.cookie == "hide=1") { $menuHide.hide(); $menuShow.show(); $menuList.hide(); } else { $menuHide.show(); $menuShow.hide(); $menuList.show(); } });
'use strict'; /* App Module */ angular.module('telugutipsApp', ['ngRoute', 'ngSanitize', 'ngMaterial', 'jm.i18next', 'underscore', 'chitkalu.controllers', 'chitkalu.services', 'chitkalu.cache','telegutipsFilters']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/home', { templateUrl : 'partials/home.html', controller : 'HomeCtrl', controllerAs: 'homeCtrl' }).when('/tips/:cat', { templateUrl : 'partials/tips.html', controller : 'TipsCtrl', controllerAs: 'tipsCtrl' }).when('/tip/detail/:index', { templateUrl : 'partials/tip.html', controller : 'TipCtrl', controllerAs: 'tipCtrl' }).when('/tip/:id', { templateUrl : 'partials/tip.html', controller : 'TipCtrl', controllerAs: 'tipCtrl' }).when('/disclaimer', { templateUrl : 'partials/disclaimer.html', }).otherwise({ redirectTo : '/home' }); } ]) //Global Functions .run(function($rootScope, $log, $mdSidenav, $mdDialog, $location) { //Toggle nav $rootScope.toggleNav = function () { $mdSidenav('navbar') .toggle() .then(function () { $log.debug("toggle navbar is done"); } ) } //Go Back $rootScope.back = function () { window.history.back(); }; //Go Back $rootScope.home = function () { $location.path("/home"); }; //Share App $rootScope.share = function () { window.Firebase.trackEvent("Menu Action", "App Share"); var platform = device.platform; if(platform == 'Android') { window.plugins.socialsharing.share('Try this great Telugu App - ', '1500+ Telugu Tips', 'www/images/banner.png','https://play.google.com/store/apps/details?id=com.smart.droid.telegu.tips'); } else if(platform == "iOS") { $log.debug('IOS App Share'); //window.plugins.socialsharing.share('Try this great Tamil App - ', 'Kuripugal',null,'https://itunes.apple.com/app/id1072440433'); } else { alert('Share not supported for : ' + platform); } } //Rate US $rootScope.rateus = function () { window.Firebase.trackEvent("Menu Action", "App Rating"); var version = device.platform; if(version == "Android") { var url = "market://details?id=com.smart.droid.telegu.tips"; window.open(url,"_system"); } else if(platform == "iOS") { $log.debug('IOS App rate'); //var url = "itms-apps://itunes.apple.com/app/id1072440433"; //window.open(url); } else { alert('Rate Me not supported for : ' + platform); } }; //Feedback $rootScope.feedback = function () { window.Firebase.trackEvent("Menu Action", "App Rating"); //FIXME - Collect Version Dynamically window.plugin.email.open({ to: ['tips2stayhealthy@gmail.com'], subject: 'Feedback on Telegu Tips', body: '', isHtml: true }); }; /* //Feedback $rootScope.disclaimer = function () { window.Firebase.trackEvent("App Displaimer", device.uuid); $mdDialog.show({ contentElement: '#disclaimer', parent: angular.element(document.body) }); }; */ var deviceUUID = device.uuid; //$log.debug("Device Id : " + deviceUUID + " - Test Device : " + testDevice); if(deviceUUID == testDevice) { $rootScope.isTestDevice = true; } }) //Theme configure .config(function($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('pink') .accentPalette('red') .warnPalette('amber'); }); //ng-i18next - use i18next with Angularjs angular.module('jm.i18next').config(['$i18nextProvider', function ($i18nextProvider) { $i18nextProvider.options = { lng: 'te', useCookie: false, useLocalStorage: false, fallbackLng: 'en', resGetPath: 'locales/__lng__/__ns__.json', defaultLoadingValue: '' // ng-i18next option, *NOT* directly supported by i18next }; }]);
import FileManagementPage from '../pages/FileManagementPage' import FileDashboardPage from '../pages/FileDashboardPage' const routes = [ {name: 'FileManagementPage', path: '/file-management', component: FileManagementPage}, {name: 'FileDashboardPage', path: '/file-dashboard', component: FileDashboardPage} ] export default routes;
module.exports = { /** * Customize webpack configuration. */ webpackConfig: { // } }
import GameObject from '../core/gameObject'; import Render from '../render'; class LetterFlashDelete extends GameObject { constructor(name, sign) { super(name); this.lettersSign = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'J', 'K']; this.color = this.lettersSign.findIndex(elem => elem === sign); this.addRender(new Render('../images/letterFlashDelete04.png')); this.render.setZIndex(200); this.render.setSize(80, 300); this.render.setSource(this.color*80, 0); // this.render.setSource(0, 0); this.opacityDelta = 60; this.opacityTime = Date.now() + this.opacityDelta; this.opacity = 1.0; this.opacityStep = 0.3; this.animFrame = 0; } update() { if (this.opacityTime < Date.now()) { this.opacityTime = Date.now() + this.opacityDelta; if (this.animFrame >= 1) { (this.opacity - this.opacityStep >= 0) ? this.opacity -= this.opacityStep: this.opacity = 0.0; this.render.changeOpacity(this.opacity); } this.animFrame++; } } } export default LetterFlashDelete;
import * as actions from '../constants' export function load(offset = 0) { return async (dispatch, getState, { get }) => { const { result } = await get('payout/list', { body: { offset, perpage: 30 }, loader: offset === 0 }) return dispatch({ type: actions.load, ...result, }) } } export function change(field, value) { return { type: actions.change, field, value, } } export function send() { return async (dispatch, getState, { post }) => { const { amount, address } = getState().payout const body = { amount: parseFloat(amount).toFixed(2), address, } await post('payout/add', { body }) dispatch(load()) dispatch(change('amount', '')) dispatch(change('address', '')) } }
import React, {Suspense} from 'react'; import {connect} from 'react-redux'; import {getData} from './actions/action'; const Item = React.lazy(() => import('./item')); const Filter = React.lazy(() => import('./filter')); class App extends React.Component { constructor(props){ super(props); this.state = { launch_year:'', launch_success:'', landing:'', limit:'100', status:null, data:[], current:[], loading:false, count:12, hasMoreData:true, years:[2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] } } componentDidMount(){ this.props.getData({limit:this.state.limit}); window.addEventListener('scroll', () => { if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight) return; this.loadMoreColleges(); }); } loadMoreColleges=()=>{ if(this.state.count >= this.state.data.length){ this.setState({ hasMoreData: false }); } else { this.setState({ loading: true }); let c = this.state.count+12; let data = this.state.data.slice(0, c); setTimeout(() => { this.setState({ current:data, count:c, loading: false, hasMoreData:true }); }, 1000); } } componentWillUnmount() { window.removeEventListener('scroll'); } static getDerivedStateFromProps(nextProps, prevstate){ return { status:nextProps.status, data:nextProps.data, current:nextProps.data.slice(0, prevstate.count) } } handleChange = (e) => { const {name, value } = e.target; this.props.getData({limit:this.state.limit, name, value}); } renderData(status, data){ if(status === null) return <span>we are Loading data ...</span> if(status && data.length>0 ) { return data.map((item, i)=>{ return <Item key={i} data={item} /> }) } else return <span>no data Found</span> } render(){ const { years, status, current } = this.state; return ( <div className="container" > <h3 className="heading">SpacEx launch programs</h3> <div className="row wrapper"> <Suspense fallback={<div>Loading...</div>}> <Filter years={years} handleChange={this.handleChange} /> </Suspense> <Suspense fallback={<div>Loading...</div>}> <div className="col-md-10 data-wrapper"> {this.renderData(status, current)} {this.state.loading ? <div className="loader"> Loading ...</div>: null} </div> </Suspense> </div> </div> ); } } const getState = (state) => { return { status: state.getData.status, data:state.getData.data } } export default connect(getState, {getData})(App);
/* ------------------------------------ sec180 CSS Transitions・CSS Animationsを使う -------------------------------------*/ function sec180() { const btn180 = document.querySelector('.btn180'); btn180.addEventListener('click', handleClick); function handleClick() { if (btn180.classList.contains('on') === false) { btn180.classList.add('on'); } else { btn180.classList.remove('on'); } } } sec180(); /* ------------------------------------ sec181 transitionendイベント -------------------------------------*/ function sec181() { const btn181 = document.querySelector('.btn181'); btn181.addEventListener('transitionend', (e) => { e.target.innerHTML = 'transition完了'; }); } sec181(); /* ------------------------------------ sec182 CSS Animationイベント -------------------------------------*/ function sec182() { const circle182 = document.querySelector('.circle182'); const circle182_i = document.querySelector('.circle182_i'); circle182.addEventListener('click', handleClick); circle182_i.addEventListener('click', handleClick); circle182.addEventListener('animationstart', (e) => { e.target.innerHTML = '開始'; }); circle182.addEventListener('animationend', (e) => { e.target.innerHTML = '終了'; }); circle182_i.addEventListener('animationstart', (e) => { e.target.innerHTML = '開始'; }); circle182_i.addEventListener('animationiteration', (e) => { e.target.innerHTML = '繰り返す'; }); function handleClick(e) { if (e.target.classList.contains('on') === false) { e.target.classList.add('on'); } } } sec182(); /* ------------------------------------ sec183 Web Animation API -------------------------------------*/ function sec183() { const square183 = document.querySelector('.square183'); square183.animate( { transform: [ 'translateX(0px) rotate(0deg)', 'translateX(500px) rotate(360deg)' ] }, { duration: 3000, iterations: Infinity, direction: 'normal', easing: 'ease' } ); } sec183(); /* ------------------------------------ sec184 scale -------------------------------------*/ function sec184() { const square184 = document.querySelector('.square184'); square184.animate( { transform: [ 'scale(1)', 'scale(3)' ] }, { duration: 3000, fill: 'forwards', easing: 'ease' } ); } /* ------------------------------------ sec185 scale -------------------------------------*/ function sec185() { const square185 = document.querySelector('.square185'); square185.animate( { transform: [ 'translate(0px)', 'translate(600px)' ] }, { duration: 3000, fill: 'forwards', easing: 'ease' } ); } /* ------------------------------------ sec186 scale -------------------------------------*/ function sec186() { const square186 = document.querySelector('.square186'); square186.animate( { opacity: [ '1.0', '0.2' ] }, { duration: 1000, fill: 'forwards', easing: 'ease' } ); } /* ------------------------------------ sec187 brightness -------------------------------------*/ function sec187() { const square187 = document.querySelector('.square187'); square187.animate( { filter: [ 'brightness(100%)', 'brightness(300%)' ] }, { duration: 3000, fill: 'forwards', easing: 'ease' } ); } /* ------------------------------------ sec188 grayscale -------------------------------------*/ function sec188() { const square188 = document.querySelector('.square188'); square188.animate( { filter: [ 'grayscale(0%)', 'grayscale(100%)' ] }, { duration: 3000, fill: 'forwards', easing: 'ease' } ); } /* ------------------------------------ sec190 grayscale -------------------------------------*/ function sec190() { const el = document.querySelector('.stoker'); el.classList.add('on'); //マウス座標 let mouseX = 0; let mouseY = 0; //ストーカー座標 let currentX = 0; let currentY = 0; //マウス移動時 document.body.addEventListener('mousemove', (e) => { //マウス座標を保存 mouseX = e.clientX; mouseY = e.clientY; }); tick(); function tick() { //アニメーションフレームを指定 requestAnimationFrame(tick); //マウス座標を遅延してストーカー座標へ反映 currentX += (mouseX - currentX) * 0.1; currentY += (mouseY - currentY) * 0.1; //ストーカーへ反映 el.style.transform = `translate(${currentX}px, ${currentY}px)`; } }
describe('Controlled Popover component', () => { beforeEach(() => { cy.visit('/iframe.html?path=Popover__controlled&source=false'); }); it('should open when clicking the trigger', () => { cy.get('button') .first() .click(); cy.get('[data-id="popover-content"]').should('be.visible'); }); describe('when opened', () => { beforeEach(() => { cy.get('button') .first() .click(); }); it('should close when clicking outside the popover', () => { cy.get('[data-id="popover-content"]').should('be.visible'); cy.get('html').click(100, 300); cy.get('[data-id="popover-content"]').should('not.exist'); }); it('should close when pressing the escape key', () => { cy.get('[data-id="popover-content"]').should('be.visible'); cy.get('body').type('{esc}'); cy.get('[data-id="popover-content"]').should('not.exist'); }); it('should close when pressing a close button', () => { cy.get('[data-id="popover-content"]').should('be.visible'); cy.get('[data-id="close-button"]').click(); cy.get('[data-id="popover-content"]').should('not.exist'); }); }); }); describe('Uncontrolled Popover with Actionlist', () => { beforeEach(() => { cy.visit('/iframe.html?path=Popover__with-an-ActionList&source=false'); cy.wait(500); // The element that handles click events requires time to calculate dimensions }); it('should open when clicking the trigger', () => { cy.contains('More Actions').click(); cy.get('[data-id="popover-content"]').should('be.visible'); }); it('should toggle open with enter key', () => { cy.contains('More Actions').type('{enter}'); cy.get('[data-id="popover-content"]').should('be.visible'); }); it('should tab through actionlist buttons', () => { cy.contains('More Actions').click(); cy.get('[data-id="popover-content"]').should('be.visible'); cy.focused().should('have.attr', 'tabindex', '-1'); // Container is focused with tabindex=-1 here, not "tabbable" by cypress // So we reset to start at the button instead cy.get('body').tab(); cy.focused().tab(); cy.focused().should('have.text', 'Edit'); cy.focused().tab(); cy.focused().should('have.text', 'Delete'); }); it('should close when clicking outside the popover', () => { cy.contains('More Actions').click(); cy.get('[data-id="popover-content"]').should('be.visible'); cy.get('html').click(100, 600); cy.get('[data-id="popover-content"]').should('not.exist'); }); it('should close when pressing the escape key', () => { cy.contains('More Actions').click(); cy.get('[data-id="popover-content"]').should('be.visible'); cy.get('body').type('{esc}'); cy.get('[data-id="popover-content"]').should('not.exist'); }); });
import React from 'react'; class Activity extends React.Component { img = this.props.img; title = this.props.title; idName = this.props.idName; clicked = false; clickActivity = (e) => { var element = document.getElementById(this.idName); if(!this.clicked){ this.clicked = true; element.classList.add('chooseClicked'); } else { this.clicked = false; element.classList.remove('chooseClicked') } this.props.activityClicked(this.idName); } render() { return( <div id={this.idName} className="selectable" onClick={this.clickActivity}> <img src={this.img} alt=""/> <h4>{this.title}</h4> </div> ); } } export default Activity;
import React from 'react'; import { Row, Col,Card, Button, Icon, Divider, Message, Form, Select, Input, Table, DatePicker} from 'antd'; import {fetch} from '../../api/tools' const FormItem = Form.Item; const Option = Select.Option; class Prepayment extends React.Component { state = { activeIndex: 0, list:[], total:0, current: 1, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { let beginTime = values.beginTime && values.beginTime.format('YYYY-MM-DD')||'' let endTime = values.endTime && values.endTime.format('YYYY-MM-DD')||'' let current = 1 this.setState({list:[],current: current, exId: values.exId, status: values.status,tradeType: values.tradeType,beginTime:beginTime,endTime:endTime},()=>{ this.fetchList(current,values.exId,values.status,values.tradeType,beginTime,endTime) }) } }); }; onChange = (value) =>{ // console.log(value); } componentDidMount(){ this.fetchList(1) } fetchList = (current,exId='',status='',tradeType='',beginTime='',endTime='', shopServiceId=this.props.shopServiceId) => { fetch('get',`/usercenter/transaction/advance-charge-trans-detail-list?current=${current}&exId=${exId}&status=${status}&tradeType=${tradeType}&beginTime=${beginTime}&endTime=${endTime}&shopServiceId=${shopServiceId}`).then(res=>{ if(res.code == 0){ let list = res.data.records // list = this.state.list.concat(list); list.forEach((item,index)=>{ let tradeType = item.tradeType; let status = item.status item.number = (current-1)*10 + index+1; switch (tradeType){ case 'ALL': item.tradeType = '所有交易' break case 'REVERSE': item.tradeType = '冲正'; break case 'WITHDRAW': item.tradeType = '线下提现'; break case 'RECHARGE': item.tradeType = '线下充值'; break case 'RECHARGE_OL': item.tradeType = '在线充值'; break case 'UNFREEZE': item.tradeType = '解冻'; break case 'FREEZE': item.tradeType = '冻结'; break case 'REFUND': item.tradeType = '退款'; break case 'TRANSFER': item.tradeType = '转账'; break case 'ESTABLISH': item.tradeType = '开户'; break } switch (status){ case 0: item.status = '取消' break case 1: item.status = '正常'; break case 2: item.status = '部分取消'; } }) this.setState({list: list, total: res.data.total, current: current}) }else{ Message.destroy() Message.error(res.msg) } }) } fetchMore = (page,pageSize) =>{ this.fetchList(page.current, this.state.exId,this.state.status,this.state.tradeType,this.state.beginTime,this.state.endTime) } render() { const { getFieldDecorator } = this.props.form; const { list , total, current} = this.state return ( <div> <Form layout="inline" onSubmit={this.handleSubmit} > <FormItem> {getFieldDecorator('exId', { rules: [], })( <Input style={{width: '150px'}} placeholder="请输入订单号" /> )} </FormItem> <FormItem> {getFieldDecorator('tradeType', { rules: [], })( <Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择交易类型"> {dealType.map((item,index)=> <Option value={item.key} key={index}>{item.name}</Option> )} </Select> )} </FormItem> <FormItem> {getFieldDecorator('status', { rules: [], })( <Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择状态"> {orderType.map((item,index)=> <Option value={item.key} key={index}>{item.name}</Option> )} </Select> )} </FormItem> <FormItem> {getFieldDecorator('beginTime', { rules: [], })( <DatePicker placeholder={'请选择起始日期'}/> )} </FormItem> <FormItem> {getFieldDecorator('endTime', { rules: [], })( <DatePicker placeholder={'请选择结束日期'}/> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" > 查询 </Button> </FormItem> {/*<FormItem>*/} {/*<Button type="primary">导出</Button>*/} {/*</FormItem>*/} </Form> <Table className='mt15' columns={columns} dataSource={list} pagination={{total: total, current: current}} onChange={(page,pageSize)=>{this.fetchMore(page,pageSize)}}/> </div> ); } } const columns = [{ title: '序号', dataIndex: 'number', key: 'number', }, { title: '交易流水 ', dataIndex: 'walletId', key: 'walletId', }, { title: '订单号', dataIndex: 'exId', key: 'exId', }, { title: '交易类型', dataIndex: 'tradeType', key: 'tradeType', },{ title: '初始金额', dataIndex: 'primevalAmount', key: '1', },{ title: '变动金额', dataIndex: 'variationAmount', key: '2', },{ title: ' 余额', dataIndex: 'balance', key: '3', },{ title: '状态', dataIndex: 'status', key: '4', },{ title: '创建时间', dataIndex: 'createTime', key: '5', },{ title: ' 备注', dataIndex: 'remark', key: '6', },]; const dealType = [ {key:'ALL',name:'所有交易'}, {key:'ESTABLISH',name:'开户'}, {key:'TRANSFER',name:'转账'}, {key:'FREEZE',name:'冻结'}, {key:'UNFREEZE',name:'解冻'}, {key:'RECHARGE_OL',name:'在线充值'}, {key:'RECHARGE',name:'线下充值'}, {key:'WITHDRAW',name:'线下提现'}, {key:'REVERSE',name:'冲正'}, ]; const orderType = [ {key:1,name:'正常'}, {key:0,name:'取消'}, {key:2,name:'部分取消'}, ] export default Form.create()(Prepayment);
/*------------------------------------------------------------------------------------* * * ui layout (widgets and controls), based on jquery * * by xiang 'anthony' chen, xiangchen@acm.org * *------------------------------------------------------------------------------------*/ var panel = $('<div></div>'); panel.css('width', WIDTHPANEL + 'px'); panel.css('height', '100%'); panel.css('color', '#000000'); panel.css('background-color', 'rgba(192, 192, 192, 0.5)'); panel.css('top', '0px'); panel.css('position', 'absolute'); panel.css('font-family', 'Helvetica'); panel.css('font-size', '12px'); panel.css('overflow', 'auto'); var title = $('<h3>Topy</h3>'); title.html('Topy'); title.css('margin-top', '10px'); title.css('margin-bottom', '10px'); title.css('margin-left', '10px'); title.css('margin-right', '10px'); panel.append(title); // // problem name input // var tblInfo = $('<table class="ui-widget"></table>'); tblInfo.css('margin', '5px'); var trName = $('<tr></tr>'); trName.append($('<td style="padding: 5px">Problem name: </td>')); trName.append($('<td style="padding: 5px"><input type="text" id="probName" size="24"></td>')); tblInfo.append(trName); panel.append(tblInfo); // // TODO: convergence conditions // // // // specify elements, boundary and load // // var tblAxes = $('<table class="ui-widget"></table>'); tblAxes.css('margin', '5px'); var axes = ['Z', 'Y', 'X']; for (var i = axes.length - 1; i >= 0; i--) { var trAxis = $('<tr></tr>'); trAxis.append($('<td style="padding: 5px">' + axes[i] + '</td>')); trAxis.append($('<td style="padding: 5px"><input type="text" id="nElm' + axes[i] + '" size="3"></td>')); trAxis.append($('<td width="256px" style="padding: 5px"><div id="sldr' + axes[i] + '"></div></td>')); trAxis.append($('<td style="padding: 5px"><label id="layer' + axes[i] + '" ></label></td>')); tblAxes.append(trAxis); } panel.append(tblAxes); // // // dialog for specifying boundary, load, and others // // var dlgVoxelSpec = $('<div></div>'); dlgVoxelSpec.title = 'Boundary and Load'; dlgVoxelSpec.append(''); var tblVoxelSpec = $('<table class="ui-widget" cellspacing="2" cellpadding="2"></table>'); dlgVoxelSpec.append(tblVoxelSpec); var trBound = $('<tr></tr>'); trBound.append($('<td>Boundary: </td>')); for (var i = axes.length - 1; i >= 0; i--) { trBound.append($('<td style="padding: 5px">' + axes[i] + '</td>')); trBound.append($('<td style="padding: 5px"><input type="checkbox" id="cb' + axes[i] + '"></td>')); } tblVoxelSpec.append(trBound); var trLoad = $('<tr></tr>'); trLoad.append($('<td>Load: </td>')); for (var i = axes.length - 1; i >= 0; i--) { trLoad.append($('<td style="padding: 5px">' + axes[i] + '</td>')); trLoad.append($('<td style="padding: 5px"><input type="text" id="load' + axes[i] + '" size="3"></td>')); } tblVoxelSpec.append(trLoad); // dlgVoxelSpec.append($('<br>')); var tblFixRemove = $('<table class="ui-widget" cellspacing="2" cellpadding="2"></table>'); dlgVoxelSpec.append(tblFixRemove); var trFixRemove = $('<tr></tr>'); trFixRemove.append($('<td style="padding: 5px">Fix </td>')); trFixRemove.append($('<td style="padding: 5px"><input type="checkbox" id="cbFixed"></td>')); trFixRemove.append($('<td style="padding: 5px">Remove </td>')); trFixRemove.append($('<td style="padding: 5px"><input type="checkbox" id="cbRemoved"></td>')); tblFixRemove.append(trFixRemove); dlgVoxelSpec.append($('<br>')); var btnOk = $('<div style="float: right;">OK</div>'); dlgVoxelSpec.append(btnOk); $(document.body).append(dlgVoxelSpec); // // finish-up buttons // var tblButtons = $('<table><tr></tr></table>'); tblButtons.css('margin', '10px'); var btnRun = $('<div>Run</div>'); var tdRun = $('<td></td>'); tdRun.append(btnRun); tblButtons.append(tdRun); panel.append(tblButtons); // // script view // var tblScript = $('<table class="ui-widget"></table>'); tblScript.css('margin', '15px'); // tblScript.append($('<tr><td>tpd file</td></tr>')); var trScript = $('<tr></tr>'); var taScript = $('<textarea rows="36" cols="52"></textarea>'); trScript.append(taScript); tblScript.append(trScript); panel.append(tblScript); addUIforParam('probName', 'PROB_NAME'); addUIforParam('nElmX', 'NUM_ELEM_X'); addUIforParam('nElmY', 'NUM_ELEM_Y'); addUIforParam('nElmZ', 'NUM_ELEM_Z'); // // subroutines for adding editable parameters and the corresponding uis // @param ui - the id (for jquery) of the ui // @param param - the corresponding tpd parameter // function addUIforParam(ui, param) { UIOFPARAMS.push(ui); PARAMSFORUI.push(param); }
function Socket(uri) { uri = getWSParts(uri); this.session = new Session(uri.key); this.baseURI = uri.protocol + "://" + uri.host + uri.port + "/sockets/"; this.ws = null; } Socket.prototype.toString = function() { return this.baseURI; } Socket.prototype.log = function(line) { log(this.toString() + " " + line) } Socket.prototype.connect = function(signaling) { var ws, self=this; function socket_open() { self.ws = ws; if (self.session.isIdentified()) { ws.send(JSON.stringify({ "challenge": self.session.challenge })); ws.onmessage = socket_authenticate; } else { var P = self.session.privateKeys; ws.send(JSON.stringify({ "publicKey": [P.x, P.y] })); ws.onmessage = socket_identify; } } function socket_exception(e) { self.log(e); ws.onmessage = pass; ws.close(); } function socket_identify(evt) { try { signaling.onConnect(self); self.session.identify(JSON.parse(evt.data).publicKey); ws.onmessage = socket_authorized; signaling.onReady(self); } catch (e) { socket_exception(e) } } function socket_authenticate(evt) { try { signaling.onConnect(self); var req = JSON.parse(evt.data), res = self.session.authenticate(req); if (res == "unauthorized") { signaling.onUnauthorized(self); ws.onmessage = pass; ws.close(); } else { ws.send(JSON.stringify(res)); ws.onmessage = socket_authorized; signaling.onReady(self); } } catch (e) { socket_exception(e); } } function socket_authorized(evt) { try { var message = JSON.parse(evt.data); } catch (e) { message = {"error": e.toString()}; } try { signaling.onSignal(self, message); } catch (e) { socket_exception(e); } } function socket_reconnect() { socket_close(); self.connect(); } function socket_close() { signaling.onDisconnect(self); signaling = self.ws = ws = null; } ws = new WebSocket(this.baseURI+this.session.id); ws.onclose = socket_close; ws.onopen = socket_open; return this; } Socket.prototype.isConnected = function() { return this.ws !== null; }
var app = getApp() let videoAd = null let interstitialAd = null Page({ /** * 页面的初始数据 */ data: { nickname: '姓名', imgSrc: '', point: 2, isLogin: 0, signCount: 0, shareCount: 0, videoCount: 0, }, toSign: function(options) { var that = this; var currPoint = that.data.point; var currSignPoint = that.data.signCount; console.log("签到" + currPoint); wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/add?id=' + wx.getStorageSync("userInfo").id + '&type=3', method: 'GET', success(res) { console.log(res.data); wx.hideLoading(); var data = res.data; if (data.code >= 0) { wx.showToast({ title: ' 签到成功,增加2积分!', icon: 'none', duration: 2000 }) that.setData({ point: currPoint + 2, signCount: currSignPoint + 1, }) } else if (data.code == -102) { wx.showToast({ title: ' 您今天已经签过到了,请明天再来!', icon: 'none', duration: 2000 }) } else { wx.showToast({ title: ' 服务器异常,请稍后重试!', icon: 'none', duration: 2000 }) } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }); }, toShare: function(options) { console.log("分享"); }, toVideo: function(options) { console.log("视频"); var that = this; if (videoAd) { videoAd.show().catch(() => { // 失败重试 videoAd.load() .then(() => videoAd.show()) .catch(err => { console.log('激励视频 广告显示失败') }) }) } }, /** * 用户点击右上角分享 */ onShareAppMessage: function(res) { var that = this; if (res.from === 'button') { var currPoint = that.data.point; var currShareCount = that.data.shareCount; console.log("来自页面内转发按钮"); console.log(res.target); wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/add?id=' + wx.getStorageSync("userInfo").id + '&type=2', method: 'GET', success(res) { console.log(res.data); wx.hideLoading(); var data = res.data; if (data.data != null && data.code >= 0) { wx.showToast({ title: '分享成功,增加1积分!', icon: 'none', duration: 2000 }) that.setData({ point: currPoint + 1, shareCount: (currShareCount > 0) ? 1 : (currShareCount + 1), }) } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }); } else { console.log("来自右上角转发菜单") } return { title: '我发现了一个好用的短视频去水印工具', path: '/pages/me/me', success: function(res) { console.log('成功', res) } } }, sRequest: function() { wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/srequest?id=' + wx.getStorageSync("userInfo").id, method: 'GET', success(res) { console.log(res.data); if (res.data.code >= 0) { wx.showToast({ title: '特殊请求成功!', icon: 'none', duration: 3000 }) }else{ wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function() { var that = this; if (wx.createInterstitialAd) { interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-e7d9cd4b1f5a4c00' // adUnitId: 'adunit-e9f570fae626adde' }) interstitialAd.onLoad(() => { }) interstitialAd.onError((err) => { }) interstitialAd.onClose(() => { }) }; if (wx.createRewardedVideoAd) { videoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-498062c378a63ba4' // adUnitId: 'adunit-5d02f2f2d3e5bf49' }) videoAd.onLoad(() => {}) videoAd.onError((err) => { wx.showToast({ title: '暂无合适的广告,请稍后再尝试!', icon: 'none', duration: 2000 }) }); videoAd.onClose(res => { var currPoint = that.data.point; var currVideoCount = that.data.videoCount; // 用户点击了【关闭广告】按钮 if (res && res.isEnded) { // 正常播放结束,可以下发游戏奖励 console.log("广告播放完毕"); wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/add?id=' + wx.getStorageSync("userInfo").id + '&type=1', method: 'GET', success(res) { console.log(res.data); wx.hideLoading(); var data = res.data; if (data.code >= 0) { wx.showToast({ title: '观看成功,增加9积分!', icon: 'none', duration: 2000 }); videoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-498062c378a63ba4' }) that.setData({ point: currPoint + 9, videoCount: currVideoCount + 1, }) } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }); } else { wx.showToast({ title: '观看完广告才有积分奖励,谢谢支持!', icon: 'none', duration: 3000 }) } }); } if (wx.getStorageSync("userInfo") == undefined || wx.getStorageSync("userInfo") == "") { //未登录,请前去登录 that.setData({ isLogin: 0 }) wx.showModal({ title: '您尚未登录', content: '必须登录后才能使用,点击确定后授权微信登录', success: function(res) { if (res.confirm) { wx.login({ success(res) { if (res.code) { //发起网络请求 wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/login?code=' + res.code, method: 'GET', success(res) { console.log(res.data); wx.hideLoading(); var userInfo = res.data.data; if (userInfo != null) { wx.setStorageSync("userInfo", userInfo); that.setData({ isLogin: 1 }) wx.showModal({ title: '登录成功', content: '新用户将赠送您50积分,下载一次需要2积分,积分不够了可以去个人中心完成简单的任务获取', success: function(res) { if (res.confirm) { wx.switchTab({ url: '/pages/me/me' }) } else if (res.cancel) { wx.showToast({ title: '任务极为简单,试一试就知道了哦', icon: 'none', duration: 2000 }) } } }); } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }) } else { console.log('登录失败!' + res.errMsg) } } }) } else if (res.cancel) { wx.showToast({ title: '未登录将无法使用本程序!', icon: 'none', duration: 2000 }) } } }); } else { that.setData({ isLogin: 1 }) that.onShow(); } }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { var that = this; if (interstitialAd) { interstitialAd.show().catch((err) => { console.error(err) }) } wx.request({ url: app.globalData.myApiUrl + 'hishelp/shuiyin/find?id=' + wx.getStorageSync("userInfo").id, method: 'GET', success(res) { console.log(res.data); wx.hideLoading(); var userInfo = res.data.data; if (userInfo != null) { wx.setStorageSync("userInfo", userInfo); that.setData({ point: userInfo.point, videoCount: userInfo.videoCount, shareCount: userInfo.shareCount, signCount: userInfo.signCount }); } }, fail() { wx.showToast({ title: '网络请求失败,请稍后重试!', icon: 'none', duration: 3000 }) } }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, })
import styled from "styled-components"; import { mainColor, lightestColor } from "../../colors"; import { defaultSpace, doubleSpace } from "../../spaces"; import { fontMedium } from "../../typograph"; const Button = styled.button` background-color: ${lightestColor}; border: solid 2px ${mainColor}; border-radius: 4px; color ${mainColor}; cursor: pointer; font-size: ${fontMedium} padding: ${defaultSpace} ${doubleSpace}; &:disabled { opacity: .75; } `; export { Button }
import React from 'react'; import { List, ListItem, ListItemText } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', justifyContent: 'center', padding: '0 20%', flexDirection: 'column', }, listItem: { height: 100, }, })); const JobListings = () => { const classes = useStyles(); return ( <div className={classes.root}> <List component="nav"> <ListItem button divider className={classes.listItem}> <ListItemText primary="Project one" /> </ListItem> <ListItem button divider className={classes.listItem}> <ListItemText primary="Project two" /> </ListItem> <ListItem button divider className={classes.listItem}> <ListItemText primary="Project three" /> </ListItem> <ListItem button divider className={classes.listItem}> <ListItemText primary="Project four" /> </ListItem> </List> </div> ); }; export default JobListings;
var searchData= [ ['concretebaseattack_2ehpp',['concreteBaseAttack.hpp',['../concreteBaseAttack_8hpp.html',1,'']]], ['concretebaseattackspebase_2ehpp',['concreteBaseAttackSpeBase.hpp',['../concreteBaseAttackSpeBase_8hpp.html',1,'']]], ['concretehploss_2ehpp',['concretehploss.hpp',['../concretehploss_8hpp.html',1,'']]], ['concretehplossspedef_2ehpp',['concretehplossspedef.hpp',['../concretehplossspedef_8hpp.html',1,'']]], ['concretemove_2ehpp',['concretemove.hpp',['../concretemove_8hpp.html',1,'']]] ];
const express = require('express'); // Our router with which we define each route. const router = express.Router(); // Default behavior for any routes router.use(function(req, res, next) { // Authentication of users using NARMS server. // Ensure to pass through all routes. next(); }); // middleware handling login event. router.post('/login', require('./middleware/login')); // middleware handling logout event. router.post('/logout', require('./middleware/logout')); // middleware handling roleChange event. router.post('/roleChange', require('./middleware/roleChange')); // middleware handling workstations event. router.get('/workstations', require('./middleware/workstations')); // Export the router. module.exports = router;
var resume = require('../actions/resume'); var config = require('../config'); var Reflux = require('reflux'); var http = require('http'); var extend = require('lodash/object/extend'); var resumeFixture = require('../../../server/models/defaults'); var store = module.exports = Reflux.createStore({ listenables: [ resume ], init: function () { this.store = {}; }, onLoad: function () { this.trigger(resumeFixture); // http.get({ // path: config.service.resume.path // }, function (res) { // var data = ''; // res.on('data', function (buf) { // data += buf; // }); // res.on('end', function () { // data = JSON.parse(data); // extend(this.store, data); // this.trigger(this.store); // }.bind(this)); // res.on('error', function (err) { // resume.load.failed(err); // }.bind(this)); // }.bind(this)); }, });
const dotenv = require("dotenv"); dotenv.config(); const databaseconfig = { host: process.env.DB_HOST, database: process.env.MYSQL_DB, user: process.env.DB_USER, password: process.env.DB_PASS, port: process.env.MYSQL_PORT }; module.exports = { databaseconfig: databaseconfig };
import React from 'react'; import AppContainer from '../../utils/AppContainer'; import { BrowserRouter as Router, Switch, Route, Link, Redirect, useLocation, useRouteMatch } from 'react-router-dom'; import { BackTop, Button, Row, Col, Divider, Pagination, Image, Card, Typography } from 'antd'; import {ProductData} from './Product/ProductData'; import '../Homepage/Home.css'; import './OurProduct.css'; import Leafy from '../Homepage/Banner/Leafy.mp4'; const { Title, Paragraph } = Typography; const { Meta } = Card; const style = { background: '#446B40', padding: '8px 0' }; function OurProduct() { // The `path` lets us build <Route> paths that are // relative to the parent route, while the `url` lets // us build relative links. let { path, url } = useRouteMatch(); console.log('path', path) console.log('url', url) return ( <AppContainer> <div className='OurProduct-body'> <header className='product-moving-banner'> <div className='product-video-container'> <video src={Leafy} autoPlay muted loop></video> </div> <div className='product-moving-banner-content'> <Title level={2}>All Products</Title> </div> </header> <div className='product-container'> <Divider orientation="left"><h2>Vegetables</h2></Divider> <Row> { ProductData.map((item, index) => { return( <Col> <Link to={`${url}${item.path}`}> <Card hoverable style={{ width: 240}} cover={item.image} > <Meta title={item.title} description={item.description} /> </Card> </Link> </Col> ) }) } </Row> <Pagination className='pagination' current='1' simple defaultCurrent={2} total={20} responsive={true} /> </div> </div> </AppContainer> ) } export default OurProduct;
import Rebase from "re-base"; import firebase from "firebase"; import config from "./keys"; // database const fireBaseApp = firebase.initializeApp(config); const base = Rebase.createClass(fireBaseApp.database()); // authentication // exports export { fireBaseApp }; export default base;
$(function () { $('a.landingButton').on('click', function(event) { // smooth scroll to first button if (this.hash !== "") { event.preventDefault(); let hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 1000, function () { window.location.hash = hash; }); } setTimeout(() => { moduleOne() }, 1500); }); moduleOne = () => { // module one learning info $('header').css('border', '4px solid #F5221B'); Swal.fire({ title: 'Meet <br> < header >!', text: 'It\'s called < header > because it\'s in the "head" of every web page.', confirmButtonText: 'Got it!' }) .then(() => { $('header').css('border', '4px solid #FFFFFF'); $('footer').css('border', '4px solid #F5221B'); Swal.fire({ title: 'This is <br> < footer >!', text: 'It\'s at the very bottom of every web page. Just like your foot is at the very bottom of your body.', confirmButtonText: 'Got it!' }) .then(() => { $('footer').css('border', '4px solid #FFFFFF'); }) .then(() => { $('main').css('border', '4px solid #F5221B'); Swal.fire({ title: 'This is <br>< main >!', text: 'It has everything you want to see when you open the web page.', confirmButtonText: 'Got it!' }) .then(() => { $('main').css('border', '4px solid #FFFFFF'); }) .then(() =>{ Swal.fire({ title: 'Hooray!', text: "You just learnt the most popular tags used to create any web page. Now it's time for the real challenge. Are you ready?", showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, let\'s do it!', cancelButtonText: 'I want to review tags one more time' }) .then((result) => { if (result.value) { $('html, body').animate({ scrollTop: $("#infoQuizPage").offset().top }, 1000); window.scrollTo(0, 100); } else { return moduleOne(); } }); }); }); }); }; $('a.quizButton').on('click', function (event) { // smooth scroll if (this.hash !== "") { event.preventDefault(); let hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 1000, function () { window.location.hash = hash; }); } setTimeout(() => { quizOne(); }, 1500); }); // QUIZ part //questions questionOne = () => { Swal.fire({ text: 'What is on the bottom of a web page?', confirmButtonText: 'On it!' }); } questionTwo = () => { Swal.fire({ text: 'Where can you find major information of a web page?', confirmButtonText: 'On it!' }); } questionThree = () => { Swal.fire({ text: 'What\'s on the top of a page?', confirmButtonText: 'On it!' }); } randomQuestions = () => { //making random questions let questionsArray = [questionOne, questionTwo, questionThree]; let randomQuestion1 = questionsArray[Math.floor(Math.random() * questionsArray.length)]; let index1 = questionsArray.indexOf(randomQuestion1); questionsArray.splice(index1, 1); let randomQuestion2 = questionsArray[Math.floor(Math.random() * questionsArray.length)]; let index2 = questionsArray.indexOf(randomQuestion2); questionsArray.splice(index2, 1); let randomQuestion3 = questionsArray[0]; randomQuestionsArray = [randomQuestion1, randomQuestion2, randomQuestion3]; return randomQuestionsArray; } randomTags = () => { //making random tags let myTags = ['<p>< aside \></p>', '<p>< footer \></p>', '<p>< main \></p>', '<p>< div \></p>', '<p>< header \></p>',] let randomTag1 = myTags[Math.floor(Math.random() * myTags.length)]; let tagIndex1 = myTags.indexOf(randomTag1); myTags.splice(tagIndex1, 1); let randomTag2 = myTags[Math.floor(Math.random() * myTags.length)]; let tagIndex2 = myTags.indexOf(randomTag2); myTags.splice(tagIndex2, 1); let randomTag3 = myTags[Math.floor(Math.random() * myTags.length)]; let tagIndex3 = myTags.indexOf(randomTag3); myTags.splice(tagIndex3, 1); let randomTag4 = myTags[Math.floor(Math.random() * myTags.length)]; let tagIndex4 = myTags.indexOf(randomTag4); myTags.splice(tagIndex4, 1); let randomTag5 = myTags[0]; let myNewTags = [randomTag1, randomTag2, randomTag3, randomTag4, randomTag5]; return myNewTags; } addTagsToClouds = () => { let tags = randomTags(); $(".quizOne .cloudOne .cloud p").append(tags[0]); $(".quizOne .cloudTwo .cloud p").append(tags[1]); $(".quizOne .cloudThree .cloud p").append(tags[2]); $(".quizOne .cloudFour .cloud p").append(tags[3]); $(".quizOne .cloudFive .cloud p").append(tags[4]); } quizOne = () => { let questions = randomQuestions(); questions[0](); addTagsToClouds(); if (questions[0] === questionOne) { $('.quizOne .cloud p:contains("footer")').on('click', function () { $('.quizOne .cloud p').empty(); finalMessage(); }); $('.quizOne .cloud p:not(:contains("footer"))').on('click', function () { fail(); }); } else if (questions[0] === questionTwo) { $('.quizOne .cloud p:contains("main")').on('click', function () { $('.quizOne .cloud p').empty(); finalMessage(); }); $('.quizOne .cloud p:not(:contains("main"))').on('click', function () { fail(); }); } else if (questions[0] === questionThree) { $('.quizOne .cloud p:contains("header")').on('click', function () { $('.quizOne .cloud p').empty(); finalMessage(); }); $('.quizOne .cloud p:not(:contains("header"))').on('click', function () { fail(); }); } else { fail(); } } //in case user scrolls to another section $('.infoPage, .samplePage, .infoQuizPage, .finalPage').on('click', function () { $('.quizOne .cloud p').empty(); }) fail = () => { Swal.fire({ icon: 'error', title: 'Try again!', showConfirmButton: false }).then((result) => { $('.quizOne .cloud p').empty(); return quizOne(); }); } finalMessage = () => { Swal.fire({ icon: 'success', text: "That's correct! Wanna try one more time?", showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, let\'s do it!', cancelButtonText: 'No, I\'m good.' }).then((result) => { if (result.value) { return quizOne(); } else { $('html, body').animate({ scrollTop: $("#finalPage").offset().top }, 1000); window.scrollTo(0, 100); } }); } });
import React, { Component } from 'react'; import { NavLink, Link } from 'react-router-dom'; class Header extends Component { render() { return ( <header> <div className='center'> <div className='logo'><Link to="/">evvchsk</Link></div> <ul> <li><NavLink to="/" exact activeStyle={{ color: '#faff70' }}>Home</NavLink></li> <li><NavLink to="/about" exact activeStyle={{ color: '#faff70' }}>About</NavLink></li> <li><NavLink to="/work" activeStyle={{ color: '#faff70' }}>Work</NavLink></li> </ul> <div className='clear'></div> </div> </header> ); } } export default Header;
const MODERN_ACTIVITY= 15; const HALF_LIFE_PERIOD= 5730; module.exports = function dateSample(sampleActivity) { if (typeof sampleActivity === 'string') { const activityValue = Number.parseFloat(sampleActivity); return Boolean(activityValue) && (activityValue > 0 && activityValue < MODERN_ACTIVITY) && Math.ceil(Math.log(MODERN_ACTIVITY / activityValue) / (0.693 / HALF_LIFE_PERIOD)); } return false; };
import React from 'react'; import './Header.css'; import {Link} from 'react-router-dom'; const renderedLinks = () => { return ( <div className="LinkGrid"> <a href={'/about'}>About</a> <a href={'/gallery'}>Gallery</a> </div> ) } const Header = () => { return ( <div className="Header"> <div className="Grid"> <div className="Logo"> <a href={'/'}> <img src="logo.png"></img> </a> </div> <nav className="NavLinks">{renderedLinks()}</nav> <div className="ActionButton"><button><h4>CALL NOW</h4></button></div> </div> </div> ); } export default Header;
// next.config.js // module.exports = { // /* make the game page not prerender */ // devIndicators: { // autoPrerender: false, // }, // } const withSass = require('@zeit/next-sass'); const withImages = require('next-images'); const devIndicators = { autoPrerender: false } module.exports = withSass(withImages(devIndicators));
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const orderSchema = new Schema({ userId: String, userName: String, userEmail: String, products: [], tax: Number, subtotal: Number, taxAmount: Number, total: Number }, { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }); module.exports = mongoose.model("Order", orderSchema);
import Promise from 'bluebird'; import mongoose from 'mongoose'; import httpStatus from 'http-status'; import APIError from '../lib/APIError'; import validator from 'validator'; import bcrypt from 'bcrypt-nodejs'; const ProfessionalSchema = new mongoose.Schema({ email:{ type: String, required: true, validate: [ validator.isEmail, 'invalid email' ], unique: true }, firstname: { type: String, }, lastname: { type: String, }, title: { type: String, }, imageUrl: { type: String, }, organization: { type: mongoose.Schema.ObjectId, ref: 'Organization' }, clients:[{type:mongoose.Schema.ObjectId,ref:'Client'}], //1 = active, 0 = disabled or disactive status: { type: Boolean }, createdAt: { type: Date, default: Date.now } }); /** * Statics */ ProfessionalSchema.statics = { /** * Get Professional * @param {ObjectId} email - The email of Professional. * @returns {Promise<Professional, APIError>} */ get(id) { return this.findById(id) .populate('clients organization') .exec() .then((Professional) => { if (Professional) { return Professional; } else{ const err = new APIError('No such Professional exists!', httpStatus.NOT_FOUND); return Promise.reject(err); } }); }, /** * Get Professional by Email * @param {string} email - The email of Professional. * @returns {Promise<Professional, APIError>} */ getByEmail(email) { return this.exists(email).then(Professional => { if (Professional) { return Professional; } else{ const err = new APIError('No such Professional exists!', httpStatus.NOT_FOUND); return Promise.reject(err); } }) }, /** * Get Professional by Email * @param {string} email - The email of Professional. * @returns {Promise<Professional, APIError>} */ exists(email) { return this.findOne({email:email}) .populate('clients') .exec().then((Professional) => { if (Professional) { return Professional; } return null; }); }, /** * List Professionals in descending order of 'createdAt' timestamp. * @param {number} skip - Number of Professionals to be skipped. * @param {number} limit - Limit number of Professionals to be returned. * @returns {Promise<Professional[]>} */ list({ skip = 0, limit = 50 } = {}) { return this.find() .sort({ createdAt: -1 }) .skip(skip) .limit(limit) .exec(); } }; export default mongoose.model('Professional', ProfessionalSchema);
const bcrypt = require('bcrypt'); const SaltRounds = 9; module.exports = { hash(password) { return bcrypt.hash(password, SaltRounds); // auto generates salt }, compare(hash, plaintextPassword) { return bcrypt.compare(plaintextPassword, hash); } };
commonInit = () => { //操作說明 /* 宣告註冊 燈箱id 燈箱遮罩ID 燈箱xx按鈕ID ex. ooxx = document.getElementById('ooxx'); 啟動你要ㄉ動作執行帶入ooxxLightBox函式 ex. ooxx.addEventListener('click', () => { ooxxLightBox(燈箱ID,燈箱遮罩ID,燈箱xx按鈕ID); }) */ // ooxxLightBox(燈箱ID,燈箱遮罩ID,燈箱xx按鈕ID) ooxxLightBox = (...lightBoxArray) => { let LightBox = lightBoxArray[0]; let LightBoxMask = lightBoxArray[1]; let lightBoxXX = lightBoxArray[2]; LightBox.style.display = 'none'; opacity = 0; // 關掉按鈕樣式 lightBoxXXGo = (e) => { if ((e.type == 'mousedown') || (e.type == 'touchstart')) { lightBoxXX.classList.add('lightBoxDown'); } else if ((e.type == 'mouseup') || (e.type == 'touchend')) { lightBoxXX.classList.remove('lightBoxDown'); } } lightBoxXX.addEventListener('mousedown', lightBoxXXGo); lightBoxXX.addEventListener('mouseup', lightBoxXXGo); lightBoxXX.addEventListener('touchstart', lightBoxXXGo); lightBoxXX.addEventListener('touchend', lightBoxXXGo); //燈箱開始 LightBox.style.display = 'none'; opacity = 0; //打開淡入 OpenLightBox = () => { LightBox.style.display = 'block'; LightBoxMask.style.display = 'block'; opacity += 0.086; LightBox.style.opacity = opacity; OpenLightBoxId = window.requestAnimationFrame(OpenLightBox); if (opacity > 1) { opacity = 1; LightBox.style.opacity = 1; cancelAnimationFrame(OpenLightBoxId); } } //關掉燈箱喔 closeLightBox = () => { if (opacity > 0.4) { opacity -= 0.086; } else { opacity -= 0.026; } LightBox.style.opacity = opacity; closeLightBoxId = window.requestAnimationFrame(closeLightBox); if (opacity <= 0) { LightBoxMask.style.display = 'none'; opacity = 0; LightBox.style.opacity = opacity; cancelAnimationFrame(closeLightBoxId); LightBox.style.display = 'none'; } } // 開啟燈箱 if (LightBox.style.display == 'none') { OpenLightBoxId = window.requestAnimationFrame(OpenLightBox); } //關掉燈箱函式 lightBoxXX.addEventListener('click', () => { closeLightBoxId = window.requestAnimationFrame(closeLightBox); }) LightBoxMask.addEventListener('click', () => { closeLightBoxId = window.requestAnimationFrame(closeLightBox); }) } } window.addEventListener('load', commonInit); //雜亂程式區 // cancelAnimationFrame(OpenLightBoxId) // window.getComputedStyle(LightBox, null).getPropertyValue("opacity"); // ooxxBtn.addEventListener('click', LightBoxRun); /* //燈箱關閉按鈕 const lightBoxXX = document.getElementById('lightBoxXX'); lightBoxXXGo = (e) => { if ((e.type == 'mousedown') || (e.type == 'touchstart')) { lightBoxXX.classList.add('lightBoxDown'); } else if ((e.type == 'mouseup') || (e.type == 'touchend')) { lightBoxXX.classList.remove('lightBoxDown'); } } lightBoxXX.addEventListener('mousedown', lightBoxXXGo); lightBoxXX.addEventListener('mouseup', lightBoxXXGo); lightBoxXX.addEventListener('touchstart', lightBoxXXGo); lightBoxXX.addEventListener('touchend', lightBoxXXGo); //燈箱開始 const LightBox = document.getElementById('LightBox'); const LightBoxMask = document.getElementById('LightBoxMask'); LightBox.style.display = 'none'; opacity = 0; //打開燈箱拉 OpenLightBox = () => { LightBox.style.display = 'block'; LightBoxMask.style.display = 'block'; opacity += 0.086; LightBox.style.opacity = opacity; OpenLightBoxId = window.requestAnimationFrame(OpenLightBox); if (opacity > 1) { opacity = 1; LightBox.style.opacity = 1; cancelAnimationFrame(OpenLightBoxId); } } //關掉燈箱喔 closeLightBox = () => { if (opacity > 0.4) { opacity -= 0.086; } else { opacity -= 0.026; } LightBox.style.opacity = opacity; closeLightBoxId = window.requestAnimationFrame(closeLightBox); if (opacity <= 0) { LightBoxMask.style.display = 'none'; opacity = 0; LightBox.style.opacity = opacity; cancelAnimationFrame(closeLightBoxId); LightBox.style.display = 'none'; } } //打開燈箱ㄉ函式 LightBoxRun = () => { if (LightBox.style.display == 'none') { OpenLightBoxId = window.requestAnimationFrame(OpenLightBox); } } //關掉燈箱函式 lightBoxXX.addEventListener('click', () => { closeLightBoxId = window.requestAnimationFrame(closeLightBox); }) LightBoxMask.addEventListener('click', () => { closeLightBoxId = window.requestAnimationFrame(closeLightBox); }) */
const express = require('express') const router = express.Router() const controller = require("../../controllers/admin/liveStreaming") const is_admin = require("../../middleware/admin/is-admin") router.get('/live-streaming/settings', is_admin, controller.settings); router.post('/live-streaming/settings', is_admin, controller.settings); router.get('/live-streaming/levels/:level_id?', is_admin, controller.levels); router.post('/live-streaming/levels/:level_id?', is_admin, controller.levels); router.get("/live-streaming/delete/:id",is_admin,controller.delete) module.exports = router;
require("default.thm.min.js")
describe('Clique.browser', function(){ var _c = window.Clique; describe('#loaded', function() { it('Browser is saved as a component', function() { _c.components.should.have.property('browser'); }); }); describe('#instatiation', function() { it('Browser is booted', function() { console.log(_c.components); _c.components.browser.booted.should.be.true; }); }); describe('#methods', function() { it('Should have method `boot`', function() { var obj = _c.components.browser; obj.prototype.boot.should.be.a.Function; }); it('Should have method `init`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `getProperties`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `test`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `exec`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `uamatches`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `version`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectDevice`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectScreen`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectTouch`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectOS`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectBrowser`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectLanguage`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectPlugins`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `detectSupport`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `addClasses`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); it('Should have method `removeClasses`', function() { var obj = _c.components.browser; obj.prototype.init.should.be.a.Function; }); }); });
export const FORM_SAVE_REGISTER = 'FORM_SAVE_REGISTER'; // export const DECREMENT = 'DECREMENT'; export const formSaveRegister = payload => { return { type: FORM_SAVE_REGISTER, payload }; }; // export const decrement = () => { // return { // type: DECREMENT // }; // };
document.write('<div class="foot"> \ <div class="foot-cot"> \ <h2></h2> \ <p class="foot-cot-txt1">北京精准沟通传媒科技股份有限公司 版权所有 京ICP备11006567号-2</p> \ <p class="foot-cot-txt2"> \ <a href="http://www.pcmglobe.com/">www.pcmglobe.com</a> 2007-<b class="year"></b> © All Rights Reserved.</p> \ </div> \ </div>') $(function (){ //导航点击变色 $('.main-nav li a').click(function (){ $('.main-nav li a').removeClass('active'); $(this).addClass('active'); }); //当滚动条的距离大于100是淡入,小于100是淡出 $(window).scroll(function (){ if ($(window).scrollTop()>100) { $('#top').fadeIn(500); } else { $('#top').fadeOut(500); } }); //点击top回到顶部 $('#top').click(function (){ $('body,html').stop().animate({scrollTop:0},500); }); // 获取年份 var date=new Date; var year=date.getFullYear(); $('.year').html(year); });
import React, { useState, useEffect } from "react"; import { View, Text, FlatList, ActivityIndicator, Image, TouchableOpacity, ScrollView, } from "react-native"; import firebase from "../Firebase"; function MyOrders(props) { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const db = firebase.firestore(); const FetchData = async () => { const uid = global.UID; await db .collection("users") .doc(uid) .collection("Groups") .doc("groups") .collection("LIVE") .get() .then((snapshot) => { const data = []; snapshot.forEach((doc) => { doc.data().mybagitems.forEach((item) => { data.push(item); }); }); setData(data); setLoading(false); }); }; useEffect(() => { FetchData(); const willFocusSubscription = props.navigation.addListener("focus", () => { FetchData(); }); return willFocusSubscription; }, []); return ( <ScrollView style={{ flex: 1, backgroundColor: "white" }}> {loading ? ( <ActivityIndicator /> ) : ( <FlatList data={data} renderItem={({ item }) => { return ( <View style={{ margin: 10 }}> <View style={{ borderWidth: 1, padding: 8, flexDirection: "row", borderColor: "#E5E5E5", borderRadius: 20, }} > <Image source={{ uri: item.itemImage }} style={{ height: 150, width: 140, resizeMode: "cover", borderRadius: 10, }} /> <View style={{ flex: 1, padding: 10, }} > <Text style={{ fontSize: 13, fontWeight: "bold" }}> {item.itemBrand} </Text> <Text style={{ fontSize: 13, fontWeight: "bold" }}> {item.itemTitle} </Text> <Text style={{ fontSize: 14, marginTop: 20, color: "red" }}> Status : Delivered </Text> <View style={{ flexDirection: "row", // justifyContent: "space-between", margin: 2, marginTop: 10, }} > <TouchableOpacity style={{ padding: 10, backgroundColor: "#FDA5A5", borderRadius: 10, paddingHorizontal: 15, }} > <Text style={{ fontSize: 16, fontWeight: "bold", color: "white", }} > Return </Text> </TouchableOpacity> <TouchableOpacity style={{ padding: 10, backgroundColor: "#FDA5A5", borderRadius: 10, paddingHorizontal: 15, marginLeft: 12, }} > <Text style={{ fontSize: 16, fontWeight: "bold", color: "white", }} > Review </Text> </TouchableOpacity> </View> </View> </View> </View> ); }} keyExtractor={(item) => item.itemId} /> )} </ScrollView> ); } export default MyOrders;
class Reward { constructor(company, title, description, points, expiryDate, category) { this.company = company; this.title = title; this.description = description; this.points = points; this.expiryDate = expiryDate; this.category = category; } } module.exports = Reward;
/** * @providesModule PFontSet */ export default { FontAwesome: 'http://foo.com/bar/FontAwesome.ttf', };
import { fetchPosts } from "@/services/post.service"; export default { namespaced: true, state: { postList: { loading: false, data: [], error: null, timeTraveling: false, }, actionStack: [], }, mutations: { FETCH_POSTS_SUCCESS: (state, response) => { state.postList = { ...state.postList, loading: false, error: null, data: response.data ? response.data.slice(0, 5) : response.data, }; }, FETCH_POSTS_ERROR: (state, response) => { state.postList = { ...state.postList, loading: false, data: null, error: response ? response.data ? response.data.message : response.data : null, }; }, MOVE_UP_POST: (state, payload) => { state.postList = { ...state.postList, loading: false, data: payload, error: null, }; }, MOVE_DOWN_POST: (state, payload) => { state.postList = { ...state.postList, loading: false, data: payload, error: null, }; }, ADD_TO_ACTION_STACK: (state, payload) => { state.actionStack = [...state.actionStack, payload]; }, TIME_TRAVEL_TO_ACTION: (state, payload) => { state.actionStack = payload.actionStack; state.postList = { ...state.postList, data: payload.postOrder, timeTraveling: false, }; }, }, actions: { FETCH_POSTS: () => { fetchPosts(); }, }, };
import {Users} from "../../db/models"; import HTTPStatus from "http-status"; import {v4 as uuidv4} from "uuid"; //const {Users} = model; export const register = async (req, res, next) => { try { let apiKey = uuidv4(); if ((await doesUsernameExists(req.body.username)) != null) { return res .status(HTTPStatus.BAD_REQUEST) .send({message: "Username already exist"}); } if ((await doesEmailExists(req.body.email)) != null) { return res .status(HTTPStatus.BAD_REQUEST) .send({message: "Email already exist"}); } const user = await Users.create({ username: req.body.username, password: req.body.password, email: req.body.email, }); return res.status(HTTPStatus.CREATED).send(user); } catch (err) { console.error(err.message); if (err) next(err); } }; export const login = async (req, res, next) => { try { const user = await Users.findOne({ where: {username: req.body.username}, }); if (!user || !user.authenticate(req.body.password)) { return res .status(HTTPStatus.BAD_REQUEST) .send({message: "Invalid credentials"}); } const u = user.auth(); await Users.update( {lastLoginAt: Date.now()}, { where: { username: req.body.username, }, } ); return res.status(HTTPStatus.ACCEPTED).send(u); } catch (err) { console.error(err.message); if (err) next(err); } }; async function doesUsernameExists(username) { return await Users.findOne({where: {username}}); } async function doesEmailExists(email) { return await Users.findOne({where: {email}}); }
import axios from 'axios' import config from './config' export function getSongUrl (id) { const url = `${config.baseUrl}/music/url?id=${id}` return axios.get(url).then((res) => { return Promise.resolve(res.data) }) } export function getSongLyric (id) { const url = `${config.baseUrl}/lyric?id=${id}` return axios.get(url).then((res) => { return Promise.resolve(res.data) }) } export function getSongDetail (id) { const url = `${config.baseUrl}/song/detail?ids=${id}` return axios.get(url).then((res) => { return Promise.resolve(res.data) }) }
window.CRMGuid = 'B9D726CA-37C3-4D21-910E-AC7ECB9894A2'; window.PreferredLanguage = 'en'; if (location.hostname=='rcrm.responsecrm.com') window.BaseURI = 'https://crmapi.responsecrm.com'; else window.BaseURI = 'https://crmapi.thesafetransaction.com';
const express = require("express"); const Article = require("../models/articlesModel"); const router = express.Router(); router.get("/new", (req, res) => { // res.send("In a articles"); res.render("articles/new", { articles: new Article() }); }); router.get("/edit/:id", async (req, res) => { const objArticle = await Article.findById(req.params.id); res.render("articles/edit", { articles: objArticle }); }); // router.get("/:id", async (req, res) => { // luc dau dung id router.get("/:slug", async (req, res) => { // res.send(req.params.id); // const objArticle = await Article.findById(req.params.id); //id: tim id trong mang do const objArticle = await Article.findOne({ slug: req.params.slug }); if (objArticle === null) res.redirect("/"); res.render("articles/show", { articles: objArticle }); }); //create router.post( "/", async (req, res, next) => { // let objArticle = new Article({ // title: req.body.title, // description: req.body.description, // markdown: req.body.markdown, // }); // try { // objArticle = await objArticle.save(); // // res.redirect(`/articles/${objArticle.id}`); // luc dau dung id // res.redirect(`/articles/${objArticle.slug}`); // } catch (error) { // console.log(error); // res.render("articles/new", { // articles: objArticle, // }); // } req.articles = new Article(); next(); }, onSaveArticleRedirect("new") ); //delete router.delete("/:id", async (req, res) => { await Article.findByIdAndDelete(req.params.id); res.redirect("/"); }); //update router.put( "/:id", async (req, res, next) => { req.articles = await Article.findById(req.params.id); next(); }, onSaveArticleRedirect("edit") ); function onSaveArticleRedirect(path) { return async (req, res) => { let objArticle = req.articles; objArticle.title = req.body.title; objArticle.description = req.body.description; objArticle.markdown = req.body.markdown; try { objArticle = await objArticle.save(); // res.redirect(`/articles/${objArticle.id}`); // luc dau dung id res.redirect(`/articles/${objArticle.slug}`); } catch (error) { console.log(error); res.render(`articles/new/${path}`, { articles: objArticle, }); } }; } module.exports = router;
// Operationi con le variabili // come per le operazioni con valori e come visto all'inizio di questa lezione basta utilizzare gli operandi tra le variabili per effettuare delle operazioni // (math expression) const incrementoPrezzoProdotto = 1.2; prezzoProdotto = prezzoProdotto * incrementoPrezzoProdotto; // moltiplicazione tra variabili di tipo "number" var prezzoConMoneta = prezzoProdotto + "€"; // addizione tra numero e stringa var nomeProdotto2 = nomeProdotto + " e Quadretto"; // addizione tra variabili di tipo "stringa" var prezzoProdotto2 = prezzoProdotto + 50; var prezzoConMoneta2 = prezzoProdotto2 + "€"; // console.log // Console.log è una funzione comune di javascript, presente sia lato server che browser per scrivere nella console // variabili o valori di qualsisi tipo essi siano. console.log(nomeProdotto); console.log("CIAO"); console.log(2); console.log({}); // "if" "else if" "else" "ternary" // Sono 4 statement utilizzati per il controllo del flusso dei dati if (prezzoProdotto2 < 50) { console.log('Giorgio dice: "Non lo voglio costa troppo poco per me."'); } else if (prezzoProdotto >= 100) { console.log('Ivan dice: "Massi dai prendo solo la "' + nomeProdotto + '.'); } else { console.log('Nicola dice: "Compro tutto"'); } // controllo di tipo if (typeof prezzoProdotto2 == "number") { console.log("Vero cavolo!"); } if (typeof incrementoPrezzoProdotto == "string") { console.log("Qualcosa qui non quadra..."); } // ternary (io la chiamo "if inline" però non ascoltatemi/leggete) var nonNumero = (typeof nomeProdotto === "string") ? true : false; console.log(nonNumero); var nonNumero = (typeof nomeProdotto == "string") ? true : false; console.log(nonNumero); // utilizzo dello statement "typeof" console.log(typeof nomeProdotto);
import React from "react"; import { useStaticQuery, graphql } from "gatsby"; import PropTypes from "prop-types"; import Helmet from "react-helmet"; import Header from "../Header"; import Footer from "../Footer"; import "../../../node_modules/simple-line-icons/css/simple-line-icons.css"; import "./reboot.css"; import "./index.css"; const query = graphql` query PageQuery { site { siteMetadata { title description keywords } } } `; function Layout({ children }) { const { site: { siteMetadata: { title, description, keywords }, }, } = useStaticQuery(query); return ( <div> <Helmet> <title>{title}</title> <meta name="description" content={description} /> <meta name="keywords" content={keywords} /> </Helmet> <Header /> <div className="Content">{children}</div> <Footer /> </div> ); } Layout.propTypes = { children: PropTypes.func.isRequired, data: PropTypes.shape({ site: PropTypes.shape({ siteMetadata: PropTypes.shape({ title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, keywords: PropTypes.string.isRequired, }).isRequired, }).isRequired, }).isRequired, }; export default Layout;
(function () { 'use strict'; angular .module('presse') .config(config); function config($stateProvider) { $stateProvider .state('presse', { url: '/presse', templateUrl: 'presse/views/presse.tpl.html', controller: 'PresseCtrl', controllerAs: 'presse' }); } }());
import { connect } from 'react-redux'; import Breadcrumb from './component'; const mapStateToProps = ({ routing: { location: { pathname } } }) => ({ pathname }); const BreadcrumbContainer = connect( mapStateToProps, null )(Breadcrumb); export default BreadcrumbContainer;
import React from 'react'; function DummyPage(){ return( <div> <div> Dummy Page </div> </div> ) } export default DummyPage;
{ "code": 0 ,"msg": "" ,"data": [{ "title": "用户" ,"icon": "layui-icon-user" ,"list": [{ "title": "小程序用户" ,"jump": "secret/appuser" }, { "name": "homepage1" ,"title": "后台用户" ,"jump": "secret/secretuser" }] },{ "name" : "secretapp" ,"title": "秘密" ,"icon": "layui-icon-diamond" ,"list": [{ "name": "secretlist" ,"title": "列表" ,"jump": "secretapp/list" }, { "name":"secrets" ,"title": "关系" ,"jump": "secretapp/ship" }] },{ "name" : "config" ,"title": "设置" ,"icon": "layui-icon-set" ,"list": [{ "name": "secretlist" ,"title": "小程序设置" ,"jump": "config/app" }, { "name":"configs" ,"title": "后台设置" ,"jump": "secret/web" }] }] }
function tabs(tabsSelector, tabParentSelector, contentSelector, active){ const tabs = document.querySelectorAll(tabsSelector), tabParent = document.querySelector(tabParentSelector), content = document.querySelectorAll(contentSelector); function hideContent(){ content.forEach(item => { item.classList.remove('show'); item.classList.add('hide'); }); tabs.forEach(tab => { tab.classList.remove(active); }); } hideContent(); showContent(0); function showContent(i){ tabs[i].classList.add(active); content[i].classList.remove('hide'); content[i].classList.add('show'); } tabParent.addEventListener('click', (event) => { if(event.target && event.target.classList.contains(tabsSelector.slice(1))){ tabs.forEach((tab, i) => { if(tab == event.target){ hideContent(); showContent(i); } }); } }); } export default tabs;
import React, { Component } from 'react'; import Login from './Login'; import mySocket from 'socket.io-client';//importing socket packege class Signup extends Component { constructor(props){ super(props); this.state={ username: "", password: "", changeToSignIn: false } this.handleUsername=this.handleUsername.bind(this); this.handlePassword=this.handlePassword.bind(this); this.addAccount=this.addAccount.bind(this); this.changePage=this.changePage.bind(this); } // collect string data from what you entered into your input handleUsername(evt){ this.setState({ username:evt.target.value }) } handlePassword(evt){ this.setState({ password:evt.target.value }) } addAccount(){ console.log("working account"+this.state.username); console.log("working account"+this.state.password); fetch("/addUser/"+this.state.username); fetch("/addPW/"+this.state.password); this.setState ({ changeToSignIn: true }); } changePage() { this.setState ({ changeToSignIn: true }) } render() { var ui = null; if (this.state.changeToSignIn === false) { ui = ( <div> <h3>Welcome to Monika and Harks Page!</h3> <h4>Sign Up With Us!</h4> <p>Username:</p> <p><input type="text" placeholder="username" onChange={this.handleUsername}/></p> <p>Password:</p> <p><input type="text" placeholder="password" onChange={this.handlePassword}/></p> <hr/> <div className="Main"> <span></span> <span className="btnArea"> <button onClick={this.addAccount}>Confirm</button> </span> <span></span> </div> </div> ); } else if (this.state.changeToSignIn === true) { ui = ( <Login /> ); } return ( <div className="App"> {ui} </div> ); } } export default Signup;
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.createTable('users', { id: Sequelize.INTEGER }); */ var sequelize = queryInterface.sequelize; return sequelize.transaction(function (t) { return queryInterface.addColumn('TweetActions', "action", Sequelize.STRING, {transaction: t}) .then(function() { return queryInterface.removeColumn('TweetActions', "contacted_or_replied", {transaction: t}) }) .then(function() { return queryInterface.removeColumn('TweetActions', "follower_or_friend", {transaction: t}) }) .then(function() { return queryInterface.removeColumn('TweetActions', "read", {transaction: t}) }) }); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.dropTable('users'); */ var sequelize = queryInterface.sequelize; return sequelize.transaction(function (t) { return queryInterface.removeColumn('TweetActions', "action", {transaction: t}) .then(function() { return queryInterface.addColumn('TweetActions', "contacted_or_replied", Sequelize.BOOLEAN, {transaction: t}) }) .then(function() { return queryInterface.addColumn('TweetActions', "follower_or_friend", Sequelize.BOOLEAN, {transaction: t}) }) .then(function() { return queryInterface.addColumn('TweetActions', "read", Sequelize.BOOLEAN, {transaction: t}) }) }); } };
'use strict'; /** * @ngdoc function * @name laoshiListApp.controller:JobsCtrl * @description * # JobsCtrl * Controller of the laoshiListApp */ angular.module('laoshiListApp') .controller('JobsCtrl', ['jobs__', 'jobs_', 'llConstants', 'User_', 'currentAuth', 'fbMethods', '$scope', '$location', function (jobs__, jobs_, llConstants, User_, currentAuth, fbMethods, $scope, $location) { jobs__.getJobs().then(function(jobs) { $scope.jj = jobs.data; }); // important since firebase indices don't seem to be able to be set in ascending order $scope.groupBy = '-dateModified'; // pass constants to filter $scope.statuses = llConstants.jobstatus(); $scope.subjects = llConstants.subjects(); $scope.ages = llConstants.ages(); $scope.cities = llConstants.cities(); $scope.addJob = function() { jobs__.addJob({ status: 1, dateModified: Date.now() }).then(function(ref) { $location.path('/job-edit/' + ref.data) }) } }]);
export default { rpc: 'http://127.0.0.1:9545', factory: '0x3C56BB02196B0e2792d2ce4Ad88fEE6A4eca9aF3', allowedChains: [1337], chains: { 1337: 'Mainnet', }, app: { batchSize: 10, coinsIds: { WBNB: 'wbnb', BUSD: 'binance-usd', }, }, };
import Home from './screens/Home' export default Home
//------------------------------------------------------------------------------- var http = require('http') var net = require('net') var exec = require('child_process').exec var server = http.createServer(onRequest) var serverPort = '8083' // Same is in various groovy files. var scriptPath = '/home/pi/HomeAutomation/mFi/mfictrl.sh -l' server.listen(serverPort) console.log("mFi Server") //-- For each request received from SmartThings. ---------------------------- function onRequest(request, response){ console.log(" ") console.log(new Date()) var callString = '/home/pi/HomeAutomation/mFi/mfictrl.sh -l -u ' + request.headers["username"] + ' -a ' + request.headers["password"] + ' -p ' + request.headers["outlet"] + ' ' + request.headers["deviceip"] + ' ' + request.headers["command"] console.log(callString) exec(callString, (err, stdout, stderr) => { console.log(stdout) response.setHeader("cmd-response", stdout.replace(/\r?\n?/g, '')) response.end() }) } //-- Response to mFi Commands --------------------------------------- function processRequest(request, response) { var command = request.headers["command"] var deviceIP = request.headers["device-ip"] console.log("Sending to IP address: " + deviceIP + " Command: " + command) //--- Encrypt then send command to device and wait for response. ------- return new Promise((resolve, reject) => { var socket = net.connect(9999, deviceIP) socket.setKeepAlive(false) socket.setTimeout(2000) // 2 seconds. socket.on('connect', () => { socket.write(encrypt(command)) }) //-- Decrypt response (less header) then send to SmartThings. ------------------ socket.on('data', (data) => { data = decrypt(data.slice(4)).toString('ascii') console.log("Command Response sent to SmartThings!") response.setHeader("cmd-response", data) response.end() socket.end() resolve(data) //-- If a timeout, send a timeout indication to SmartThings. ------------------ }).on('timeout', () => { socket.end() response.setHeader("cmd-response", '{"error":"TCP Timeout"}') response.end() reject('Device TCP timeout') }).on('error', (err) => { socket.end() reject(err) }) }) //-- Encrypt the command including a 4 byte TCP header. ----------------------- function encrypt(input) { var buf = Buffer.alloc(input.length) var key = 0xAB for (var i = 0; i < input.length; i++) { buf[i] = input.charCodeAt(i) ^ key key = buf[i] } var bufLength = Buffer.alloc(4) bufLength.writeUInt32BE(input.length, 0) return Buffer.concat([bufLength, buf], input.length + 4) } //--- Decrypt the response. --------------------------------------------------- function decrypt(input, firstKey) { var buf = Buffer.from(input) var key = 0x2B var nextKey for (var i = 0; i < buf.length; i++) { nextKey = buf[i] buf[i] = buf[i] ^ key key = nextKey } return buf } }
function create() { return [0, 0, 0]; } function equals(a, b) { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; } function set(a, b) { a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; return a; } function add(a, b) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; return a; } function sub(a, b) { a[0] -= b[0]; a[1] -= b[1]; a[2] -= b[2]; return a; } function scale(a, n) { a[0] *= n; a[1] *= n; a[2] *= n; return a; } function multMat4(a, m) { var x = a[0]; var y = a[1]; var z = a[2]; a[0] = m[0] * x + m[4] * y + m[8] * z + m[12]; a[1] = m[1] * x + m[5] * y + m[9] * z + m[13]; a[2] = m[2] * x + m[6] * y + m[10] * z + m[14]; return a; } function multQuat(a, q) { var x = a[0]; var y = a[1]; var z = a[2]; var qx = q[0]; var qy = q[1]; var qz = q[2]; var qw = q[3]; var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = -qx * x - qy * y - qz * z; a[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; a[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; a[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; return a; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function cross(a, b) { var x = a[0]; var y = a[1]; var z = a[2]; var vx = b[0]; var vy = b[1]; var vz = b[2]; a[0] = y * vz - vy * z; a[1] = z * vx - vz * x; a[2] = x * vy - vx * y; return a; } function length(a) { var x = a[0]; var y = a[1]; var z = a[2]; return Math.sqrt(x * x + y * y + z * z); } function lengthSq(a) { var x = a[0]; var y = a[1]; var z = a[2]; return x * x + y * y + z * z; } function normalize(a) { var x = a[0]; var y = a[1]; var z = a[2]; var l = Math.sqrt(x * x + y * y + z * z); l = 1.0 / (l || 1); a[0] *= l; a[1] *= l; a[2] *= l; return a; } function distance(a, b) { var dx = b[0] - a[0]; var dy = b[1] - a[1]; var dz = b[2] - a[2]; return Math.sqrt(dx * dx + dy * dy + dz * dz); } function distanceSq(a, b) { var dx = b[0] - a[0]; var dy = b[1] - a[1]; var dz = b[2] - a[2]; return dx * dx + dy * dy + dz * dz; } function limit(a, n) { var x = a[0]; var y = a[1]; var z = a[2]; var dsq = x * x + y * y + z * z; var lsq = n * n; if (lsq > 0 && dsq > lsq) { var nd = n / Math.sqrt(dsq); a[0] *= nd; a[1] *= nd; a[2] *= nd; } return a; } function lerp(a, b, n) { var x = a[0]; var y = a[1]; var z = a[2]; a[0] = x + (b[0] - x) * n; a[1] = y + (b[1] - y) * n; a[2] = z + (b[2] - z) * n; return a; } function toString(a, precision) { var scale = Math.pow(10, precision !== undefined ? precision : 4); var s = '['; s += Math.floor(a[0] * scale) / scale + ', '; s += Math.floor(a[1] * scale) / scale + ', '; s += Math.floor(a[2] * scale) / scale + ']'; return s; } function copy(a) { return a.slice(0); } function addScaled(v, w, n) { v[0] += w[0] * n; v[1] += w[1] * n; v[2] += w[2] * n; return v; } var Vec3 = { create: create, set: set, copy: copy, equals: equals, add: add, addScaled: addScaled, sub: sub, scale: scale, multMat4: multMat4, multQuat: multQuat, dot: dot, cross: cross, length: length, lengthSq: lengthSq, normalize: normalize, distance: distance, distanceSq: distanceSq, limit: limit, lerp: lerp, toString: toString }; var vec3 = Vec3; // https://github.com/hughsk/mesh-normals // Compute normals for the mesh based on faces/cells information // If there are two vertices with the same position but different index there will be discontinuity (hard edge) function computeNormals(positions, cells, out) { var vertices = positions; var faces = cells; var normals = out || []; normals.length = 0; var count = []; var ab = [0, 0, 0]; var ac = [0, 0, 0]; var n = [0, 0, 0]; for (let fi = 0, numFaces = faces.length; fi < numFaces; fi++) { var f = faces[fi]; var a = vertices[f[0]]; var b = vertices[f[1]]; var c = vertices[f[2]]; vec3.normalize(vec3.sub(vec3.set(ab, b), a)); vec3.normalize(vec3.sub(vec3.set(ac, c), a)); vec3.normalize(vec3.cross(vec3.set(n, ab), ac)); for (let i = 0, len = f.length; i < len; i++) { if (!normals[f[i]]) { normals[f[i]] = [0, 0, 0]; } vec3.add(normals[f[i]], n); count[f[i]] = count[f[i]] ? 1 : count[f[i]] + 1; } } for (let i = 0, len = normals.length; i < len; i++) { if (normals[i]) { vec3.normalize(normals[i]); } else { normals[i] = [0, 1, 0]; } } return normals; } var geomNormals = computeNormals; export default geomNormals;
import React, { Component } from 'react'; //import logo from './logo.svg'; import './App.css'; import Input from './components/Input'; import SunTimesChart from './components/SunTimesChart'; class App extends Component { constructor(props) { super(props); this.state = { startDate: "2019-01-01", endDate: "2019-12-31", wakeUpTime: "07:00", workStart: "08:30", workEnd: "17:30", bedTime: "23:00", latitude: 0, longitude: 0, timeModel: "clockChange" }; this.changeStateValue = this.changeStateValue.bind(this); } componentDidMount() { navigator.geolocation.getCurrentPosition( (position) => { this.setState({ latitude: parseFloat(position.coords.latitude.toFixed(2)), longitude: parseFloat(position.coords.longitude.toFixed(2)) }); console.log(position.coords.latitude); } ) } changeStateValue(name, newValue) { this.setState({ [name]: newValue }); } render() { return ( <div className="App"> <h1>{this.state.timeModel}</h1> <Input startDate={this.state.startDate} endDate={this.state.endDate} wakeUpTime={this.state.wakeUpTime} workStart={this.state.workStart} workEnd={this.state.workEnd} bedTime={this.state.bedTime} latitude={this.state.latitude} longitude={this.state.longitude} onChange={this.changeStateValue} timeModel={this.state.timeModel}/> <SunTimesChart startDate={this.state.startDate} endDate={this.state.endDate} wakeUpTime={this.state.wakeUpTime} workStart={this.state.workStart} workEnd={this.state.workEnd} bedTime={this.state.bedTime} latitude={this.state.latitude} longitude={this.state.longitude} timeModel={this.state.timeModel} /> </div> ); } } export default App;
const socket = io(); const name = parseSubmitRequest("username") || 'Anonymous'; const room = parseSubmitRequest("room") || 'No Room Selected'; const roomTitle = document.querySelector('.room-title'); roomTitle.innerHTML = 'channel - ' + room; const avatarName = document.querySelector('.avatar-name'); avatarName.innerHTML = name; const userMessageStyle = [ 'font-size: 16px', 'color: black', 'padding-left: 10px'].join(';'); const formChat = document.getElementById('btn'); formChat.addEventListener('click', funcSubmit); const messageInput = document.getElementById('postedMessage'); const typing = document.getElementById('typing'); messageInput.addEventListener('keypress', () => { socket.emit('typing', { name: name, message: ' is typing ...' }) }); socket.on('notifyTyping', data => { typing.innerHTML = data.name + ' ' + data.message; }); messageInput.addEventListener('keyup', () => { socket.emit('stopTyping', ""); }); socket.on('notifyStopTyping', () => { typing.innerHTML = "" }); const createMessage = (data) => { const userMessage = document.createElement('span'); userMessage.setAttribute('style', userMessageStyle); userMessage.innerHTML = data.message; const userSaid = document.createElement('span'); userSaid.innerHTML = data.sender + ' says: '; const messages = document.getElementById('messages'); const messagesLi = document.createElement('li'); messagesLi.setAttribute('style', 'color: blue'); messagesLi.appendChild(userSaid); messagesLi.appendChild(userMessage); messages.appendChild(messagesLi); }; socket.on('chat message', function (msg) { createMessage(msg); }); socket.on("message", function (msg) { const messages = document.getElementById('messages'); const message = document.createElement('li'); message.setAttribute('style', userMessageStyle); message.innerHTML ='<p>' + msg.text + '</p'; messages.appendChild(message); let objDiv = document.getElementById("messages"); objDiv.scrollTop = objDiv.scrollHeight; }) // fires when client successfully connects to the server socket.on("connect", function () { console.log("Connected to Socket I/O Server!"); console.log(name + " wants to join channel " + room); socket.emit('joinRoom', new MessageItem(name, room)); App.fetchChatMessages(); }); class MessageItem { constructor(name, room) { this.name = name; this.room = room; } } class App { static fetchChatMessages() { fetch("/chats") .then(handleErrors) .then(json => { json.map(data => { createMessage(data); }); let objDiv = document.getElementById("messages"); objDiv.scrollTop = objDiv.scrollHeight; }) .catch(error => { console.log("Error = " + error) }); } };
const API = require("./data"); let placeholder = document.querySelector(".employees"); const PRINTINFO = { toDom(user) { let temp = document.createElement("article"); temp.setAttribute("class", "employee"); temp.innerHTML = ` <header class="employee__name"> <h1>${user.name}</h1> </header>` API.getDept(user.departmentId) .then(dept => { temp.innerHTML += ` <section class="employee__department"> Department: ${dept} </section>`; }) API.getEquip(user.equipmentId) .then(equip => { temp.innerHTML += ` <section class="employee__equipment"> Technology Issued: ${equip} </section>` placeholder.appendChild(temp); }); } }; module.exports = PRINTINFO;
function setup() { logger("setting up","Page"); showButtons(); } $(window).on("load",function(event) { setup(); }) //############################################################### function getState(){ var styleID = findGetParameter("styleID"); if(styleID.length === undefined) {styleID = ""} logger("found styleID", styleID) var brandID = findGetParameter("brandID"); if(brandID.length === undefined) {brandID = ""} logger("found brandID", brandID) var collectionID = findGetParameter("collectionID");if(collectionID.length === undefined) {collectionID = ""} logger("found collectionID", collectionID) var pickattr = findGetParameter("pickattr"); if(pickattr.length === undefined) {pickattr = ""} logger("found pickattr", pickattr) var category = findGetParameter("category"); if(category.length === undefined) {category = "none"} logger("found category", category); var style = findGetParameter("style"); if(style.length === undefined) {style = "none"} logger("found style", style) var brand = findGetParameter("brand"); if(brand.length === undefined) {brand = "none"} logger("found brand", brand) var collection = findGetParameter("collection");if(collection.length === undefined) {collection = "none"} logger("found collection", collection) var attr = findGetParameter("attr"); if(attr.length === undefined) {attr = "none"} logger("found attr", attr) //always false except get "true" from click var endf = findGetParameter("endflag"); if(endf.length === undefined) {endf = "false"} logger("found endflag", endf) var lang = findGetParameter("lang"); if(lang.length === undefined) {lang = "ENG"} logger("found lang", lang) var flow = findGetParameter("flow"); if(flow.length === undefined) {flow = "none"} logger("found flow", flow) var state = whereAreWe(category,style,brand,collection,attr,endf,flow); //get state status logger("type of state", typeof state); logger("user's on: ",state["onStep"] + " | value: " + state["stepValue"]); //pass other parameter to use on another function var helper = { "pickattr": pickattr, "collectionID":collectionID, "brandID": brandID, "styleID": styleID, "lang":lang, "flow":flow }; $.extend(state,helper); return state } //on each state, Select UI/ menu to show function stateMenuHandle(_state){ var onStep = _state["onStep"]; var stepValue = _state["stepValue"]; var flow = _state["flow"]; // state = { // "onStep": category <-- ?category=categories // "stepValue": categories <-- ?category=categories // "pickattr": blue, <-- ?pickattr=blue // "collectionID":12345 <-- ?collectionID=12345 // "brandID": 555 <-- ?brandID=555 // "styleID": 666 <-- ?styleID=666 // "lang":ENG <-- ?lang=ENG // "flow":flow <-- ?flow=BSCAL // } var UI = processUI(onStep,stepValue,flow); logger("ui",UI) UI = prep(UI); UI.map(function(choice) { //##################### UI building start here ###################### if(choice.length === 1){ var html = "<li class='item-divider'>" + choice + "</li>"; var elem = $(html).appendTo('ul') } else { var html = "<li><label class='label-radio item-content'>" + "<div class='item-inner'>" + "<div class='item-title'>" + choice + "</div>" + "</div>" + "</label>" + "</li>" var elem = $(html).appendTo('ul') } //##################### UI building end here ###################### //add tap properties $(elem).on("tap",function(evt){ clickButton(evt, choice, _state) })//end elem })//end buttons } //show UI menu function showButtons() { var _state = getState(); var onStep = _state["onStep"]; var stepValue = _state["stepValue"]; var collectionID = _state["collectionID"]; var pickattr = _state["pickattr"]; var brandID = _state["brandID"]; var styleID = _state["styleID"]; var lang = _state["lang"]; var flow = _state["flow"]; var link="#"; if(onStep != "end"){ insertSkipButton("#sweetbox");//<!-- <div class="skip-button"></div> --> var link = skipThrow(onStep,stepValue,lang,flow); $(".skip-button").on("tap",function(evt){ location.assign(link); }) } if(onStep !== "end"){ stateMenuHandle(_state); } else { insertLoadingGif('#shownitem','images/loading.gif'); goSearchLuxsens(lang,collectionID,styleID,brandID,pickattr); } }//end show button function clickButton(evt, choice, _state) { //somehow state is not static? var onStep = _state["onStep"]; var stepValue = _state["stepValue"]; var flow = _state["flow"]; logger("state",onStep + "/ " + stepValue); //get EN word from choice var choice = choice.split(' |')[0].toLowerCase(); //check status logger("selected choice :", choice); //get URL address var now = location.href; //###################################################################################################### // navigation step using if condition // //###################################################################################################### //########################################################################################### //# regular process -- BSCAL Brands --> Styles --> Collection --> attr --> Luxsens Search # //########################################################################################### if(flow == "BSCAL"){ //3) onStep collection if(onStep == "collection") { var _collectionID = getCollectionID(choice);//return 12345 sessionStorage.setItem("pickcollection",choice); //skip attr just go to search page location.assign(now.concat("&collectionID=" + _collectionID + "&attr=other" + "&pickattr="+"&endflag=go")); } //2) onStep style if(onStep === "style") { var _styleID = getStyleID(choice);// ex. [123456,"Cluth"] var brand = sessionStorage.pickbrand; var style = sessionStorage.pickstyle; sessionStorage.setItem("pickstyle",choice);// remember pick style location.assign(now.concat("&styleID="+_styleID +"&collection=" + brand)); } // 1) start : show all brands if(onStep === "brand") { var _brandID = getBrandID(choice);// ex. [123456,"hermes"] sessionStorage.setItem("pickbrand",choice);// remember pick brand --> "hermes" //if it is a watch if(stepValue == "wbrand") if(hasCollection2(choice)) { //1 has a collection go to collection sessionStorage.setItem("pickstyle","wrist watches") location.assign(now.concat("&brandID=" + _brandID[0] +"&style=none&styleID=1568"+"&collection=" + _brandID[1])) } else { //2 if it does not have collection --> skip attr --> go to Luxsens location.assign(now.concat("&brandID=" + _brandID[0] +"&style=none&styleID=1568&collection=other&collectionID=&attr=other&pickattr=&endflag=go")) } //if it is a bag if(stepValue == "bbrand"){ if(hasStyle(choice)) { //1 has a style go to that style location.assign(now.concat("&brandID=" + _brandID[0] +"&style=bstyle")); } else if(hasCollection2(choice)) { //2 if it does not have style --> goto collection location.assign(now.concat("&brandID=" + _brandID[0] +"&style=watch&styleID=1568"+"&collection=" + _brandID[1])); } else { //if don't have style&collection --> skip attr -->go to luxsens location.assign(now.concat("&brandID=" + _brandID[0] +"&collection=other&collectionID=&style=all&styleID=&attr=other&pickattr=&endflag=go")) } } } } //########################################################################################### //# All brands flow -- BSCAL Brands --> Collection --> attr --> Luxsens Search # //########################################################################################### if(flow == "allbrand"){ //3) onStep collection if(onStep == "collection") { var _collectionID = getCollectionID(choice);//return 12345 sessionStorage.setItem("pickcollection",choice); //skip attr just go to search page location.assign(now.concat("&collectionID=" + _collectionID + "&attr=other" + "&pickattr="+"&endflag=go")); } //2) onStep style if(onStep === "style") { var _styleID = getStyleID(choice);// ex. [123456,"Cluth"] var brand = sessionStorage.pickbrand; var style = sessionStorage.pickstyle; sessionStorage.setItem("pickstyle",choice);// remember pick style location.assign(now.concat("&styleID="+_styleID +"&collection=" + brand)); } // 1) start : show all brands if(onStep === "brand" && stepValue == "allbrand") { var _brandID = getBrandID(choice);// ex. [123456,"hermes"] sessionStorage.setItem("pickbrand",choice);// remember pick brand --> "hermes" if(hasStyle(choice)) { //1 has a style go to that style location.assign(now.concat("&brandID=" + _brandID[0] +"&style=astyle")); } else if(hasCollection2(choice)) { //2 if it does not have style --> goto collection location.assign(now.concat("&brandID=" + _brandID[0] +"&style=none&styleID=1568"+"&collection=" + _brandID[1])); } else { //if don't have style&collection --> skip attr -->go to luxsens location.assign(now.concat("&brandID=" + _brandID[0] +"&collection=other&collectionID=&style=all&styleID=&attr=other&pickattr=&endflag=go")) } } } //########################################################################################################### //# Category process -- CSBCAL Categories --> Styles --> Brands --> Collection --> attr --> Luxsens Search # //########################################################################################################### if(flow == "CSBCAL"){ //3) onStep collection if(onStep == "collection") { var _collectionID = getCollectionID(choice);//return 12345 sessionStorage.setItem("pickcollection",choice); //skip attr just go to search page location.assign(now.concat("&collectionID=" + _collectionID + "&attr=other" + "&pickattr="+"&endflag=go")); } // 1) start : show all brands if(onStep === "brand") { var _brandID = getBrandID(choice);// ex. [123456,"hermes"] sessionStorage.setItem("pickbrand",choice);// remember pick brand --> "hermes" var brand = sessionStorage.pickbrand; var style = sessionStorage.pickstyle; if(stepValue == "bbrand") { //1 has a collection go to that collection if(hasCollection(style,brand)){ location.assign(now.concat("&brandID=" + _brandID[0] +"&collection=" + _brandID[1])); } else { //if don't have collection --> skip attr -->go to luxsens location.assign(now.concat("&brandID=" + _brandID[0] +"&collection=other&collectionID=&attr=other&pickattr=&endflag=go")) } } else if(stepValue == "wbrand") { //1 has a collection go to that collection if(hasCollection2(brand)){ location.assign(now.concat("&brandID=" + _brandID[0] +"&style=none&styleID=1568&collection=" + _brandID[1])); } else { //if don't have collection --> skip attr -->go to luxsens location.assign(now.concat("&brandID=" + _brandID[0] +"&style=none&styleID=1568&collection=other&collectionID=&attr=other&pickattr=&endflag=go")) } } } //2) onStep style if(onStep === "style") { var _styleID = getStyleID(choice);// ex. [123456,"Cluth"] sessionStorage.setItem("pickstyle",choice);// remember pick style location.assign(now.concat("&styleID="+_styleID +"&brand=bbrand")); } // 1) start : show 2 categories if(onStep == "category") { if(choice == "bag"){ location.assign(now.concat("&style=bstyle")); } else if(choice == "watch") { //2 if it does not have style --> goto collection sessionStorage.setItem("pickstyle","wrist watches") location.assign(now.concat("&style=none&styleID=1568&brand=wbrand")); } } } } //############################################################################# function goSearchLuxsens(lang,_collectionid,_stylesid,_brandid,_pickattr){ if(_pickattr == "all"){ _pickattr = ""; } if(lang == "CHN") { location.replace( "http://chs.luxsens.com/m/index.php/view/product/list.html/+attr/item_collection/" + _collectionid + "/item_style/" + _stylesid + "/item_brand/" + _brandid + "/+category/45/+searching/" + _pickattr ) } else if(lang == "ENG") { location.replace( "http://www.luxsens.com/m/index.php/view/product/list.html/+attr/item_collection/" + _collectionid + "/item_style/" + _stylesid + "/item_brand/" + _brandid + "/+category/45/+searching/" + _pickattr ) } } function insertLoadingGif(id,path){ var html = "<div class='prompt'>" + "<img src='" + path +"''>" + "</img>" + "</div>"; $(html).appendTo(id); } function insertSkipButton(id){ var html = "<div class='skip-button'>SKIP</div>"; $(html).prependTo(id); } function skipThrow(onStep,stepValue,lang,flow){ var prefix = "www"; var link="#"; if(lang == "CHN") prefix = "chs"; if(flow == "BSCAL"){ if(onStep == "brand" && stepValue == "bbrand"){ link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+category/72" } else if(onStep == "brand" && stepValue == "wbrand"){ link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+category/73" } else if(onStep == "style"){//get all items in that Brands except watch var b_id = findGetParameter("brandID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr/item_brand/"+b_id+"/+category/72" } else if(onStep == "collection"){//bags get all collection on styles&brands -- watch get all collection var b_type = findGetParameter("brand"); var b_id = findGetParameter("brandID"); if(findGetParameter("styles") != "none") var s_id = findGetParameter("styleID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr/item_style/"+s_id+"/item_brand/"+b_id+"/+category/45" } } if(flow == "allbrand"){ if(onStep == "brand"){ link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+category/45" } else if(onStep == "style"){//get all items in that Brands except watch var b_id = findGetParameter("brandID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr/item_brand/"+b_id+"/+category/72" } else if(onStep == "collection"){//bags get all collection on styles&brands -- watch get all collection var b_type = findGetParameter("brand"); var b_id = findGetParameter("brandID"); if(findGetParameter("styles") != "none") var s_id = findGetParameter("styleID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr/item_style/"+s_id+"/item_brand/"+b_id+"/+category/45" } } if(flow == "CSBCAL"){ if(onStep == "category"){ link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+category/45" } else if(onStep == "style"){//get all items in that Brands except watch link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+category/72" } else if(onStep == "brand"){ var s_id = findGetParameter("styleID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr"+"/item_style/"+s_id+"+category/45" } else if(onStep == "collection"){//bags get all collection on styles&brands -- watch get all collection var b_type = findGetParameter("brand"); var b_id = findGetParameter("brandID"); if(findGetParameter("styles") != "none") var s_id = findGetParameter("styleID"); link = "http://" + prefix + ".luxsens.com/m/index.php/view/product/list.html/+attr/item_style/"+s_id+"/item_brand/"+b_id+"/+category/45" } } return link } function processUI(onStep,stepValue,flow){ var _case = 666; //fail case var UI; //becareful of load order, the first page must be on the buttom if(onStep =="end"){ _case = 4 // wait for redirect, do nothing } //########################################################################################### //# regular process -- BSCAL Brands --> Styles --> Collection --> attr --> Luxsens Search # //########################################################################################### if(flow == "BSCAL"){ if( onStep =="attr") { _case = 040; //show attr } else if( onStep =="collection") { _case = 030; //got brand and style, g for collection } else if( onStep =="style") { _case = 020; //go to search style of that brands } else if( onStep =="brand" && stepValue == "wbrand") { _case = 011; //go to possible watches brand include Chanel/Lv/etc. } else if( onStep =="brand" && stepValue == "bbrand") { _case = 010; //go to handle bags brand } else{ _case = 27; //unreachable } } //########################################################################################### //# all brand process -- Brands --> Styles --> Collection --> attr --> Luxsens Search # //########################################################################################### if(flow == "allbrand"){ if(onStep =="attr") { _case = 040; //show attr //} else if( onStep =="collection" && findGetParameter("styleID") == 1568) { // _case = 031; //got brand and style, go for collection } else if( onStep =="collection") { _case = 030; //got brand and style, go for collection } else if( onStep =="style") { _case = 021; //go to search style of that brands } else if( onStep =="brand") { _case = 012; //go to possible watches brand include Chanel/Lv/etc. } else{ _case = 27; //unreachable } } //########################################################################################################### //# Category process -- CSBCAL Categories --> Styles --> Brands --> Collection --> attr --> Luxsens Search # //########################################################################################################### if(flow == "CSBCAL"){ if( onStep =="attr") { _case = 040; //show attr } else if( onStep =="collection") { _case = 030; //got brand and style, g for collection } else if( onStep =="brand" && stepValue == "wbrand") { _case = 011; //go to possible watches brand include Chanel/Lv/etc. } else if( onStep =="brand" && stepValue == "bbrand") { _case = 010; //go to handle bags brand } else if( onStep =="style") { _case = 022; //go to search style of that brands } else if( onStep =="category") { _case = 000; //show categories } else { _case = 27; //unreachable } } switch(_case){ case 4: UI = {}; case 031: //Note:case sensitive. in database first letter is capitalize ex. "Backpack" var brand = sessionStorage.pickbrand; UI = queryCollection2(brand); break; case 030: //Note:case sensitive. in database first letter is capitalize ex. "Backpack" var style = sessionStorage.pickstyle; var brand = sessionStorage.pickbrand; UI = queryCollection(style,brand); break; case 022: //simply show array in menuData.js; key =stepValue UI = queryMenuData('bstyle'); break; case 021: //obtain brand; query all possible style according to that brand. //Note:case sensitive. in database first letter is capitalize ex. "Backpack" var brand = sessionStorage.pickbrand; UI = queryStyles2(brand); break; case 020: //obtain brand; query all possible style according to that brand. //Note:case sensitive. in database first letter is capitalize ex. "Backpack" var brand = sessionStorage.pickbrand; UI = queryStyles(brand); break; case 012: //show all brands that has wrist watches //Note:case sensitive. in database first letter is capitalize ex. "Backpack" UI = queryAllBrand(); break; case 011: //show all brands that has wrist watches //Note:case sensitive. in database first letter is capitalize ex. "Backpack" UI = queryBrand('wrist watches'); break; case 010: //simply show array in menuData.js; key =stepValue UI = queryMenuData('bbrand'); break; case 000: //simply show array in menuData.js; key =stepValue UI = queryMenuData('categories'); break; case 27: //lost alert("Error#27: how did you get here, buddy?, please start over.") break; case 666: //error alert("Error#666: can't handle!! selection, please start over.") break; } return UI; }
import React from 'react'; import PropTypes from 'prop-types'; import LazyLoad from 'react-lazyload'; import styles from './Image.module.scss'; const Image = ({ src, alt }) => ( <LazyLoad height="100%" once classNamePrefix={`${styles.revealer} lazyload`}> <img src={src} alt={alt} /> </LazyLoad> ); Image.propTypes = { src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, }; export default Image;
import db from '../../../db/index.js' const deleteEatRow = async (eatId) => { return new Promise((resolve, reject) => { db.query(` DELETE FROM eat WHERE eat_id = $1 ` , [eatId] , (err, dbRes) => { if (err) { console.log('eat/delete err:', err) reject(err) } else { resolve(dbRes) } }) }) } export default async function deleteEat (req, res) { try { const { eatId } = req.body await deleteEatRow(eatId) res.status(200).send({ done: true }) } catch (error) { console.error(error) res.status(500).end(error.message) } }
'use strict'; module.exports = (sequelize, DataTypes) => { const Request = sequelize.define('Request', { type: DataTypes.STRING, target_id: DataTypes.INTEGER, requester: DataTypes.STRING, comment: DataTypes.STRING, request: DataTypes.JSON, old: DataTypes.JSON, approved: DataTypes.BOOLEAN, reviewer_id: DataTypes.INTEGER, reviewed: DataTypes.DATE, feedback: DataTypes.STRING }, { timestamps: true, updatedAt: false }); Request.associate = function(models) { // associations can be defined here }; return Request; };
var content = { tasks: [ { // 1. FELADAT --------------------------------------------------------------------------------------------------- type: "test", hu: { question: "Milyen állatcsoportba tartoznak a denevérek?", answers: [ "<h2>madarak</h2>", "<h2>puhatestűek</h2>", "<h2>emlősök</h2>" ] }, en: { question: "Which group of animals do bats belong to?", answers: [ "<h2>birds</h2>", "<h2>molluscs</h2>", "<h2>mammals</h2>" ] }, hr: { question: "U koju skupinu životinja spadaju šišmiši?", answers: [ "<h2>ptice</h2>", "<h2>mekušci</h2>", "<h2>sisavci</h2>" ] }, rightAnswer: 3, time: 15, score: 6, background: "./g/bg_quiz-1.jpg" }, { // 2. FELADAT --------------------------------------------------------------------------------------------------- type: "test", hu: { question: "Melyik tápláléktípust nem eszik a denevérek?", answers: [ "<h2>giliszta</h2>", "<h2>nektár</h2>", "<h2>szúnyogok</h2>" ], }, en: { question: "Which food type bats do not eat?", answers: [ "<h2>earthworms</h2>", "<h2>nectar</h2>", "<h2>mosquitoes</h2>" ], }, hr: { question: "Koju vrstu hrane ne jedu šišmiši?", answers: [ "<h2>gliste</h2>", "<h2>nektar</h2>", "<h2>komarci</h2>" ], }, rightAnswer: 1, time: 15, score: 6, background: "./g/bg_quiz-2.jpg" }, { // 3. FELADAT --------------------------------------------------------------------------------------------------- type: "test", hu: { question: "Hányszor ellenek a denevérek egy évben?", answers: [ "<h2>1x</h2>", "<h2>2x</h2>", "<h2>3-4x</h2>" ], }, en: { question: "How many times do bats give birth a year?", answers: [ "<h2>1x</h2>", "<h2>2x</h2>", "<h2>3-4x</h2>" ], }, hr: { question: "Koliko puta se godišnje okote šišmiši?", answers: [ "<h2>1x</h2>", "<h2>2x</h2>", "<h2>3-4x</h2>" ], }, rightAnswer: 1, time: 15, score: 6, background: "./g/bg_quiz-3.jpg" }, { // 4. FELADAT --------------------------------------------------------------------------------------------------- type: "test", hu: { question: "Mennyi szúnyogot eszik egy törpedenevér egy éjszaka alatt?", answers: [ "<h2>10</h2>", "<h2>100</h2>", "<h2>1000</h2>" ], }, en: { question: "How many mosquitoes does a pipistrelle eat in one night?", answers: [ "<h2>10</h2>", "<h2>100</h2>", "<h2>1000</h2>" ], }, hr: { question: "Koliko komaraca pojede patuljasti šišmiš za jednu noć?", answers: [ "<h2>10</h2>", "<h2>100</h2>", "<h2>1000</h2>" ], }, rightAnswer: 3, time: 15, score: 6, background: "./g/bg_quiz-4.jpg" }, { // 5. FELADAT --------------------------------------------------------------------------------------------------- type: "test", hu: { question: "Hány millió éves a legrégebbi ismert denevér fosszília?", answers: [ "<h2>5</h2>millió", "<h2>5,2</h2>millió", "<h2>52,5</h2>millió" ], }, en: { question: "What is the age of the oldest bat fossil?", answers: [ "<h2>5</h2>million years", "<h2>5,2</h2>million years", "<h2>52,5</h2>million years" ], }, hr: { question: "Koliko milijuna godina je najstariji pronađeni fosil šišmiša?", answers: [ "<h2>5</h2>milijuna", "<h2>5,2</h2>milijuna", "<h2>52,5</h2>milijuna" ], }, rightAnswer: 3, time: 15, score: 6, background: "./g/bg_quiz-5.jpg" }, { // 6. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", iconPosition: { x: 150, y: 0 }, hideReset: true, snap: true, hu: { question: "Melyik állatra illik az öt állítás?", question2: "Húzd a helyes nevet az állat képére", extra1: { text: "a. szárnya van", x: 527, y: 580 }, extra2: { text: "b. tud repülni", x: 527, y: 630 }, extra3: { text: "c. szárnyfesztávolsága 1,5 méter", x: 527, y: 680 }, extra4: { text: "d. gyümölcsökkel táplálkozik", x: 527, y: 730 }, extra5: { text: "e. az ázsiai trópusokon él", x: 527, y: 780 } }, en: { question: "Which animal is described with the following five features?", question2: "Move the correct species name to the picture of the animal", extra1: { text: "a. it has wings", x: 527, y: 580 }, extra2: { text: "b. it can fly", x: 527, y: 630 }, extra3: { text: "c. it has a wingspan of 1.5 m", x: 527, y: 680 }, extra4: { text: "d. it feeds on fruits", x: 527, y: 730 }, extra5: { text: "e. it lives in Asian tropical areas", x: 527, y: 780 } }, hr: { question: "Na koju životinju se odnose sljedeće tvrdnje?", question2: "Povuci ispravni naziv na sliku životinje", extra1: { text: "a. ima krila", x: 527, y: 580 }, extra2: { text: "b. umije letjeti", x: 527, y: 630 }, extra3: { text: "c. raspon krila 1,5 metra", x: 527, y: 680 }, extra4: { text: "d. hrani se plodovima", x: 527, y: 730 }, extra5: { text: "e. živi u suptropskim krajevima Azije", x: 527, y: 780 } }, destinations: [ { name: "step2", x: { hu: 1030, en: 1030, hr: 1030 }, y: { hu: 594, en: 594, hr: 594 }, width: 210, height: 210 } ], answers: [ { image: "./g/barchoba_label.png", rightAnswer: "step1", x: 527, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "malajziai óriás<br>repülő mókus", en: "Malayan giant<br>flying squirrel", hr: "malajzijska golema<br>leteća vjeverica" } }, { image: "./g/barchoba_label.png", rightAnswer: "step2", x: 855, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "óriás<br>repülőkutya", en: "large<br>flying fox", hr: "golema<br>leteća lisica" } }, { image: "./g/barchoba_label.png", rightAnswer: "step3", x: 1183, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "brazil<br>repülő vidra", en: "Brazilian<br>flying otter", hr: "brazilska<br>leteća vidra" } }, ], labelStyle: "label_inner_barchoba", time: 60, score: 7, background: "./g/bg_barchoba.jpg" }, { // 7. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 150, y: 0 }, hideReset: true, hu: { question: "Melyik állatra illik az öt állítás?", question2: "Húzd a helyes nevet az állat képére", extra1: { text: "a. faodúban vagy házakban lakik", x: 527, y: 580 }, extra2: { text: "b. a Föld egyik legkisebb denevére", x: 527, y: 630 }, extra3: { text: "c. testtömege 5 gramm", x: 527, y: 680 }, extra4: { text: "d. szúnyogokkal táplálkozik", x: 527, y: 730 }, extra5: { text: "e. Európában él", x: 527, y: 780 } }, en: { question: "Which animal is described with the following five features?", question2: "Move the correct species name to the picture of the animal", extra1: { text: "a. it lives in tree holes or in houses", x: 527, y: 580 }, extra2: { text: "b. it is one of the smallest bats living on Earth", x: 527, y: 630 }, extra3: { text: "c. its body weight is 5 grams", x: 527, y: 680 }, extra4: { text: "d. it feeds on mosquitoes", x: 527, y: 730 }, extra5: { text: "e. it lives in Europe", x: 527, y: 780 } }, hr: { question: "Na koju životinju se odnosi ovih pet tvrdnji?", question2: "Povuci ispravni naziv na sliku životinje", extra1: { text: "a. živi u šupljinama drveća ili po kućama", x: 527, y: 580 }, extra2: { text: "b. jedan je od najmanjih šišmiša", x: 527, y: 630 }, extra3: { text: "c. teži 5 grama", x: 527, y: 680 }, extra4: { text: "d. hrani se komarcima", x: 527, y: 730 }, extra5: { text: "e. živi u Europi", x: 527, y: 780 } }, destinations: [ { name: "step3", x: { hu: 1030, en: 1030, hr: 1030 }, y: { hu: 594, en: 594, hr: 594 }, width: 210, height: 210 } ], answers: [ { image: "./g/barchoba_label.png", rightAnswer: "step1", x: 527, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "tenor<br>törpedenevér", en: "tenor<br>pipistrelle", hr: "patuljasti<br>šumski šišmiš" } }, { image: "./g/barchoba_label.png", rightAnswer: "step2", x: 855, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "basszus<br>törpedenevér", en: "bass<br>pipistrelle", hr: "golemi<br>močvarni šišmiš" } }, { image: "./g/barchoba_label.png", rightAnswer: "step3", x: 1183, y: 297, labelStyle: "label_inner_barchoba", label: { hu: "szoprán<br>törpedenevér", en: "soprano<br>pipistrelle", hr: "patuljasti<br>močvarni šišmiš" } }, ], labelStyle: "label_inner_barchoba", time: 60, score: 7, background: "./g/bg_barchoba-1.jpg" }, { // 8. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 300, y: 130 }, hideReset: true, hu: { question: "Húzd a helyes kifejezést az üres helyre a mondatban", question2: "", extra1: { text: "<h3>Az európai denevérek október végétől márciusig téli álmot alszanak.", x: 600, y: 690 }, extra2: { text: "<h3>Tudományosan ezt ............................... nevezzük.", x: 600, y: 765 } }, en: { question: "Move the correct expression to the empty space in the following sentence", question2: "", extra1: { text: "<h3>European bats are in a state of seasonal inactivity from late October to March.", x: 600, y: 690 }, extra2: { text: "<h3>The proper scientific term for this is ..........................", x: 600, y: 765 } }, hr: { question: "Povuci ispravni izraz na prazno mjesto u rečenici", question2: "", extra1: { text: "<h3>Europski šišmiši od konca listopada do ožujka spavaju zimski san.", x: 600, y: 690 }, extra2: { text: "<h3>Znanstveno se to naziva ............................", x: 600, y: 765 } }, destinations: [ { name: "step2", x: { hu: 838, en: 1080, hr: 910 }, y: { hu: 600, en: 596, hr: 598 }, width: 336, height: 336 } ], answers: [ { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step1", x: 1227, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "kibernációnak", en: "cybernation", hr: "kibernacijom" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step2", x: 792, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "hibernációnak", en: "hibernation", hr: "hibernacijom" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step3", x: 356, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "hipotermiának", en: "hypothermia", hr: "hipotermijom" } }, ], labelStyle: "label_inner_kiegeszites", time: 60, score: 7, background: "./g/bg_egeszitsd_ki.jpg" }, { // 9. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 265, y: 130 }, hideReset: true, hu: { question: "Húzd a helyes kifejezést az üres helyre a mondatban", question2: "", extra1: { text: "<h3>A júniusban megszületett kölykét a nőstény ..................... ", x: 604, y: 693 }, extra2: { text: "<h3>szoptatja, ezután lesz önálló a fiatal denevér", x: 600, y: 768 } }, en: { question: "Move the correct expression to the empty space in the following sentence", question2: "", extra1: { text: "<h3>Bat babies are born in June and are then nursed by the female .............................,", x: 604, y: 693 }, extra2: { text: "<h3>only after which they are weaned and become independent.", x: 600, y: 768 } }, hr: { question: "Povuci ispravni izraz na prazno mjesto u rečenici", question2: "", extra1: { text: "<h3>Svoje mladunče rođeno u lipnju ženka doji ........................,", x: 604, y: 693 }, extra2: { text: "<h3>nakon toga mladi šišmiš postaje samostalan.", x: 600, y: 768 } }, destinations: [ { name: "step1", x: { hu: 1170, en: 1476, hr: 1160 }, y: { hu: 528, en: 528, hr: 528 }, width: 336, height: 336 } ], answers: [ { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step1", x: 792, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "1 hónapig", en: "for 1 month", hr: "1 tjedan" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step2", x: 1227, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "1 hétig", en: "for 1 week", hr: "1 mjesec" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step3", x: 356, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "6-8 hétig", en: "for 6-8 weeks", hr: "6-8 tjedana" } }, ], labelStyle: "label_inner_kiegeszites", time: 60, score: 7, background: "./g/bg_egeszitsd_ki.jpg" }, { // 10. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 320, y: 130 }, hideReset: true, hu: { question: "Húzd a helyes kifejezést az üres helyre a mondatban", question2: "", extra1: { text: "<h3>Európában ........", x: 600, y: 686 }, extra2: { text: "<h3>vérszívó denevérfaj él.", x: 600, y: 761 } }, en: { question: "Move the correct number to the empty space in the following sentence", question2: "", extra1: { text: "<h3>In Europe there are ........", x: 600, y: 686 }, extra2: { text: "<h3>sanguivorous bat species.", x: 600, y: 761 } }, hr: { question: "Povuci ispravni izraz na prazno mjesto u rečenici", question2: "", extra1: { text: "<h3>U Europi živi ........", x: 600, y: 686 }, extra2: { text: "<h3>vrsta šišmiša krvopija.", x: 600, y: 761 } }, destinations: [ { name: "step3", x: { hu: 630, en: 750, hr: 650 }, y: { hu: 520, en: 520, hr: 520 }, width: 336, height: 336 } ], answers: [ { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step1", x: 1227, y: 280, labelStyle: "label_inner_kiegeszites_1", label: { hu: "1", en: "1", hr: "1" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step2", x: 792, y: 280, labelStyle: "label_inner_kiegeszites_1", label: { hu: "2", en: "2", hr: "2" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step3", x: 356, y: 280, labelStyle: "label_inner_kiegeszites_1", label: { hu: "0", en: "0", hr: "0" } }, ], labelStyle: "label_inner_kiegeszites", time: 60, score: 7, background: "./g/bg_egeszitsd_ki.jpg" }, { // 11. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 300, y: 130 }, hideReset: true, hu: { question: "Húzd a helyes kifejezést az üres helyre a mondatban", question2: "", extra1: { text: "<h3>A denevérek fennmaradását a(z) .........................", x: 457, y: 686 }, extra2: { text: "<h3>veszélyezteti.", x: 457, y: 761 }, }, en: { question: "Move the correct expression to the empty space in the following sentence", question2: "", extra1: { text: "<h3>The survival of bats", x: 557, y: 686 }, extra2: { text: "<h3>is threatened by ..............................", x: 557, y: 761 }, }, hr: { question: "Povuci ispravni izraz na prazno mjesto u rečenici", question2: "", extra1: { text: "<h3>Opstanak šišmiša ugrožava ..............................", x: 557, y: 686 }, extra2: { text: "<h3> ", x: 557, y: 761 }, }, destinations: [ { name: "step1", x: { hu: 890, en: 765, hr: 943 }, y: { hu: 518, en: 595, hr: 518 }, width: 336, height: 336 } ], answers: [ { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step2", x: 792, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "zsíros étrend", en: "their fatty diet", hr: "masna ishrana" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step1", x: 1227, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "erdőirtás", en: "deforestation", hr: "krčenje šuma" } }, { image: "./g/egeszitsd_ki_valasz.png", rightAnswer: "step3", x: 356, y: 280, labelStyle: "label_inner_kiegeszites", label: { hu: "UV sugárzás", en: "UV radiation", hr: "UV zračenje" } }, ], labelStyle: "label_inner_kiegeszites", time: 60, score: 7, background: "./g/bg_egeszitsd_ki.jpg" }, { // 12. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 150, y: 0 }, hu: { question: "Mik veszélyeztetik a denevérek fennmaradását, és mit tehetünk ellenük?", question2: "Húzd a képeket a megfelelő helyre", extra1: { text: " ", x: 357, y: 688 }, extra2: { text: " ", x: 1464, y: 403 }, extra3: { text: " ", x: 1464, y: 702 } }, en: { question: "What can threaten the survival of bats, and what can we do against these?", question2: "Move the images to the correct positions", extra1: { text: " ", x: 357, y: 688 }, extra2: { text: " ", x: 1464, y: 403 }, extra3: { text: " ", x: 1464, y: 702 } }, hr: { question: "Što sve ugrožava opstanak šišmiša i što možemo učiniti protiv toga?", question2: "Povuci na odgovarajuće mjesto", extra1: { text: " ", x: 357, y: 688 }, extra2: { text: " ", x: 1464, y: 403 }, extra3: { text: " ", x: 1464, y: 702 } }, destinations: [ { name: "step1", x: { hu: 523, en: 523, hr: 523 }, y: { hu: 483, en: 483, hr: 483 }, width: 177, height: 255 }, { name: "step2", x: { hu: 832, en: 832, hr: 832 }, y: { hu: 329, en: 329, hr: 329 }, width: 177, height: 255 }, { name: "step3", x: { hu: 1052, en: 1052, hr: 1052 }, y: { hu: 329, en: 329, hr: 329 }, width: 177, height: 255 }, { name: "step4", x: { hu: 1274, en: 1274, hr: 1274 }, y: { hu: 329, en: 329, hr: 329 }, width: 177, height: 255 }, { name: "step5", x: { hu: 834, en: 834, hr: 834 }, y: { hu: 629, en: 629, hr: 629 }, width: 177, height: 255 }, { name: "step6", x: { hu: 1053, en: 1053, hr: 1053 }, y: { hu: 629, en: 629, hr: 629 }, width: 177, height: 255 }, { name: "step7", x: { hu: 1273, en: 1273, hr: 1273 }, y: { hu: 629, en: 629, hr: 629 }, width: 177, height: 255 } ], answers: [ { image: "./g/12-serult-denever-etetes.png", rightAnswer: "step4", x: 235, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-barlang-zaras.png", rightAnswer: "step3", x: 450, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-odu.png", rightAnswer: "step2", x: 650, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-permetezes.png", rightAnswer: "step5", x: 850, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-erdoirtas.png", rightAnswer: "step7", x: 1050, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-epuletfelujitas.png", rightAnswer: "step6", x: 1250, y: 850, label: { hu: " ", en: " ", hr: " " } }, { image: "./g/12-vedd-oket.png", rightAnswer: "step1", x: 1450, y: 850, label: { hu: " ", en: " ", hr: " " } }, ], labelStyle: "label_under", time: 60, score: 2, background: "./g/bg_eromu_mukodese.jpg" }, { // 13. FELADAT --------------------------------------------------------------------------------------------------- type: "drag", snap: true, iconPosition: { x: 150, y: 0 }, hu: { question: "Húzd a kifejezéseket a megfelelő képekhez", question2: " ", extra1: { text: "", x: 1270, y: 300 }, extra2: { text: "", x: 359, y: 416 }, extra3: { text: "", x: 358, y: 640 }, extra4: { text: "", x: 358, y: 857 }, extra5: { text: "", x: 774, y: 416 }, extra6: { text: "", x: 774, y: 600 } }, en: { question: "Move the expressions to the corresponding images", question2: " ", extra1: { text: "", x: 1272, y: 302 }, extra2: { text: "", x: 361, y: 418 }, extra3: { text: "", x: 360, y: 642 }, extra4: { text: "", x: 360, y: 859 }, extra5: { text: "", x: 776, y: 418 }, extra6: { text: "", x: 776, y: 602 } }, hr: { question: "Povuci izraze na odgovarajuće slike", question2: " ", extra1: { text: "", x: 1272, y: 302 }, extra2: { text: "", x: 361, y: 418 }, extra3: { text: "", x: 360, y: 642 }, extra4: { text: "", x: 360, y: 859 }, extra5: { text: "", x: 776, y: 418 }, extra6: { text: "", x: 776, y: 602 } }, destinations: [ { name: "step1", x: { hu: 849, en: 849, hr: 849 }, y: { hu: 791, en: 791, hr: 791 }, width: 218, height: 218 }, { name: "step2", x: { hu: 604, en: 604, hr: 604 }, y: { hu: 657, en: 657, hr: 657 }, width: 218, height: 218 }, { name: "step3", x: { hu: 850, en: 850, hr: 850 }, y: { hu: 513, en: 513, hr: 513 }, width: 218, height: 218 }, { name: "step4", x: { hu: 1099, en: 1099, hr: 1099 }, y: { hu: 665, en: 665, hr: 665 }, width: 218, height: 218 }, { name: "step5", x: { hu: 1099, en: 1099, hr: 1099 }, y: { hu: 371, en: 371, hr: 371 }, width: 218, height: 218 }, { name: "step6", x: { hu: 603, en: 603, hr: 603 }, y: { hu: 366, en: 366, hr: 366 }, width: 218, height: 218 }, { name: "step7", x: { hu: 849, en: 849, hr: 849 }, y: { hu: 238, en: 238, hr: 238 }, width: 218, height: 218 } ], answers: [ { image: "./g/parositsd.png", rightAnswer: "step4", x: 1354, y: 561, labelStyle: "label_inner_parositsd_1", label: { hu: "genetikai<br>kutatás", en: "genetic<br>research", hr: "genetsko<br>istraživanje" } }, { image: "./g/parositsd.png", rightAnswer: "step2", x: 1612, y: 691, labelStyle: "label_inner_parositsd_2", label: { hu: "infra<br>kamerás<br>felvétel", en: "infrared<br>camera<br>images", hr: "nimanje<br>infra<br>kamerom" } }, { image: "./g/parositsd.png", rightAnswer: "step5", x: 119, y: 671, labelStyle: "label_inner_parositsd_1", label: { hu: "denevér<br>gyűrűzés", en: "bat<br>ringing", hr: "prstenovanje<br>šišmiša" } }, { image: "./g/parositsd.png", rightAnswer: "step1", x: 1548, y: 386, labelStyle: "label_inner_parositsd_1", label: { hu: "ultrahang<br>detektor", en: "ultrasound<br>detector", hr: "ultrazvučni<br>detektor" } }, { image: "./g/parositsd.png", rightAnswer: "step3", x: 327, y: 453, labelStyle: "label_inner_parositsd_2", label: { hu: "rádió<br>telemetriás<br>kutatás", en: "radio<br>telemetry<br>research", hr: "radio-<br>telemetrijsko<br>istraživanje" } }, { image: "./g/parositsd.png", rightAnswer: "step6", x: 368, y: 780, labelStyle: "label_inner_parositsd_1", label: { hu: "hálózásos<br>befogás", en: "bat trapping using mist nets", hr: "hvatanje<br>mrežom" } }, { image: "./g/parositsd.png", rightAnswer: "step7", x: 76, y: 383, labelStyle: "label_inner_parositsd", label: { hu: "húrcsapda", en: "harp trap", hr: "hvatanje žicom" } }, ], labelStyle: "", time: 60, score: 2, background: "./g/bg_novenyek.jpg" } ], // ÁLTALÁNOS SZÖVEGEK ----------------------------------------------------------------------------------------------- texts: { check_btn: { hu: "Helyes<br>válasz", en: "Check", hr: "Ispravan<br>odgovor" }, next_btn: { hu: "Tovább", en: "Next", hr: "Dalje" }, reset_btn: { hu: "Újra", en: "Reset", hr: "Reset" }, again_btn: { hu: "Újra", en: "Again", hr: "Ponovo" }, eval100: { hu: "Gratulálunk!<br>Akár munkatársunk is lehetnél.", en: "Congratulations, you have reached the maximum possible score!", hr: "Čestitamo! Mogao bi nam biti suradnik."}, eval90: { hu: "Jó megfigyelő vagy,<br>de lehetne ez jobb is.", en: "Congratulations, you are a great observer!", hr: "Dobro zapažaš, ali bi moglo biti i bolje."}, eval60: { hu: "Máshol jártak a gondolataid.<br>Megpróbálod újra?", en: "You must have listened to something else! Do you want to try again?", hr: "Misli su ti negdje drugdje. Hoćeš li pokušati ponovo?"} } }
import Head from 'next/head' import Navbar from './Navbar' const Layout = ({ children }) => { return ( <header> <Head> <title>Nextjs | GraphQL | Resume</title> <meta name="description" content="Full Stack Next.js, GraphQL, Apollo Resume" /> <meta name="keywords" content="Next.js, GraphQL, Apollo, Nexus Schema, Materialize" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossOrigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </Head> <Navbar /> { children} </header> ) } export default Layout
const test = require('tape'); const isTypedArray = require('./isTypedArray.js'); test('Testing isTypedArray', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof isTypedArray === 'function', 'isTypedArray is a Function'); //t.deepEqual(isTypedArray(args..), 'Expected'); //t.equal(isTypedArray(args..), 'Expected'); //t.false(isTypedArray(args..), 'Expected'); //t.throws(isTypedArray(args..), 'Expected'); t.end(); });
var nextDataKey = 1; export function generateDataKey() { return 'vectormap-data-' + nextDataKey++; }
/*EXPECTED -1 -1 4294967295 */ class _Main { static function main(args : string[]) : void { var a = [ 0xffffffff ] : Array.<int>; log a[0]; var m = { k: 0xffffffff } : Map.<int>; log m["k"]; var v = { k : 0xffffffff } : variant; log v["k"]; } }
import KeyCodes from 'keycodes-enum'; import AccessibilityModule from '../../index'; describe('RadioData', () => { describe('register role', () => { let cjsRadio; let inputEl; let isChecked; let positionVal; let shouldEnableKeyEvents; let sizeVal; let valueVal; beforeEach(() => { cjsRadio = new createjs.Shape(); // dummy object isChecked = false; positionVal = 7; shouldEnableKeyEvents = false; sizeVal = 99; valueVal = 7; AccessibilityModule.register({ accessibleOptions: { checked: isChecked, enableKeyEvents: shouldEnableKeyEvents, position: positionVal, size: sizeVal, value: valueVal, }, displayObject: cjsRadio, parent: container, role: AccessibilityModule.ROLES.RADIO, }); stage.accessibilityTranslator.update(); inputEl = parentEl.querySelector('input'); }); describe('rendering', () => { it('creates input[type=radio] element', () => { expect(inputEl.type).toEqual('radio'); }); it('sets "aria-posinset" attribute', () => { expect(parseInt(inputEl.getAttribute('aria-posinset'), 10)).toEqual( positionVal ); }); it('sets "aria-setsize" attribute', () => { expect(parseInt(inputEl.getAttribute('aria-setsize'), 10)).toEqual( sizeVal ); }); }); describe('accessible options getters and setters', () => { it('can read and set "position" property [for "aria-posinset"]', () => { expect(cjsRadio.accessible.position).toEqual(positionVal); const newVal = -1; cjsRadio.accessible.position = newVal; expect(cjsRadio.accessible.position).toEqual(newVal); }); it('can read and set "size" property [for "aria-setsize"]', () => { expect(cjsRadio.accessible.size).toEqual(sizeVal); const newVal = -1; cjsRadio.accessible.size = newVal; expect(cjsRadio.accessible.size).toEqual(newVal); }); }); describe('other options getters and setters', () => { it('can read and set "checked" property', () => { expect(cjsRadio.accessible.checked).toEqual(isChecked); const newVal = true; cjsRadio.accessible.checked = newVal; expect(cjsRadio.accessible.checked).toEqual(newVal); }); it('can read and set "enableKeyEvents" property', () => { expect(cjsRadio.accessible.enableKeyEvents).toEqual( shouldEnableKeyEvents ); const newVal = true; cjsRadio.accessible.enableKeyEvents = newVal; expect(cjsRadio.accessible.enableKeyEvents).toEqual(newVal); }); it('can read and set "value" property', () => { expect(cjsRadio.accessible.value).toEqual(valueVal); const newVal = 99; cjsRadio.accessible.value = newVal; expect(cjsRadio.accessible.value).toEqual(newVal); }); }); describe('"onKeydown" event listener', () => { it('emits "keyboardClick" event on Enter and Space', () => { const keyboardClickListener = jest.fn(); let keyCode = KeyCodes.enter; cjsRadio.on('keyboardClick', keyboardClickListener); inputEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(keyboardClickListener).toBeCalledTimes(1); keyCode = KeyCodes.space; inputEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(keyboardClickListener).toBeCalledTimes(2); }); }); describe('"onChange" event listener', () => { it('emits "change" event', () => { const changeListener = jest.fn(); cjsRadio.on('change', changeListener); inputEl.dispatchEvent(new KeyboardEvent('change')); expect(changeListener).toBeCalledTimes(1); }); }); }); });
FintUI.importData=''; FintUI.initFunctions.home=function() { console.log('init home'); //$('#homeimportstatus .message').html('Last Updated: '); // MESSAGES $('#homeimportstatus .message').html(finance.home.updateStatusMessages()); $('#homeimportstatus .message').click(function () { $('#homeimportstatus .message').html(finance.home.updateStatusMessages()); return false; }); // HOMESCREEN WIDGETS $('.homewidget h3').click(function() { finance.home.toggleHomeWidget(this); }); $('#content').tabs('load',4); // preload help ?? //$("#homerightcol").accordion(); // one click import sample data $('#homeimportsomedata').click(function() { //$('#content').tabs({load : function(){alert('activs'); }}); $('#content').tabs('option','active','4'); $('#sharemanager').tabs('option','active','1'); console.log('ALLRECS',$('#allrecordsjson').val()); $('#importtext').val($('#allrecordsjson').val()); $('#importtext').keyup(); }); } /* //QUERIES // nested tags SELECT t.name tn,tp.name tpn,tpp.name tppn,tp.name||t.name tr FROM tags t LEFT JOIN tags tp ON tp.rowid=t.parenttags LEFT JOIN tags tpp on tpp.rowid=tp.parenttags create index accounts.index on accounts ( create index "16.i_tags" on mm_transactionstags (tags); create index "16.i_tags" on mm_transactionstags (transactions); create index "16.i_transactionstags" on mm_transactionstags (transactions,tags); create index "16.i_rulestags" on rules (tags); create index "16.i_rulesaccounts" on rules (accounts); create index "16.i_rulesaccountstags" on rules (accounts,tags); create index "16.i_tagsparenttags" on tags (parenttags); create index "16.i_accountsbanks" on accounts (banks); create index fintfinance.i_accounts on mm_transactionstags (accounts); create index quickdb.i_tags on mm_transactionstags (tags); --drop index "16.i_transactions"; --drop index "16.i_tags"; --drop index "16.i_transactionstags"; create index "16.i_transactions" on mm_transactionstags (transactions); create index "16.i_tags" on mm_transactionstags (tags); create index "16.i_transactionstags" on mm_transactionstags (transactions,tags); create index "16.i_rulestags" on rules (tags); create index "16.i_rulesaccounts" on rules (accounts); create index "16.i_rulesaccountstags" on rules (accounts,tags); create index "16.i_tagsparenttags" on tags (parenttags); create index "16.i_accountsbanks" on accounts (banks); */ FintUI.activateFunctions.home=function(settings) { console.log('activate home'); // MESSAGES $('#homeimportstatus .message').html(finance.home.updateStatusMessages()); $('#homeimportstatus .message').click(function () { $('#homeimportstatus .message').html(finance.home.updateStatusMessages()); return false; }); // HOMESCREEN WIDGETS $('.homewidget h3').click(function() { finance.home.toggleHomeWidget(this); }); $('#homeimportsomedata').click(function() { //$('#content').tabs({load : function(){alert('activs'); }}); $('#content').tabs('option','active','4'); $('#sharemanager').tabs('option','active','1'); $('#importtext').val('{"rules":[],"tags":[{"rowid":1,"name":"income","parenttags":""},{"rowid":2,"name":"personal income","parenttags":"1"},{"rowid":3,"name":"taxable income","parenttags":"1"}],"ebankingsites":[],"banks":[{"rowid":1,"name":"anz","logo":null},{"rowid":2,"name":"commonwealth","logo":null}],"accounts":[{"rowid":1,"name":"saver","number":"987987987","banks":"2","ebankingsites":null},{"rowid":2,"name":"saver","number":"8768768767","banks":"1","ebankingsites":null}],"transactions":[{"rowid":1,"date":"2013-03-13","description":"COLES SUPERMARKETS","amount":"76.66","balance":"","split":"","comment":"","accounts":"1","tags":""},{"rowid":2,"date":"2013-12-31","description":"DICK SMITH ELECTRONICS 9789888","amount":"278.00","balance":"","split":"","comment":"","accounts":"2","tags":""},{"rowid":3,"date":"2013-12-27","description":"BP PETROLEUM 76877768777","amount":"77.00","balance":"","split":"","comment":"","accounts":"1","tags":""}]}'); $('#importtext').keyup(); }); //console.log('activate home'); //console.log('scroll top'); //var plugin=$('#hometransactionmanagersearch').quickDB(settings)[0]; $(document).scrollTop(0); } // transaction manager searcher and main list FintUI.initFunctions.hometransactionmanagersearch=function(settings) { console.log('init hometransactionmanagersearch'); var plugin=$('#hometransactionmanagersearch').quickDB(settings)[0]; plugin.settings.templates.listRow = "<tr><td><input type='checkbox' checked class='listrowcheckbox' data-rowid='${rowid}' />${listButtons.edit}${listButtons.delete}</td>${listFields}<td>${listButtons.approve}${listButtons.tag}${listButtons.rule}${listButtons.split}</td></tr>"; plugin.settings.templates.listHeaders = "<tr><th><input type='checkbox' checked class='listrowtoggleall'/>${listHeaderButtons.add}</th>${listHeaders}<th>${listHeaderButtons.approveselected}${listHeaderButtons.tagselected}${listHeaderButtons.rulefromselected}${listHeaderButtons.splitrulefromselected}</th></tr>"; plugin.settings.templates.listCollateItemWrap = "<div ><h3><input type='checkbox' checked class='listrowtogglecollated'/>${collateValue}</h3>${list}</div>"; plugin.settings.templates.listCollateBy='accounts'; $.extend(plugin.settings.templates.listButtons,{ "approve":"<img src='images/tick.png' title='Approve record ID ${rowid}' />",// markers - <row values> "rule":"<img src='images/things.png' title='Create rule from record ID ${rowid}' />", "split":"<img src='images/split.png' title='Split record ID ${rowid}' />",// markers - <row values> "tag":"<img src='images/tag.png' title='Tag record ID ${rowid}' />"// markers - <row values> }); $.extend(plugin.settings.templates.listHeaderButtons,{ "approveselected":"<img style='dispjlay:none;' src='images/tick.png' title='Approve selected records' />",// markers - <row values> "rulefromselected":"<img src='images/things.png' title='Create rule from selected records' />", "splitrulefromselected":"<img src='images/split.png' title='Split rule from selected records' />", "tagselected":"<img src='images/tag.png' title='Tag selected' />" }); // WHEN THE ACCOUNTS MANAGER CHECK SELECTIONS CHANGE, UPDATE MY LIST plugin.api.view.renderListFinalCallback=function() { //var plugin=this; // MUNGE LIST TAGS //transactions.rowid in (select rowid from transactions where description match ruleswithtags.filtertext) left join tags ruletags on ruletags.rowid=ruleswithtags.tags $(".editablerecords .row-odd,.editablerecords .row-even").each(function() { var thisRow=this; //console.log($('.list-field-description',this).text()); //var query="select rules.rowid,rules.name,tags.name from rules left join tags on tags.rowid=rules.tags where '"+$('.list-field-description',this).text()+"' match rules.filtertext "; //console.log(query); setTimeout(function() { //console.log('do timeout'); //return; var combinedTags={}; $.each($('.list-field-selectedtags .join-value',thisRow),function() { if (!combinedTags[$(this).data('join-rowid')]) combinedTags[$(this).data('join-rowid')]={}; combinedTags[$(this).data('join-rowid')].label=$(this).text(); combinedTags[$(this).data('join-rowid')].selected=true; combinedTags[$(this).data('join-rowid')].selectedText=' selected '; //$(this).remove(); //console.log('ROWID',$(this).data('join-rowid')); }); $.each($('.list-field-ruleswithtags .join-value',thisRow),function() { if (!combinedTags[$(this).data('join-rowid')]) combinedTags[$(this).data('join-rowid')]={selectedText:'',suggestedText:''}; combinedTags[$(this).data('join-rowid')].label=$(this).text(); combinedTags[$(this).data('join-rowid')].suggested=true; combinedTags[$(this).data('join-rowid')].suggestedText=' suggested '; //console.log('ROWIDrules',$(this).data('join-rowid')); }); var finalTags=[]; // console.log('combinedTags',combinedTags); $.each(combinedTags,function(tagId,tagMeta) { //console.log('renTAGS',tagId,tagMeta); var buttons=[]; if (tagMeta.suggested && !tagMeta.selected) { buttons.push("<img src='images/tick.png' class='approvetagbutton' title='Approve Tag' />"); } else if (tagMeta.selected) { buttons.push("<img src='images/deleterecord.png' class='removetagbutton' title='Deselect Tag' />") } //console.log('buttons',buttons); finalTags.push('<span class="join-value'+tagMeta.selectedText+tagMeta.suggestedText+'" data-join-rowid="'+tagId+'">'+tagMeta.label+buttons.join("")+'</span>'); }); //if (finalTags.length>0) console.log('finalTags',finalTags); //else console.log('notags'); $('.list-field-selectedtags',thisRow).html(finalTags.join("")); $('.list-field-ruleswithtags').hide(); $('.list-field-status').hide(); },10); }); finance.home.bindHomeTransactionListButtons(plugin); } //$('#sharebutton').bind('click',function() {$('#sharemenu').menu().toggle(); return false;}); //$('#optionsbutton').bind('click',function() {$('#optionsmenu').menu().toggle(); return false;}); }; FintUI.activateFunctions.hometransactionmanagersearch=function(settings) { console.log('activate hometransactionmanagersearch'); var plugin=$('#hometransactionmanagersearch').quickDB(settings)[0]; $(document).scrollTop(0); } // accounts manager tab FintUI.initFunctions.homeaccountsmanager=function(settings) { console.log('init homeaccountsmanager',settings); var plugin=$('#homeaccountsmanager').quickDB(settings)[0]; plugin.settings.formTarget=$('#homemaincol'); plugin.settings.templates.listRow = "<tr><td><input type='checkbox' checked class='listrowcheckbox' data-rowid='${rowid}' />${listButtons}</td>${listFields}</tr>"; plugin.settings.templates.listHeaders = "<tr><th><input type='checkbox' checked class='listrowtoggleall'/>${listHeaderButtons}</th>${listHeaders}</tr>"; plugin.settings.templates.listCollateItemWrap = "<div ><h3><input type='checkbox' checked class='listrowtogglecollated'/>${collateValue}</h3>${list}</div>"; plugin.settings.templates.listCollateBy='banks'; plugin.api.view.renderListFinalCallback=function() { $("#homeaccountsmanager input[type=checkbox]").prop("checked",false); $("#homeaccountsmanager .collatedlistrows").hide(); finance.home.bindAccountsCheckboxes(plugin); //console.log('pluginsettings',plugin.settings) }; }; //FintUI.pluginSettings.homecategoriesmanager={templates:{listAddButton:"<a><img src='images/addrecord.png' />&nbsp;Add Stuff</a>"}}; FintUI.activateFunctions.homeaccountsmanager=function(settings) { console.log('activate homeaccountsmanager',settings); var plugin=$('#homeaccountsmanager').quickDB(settings)[0]; $(document).scrollTop(0); } // categories manager tab FintUI.initFunctions.homecategoriesmanager=function(settings) { console.log('init homecategoriesmanager'); var plugin=$('#homecategoriesmanager').quickDB(settings)[0]; plugin.settings.formTarget=$('#homemaincol'); plugin.settings.templates.listRow = "<tr><td><input type='checkbox' checked class='listrowcheckbox' data-rowid='${rowid}' />${listButtons}</td>${listFields}</tr>"; plugin.settings.templates.listHeaders = "<tr><th><input type='checkbox' checked class='listrowtoggleall'/>${listHeaderButtons}</th>${listHeaders}</tr>"; plugin.settings.templates.listCollateItemWrap = "<div ><h3><input type='checkbox' checked class='listrowtogglecollated'/>${collateValue}</h3>${list}</div>"; plugin.settings.templates.listCollateBy='parenttags'; plugin.api.view.renderListFinalCallback=function() { //alert('renderlist'); } }; FintUI.activateFunctions.homecategoriesmanager=function(settings) { console.log('activate homecategoriesmanager'); var plugin=$('#homecategoriesmanager').quickDB(settings)[0]; $(document).scrollTop(0); }
Type.registerNamespace("Fenetre.Sitefinity.FormHandler"); Fenetre.Sitefinity.FormHandler.FormCaptcha = function (element) { this._radCaptcha = null; this._dataFieldName = null; Fenetre.Sitefinity.FormHandler.FormCaptcha.initializeBase(this, [element]); } Fenetre.Sitefinity.FormHandler.FormCaptcha.prototype = { /* --------------------------------- set up and tear down ---------------------------- */ /* --------------------------------- public methods ---------------------------------- */ // Gets the value of the field control. get_value: function () { return jQuery(this._radCaptcha).val(); }, // Sets the value of the text field control depending on DisplayMode. set_value: function (value) { jQuery(this._radCaptcha).val(value); }, /* --------------------------------- event handlers ---------------------------------- */ /* --------------------------------- private methods --------------------------------- */ /* --------------------------------- properties -------------------------------------- */ get_radCaptcha: function () { return this._radCaptcha; }, set_radCaptcha: function (value) { this._radCaptcha = value; }, get_dataFieldName: function () { return this._dataFieldName; }, set_dataFieldName: function (value) { this._dataFieldName = value; } } Fenetre.Sitefinity.FormHandler.FormCaptcha.registerClass('Fenetre.Sitefinity.FormHandler.FormCaptcha', Telerik.Sitefinity.Web.UI.Fields.FieldControl);
import React, { useState, useEffect } from 'react'; import AlbumsListComponent from '../Components/AlbumsListComponent'; const AlbumsList = () => { const [hasError, setErrors] = useState(false); const [albums, setAlbums] = useState([]); const [photos, setPhotos] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const userId = urlParams.get('id'); const url = `https://jsonplaceholder.typicode.com/users/${userId}/albums`; const fetchData = async () => { setIsLoading(true); const res = await fetch(url); res .json() .then((res) => { setAlbums(res); return res; }) .then((res) => { const albumIdsUrl = res.map( (item) => `https://jsonplaceholder.typicode.com/albums/${item.id}/photos` ); Promise.all( albumIdsUrl.map((url) => fetch(url).then((res) => res.json())) ).then((res) => { setPhotos(res.flat(1)); setIsLoading(false); }); }) .catch((err) => setErrors(err)); }; fetchData(); }, []); return ( <AlbumsListComponent hasError={hasError} albums={albums} photos={photos} isLoading={isLoading} /> ) }; export default AlbumsList;
import React, { Component } from 'react'; import {Route} from 'react-router-dom' import {Link} from 'react-router-dom' import './App.css'; import * as BooksAPI from './BooksAPI' import Header from './Header' import Shelves from './Shelves' import Shelf from './Shelf'; class App extends Component { state={ books:[], filter:'' } componentDidMount(){ this.setState( () =>( { books:[ { title: 'Alice in Wonderland', image:'', author:'A', id:1, status:'current' }, { title: 'R&J', image:'', author:'A', id:5, status:'current' }, { title: 'Sherlock', image:'', author:'B', id:2, status:'future' }, { title: 'The Great Gatsby', image:'', author:'C', id:3, status:'read' }, { title: 'Macbeth', image:'', author:'D', id:4, status:'future' }, { title: 'The Great Escape', image:'', author:'A', id:6, status:'none' }, { title: 'Of Mice & Men', image:'', author:'A', id:7, status:'none' }, { title: 'The Secret Barrister', image:'', author:'B', id:8, status:'none' }, { title: 'Der Regler', image:'', author:'C', id:9, status:'none' }, { title: 'Hamlet', image:'', author:'D', id:10, status:'none' } ] } ) ) // console.log(BooksAPI.search('cook')) } changeStatus = (book,status) => { this.removeBook(book) this.addBook(book,status) } removeBook = (remove_book) => { this.setState( (prevState) => ({ books: prevState.books.filter( (book) => { return book.id !== remove_book.id } ) } )) } addBook = (book,status) => { book.status=status this.setState( (prevState) => ({books:prevState.books.concat(book)}) ) } updateFilter = (query) => { this.setState(() => ( { filter:query } )) } filteredBooks = () => { return this.state.books.filter((book) => ( book.title.toLowerCase().includes(this.state.filter.toLowerCase()) )) } render() { return ( <div className='background'> <Route exact path='/' render={() =>( <div> <Header filter={this.state.filter} filterSearch={this.updateFilter} /> <Shelves books={this.filteredBooks()} changeStatus={this.changeStatus} filter={this.state.filter} /> <div className='add-new-books-div'> <Link to='search' className='add-new-books' > Find new Books </Link> </div> </div> )} /> <Route path='/search' render ={() =>( <div className='background'> <Header filter={this.state.filter} filterSearch={this.updateFilter} /> <Shelf status='none' books={this.filteredBooks().filter((book) => {return book.status === 'none'})} action={this.changeStatus} /> </div> )} /> </div> ) } } export default App;
(function() { 'use strict'; angular.module('awards') .config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) { $stateProvider .state('awards', { url: '/awards', templateUrl: '/awards.view.html', controller: 'AwardsCtrl as vm', resolve: { awards: function (Awards) { return Awards.initialize(); } }, ncyBreadcrumb: { label: 'Awards' } }) }]); }());
@font-face { font-family: appleLogo; src: local("Lucida Grande"); unicode-range: U+F8FF } html { height: 100% } body { position: relative; min-height: 100% } footer { border-top: 1px solid #e8e8e8; bottom: 0; left: 0; width: 100%; z-index: 10; background: #fff; padding: 40px 0 0; color: #717274 } footer section { clear: both; box-sizing: border-box; max-width: 1014px; padding: 0 1.5rem!important; margin: 0 auto } footer section h1 { font-size: 30px; line-height: 36px; font-weight: 400; margin: 0 } footer section p { line-height: 26px } footer section .grid { width: 100% } footer section .grid:after, footer section .grid:before { content: " "; font-size: 0; display: table } footer section .grid:after { clear: both } footer .ts_icon_slack_pillow { display: inline-block; width: 28px; height: 28px; color: #a0a0a2; margin-left: -3px } footer .ts_icon_slack_pillow:hover { color: #8c8c94 } footer .ts_icon_slack_pillow:before { font-size: 28px; line-height: 48px } footer small { display: block; font-size: 12px; line-height: 16px; margin: 5px 0 0 } footer .col { -webkit-tap-highlight-color: rgba(0, 0, 0, 0) } footer .col:focus { outline: 0 } footer ul { margin: 0; padding: 0; list-style-type: none } footer ul a, footer ul a:link, footer ul a:visited { font-size: .82rem; color: #717274; text-decoration: none } footer ul a:hover { color: #8c8c94; text-decoration: none!important } footer ul .cat_1, footer ul .cat_2, footer ul .cat_3, footer ul .cat_4 { text-transform: uppercase; font-size: 11px; font-family: Slack-Lato, appleLogo, sans-serif; font-weight: 700 } footer ul .cat_1 { color: #ff9000 } footer ul .cat_2 { color: #e32072 } footer ul .ts_icon_heart:before { font-size: 17px; margin-left: -2px; line-height: 13px } footer ul .cat_3 { color: #2ea664 } footer ul .cat_4 { color: #4b6bc6 } footer .footnote { margin-top: 1rem; background-color: rgba(0, 0, 0, .05); overflow: hidden; min-height: 50px; height: 50px } footer .footnote ul { margin: 0 20px 0 0; padding: 0; list-style-type: none; float: right } footer .footnote ul li { display: inline-block; list-style: none; margin-right: .7rem; float: left; line-height: 50px } footer .footnote ul li.yt { line-height: 48px; margin-right: 0 } footer.apps_footer { padding: 40px 0 } footer.apps_footer #apps_footer_content { -ms-flex-pack: distribute; -webkit-box-pack: distribute; -webkit-justify-content: space-around; -moz-justify-content: space-around; justify-content: space-around; max-width: 1024px } footer.apps_footer #apps_footer_content a { display: inline-block; text-decoration: none; color: #717274 } footer.apps_footer #apps_footer_content .slack_twitter { padding-left: 1.5rem; position: relative } footer.apps_footer #apps_footer_content .slack_twitter ts-icon { left: 0; position: absolute } @media only screen and (max-width:768px) { footer.apps_footer #apps_footer_content { -ms-flex-pack: start; -webkit-box-pack: start; -webkit-justify-content: flex-start; -moz-justify-content: flex-start; justify-content: flex-start; padding-top: 0; padding-bottom: 6rem!important; position: relative } footer.apps_footer #apps_footer_content .logo_content { bottom: 0; left: 0; position: absolute; text-align: center; width: 100% } footer.apps_footer #apps_footer_content a { padding-bottom: 1rem; padding-top: 1rem; width: 50% } } footer:not(.footer_dark) .footnote .ts_icon_twitter:hover { color: #4fa9f1 } footer:not(.footer_dark) .footnote .ts_icon_youtube:hover { color: #d11f10 } footer.footer_dark { background-color: transparent; border-top: 1px solid rgba(255, 255, 255, .1) } footer.footer_dark .footnote { background-color: rgba(255, 255, 255, .12) } footer.footer_dark .ts_icon_slack_pillow, footer.footer_dark a, footer.footer_dark a:link, footer.footer_dark a:visited { color: rgba(255, 255, 255, .5) } footer.footer_dark .ts_icon_slack_pillow:hover, footer.footer_dark a:hover, footer.footer_dark a:link:hover, footer.footer_dark a:visited:hover { color: rgba(255, 255, 255, .7) } footer.footer_dark .cat_1, footer.footer_dark .cat_2, footer.footer_dark .cat_3, footer.footer_dark .cat_4 { color: #fff } footer.footer_dark .col:before, footer.footer_dark.footer_dark_custom .ts_icon_slack_pillow, footer.footer_dark.footer_dark_custom a, footer.footer_dark.footer_dark_custom a:link, footer.footer_dark.footer_dark_custom a:visited { color: rgba(255, 255, 255, .7) } footer.footer_dark.footer_dark_custom .ts_icon_slack_pillow:hover, footer.footer_dark.footer_dark_custom a:hover, footer.footer_dark.footer_dark_custom a:link:hover, footer.footer_dark.footer_dark_custom a:visited:hover { color: #fff } @media only screen and (max-width:767px) { footer.footer_dark { background-color: #000; border-top: 0 } footer.footer_dark .links .col { border-top: 1px solid rgba(255, 255, 255, .14) } footer { padding: 0!important; border-top: 0 } footer li { display: none; text-indent: 1rem; padding: 2px 0 } footer li:first-child { text-indent: 0; display: block } footer .links { padding: 0!important } footer .links .col { cursor: pointer; border-top: 1px solid rgba(0, 0, 0, .09); padding: 14px 18px 10px } footer .links .col:before { font-family: Slack; font-size: 18px; font-style: normal; font-weight: 400; display: block; content: '\E279'; position: absolute; right: 15px; line-height: 32px } footer .links .col:not(.mobile_col) { margin: 0 } footer .links .col:last-child { border-bottom: 0 } footer .links .col.open:before { content: '\E280' } footer .links .col.open li { display: block } footer .links .col.open li:first-child { margin-bottom: .5rem } footer .footnote { height: 54px; margin-top: 0; border-top: 1px solid rgba(0, 0, 0, .06) } footer .footnote .ts_icon_slack_pillow:before { line-height: 50px } footer .footnote ul { margin-right: 0 } footer .footnote li { text-indent: 0 } footer .footnote section { padding: 0 20px!important } } @media only screen and (max-width:320px) { footer .nav_col:not(.mobile_col) { width: 100%!important } }
import React, { Component } from 'react'; import { Box, Text, } from 'grommet'; import {AreaChart, Area, Tooltip} from 'recharts'; import { CaretUp, CaretDown } from 'grommet-icons'; import { AccordionWithHeader, AccordionNode, AccordionHeader, AccordionPanel } from 'react-accordion-with-header'; import { trainsWithProblem, trainsWithoutProblem } from './database'; const carriagesData = (data) => ( <div style={{justifyContent: 'center', display: 'flex', flexDirection:'row', padding: '32px 0 32px', overflow: 'auto'}}> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', borderRadius: '56px 0 0 0', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[0]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[1]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[2]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[3]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[4]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[5]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[6]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> <div style={{width: '132px', height: '80px', backgroundColor: '#fff', border: '1px solid #AAAAAA', borderRadius: '0 56px 0 0', margin: '0 8px'}}> <AreaChart width={142} height={90} data={data[7]} margin={{top: 10, right: 10, left: 0, bottom: 24}}> <Tooltip/> <Area isAnimationActive={false} type='monotone' dataKey='hvac' stroke='#70a1ff' fill='#70a1ff' /> <Area isAnimationActive={false} type='monotone' dataKey='temperature' stroke='#7bed9f' fill='#7bed9f' /> </AreaChart> </div> </div> ) export default class Dashboard extends Component { state = { accordionStatesProblem: null, accordionStatesNormal: null, activeIndexNormal: [] } actionCallbackProblem = (panels) => { this.setState({accordionStatesProblem: panels}); } actionCallbackNormal = (panels) => { this.setState({accordionStatesNormal: panels}); } render() { const { accordionStatesProblem, accordionStatesNormal } = this.state; return ( <div> <Box margin='medium'> <Text style={{marginBottom: '8px'}}>Trains with problem (2)</Text> <Box background="light-1" elevation='xsmall'> <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-around'}}> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Class</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Time</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>From</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>To</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Status</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> </div> </div> <AccordionWithHeader actionCallback={this.actionCallbackProblem}> {trainsWithProblem.map((train, i) => ( <AccordionNode key={i} > <AccordionHeader horizontalAlignment="spaceBetween" verticalAlignment="center"> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.class}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.time}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.from}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.to}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text style={{color: train.status === 'Normal' ? '#7bed9f' : 'orange'}}>{train.status}</Text> </div> <div style={{flex: 1, textAlign: 'center', paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> {(accordionStatesProblem && accordionStatesProblem.length && accordionStatesProblem[i].open) ? <CaretUp size='small' /> : <CaretDown size='small' />} </div> </AccordionHeader> <AccordionPanel> {carriagesData(train.carriagesData)} </AccordionPanel> </AccordionNode> ))} </AccordionWithHeader> </Box> </Box> <Box margin='medium'> <Text style={{marginBottom: '8px'}}>Rolling Stock in Service (350)</Text> <Box background="light-1" elevation='xsmall'> <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-around'}}> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Class</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Time</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>From</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>To</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>Status</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> </div> </div> <AccordionWithHeader actionCallback={this.actionCallbackNormal}> {trainsWithoutProblem.map((train, i) => ( <AccordionNode key={i} > <AccordionHeader horizontalAlignment="spaceBetween" verticalAlignment="center"> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.class}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.time}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.from}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text>{train.to}</Text> </div> <div style={{flex: 1, paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> <Text style={{color: train.status === 'Normal' ? '#7bed9f' : 'orange'}}>{train.status}</Text> </div> <div style={{flex: 1, textAlign: 'center', paddingLeft: '24px', paddingTop: '16px', paddingBottom: '16px'}}> {(accordionStatesNormal && accordionStatesNormal.length && accordionStatesNormal[i].open) ? <CaretUp size='small' /> : <CaretDown size='small' />} </div> </AccordionHeader> <AccordionPanel> {carriagesData(train.carriagesData)} </AccordionPanel> </AccordionNode> ))} </AccordionWithHeader> </Box> </Box> </div> ); } }
export function getParsedCampaignQueryWithAttr (query, id) { for (let key in query) { if (key.includes('attributes')) { if (typeof query[key] === 'object') { Object.assign(query, query[key]) } else { const splitQueryValue = query[key].split('|') query[splitQueryValue[0]] = splitQueryValue[1] } delete query[key] } } id && (query.cat = id) return query }
export const SET_WITHDRAW_INFO = 'SET_WITHDRAW_INFO'; export function setWithdrawInfo(data) { return { type: SET_WITHDRAW_INFO, action : data }; }
const express=require('express'); const router=express.Router(); const viewuserleave=require('../Models/viewuserleavemodel'); router.get("/viewadmin", async (req,res) => { try{ console.log(req.body); let viewallleave=await viewuserleave.adminview(); let i=0,j=0,k=0; let info=[]; viewallleave.forEach(element => { let dates=element.dates; //o[key3]=element.uuid; dates.forEach(ele => { if(ele.hrs!=0) { j=j+1; } k=k+1; }) info.push({ uuid:element.uuid, totaldays:k, present:j }); k=0; j=0; } ) res.json(info); }catch(error){ console.log(error); } }) module.exports=router;
import "./reset.css" import { createGlobalStyle } from "styled-components"; export default createGlobalStyle` body { font-family: 'Lexend Deca', sans-serif; background-color: #F2F2F2; } button { cursor: pointer; height: 45px; background-color:#52B6FF; color: white; font-size: 21px; border: none; border-radius: 4.65px; &:disabled { opacity: 0.7; } } input { width: 300px; height: 45px; border: 1.5px solid#D5D5D5; color:#666666; line-height: 25px; font-size: 16px; border-radius: 5px; margin-bottom: 6px; padding-left: 10px; outline: none; &::placeholder { color: #DBDBDB; font-size: 20px; } &:invalid:not([value=""]) { border: 1.5px solid red; } &:disabled { background-color: #F2F2F2; } } `;
/* globals describe it expect */ import colorMiddleware from '../src/color-middleware' import { input, output } from '../src/middleware' const pointlessMiddleware = { name: 'pointless', input: value => { if (typeof value === 'object' && value.middleware === colorMiddleware.name) { return { ...value, g: { middleware: 'pointless' } } } return value }, output: value => { if (typeof value === 'object' && value.middleware === 'pointless') { return 255 } return value } } describe('input', () => { it('should return the same value if no middleware applies', () => { const middleware = [ colorMiddleware ] const value = { foo: 1 } expect(input(value, middleware)).toEqual(value) }) it('should apply middleware to object values', () => { const middleware = [ colorMiddleware ] const value = { foo: 1, bar: '#FFF' } const expectedResult = { foo: 1, bar: { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } } expect(input(value, middleware)).toEqual(expectedResult) }) it('should apply middleware to array items', () => { const middleware = [ colorMiddleware ] const value = [ 'rgb(255, 255, 255)' ] const expectedResult = [ { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } ] expect(input(value, middleware)).toEqual(expectedResult) }) it('should apply middleware to strings', () => { const middleware = [ colorMiddleware ] const value = 'rgba(255,255,255,1)' const expectedResult = { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } expect(input(value, middleware)).toEqual(expectedResult) }) it('should compound if multiple middleware apply', () => { const middleware = [ colorMiddleware, pointlessMiddleware ] const value = 'rgba(255,255,255,1)' const expectedResult = { middleware: colorMiddleware.name, r: 255, g: { middleware: 'pointless' }, b: 255, a: 1 } expect(input(value, middleware)).toEqual(expectedResult) }) describe('output', () => { it('should return the same value if no middleware applies', () => { const middleware = [ colorMiddleware ] const value = { foo: 1 } expect(output(value, middleware)).toEqual(value) }) it('should apply middleware to object values', () => { const middleware = [ colorMiddleware ] const value = { foo: 1, bar: { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } } const expectedResult = { foo: 1, bar: 'rgba(255,255,255,1)' } expect(output(value, middleware)).toEqual(expectedResult) }) it('should apply middleware to array items', () => { const middleware = [ colorMiddleware ] const value = [ { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } ] const expectedResult = [ 'rgba(255,255,255,1)' ] expect(output(value, middleware)).toEqual(expectedResult) }) it('should apply middleware to strings', () => { const middleware = [ colorMiddleware ] const value = { middleware: colorMiddleware.name, r: 255, g: 255, b: 255, a: 1 } const expectedResult = 'rgba(255,255,255,1)' expect(output(value, middleware)).toEqual(expectedResult) }) it('should compound if multiple middleware apply', () => { const middleware = [ colorMiddleware, pointlessMiddleware ] const value = { middleware: colorMiddleware.name, r: 255, g: { middleware: 'pointless' }, b: 255, a: 1 } const expectedResult = 'rgba(255,255,255,1)' expect(output(value, middleware)).toEqual(expectedResult) }) }) })
var searchData= [ ['nb_5fcoup_5fpossible',['nb_coup_possible',['../menu_8c.html#a3d382280de923232845dc0ac1aa99349',1,'nb_coup_possible():&#160;menu.c'],['../ordi__contre__joueur_8c.html#a3d382280de923232845dc0ac1aa99349',1,'nb_coup_possible():&#160;menu.c']]] ];
const { put, take, takeEvery, takeLatest, select } = require('redux-saga/effects'); const { addPlayer, addedToLobby, syncPlayers, gameStarted, sendSentence, updateStatus } = require('../src/actions'); // Fisher-Yates shuffle function shuffle(array) { let arrayCopy = array.slice(); let currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = arrayCopy[currentIndex]; arrayCopy[currentIndex] = arrayCopy[randomIndex]; arrayCopy[randomIndex] = temporaryValue; } return arrayCopy; } const sentences = require('../src/sentences.json'); function* enterLobby({ payload, meta }) { const players = yield select(state => state.players); const { key } = meta; const isLobbyEmpty = !Object.keys(players).length; yield put(addPlayer(key, payload.username)); if (isLobbyEmpty) { yield put(addedToLobby(key, 'master')); } else { yield put(addedToLobby(key, 'player')); } } function* updatePlayerList() { const host = yield select(state => state.host); const players = yield select(state => Object.keys(state.players).map(key => state.players[key])); yield put(syncPlayers(host, players)); } function* startGame() { const host = yield select(state => state.host); const players = yield select(state => Object.keys(state.players)); yield [].concat([host], players).map((key) => put(gameStarted(key))); // wait here for CHANGE_STATUS_FROM, PLAYING.WARMUP -> PLAYING.ANSWERING ? const randomizedSentences = shuffle(sentences);//.slice(0, players.length); console.log(randomizedSentences); const round = players.map((id, index) => ({ id, firstSentence: randomizedSentences[index % (sentences.length - 1)], firstAnswer: null, secondSentence: randomizedSentences[(index + 1) % (sentences.length - 1)], secondAnswer: null, })); console.log(JSON.stringify(round, false, 2)); yield round.map(({ id, firstSentence }) => put(sendSentence(id, firstSentence ))); while (round.filter(player => player.firstAnswer === null).length > 0) { const { payload, meta } = yield take('RECEIVE_ANSWER'); const { answer } = payload; const { key } = meta; const player = round.find(player => player.id === key); player.firstAnswer = answer; } yield round.map(({ id, secondSentence }) => put(sendSentence(id, secondSentence ))); while (round.filter(player => player.secondAnswer === null).length > 0) { const { payload, meta } = yield take('RECEIVE_ANSWER'); const { answer } = payload; const { key } = meta; const player = round.find(player => player.id === key); player.secondAnswer = answer; } yield put(sendResults(host, round)); // nextStatus = 'PLAYING.VOTING'; // yield [].concat([host], players).map((key) => put(updateStatus(key, nextStatus))); } function* changeStatus({ payload }) { const host = yield select(state => state.host); const players = yield select(state => Object.keys(state.players)); // reducer or saga, that is the question, sorry DRY, time's running out let nextStatus = 'LOBBY'; if (payload.status === 'LOBBY') nextStatus = 'PLAYING.WARMUP'; if (payload.status === 'PLAYING.WARMUP') nextStatus = 'PLAYING.ANSWERING'; if (payload.status === 'PLAYING.ANSWERING') nextStatus = 'PLAYING.COLLECTING'; if (payload.status === 'PLAYING.VOTING') nextStatus = 'PLAYING.WARMUP'; yield [].concat([host], players).map((key) => put(updateStatus(key, nextStatus))); } function* watchActions() { yield takeEvery('ENTER_LOBBY', enterLobby); yield takeEvery('ADDED_TO_LOBBY', updatePlayerList); yield takeLatest('START_GAME', startGame); yield takeLatest('CHANGE_STATUS_FROM', changeStatus); } module.exports = watchActions;
/** * utils.js * * Place any generic functions here that may be used by any piece of TitanDash functionality. */ /** * Loader template can be used to place loaders on a page dynamically during loads through javascript. */ let loaderTemplate = ` <div class="w-100 d-flex justify-content-center align-items-center loader-template" style="display: none;"> <div class="spinner"> <div class="rect1"></div> <div class="rect2"></div> <div class="rect3"></div> <div class="rect4"></div> <div class="rect5"></div> </div> </div> `; /** * Export a JsonObject to a .json file with the specified filename. */ function exportToJsonFile(jsonData, filename) { let dataStr = JSON.stringify(jsonData); let dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr); let exportFileDefaultName = `${filename}.json`; let linkElement = document.createElement('a'); linkElement.setAttribute('href', dataUri); linkElement.setAttribute('download', exportFileDefaultName); linkElement.click(); } /** * Generate and alert with the specified message and append it to the specified container. * * The alert will automatically fade out after 5 seconds. */ function sendAlert(message, container, style, type="success", fade=true, dismissible=false) { let alert = $(` <div style="display: none; ${style || ""}" class="alert alert-${type} dashboard-alert"> ${message} </div> `); if (dismissible) { alert.append(` <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> `) } alert.appendTo(container); alert.fadeIn(250); if (fade) { // Fadeout after five full seconds. setTimeout(function () { alert.fadeOut(500, function () { $(this).remove() }); }, 4000); } } /** * Callback function used by theme selection to update the cookie and reload the page * once one is selected. */ function selectTheme(theme) { $.ajax({ url: "/ajax/theme_change", dataType: "json", data: { "theme": theme }, complete: function() { window.location.reload(true); } }); } /** * Retrieve the active session that is currently selected by the user. This is done to determine * the users currently selected session so that multiple sessions can be started, stopped, paused, etc... */ function getActiveInstance() { let active = null; $("#dashboardInstancesTableBody").find("tr").each(function(index, value) { if ($(value).find(".instance-select-btn").first().prop("disabled")) { active = $(value).data().id; } }); return active; } /** * Copy the text within the specified container to the users clipboard. */ let copyToClipboard = function(containerId) { if (document.selection) { let range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerId)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { let range = document.createRange(); range.selectNode(document.getElementById(containerId)); window.getSelection().addRange(range); document.execCommand("copy"); } };