text
stringlengths
7
3.69M
import Color from 'color'; import { pick } from 'lodash'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import SvgIcon from 'material-ui/SvgIcon'; import TextField from 'material-ui/TextField'; import Toggle from 'material-ui/Toggle'; import React, { PureComponent, PropTypes } from 'react'; import ColorPicker from 'react-color'; import { Rect } from './Shape'; import styles from '../styles/editStyleDialog.styl'; export class EditStyleDialog extends PureComponent { static get propTypes() { return { close: PropTypes.func.isRequired, editor: PropTypes.object.isRequired, dialog: PropTypes.object.isRequired, setStyle: PropTypes.func.isRequired, onPushHistory: PropTypes.func.isRequired, }; } onHistory(style) { const { setStyle, } = this.props; setStyle(style); this.handleClose(); } handleChange(key, value) { const { editor, setStyle, } = this.props; setStyle({ ...pick(editor, [ 'fill', 'fillColor', 'fontSize', 'stroke', 'strokeColor', 'strokeWidth', ]), [key]: value, }); } handleClose() { const { close, onPushHistory, } = this.props; close('editStyle'); onPushHistory(); } render() { const { editor, dialog, } = this.props; const { fill, fillColor, fontSize, stroke, strokeColor, strokeWidth, } = editor; const actions = [ <FlatButton primary key="close" label="Close" onTouchTap={() => this.handleClose()} />, ]; return ( <Dialog autoScrollBodyContent actions={actions} open={!!dialog.editStyle} title="Edit Style" onRequestClose={() => this.handleClose()} > <div className={styles.history}> { editor.styleHistory.map((style, i) => ( <IconButton key={i} onTouchTap={() => this.onHistory(style)} > <SvgIcon> <Rect {...style} fill={ style.fill ? new Color(style.fillColor) .rgbString() : 'none' } height={22} stroke={ style.stroke ? new Color(style.strokeColor) .rgbString() : 'none' } width={22} x={1} y={1} /> </SvgIcon> </IconButton> )) } </div> <div className={styles.colorPickerContainer}> <div className={styles.colorPicker}> <Toggle label="Stroke" labelPosition="right" toggled={stroke} onToggle={ () => this.handleChange('stroke', !stroke) } /> { stroke ? ( <ColorPicker color={strokeColor} type="sketch" onChangeComplete={({ rgb }) => this.handleChange( 'strokeColor', rgb ) } /> ) : null } </div> <div className={styles.colorPicker}> <Toggle label="Fill" labelPosition="right" toggled={fill} onToggle={() => this.handleChange('fill', !fill)} /> { fill ? ( <ColorPicker color={fillColor} type="sketch" onChangeComplete={({ rgb }) => this.handleChange( 'fillColor', rgb ) } /> ) : null } </div> </div> <div className={styles.inputContainer}> <TextField fullWidth className={styles.input} defaultValue={strokeWidth} floatingLabelText="Stroke Width" type="number" onBlur={ ({ target }) => this.handleChange('strokeWidth', +target.value) } /> <TextField fullWidth className={styles.input} defaultValue={fontSize} floatingLabelText="Font Size" type="number" onBlur={ ({ target }) => this.handleChange('fontSize', +target.value) } /> </div> </Dialog> ); } }
import React, { useState } from "react"; import { Link } from "react-router-dom"; // import "../index.css"; import { AiTwotoneHome, AiOutlineSearch } from "react-icons/ai"; import { FcAbout, FcAdvertising } from "react-icons/fc"; import { MdPermContactCalendar } from "react-icons/md"; import { RiMenu4Line } from "react-icons/ri"; function Nav() { const [navWidth, setNavWidth] = useState(false); const toggleNav = () => { setNavWidth(!navWidth); }; window.onscroll = () => setNavWidth(false); return ( <div className="nav-logo"> <li className="logo"> <Link to="/">Kasi Rooms</Link> </li> <li className="menu-icon"> <RiMenu4Line onClick={toggleNav} /> </li> <div className={navWidth ? "nav-bar active" : "nav-bar"}> <ul className={navWidth ? "nav-menu active" : "nav-menu"}> <span className="close-nav" onClick={toggleNav}> X </span> <li> <Link to="/" onClick={toggleNav}> <AiTwotoneHome className="icon" /> Home </Link> </li> <li> <Link to="/about" onClick={toggleNav}> <FcAbout className="icon" /> About </Link> </li> <li> <Link to="/search" onClick={toggleNav}> <AiOutlineSearch className="icon" /> Find Room </Link> </li> <li> <Link to="/advertise" onClick={toggleNav}> <FcAdvertising className="icon" /> Advertise </Link> </li> <li> <Link to="/contact" onClick={toggleNav}> <MdPermContactCalendar className="icon" /> Contact </Link> </li> </ul> </div> </div> ); } export default Nav;
function setupPageJump(){ const VID = "JUMP_PAGE"; const TYPE_TOP = "▲"; const TYPE_BOTTOM = "▼"; if(!document.querySelector(VID)){ addDiv(TYPE_TOP); addDiv(TYPE_BOTTOM); } function addDiv(type){ var div = document.createElement("div"); div.className = VID; document.body.appendChild(div); div.style.display = "block"; div.style.color = "#ffffff"; div.style.textAlign = "center"; div.style.lineHeight = "40px"; div.style.width = "40px"; div.style.height = "40px"; div.style.position = "fixed"; div.style.bottom = type == TYPE_BOTTOM ? "20px" : "70px"; div.style.right = "20px"; div.style.zIndex = "3000"; div.style.background = "rgba(0, 0, 0, 0.4)"; div.style.borderRadius = "8px"; div.style.cursor = "pointer"; div.innerHTML = type; div.onclick = function(){ if(type == TYPE_BOTTOM){ document.documentElement.scrollTop = document.documentElement.scrollHeight; } else{ document.documentElement.scrollTop = 0; } } } }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var OfferSchema = Schema({ shop_id: {type: String, required: true}, name: {type: String, required: true}, description: String, image: String, price: {type: Number, required: true, default: 0}, until: {type: Date, required: true}, created_at: {type: Date, default: Date.now} }); module.exports = mongoose.model('Offer', OfferSchema, "Offers");
import View from 'famous-creative/display/View'; const Curves = FamousPlatform.transitions.Curves; export class Card extends View { constructor(node, options) { super(node, options); this.model = options.model; let perspective = 600; let zTransform = this.model.i * 350; this.setSizeMode(1, 1); this.setAbsoluteSize(350, 220); this.setMountPoint(.5, 0); this.setAlign(.5, 0); this.setOrigin(.5, .5, .5); this.setScale(.5, .5, .5); this.setPosition(-window.innerWidth, 300, zTransform); this.createDOMElement({ properties: { 'zIndex': zTransform, '-webkit-perspective': perspective, '-moz-perspective': perspective, 'perspective': perspective } }); // this.addCardBack(); Pulled per Sander this.addCardFront(); this.loadCard(); } addCardBack() { let cardBack = new View(this.node.addChild()); cardBack.setSizeMode(0, 0); cardBack.setProportionalSize(1, 1); cardBack.createDOMElement({ tagName: 'img', classes: [['card-img-back']], properties: { 'backface-visibility': 'visible' } }); cardBack.setDOMAttributes({ 'src': this.model.back }); } addCardFront() { let cardFront = new View(this.node.addChild()); cardFront.setSizeMode(0, 0); cardFront.setProportionalSize(1, 1); cardFront.createDOMElement({ tagName: 'img', classes: ['card-img-front'], properties: { // 'backface-visibility': 'hidden' } }); cardFront.setDOMAttributes({ 'src': this.model.front }); } loadCard() { const _this = this; this.model.rotation = { x: 0, y: 0, z: 0 }; this.model.position = { x: 0, y: 300, z: this.getPositionZ() }; switch(this.model.i) { case 0: this.model.rotation.z = (-9 * Math.PI) / 180; this.model.position.x = 30; this.model.position.y = 250; break; case 1: this.model.rotation.z = (.5 * Math.PI) / 180; this.model.position.x = 20; this.model.position.y = 312; break; case 2: this.model.rotation.z = (30 * Math.PI) / 180; this.model.position.x = -20; this.model. position.y = 355; break; case 3: this.model.rotation.z = (-23 * Math.PI) / 180; this.model.position.x = -30; this.model.position.y = 245; break; default: break; } // I want a slight delay after the app loads setTimeout(function() { _this.setPositionX(0, { curve: Curves.easeInOut, duration: 650 }, function() { // I want a slight delay after the animation is done setTimeout(function() { const options = { curve: 'outBack', duration: 500 }; _this.setRotationZ(_this.model.rotation.z, options); _this.setPositionX(_this.model.position.x, options); _this.setPositionY(_this.model.position.y, options); }, 75); }); }, 250); } }
import React, {useState} from "react"; import './hamburger.css'; function Hamburger() { const [isActive, setIsActive] = useState(false) function handleActive() { setIsActive(!isActive) } // const { active, loading } = this.props; return ( <div className="ham" onClick={() => handleActive()} style={{ position: "relative" }}> <div className={`hamburger-top ${isActive ? "active" : ""}`} /> <div className={`hamburger-center ${isActive ? "active" : ""}`} /> <div className={`hamburger-bottom ${isActive ? "active" : ""}`} /> </div> ); } // Hamburger.propTypes = { // active: PropTypes.bool, // loading: PropTypes.bool // }; // Hamburger.defaultProps = { // active: false, // loading: false // }; export default Hamburger;
(function() { 'use strict'; angular .module('iconlabApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('tache', { parent: 'entity', url: '/tache?page&sort&search', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Taches' }, views: { 'content@': { templateUrl: 'app/entities/tache/taches.html', controller: 'TacheController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true }, search: null }, resolve: { pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) { return { page: PaginationUtil.parsePage($stateParams.page), sort: $stateParams.sort, predicate: PaginationUtil.parsePredicate($stateParams.sort), ascending: PaginationUtil.parseAscending($stateParams.sort), search: $stateParams.search }; }], } }) .state('tache-detail', { parent: 'entity', url: '/tache/{id}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'], pageTitle: 'Tache' }, views: { 'content@': { templateUrl: 'app/entities/tache/tache-detail.html', controller: 'TacheDetailController', controllerAs: 'vm' } }, resolve: { entity: ['$stateParams', 'Tache', function($stateParams, Tache) { return Tache.get({id : $stateParams.id}).$promise; }] } }) .state('app.patache.tache-detail', { parent: 'app.patache', url: '/tachedesc/{idtache}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/detailtache.html', controller: 'TacheDetailController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['$stateParams', 'Tache', function($stateParams, Tache) { return Tache.get({id : $stateParams.idtache}).$promise; }] } }).result.then(function() { $state.go('app.patache', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('tache.new', {//etat de création d'une tache par un administrateur parent: 'tache', url: '/new', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-dialog1.html', controller: 'TacheDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { name: null, description: null, fichierJoint: null, fichierJointContentType: null, role: null, fromt: null, tot: null, color: null, data: null, movable: null, progress: null, lct: null, est: null, actif: null, id: null }; } } }).result.then(function() { $state.go('tache', null, { reload: true }); }, function() { $state.go('tache'); }); }] }) .state('app.tacheprojet.newusertask', {//etat de création d'une tache par un administrateur parent: 'app.tacheprojet', url: '/newtache', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-dialog1.html', controller: 'TacheDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { name: null, description: null, fichierJoint: null, fichierJointContentType: null, role: null, fromt: null, tot: null, color: null, data: null, movable: null, progress: null, lct: null, est: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('app.tacheprojet'); }); }] }).state('app.tacheprojet.newtaskuser', {//etat de création d'une tache par un administrateur parent: 'app.tacheprojet', url: '/newtachebyuser', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-dialogU.html', controller: 'TacheDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { name: null, description: null, fichierJoint: null, fichierJointContentType: null, role: null, fromt: null, tot: null, color: null, data: null, movable: null, progress: null, lct: null, est: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('app.tacheprojet'); }); }] }) .state('tache.edit', { parent: 'tache', url: '/{id}/edit', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-dialog1.html', controller: 'TacheDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Tache', function(Tache) { return Tache.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('tache', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.tacheprojet.edituser', {//édition d'une tache par un utilisateur quelconque autre que l'admin parent: 'app.tacheprojet', url: '/{idtask}/edit', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-dialogU.html', controller: 'TacheDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Tache', function(Tache) { return Tache.get({id : $stateParams.idtask}).$promise; }] } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('tache.delete', { parent: 'tache', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/tache/tache-delete-dialog.html', controller: 'TacheDeleteController', controllerAs: 'vm', windowClass:'center-modal', size: 'md', resolve: { entity: ['Tache', function(Tache) { return Tache.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('tache', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
function grid2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.bAX = 0; this.bAY = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, bAX, bAY, fC, sC, lW, ctx){ var bSIX = w / bAX; var bSIY = h / bAY; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.closePath(); ctx.beginPath(); for (i = 1; i < bAX; i++){ ctx.beginPath(); ctx.moveTo(x+(i*bSIX),y); ctx.lineTo(x+(i*bSIX),y+h); ctx.stroke(); ctx.closePath(); } for (i = 1; i < bAY; i++){ ctx.beginPath(); ctx.moveTo(x,y+(i*bSIY)); ctx.lineTo(x+w,y+(i*bSIY)); ctx.stroke(); ctx.closePath(); } }; } function triangle2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x,y+h); ctx.lineTo(x+(0.5*w),y+h-w); ctx.lineTo(x+w,y+h); ctx.lineTo(x,y+h); ctx.fill(); ctx.stroke(); ctx.closePath(); }; } function astroid2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+(0.5*w),y); ctx.quadraticCurveTo(x+(0.5*w),y+(0.5*h),x+w,y+(0.5*h)); ctx.quadraticCurveTo(x+(0.5*w),y+(0.5*h),x+(0.5*w),y+h); ctx.quadraticCurveTo(x+(0.5*w),y+(0.5*h),x,y+(0.5*h)); ctx.quadraticCurveTo(x+(0.5*w),y+(0.5*h),x+(0.5*w),y); ctx.fill(); ctx.stroke(); ctx.closePath(); }; } function pentagon2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 6) * w; var pH = (1 / 3) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+(0.5*w),y); ctx.lineTo(x+w,y+pH); ctx.lineTo(x+w-pW,y+h); ctx.lineTo(x+pW,y+h); ctx.lineTo(x,y+pH); ctx.lineTo(x+(0.5*w),y); ctx.fill(); ctx.stroke(); ctx.closePath(); }; } function star2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 6) * w; var pH = (1 / 3) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+(0.5*w),y); ctx.lineTo(x+w-pW,y+h); ctx.lineTo(x,y+pH); ctx.lineTo(x+w,y+pH); ctx.lineTo(x+pW,y+h); ctx.lineTo(x+(0.5*w),y); ctx.stroke(); ctx.fill(); ctx.closePath(); }; } function hexagon2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 4) * w; var pH = (1 / 2) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+pW,y); // top left ctx.lineTo(x+w-pW,y); // top right ctx.lineTo(x+w,y+pH); // right ctx.lineTo(x+w-pW,y+h); // bottom right ctx.lineTo(x+pW,y+h); // bottom left ctx.lineTo(x,y+pH); ctx.lineTo(x+pW,y); ctx.fill(); ctx.stroke(); ctx.closePath(); }; } function hexagram2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 2) * w; var pH = (1 / 4) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+pW,y); ctx.lineTo(x+w,y+h-pH); ctx.lineTo(x,y+h-pH); ctx.lineTo(x+pW,y); ctx.fill(); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.moveTo(x+pW,y+h); ctx.lineTo(x+w,y+pH); ctx.lineTo(x,y+pH); ctx.lineTo(x+pW,y+h); ctx.fill(); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.moveTo(x+pW,y); ctx.lineTo(x+w,y+h-pH); ctx.lineTo(x,y+h-pH); ctx.lineTo(x+pW,y); ctx.stroke(); ctx.closePath(); }; } function octagon2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 4) * w; var pH = (1 / 4) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+pW,y); // top left ctx.lineTo(x+w-pW,y); // top right ctx.lineTo(x+w,y+pH); // right top ctx.lineTo(x+w,y+h-pH); // right bottom ctx.lineTo(x+w-pW,y+h); // bottom right ctx.lineTo(x+pW,y+h); // bottom left ctx.lineTo(x,y+h-pH); // left bottom ctx.lineTo(x,y+pH); // left top ctx.lineTo(x+pW,y); // top left ctx.fill(); ctx.stroke(); ctx.closePath(); }; } function octagram2D(){ this.x = 0; this.y = 0; this.w = 0; this.h = 0; this.fC = ""; this.sC = ""; this.lW = ""; this.render = function(x, y, w, h, fC, sC, lW, ctx){ var pW = (1 / 4) * w; var pH = (1 / 4) * h; ctx.fillStyle = fC; ctx.strokeStyle = sC; ctx.lineWidth = lW; ctx.beginPath(); ctx.moveTo(x+pW,y); // top left ctx.lineTo(x+w,y+h-pH); // right bottom ctx.lineTo(x,y+h-pH); // left bottom ctx.lineTo(x+w-pW,y); // top right ctx.lineTo(x+w-pW,y+h); // bottom right ctx.lineTo(x,y+pH); // left top ctx.lineTo(x+w,y+pH); // right top ctx.lineTo(x+pW,y+h); // bottom left ctx.lineTo(x+pW,y); // top left ctx.stroke(); ctx.fill(); ctx.closePath(); }; } function rect(x,y,w,h,ctx){ ctx.fillRect(x,y,w,h); ctx.strokeRect(x,y,w,h); }
const FuncToken = artifacts.require('./FuncToken.sol') const Test = artifacts.require('Test.sol') module.exports = function(deployer) { deployer.deploy(FuncToken) deployer.deploy(Test) }
import api from "../../config/api"; export const getSearch = (query) => { return async (dispatch) => { dispatch({ type: "SEARCH_LOADING" }); try { const { data, status } = await api.search(query); if (status > 199 && status < 300) { dispatch({ type: "SEARCH_SUCCESS", data }); } } catch (e) { console.error(e); dispatch({ type: "SEARCH_FAILURE" }); } }; };
Ext.define('InvoiceApp.view.Main', { extend: 'Ext.tab.Panel', xtype: 'main', requires: [ 'InvoiceApp.view.Invoices', 'InvoiceApp.controller.Main', 'Ext.data.proxy.JsonP' ], config: { tabBarPosition: 'bottom', items: [ { xtype:'supplier_buyer' }, { xtype:'invoices' }, { xtype:'invoiceform' } ] } });
const mongoose = require('mongoose') const FeedbackSchema = new mongoose.Schema({ email: { type: String, required: true, trim: true }, actionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Action', required: true }, like: { type: Boolean, default: true }, participation: { type: Boolean }, createdAt: { type: Date, default: Date.now } }) class Feedback {} FeedbackSchema.loadClass(Feedback) module.exports = mongoose.model('Feedback', FeedbackSchema)
import React, { useEffect } from 'react'; import { connect } from 'dva'; import { Layout, Form, Input, Button, Select, InputNumber, DatePicker } from 'antd'; import locale from 'antd/lib/date-picker/locale/zh_CN'; import "./addTest.scss" const { Content } = Layout; const { Option } = Select; // const { MonthPicker, RangePicker } = DatePicker; function AddTest(props) { let { getExamTypes, getSubjects, examType, subjects, addTest } = props // console.log(props) useEffect(() => { getExamTypes() getSubjects() }, []) let handleSubmit = e => { e.preventDefault(); props.form.validateFields((err, values) => { if (!err) { // console.log('Received values of form: ', values); addTest(values) props.history.push("/main/test/createTest") } }); }; const { getFieldDecorator } = props.form; return ( <Layout style={{ padding: '0 24px 24px' }}> <h2 style={{ padding: '20px 0px', marginTop: '10px' }}>添加考试</h2> <Content style={{ background: '#fff', padding: 24, marginBottom: 24, borderRadius: 10, flex: 1 }} > <Form labelCol={{ span: 5 }} wrapperCol={{ span: 12 }} onSubmit={handleSubmit}> <div> <div className='addTest-list'> <Form.Item label="试卷名称"> {getFieldDecorator('title', { rules: [{ required: true, message: '请输入试卷名称' }], })(<Input />)} </Form.Item> <Form.Item label="选择考试类型"> {getFieldDecorator('exam_id', { rules: [{ required: true, message: '请选择考试类型' }], })( <Select style={{ width: '120px' }} > {examType && examType.map((item, index) => <Option key={index} value={item.exam_id}>{item.exam_name}</Option>)} </Select>, )} </Form.Item> <Form.Item label="选择课程"> {getFieldDecorator('subject_id', { rules: [{ required: true, message: '请选择课程' }], })( <Select style={{ width: '120px' }} > {subjects && subjects.map((item, index) => <Option key={index} value={item.subject_id}>{item.subject_text}</Option>)} </Select>, )} </Form.Item> <Form.Item label="设置题量"> {getFieldDecorator('number', { initialValue: null, rules: [{ required: true, message: '请设置题量' }], })(<InputNumber min={1} max={10} step={3} />)} </Form.Item> <Form.Item label="考试时间" className="change_time"> <Form.Item label=""> {getFieldDecorator('start_time', { rules: [{ required: true, message: '请选择考试开始时间' }], })( <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} placeholder="开始时间" locale={locale} />, )} </Form.Item> <span style={{ display: 'block', width: '24px', textAlign: 'center' }}>-</span> <Form.Item label=""> {getFieldDecorator('end_time', { rules: [{ required: true, message: '请选择考试结束时间' }], })( <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ minWidth: '100px', width: '100%' }} placeholder="结束时间" locale={locale} />, )} </Form.Item> </Form.Item> <Form.Item wrapperCol={{ span: 12, offset: 5 }}> <Button type="primary" htmlType="submit">创建试卷</Button> </Form.Item> </div> </div> </Form> </Content> </Layout> ); } AddTest.propTypes = { }; const mapStateToProps = state => { return { ...state.questions, global: state.loading.global } } const mapDispatchToProps = dispatch => { return { getExamTypes: () => { dispatch({ type: 'questions/examTypes' }) }, getSubjects: () => { dispatch({ type: 'questions/Subject' }) }, addTest: (payload) => { dispatch({ type: "addTest/addTest", payload }) } } } export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(AddTest));
import React from 'react'; import {List, ListItem} from 'material-ui/List'; import MdIconStarBorder from 'material-ui/svg-icons/toggle/star-border'; import MdIconStar from 'material-ui/svg-icons/toggle/star'; import MdIconSupervisorAccount from 'material-ui/svg-icons/action/supervisor-account'; import MdIconBook from 'material-ui/svg-icons/action/book'; import MdIconBookMark from 'material-ui/svg-icons/action/bookmark'; import MdIconPermIdentity from 'material-ui/svg-icons/action/perm-identity'; import {yellow500} from 'material-ui/styles/colors'; class ProblemListView extends React.Component { render() { var res = []; for (let i = 0, l = this.props.problemList.length; i < l; i++) { let item = this.props.problemList[i]; let primaryText, secondaryText, leftIcon, rightAvatar; if (item.type === 0) { primaryText = '打卡题'; secondaryText = item.subtitle; leftIcon = <MdIconBook />; rightAvatar = <div><MdIconStar color={yellow500}/><MdIconStarBorder /><MdIconStarBorder /></div>; } else if (item.type === 1) { primaryText = '复习题'; secondaryText = item.subtitle; leftIcon = <MdIconBookMark />; rightAvatar = <div><MdIconStar color={yellow500}/><MdIconStarBorder /><MdIconStarBorder /></div>; } else if (item.type === 2) { primaryText = '5v5 团队赛'; secondaryText = item.subtitle; leftIcon = <MdIconSupervisorAccount />; rightAvatar = <div></div>; } else if (item.type === 3) { primaryText = '1v1 单挑赛'; secondaryText = item.subtitle; leftIcon = <MdIconPermIdentity />; rightAvatar = <div></div>; } else { return; } if (typeof primaryText !== 'undefined' && typeof secondaryText !== 'undefined' && typeof leftIcon !== 'undefined' && typeof rightAvatar !== 'undefined') { res.push(( <ListItem key={i} primaryText = {primaryText} secondaryText = {secondaryText} leftIcon = {leftIcon} rightAvatar = {rightAvatar} onClick = {() => { this.props.mainApp.selectQuestion(item); }} /> )); } } return ( <List>{res}</List> ); } } export default ProblemListView;
const EventEmitter = require('events'); var url ='http://mylogger.io/log'; class Logger extends EventEmitter{ log(message) { console.log(message); this.emit('messageLogged', {id:1, url:'http://'}); } } module.exports=Logger; //module.exports.endPoint=url;
// GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('@grpc/grpc-js'); var nifi_pb = require('./nifi_pb.js'); function serialize_org_apache_nifi_processors_grpc_FlowFileReply(arg) { if (!(arg instanceof nifi_pb.FlowFileReply)) { throw new Error('Expected argument of type org.apache.nifi.processors.grpc.FlowFileReply'); } return Buffer.from(arg.serializeBinary()); } function deserialize_org_apache_nifi_processors_grpc_FlowFileReply(buffer_arg) { return nifi_pb.FlowFileReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_org_apache_nifi_processors_grpc_FlowFileRequest(arg) { if (!(arg instanceof nifi_pb.FlowFileRequest)) { throw new Error('Expected argument of type org.apache.nifi.processors.grpc.FlowFileRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_org_apache_nifi_processors_grpc_FlowFileRequest(buffer_arg) { return nifi_pb.FlowFileRequest.deserializeBinary(new Uint8Array(buffer_arg)); } // The FlowFile service definition. var FlowFileServiceService = exports.FlowFileServiceService = { // Sends a FlowFile (blocking rpc) send: { path: '/org.apache.nifi.processors.grpc.FlowFileService/Send', requestStream: false, responseStream: false, requestType: nifi_pb.FlowFileRequest, responseType: nifi_pb.FlowFileReply, requestSerialize: serialize_org_apache_nifi_processors_grpc_FlowFileRequest, requestDeserialize: deserialize_org_apache_nifi_processors_grpc_FlowFileRequest, responseSerialize: serialize_org_apache_nifi_processors_grpc_FlowFileReply, responseDeserialize: deserialize_org_apache_nifi_processors_grpc_FlowFileReply, }, }; exports.FlowFileServiceClient = grpc.makeGenericClientConstructor(FlowFileServiceService);
import React, { useContext } from 'react'; import {Container, Row,Col} from 'react-bootstrap' import logo from '../../Image/logo.svg' import { Link } from "react-router-dom"; import { FaAlignRight ,FaSearchLocation} from "react-icons/fa"; import './MenuArea.css' import { UserContext } from '../../App'; const MenuArea = () => { const [loggedInUser,setLoggedInUser]=useContext(UserContext) return ( <div className="header-top"> {/* <Container> */} <Row> <Col md ={3}> <div className=""> <img src={logo} alt=""></img> </div> </Col> <Col md ={6}> <div className="menu-area"> <div className="menu-icon"> <FaAlignRight /> </div> <div className="main-menu"> <ul> <Link to="/"> <li> <a>home</a> </li> </Link> <li> <a href="#">Room</a> </li> <li> <a href="#">service</a> </li> <li> <a href="#">protpolio</a> </li> <li> <a href="#">contact</a> </li> <button onClick={()=>setLoggedInUser({})}> Sign out</button> </ul> </div> </div> </Col> <Col md={3}> <div className="search-box"> <input className="search-txt" type="text" placeholder="Type to search"></input> <a className="search-btn" href="#"> <FaSearchLocation></FaSearchLocation> </a> </div> </Col> </Row> {/* </Container> */} </div> ); }; export default MenuArea;
import Jsonp from 'js/jsonp' import {ERR_OK,recommendParams} from './config' export const getSongs = (mid) => { const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg'; const data = Object.assign({},recommendParams,{ g_tk: 1928093487, hostUin: 0, needNewCode: 0, platform: 'yqq', order: 'listen', begin: 0, num: 80, songstatus: 1, singermid: mid }); return Jsonp(url,data,{ param:'jsonpCallback' }).then(res => { if(res.code === ERR_OK) { return res.data } throw new Error('没有获取到歌曲列表数据'); }).catch(err => { if(err) { console.log('歌曲列表获取失败' + err) } }) }
const cases = [ ]; class ShareCaseData { AddCaseShareData(caseid, sharedWith, tobeShared, tobeRemoved) { let caseData = this.getCaseWithId(caseid); if (caseData !== null) { // caseData.sharedWith = sharedWith; // caseData.markedForShare = tobeShared; // caseData.markedForUnShare = tobeRemoved; } else{ caseData = { caseId: caseid, sharedWith: sharedWith, markedForShare: tobeShared, markedForUnShare: tobeRemoved }; cases.push(caseData); } } MarkUserToShare(caseid,email){ let caseData = this.getCaseWithId(caseid); if (caseData.sharedWith.indexOf(email) === -1 && caseData.markedForShare.indexOf(email) === -1){ console.log("******* Test data Tracking: => Marking TO BE ADDED : " + caseid + " : " + email); caseData.markedForShare.push(email); } } MarkUserToUnShare(caseid, email) { let caseData = this.getCaseWithId(caseid); console.log("******* Test data Tracking: => Marking TO BE REMOVED : " + caseid + " : " + email); caseData.markedForUnShare.push(email); } CancelMarkedForShare(caseid, email){ let caseData = this.getCaseWithId(caseid); var index = caseData.markedForShare.indexOf(email); if (index > -1) { console.log("******* Test data Tracking: => cancel TO BE ADDED : " + caseid + " : " + email); caseData.markedForShare.splice(index, 1); } } CancelMarkedForUnShare(caseid, email) { let caseData = this.getCaseWithId(caseid); var index = caseData.markedForUnShare.indexOf(email); if (index > -1) { console.log("******* Test data Tracking: => cancel TO BE REMOVED : " + caseid + " : " + email); caseData.markedForUnShare.splice(index, 1); }; } ResetChanges(){ for (let i = 0; i < cases.length; i++) { let caseData = cases[i]; caseData.markedForShare = []; caseData.markedForUnShare = []; } } ResetChagesForCase(caseId){ for (let i = 0; i < cases.length; i++) { let caseData = cases[i]; if (caseData.caseId = caseId){ caseData.markedForShare = []; caseData.markedForUnShare = []; } } } changesCommited(){ for (let i = 0; i < cases.length; i++) { let caseData = cases[i]; for (let sharedWithUser = 0; sharedWithUser < caseData.markedForShare.length; sharedWithUser++){ let email = caseData.markedForShare[sharedWithUser]; if (caseData.sharedWith.indexOf(email) < 0) { caseData.sharedWith.push(email); } } for (let sharedWithUser = 0; sharedWithUser < caseData.markedForUnShare.length; sharedWithUser++) { let email = caseData.markedForUnShare[sharedWithUser]; let index = caseData.sharedWith.indexOf(email); if (index > -1) { caseData.sharedWith.splice(index, email); } } } } getCaseWithId(id) { for (let i = 0; i < cases.length; i++) { if (cases[i].caseId === id) { return cases[i]; } } return null; } GetStoredData(){ return cases; } } module.exports = new ShareCaseData();
/******************************************* * This script is the initialisation of the main FINT user interface. * Each tab needs to be initialised and then renewed each time it is focused/activated * The tabs are initialised when the script first runs * The functions in the object activateFunctions provide activation code * keyed to each tab id which is run at initialisation and each subsequent focus * * For the most part the quickDB library is used to generate the user interface * The script provides configuration options to tweak the default quickDB behavior eg categorisemanager *******************************************/ $(document).ready(function() { FintUI.doInit($('#content')[0]); // IMPORT DEFAULT VALUES //$('#categoriesmanager').quickDB('saveRecords','categories',{'rowid':'UID','description':'Description','parent':'Parent'},FintDefaults.categories); //$('#rulesmanager').quickDB('saveRecords','rules',{'rowid':'UID','rule':'Rule','category':'Category'},FintDefaults.rules); //$('#accountsmanager').quickDB('saveRecords','accounts',{'rowid':'UID','description':'Category','accountnumber':'Account Number'},FintDefaults.accounts); }); FintUI={ qdbSettings:{dbShortName:'fintfinance'}, tabSettings:{'active':0, // cache 'beforeLoad': function( event, ui ) { if ( ui.tab.data( "loaded" )) { event.preventDefault(); return; } ui.jqXHR.success(function() { ui.tab.data( "loaded", true ); }); }, 'load':function(event,ui) {FintUI.initFunction(event,ui)}, 'activate':function(container,depth) {FintUI.activateFunction(container,depth)} }, // added to in modules pluginSettings:{}, initFunctions:{ 'content':function(settings) { //$.extend(FintUI.tabSettings); $('#content').tabs(FintUI.tabSettings); } }, activateFunctions:{ }, // functions // initfunction is called when a tab is loaded // it seeks activatable dom elements with an id that is keyed in the initFunctions object initFunction: function(event,ui) { if (ui.panel) { //console.log('initfunc on'+ui.panel.id); //console.log(ui); //console.log(ui.panel); //console.log($('.activatable',ui.panel)); //var newActiveTab=ui.panel; //console.log(newActiveTab); FintUI.doInit(ui.panel); //$('.activatable', } }, doInit : function(container,depth) { if (!depth) depth=0; //console.log('do initfunction'); //console.log(container.id); //console.log(container); //console.log(initOn); var initSettings={}; if (container && container.id) { // settings for container if (container.id && FintUI.pluginSettings[container.id]) { $.extend(true,initSettings,FintUI.qdbSettings,FintUI.pluginSettings[container.id]); } else { $.extend(true,initSettings,FintUI.qdbSettings); } // init functions for container if (container.id && $.isFunction(FintUI.initFunctions[container.id])) { //sconsole.log('call init on '+container.id); FintUI.initFunctions[container.id](initSettings); } // recurse into child activatables (for one level of depth) $(".activatable",container).each(function(key,newActiveChildTabId) { //console.log('child initable'); //console.log(newActiveChildTabId.id); if (depth<1) { var a=depth+1; FintUI.doInit(newActiveChildTabId,a); } else { //console.log('limiting recursion to 1'); } }); } }, activateFunction: function(event,ui) { //console.log('ACTIVATEFUNCTION',ui); if (ui.newPanel) { //console.log('ACTIVATEFUNCTION',ui.newPanel) FintUI.doActivate(ui.newPanel); //$('.activatable', } }, doActivate : function(container,depth) { if (!depth) depth=0; //console.log('doActivate function',$(container).prop('id'),container); //console.log('TEStS',container,container.id); //console.log(initOn); var initSettings={}; if (container && $(container).prop('id')) { // settings for container if ($(container).prop('id') && FintUI.pluginSettings[$(container).prop('id')]) { $.extend(true,initSettings,FintUI.qdbSettings,FintUI.pluginSettings[$(container).prop('id')]); } else { $.extend(true,initSettings,FintUI.qdbSettings); } // activate functions for container //console.log('TRY call activate on '+$(container).prop('id')); if ($(container).prop('id') && $.isFunction(FintUI.activateFunctions[$(container).prop('id')])) { //console.log('call activate on '+$(container).prop('id')); FintUI.activateFunctions[$(container).prop('id')](initSettings); } // recurse into child activatables (for one level of depth) // if there are child tabs, only search in the visible tab var searchIn=$(container); if ($('.ui-tabs-panel',container).length>0) { //console.log('SEARCH IN CONTAINER'); searchIn=$('.ui-tabs-panel:visible',container); } // allow for panel as activatable if (searchIn.hasClass('activatable')) { if ($(searchIn).prop('id') && $.isFunction(FintUI.activateFunctions[$(searchIn).prop('id')])) { //console.log('call inner activate on '+$(searchIn).prop('id')); FintUI.activateFunctions[$(searchIn).prop('id')](initSettings); } } console.log('TRY SEARCH IN child activatable',searchIn); $(".activatable",searchIn).each(function(key,newActiveChildTabId) { //console.log('child activatable',newActiveChildTabId.id); if (depth<1) { var a=depth+1; FintUI.doActivate(newActiveChildTabId,a); } else { //console.log('limiting recursion to 1'); } }); } }, /* // WHEN ACTIVATE FUNCTION IS CALLED, ALL VISIBLE CHILDREN ARE UPDATED // only activate the tab that is visible in the content window // when clicking on a tab either // - if there are child tabs activate visible child (at any tree depth) // - otherwise call activate on this tab activateFunction : function(event,ui) { console.log('ACTIVATE',event,ui.newPanel,ui); var newActiveTab=ui.newPanel; // which tab //- 2nd level tab // - call init on parent // - call init on self //- top level tab // - call init on self var visibleTabs=$("div.activatable:visible"); var firstLevelTab=null; var secondLevelTab=null; console.log('visibleTabs'); console.log(visibleTabs); $.each(visibleTabs,function(key,value) { var childVisibleTabs=$("div.activatable:visible",value); if (childVisibleTabs.length>0) { console.log(value.id+' have visibleTabs as children'); firstLevelTab=value; } else { console.log(value.id+' have no visibleTabs as children'); secondLevelTab=value; } }); // recurse FintUI.doActivate(newActiveTab); $(".activatable:visible",newActiveTab).each(function(key,activatable) { FintUI.doActivate(activatable); }); //console.log(firstLevelTab); //console.log(secondLevelTab); FintUI.doActivate(firstLevelTab); if (secondLevelTab) { FintUI.doActivate(secondLevelTab); } }, doActivate : function(newTab) { if (newTab) { console.log('DO ACTIVATE',newTab.id,newTab); var initSettings={}; if (newTab.id && FintUI.pluginSettings[newTab.id]) { $.extend(initSettings,FintUI.qdbSettings,FintUI.pluginSettings[newTab.id]); } else { $.extend(initSettings,FintUI.qdbSettings); } if ($.isFunction(FintUI.activateFunctions[newTab.id])) { console.log('run activate' + newTab.id); //console.log(FintUI.activateFunctions[newTab.id]); FintUI.activateFunctions[newTab.id](initSettings); } } else { //console.log('skip activate on empty Element'); } } */ };
import React from 'react' import Controller from "./Controller"; function BreakIncrement(props) { const{handleClick}=props; return ( <div> <Controller id="break-increment" handleClick={handleClick} arrow="Up" /> </div> ) } export default BreakIncrement
import React from "react"; import "./App.css"; import Main from "./components/Main"; import { rootReducer } from "./redux/reducers/index.js"; import { createStore, applyMiddleware, compose } from "redux"; import { Provider } from "react-redux"; import thunk from "redux-thunk"; import { persistReducer } from "redux-persist"; import storage from "redux-persist/lib/storage"; const persistConfig = { key: "root", storage, }; const persistedReducer = persistReducer(persistConfig, rootReducer); let composeArgs = [applyMiddleware(thunk)]; if (process.env.REACT_APP_NODE_ENV !== "PROD") { composeArgs.push(window.devToolsExtension && window.devToolsExtension()); } const storeEnhancers = compose(...composeArgs); const store = createStore(persistedReducer, {}, storeEnhancers); function App() { return ( <Provider store={store}> <div className="App"> <Main /> </div> </Provider> ); } export default App;
import Layout from '../components/wrapper'; import { Container, Grid, Header } from 'semantic-ui-react'; import Contests from '../components/contests'; import factory from '../../ethereum/factory'; class Index extends React.Component { static async getInitialProps({ req }) { const deployedHotOrNots = await factory.methods.getDeployedHotOrNots().call(); return { contests: deployedHotOrNots } } render() { return ( <Layout title='Welcome to Crypto Hot or Not'> <Grid> <Grid.Row centered columns={1}> <Grid.Column> <Header as='h1' size='huge'>Welcome to Crypto Hot or Not</Header> <p> Welcome to Crytpo Hot or Not - <em>the</em> Decentralized Application where users earn ether for being voted hot. </p> </Grid.Column> </Grid.Row> </Grid> <Contests items={this.props.contests} /> </Layout> ); } } export default Index;
var reportServices = angular.module('SelectCargoService', ['ngResource']); reportServices.factory('SelectCargo', ['$resource', function($resource){ return $resource('/termodva/rest/termo/cargo/', {}, { query: { method: 'GET', isArray: true }, }); }]);
import styled from "styled-components"; export const CaptionText = styled.h1` font-size: 34px; font-weight: bold; color: #000; text-align: center; margin-top: 68px; `;
import axios from 'axios'; import { RECEIVE_LIST, getList, handleChargedListBoolean, CREATE_LIST, handleCreatedListBoolean, handleCreatedListSuccessMessage, DELETE_LIST, handleIsDeletedList, handleUpdateListBool, UPDATE_LIST, handleOpenInputUpdate, clearNameInput, } from 'src/store/reducers/list'; const listMiddleware = (store) => (next) => (action) => { const { userId } = store.getState().user; const { listId, nameInput } = store.getState().list; switch (action.type) { case RECEIVE_LIST: axios.get(`http://localhost:8000/listByUser/${userId}`) .then((res) => { const userLists = res.data; store.dispatch(getList(userLists)); store.dispatch(handleChargedListBoolean()); }) break; case CREATE_LIST: axios.post('http://localhost:8000/list/create', {user_id: userId}) .then((res) => { const { success } = res.data.success; store.dispatch(handleCreatedListSuccessMessage(success)); }) .catch((err) => { console.log(err); }) .finally(() => { store.dispatch(handleCreatedListBoolean()); }); break; case DELETE_LIST: axios.delete(`http://localhost:8000/list/delete/${listId}`) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err.response); }) .finally(() => { store.dispatch(handleIsDeletedList()); }) break; case UPDATE_LIST: axios.post('http://localhost:8000/list/update', {listId, name: nameInput}) .then((res) => { console.log(res); }) .catch((err) => { console.log(err.response); }) .finally(() => { store.dispatch(handleUpdateListBool()); store.dispatch(handleOpenInputUpdate()); store.dispatch(clearNameInput()); }); break; default: next(action); }; }; export default listMiddleware;
const router = require('express').Router(); const controller = require('./gameController'); router.param('accessCode', controller.params); router.route('/:accessCode') .get(controller.getOne); router.route('/') .post(controller.createGame); router.put('/:accessCode/join', controller.joinGame); router.put('/:accessCode/start', controller.startGame); module.exports = router;
import React from 'react'; import './LoadingIndicator.scss'; const LoadingIndicator = (props) => { return ( <div className="lds-wrapper"> <div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div> </div> ) }; export default LoadingIndicator;
import React from 'react'; import './ContactList.css' import Profile from './Profile' class ContactList extends React.Component { render() { return ( <div id='contacts-list'> <h1> Contacts </h1> <Profile /> <Profile /> <Profile /> <Profile /> </div> ) } } export default ContactList;
/** * @license * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * Registers a language handler for Haskell. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-hs">(my lisp code)</pre> * The lang-cl class identifies the language as common lisp. * This file supports the following language extensions: * lang-cl - Common Lisp * lang-el - Emacs Lisp * lang-lisp - Lisp * lang-scm - Scheme * * * I used http://www.informatik.uni-freiburg.de/~thiemann/haskell/haskell98-report-html/syntax-iso.html * as the basis, but ignore the way the ncomment production nests since this * makes the lexical grammar irregular. It might be possible to support * ncomments using the lookbehind filter. * * * @author mikesamuel@gmail.com */ PR['registerLangHandler']( PR['createSimpleLexer']( [ // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed [PR['PR_PLAIN'], /^[\t\n\x0B\x0C\r ]+/, null, '\t\n\x0B\x0C\r '], // Single line double and single-quoted strings. // char -> ' (graphic<' | \> | space | escape<\&>) ' // string -> " {graphic<" | \> | space | escape | gap}" // escape -> \ ( charesc | ascii | decimal | o octal // | x hexadecimal ) // charesc -> a | b | f | n | r | t | v | \ | " | ' | & [PR['PR_STRING'], /^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/, null, '"'], [PR['PR_STRING'], /^\'(?:[^\'\\\n\x0C\r]|\\[^&])\'?/, null, "'"], // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer -> decimal // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal [PR['PR_LITERAL'], /^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i, null, '0123456789'] ], [ // Haskell does not have a regular lexical grammar due to the nested // ncomment. // comment -> dashes [ any<symbol> {any}] newline // ncomment -> opencom ANYseq {ncomment ANYseq}closecom // dashes -> '--' {'-'} // opencom -> '{-' // closecom -> '-}' [PR['PR_COMMENT'], /^(?:(?:--+(?:[^\r\n\x0C]*)?)|(?:\{-(?:[^-]|-+[^-\}])*-\}))/], // reservedid -> case | class | data | default | deriving | do // | else | if | import | in | infix | infixl | infixr // | instance | let | module | newtype | of | then // | type | where | _ [PR['PR_KEYWORD'], /^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^a-zA-Z0-9\']|$)/, null], // qvarid -> [ modid . ] varid // qconid -> [ modid . ] conid // varid -> (small {small | large | digit | ' })<reservedid> // conid -> large {small | large | digit | ' } // modid -> conid // small -> ascSmall | uniSmall | _ // ascSmall -> a | b | ... | z // uniSmall -> any Unicode lowercase letter // large -> ascLarge | uniLarge // ascLarge -> A | B | ... | Z // uniLarge -> any uppercase or titlecase Unicode letter [PR['PR_PLAIN'], /^(?:[A-Z][\w\']*\.)*[a-zA-Z][\w\']*/], // matches the symbol production [PR['PR_PUNCTUATION'], /^[^\t\n\x0B\x0C\r a-zA-Z0-9\'\"]+/] ]), ['hs']);
angular.module('myapp') .config(function config ($stateProvider) { $stateProvider.state('common.home', { url: '/home', views: { 'main@common': { controller: 'HomeCtrl', templateUrl: 'pages/home/template.html' } }, data: { pageTitle: 'Home' } }); }) ;
// O(2^n) const fibonacci = (n) => (n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2)); // O(n) const memoizedFibonacci = (n) => { const arr = new Array(n); if (n <= 1) { arr[n] = n; return n; } if (!arr[n - 1]) { arr[n - 1] = memoizedFibonacci(n - 1); } if (!arr[n - 2]) { arr[n - 2] = memoizedFibonacci(n - 2); } return arr[n - 1] + arr[n - 2]; }; // O(n) const iterationFibonacci = (n) => { if (n <= 1) { return n; } let t0 = 0, t1 = 1, sum = 0; for (let i = 2; i <= n; i++) { sum = t0 + t1; t0 = t1; t1 = sum; } return sum; }; const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1)); const towerOfHanoi = (n, A, B, C) => { if (n) { towerOfHanoi(n - 1, A, C, B); console.log(A, C); towerOfHanoi(n - 1, B, A, C); } }; console.log(fibonacci(5)); console.log(iterationFibonacci(5)); console.log(memoizedFibonacci(5)); console.log(factorial(5)); towerOfHanoi(3, 1, 2, 3);
var redis = require('redis'); var client = redis.createClient(6379, '172.21.0.102', null); client.select(0); client.KEYS('*', function(err, result){ console.log(result); for(var a in result){ console.log(a + '--' + result[a]); client.DEL(result[a], function(err, result){ console.log('DEL result: ' + result); }); } }); 其实一个FLUSHALL就搞定的东西啊
// JavaScript Function
/* eslint-disable import/no-commonjs */ // pathToWrapper should contains named export - WrapperWidget. WrapperWidget is predefined. // Default export doesnt work module.exports = [// { name: 'Button', pathInRenovationFolder: 'ui/button.j', pathInJSFolder: 'ui/button.js' }, // { name: 'CheckBox', pathInRenovationFolder: 'ui/check_box.j', pathInJSFolder: 'ui/check_box.js' }, // { name: 'Widget', pathInRenovationFolder: 'ui/widget.j' }, // { name: 'ScrollView', pathInRenovationFolder: 'ui/scroll_view/scroll_view.j', pathInJSFolder: 'ui/scroll_view.js' }, // { name: 'Scrollable', pathInRenovationFolder: 'ui/scroll_view/scrollable.j', pathInJSFolder: 'ui/scroll_view/ui.scrollable.js' }, // { name: 'DataGrid', pathInRenovationFolder: 'ui/grids/data_grid/data_grid.j', pathInJSFolder: 'ui/data_grid.js' }, { name: 'Pager', pathInRenovationFolder: 'ui/pager/pager.j', pathInJSFolder: 'ui/pager.js', pathToWrapper: '../../../testing/helpers/renovationPagerHelper.js' } // { name: 'Bullet', pathInRenovationFolder: 'viz/sparklines/bullet.j', pathInJSFolder: 'viz/sparklines/bullet.js' }, ];
// import zhLocale from 'element-ui/lib/locale/lang/zh-CN' // const cn = { // message: { // 'hello': '你好,世界', // 'msg': '提示', // } // } // export default cn; const cn= { //登录 login:{ title:'用户登录', placeholder_username:'请输入账户', placeholder_password:'请输入密码', VerificationCode:'请输入验证码', login:'登录', loginz:'登录中. . .', jz:'记住我', desc_word:'登录即同意', xieyi:'《注册协议》', xyxieyi:'《信用授权协议》', }, // 导航栏 navbar: { // 顶部导航栏 title: '账户', personal:'个人中心', logout:'退出登录', // 顶部标签栏的对应的右击按钮 refresh:'刷新', close:'关闭', closeothers:'关闭其它', closeall:'关闭所有', // 中间四块内容 viewdetails:'查看详情', mydeal:'我的交易', devicenum:'设备数', platform:'台', myturnover:'我的交易额', myearnings:'我的收益', accumulatedearnings:'累计收益', todayearnings:'今日收益', todayinvestment:'今日投资', myteam:'我的团队', person:'人', news:'动态公告', //设备分布的大块 eda:'设备分布', gmv:'交易总额', totaltransactions:'交易笔数', totalnumberdevices:'总设备数', totalinvestment:'总投资', // 底部联系我们块 contactus:'联系我们', companyname:'公司名称', emailaccounts:'邮箱账号', // 推广链接块 referrallinks:'推广链接', copy:'复制', news_details:'公告详情' }, home:{ home:'首页', system:'系统', finance:'财务', product:'产品', team:'团队', deal:'交易', marketing:'营销', faq:'常见问题' }, // 系统 systemes:{ merchantname:'商户名称', date:'日期', to:'至', startdate:'开始日期', dateclosed:'结束日期', search:'搜索', export:'导出', devicenumber:'设备号', merchantrate:'商户费率', contractrate:'签约费率', superioragent:'上级代理', commission:'佣金($)', numberofpayments:'支付笔数', numberofpayers:'支付人数', paymentamount:'支付金额($)', // 用户管理 keyword:'关键词', enterkeywordsearch:'输入关键字搜索', type:'类型', status:'状态', username:'用户名', phone:'电话', mailbox:'邮箱', query:'查询', usertype:'用户类型', merchantidentification:'商户标识', creationdate:'创建日期', activation:'激活', lock:'锁定', //资方管理 name:'名称', proxy_code_search:'输入代理编码搜索', fold:'折叠', expand:'展开', proxy_code:'代理编码', normal:'正常', sponsored_links:'禁用', click_to_copy:'点击复制', }, //产品 products:{ //产品组合 custom_product:'自定义产品', money:'金额', period:'周期', day:'天', rate_of_return:'回报率', income_distribution:'收益分配', quantity:'数量', desk:'台', buy:'购买', confirm_purchase:'确认购买该产品吗?', determine:'确定', cancel:'取消', // 购买记录 customize:'自定义', custom_query:'自定义查询', please_select_date:'请选择日期', to:'至', reset:'重置', query:'查询', export:'导出', creationdate:'创建日期', productname:'产品名称', order_status:'订单状态', purchase_succeeded:'购买成功', completed_order:'已完成订单', purchase_failed:'购买失败', Equipment_to_be_allocated:'设备待分配', product_amount:'产品金额($)', serial_number:'流水号', member:'会员', more:'更多', //组合产品列表 new_product:'新增产品', product_price:'产品价格($)', product_prices:'产品价格', cycle_days:'周期(天)', rate_of_returns:'回报率($)', current_state:'当前状态', operating:'操作', activated:'已启用', not_activated:'未启用', edit:'编辑', delete:'删除', product:'产品', product_life:'产品周期', equipment_quantity:'设备数量', order:'次序', upload_cover:'上传封面', duplicate_name:'请不要重复使用名称', key_numbers:'请输入数字', keep_three_decimal_places:'保留小数后三位', enter_the_income_distribution:'请输入收益分配', enter_the_order:'请输入次序', }, // 财务 financeEarnings:{ wallet:'钱包', title_1:'现金钱包', title_2:'动态钱包收益', title_3:'静态钱包收益', title_4:'积分收益', detailed:'查看明细', dq_balance:'当前余额', lj_income:'累计收益', jr_earnings:'今日收益', lj_integral:'累计积分收益', withdrawal:'提现', recharge:'充值', sure:'确定', cancel:'取消', next:'下一步', prver:'上一步', email:'邮箱', cash_amount:'提现金额', cash_adress:'提现地址', withdrawal_account:'提现账户', recharge_amount:'充值金额', remarks:'备注', jy_number:'交易单号', VerificationCode:'验证码', enter_verification_code:'请输入验证码', enter_the_amount:'请输入金额', no_more:'不能大于总额度', input_pl_1:'请输入金额(提现额度不能大于总额)', input_pl_2:'请输入提现地址', input_pl_3:'请输入备注内容', input_pl_4:'请输入交易单号', click_to_copy:'点击复制', address:'地址', account:'账户', amount:'自定义查询', }, financeCash:{ title_2:'动态钱包收益($)', title_3:'静态钱包收益($)', detailed:'查看明细', customQuery:'自 定 义', custom_query:'自定义查询', rest:'重置', recharge_amount:'充值金额($)', withdrawal_amount:'提现金额($)', to:'至', query:'查询', export:'导出', date:'日期', robot_ex:'购买机器人支出($)', cash_with:'提现支出($)', operation:'操作', details:'详情', type:'类型', points_source:'积分来源', identification:'资方标识', original_integral:'原有积分', integral_growth:'积分增长', existing_integral:'现有积分', more:'更多', place_date:'请选择日期', ID:'交易ID', wallet_adress:'钱包地址', viewdetails:'查看详情', serial_number :'流 水 号', recharge_date:'充值日期', date_of_presentation:'提现日期', address:'地址', approval_status:'审核状态', remark:'备注', sh_success:'审核成功', sh_fail:'审核失败', in_audit:'审核中', adopt:'通过', reject:'驳回', reasons_for_remarks:'备注理由', transaction_id:'交易ID', transfer_time:'转账时间', account_other_party:'对方账号', transfer_amount:'转账金额($)', transfer_amount1:'转账金额', dfzh:'请输入对方账户', zzje:'请输入转账金额', transfer:'转账', name:'名称', device_number:'设备号', transaction_amount:'交易金额($)', transaction_amount2:'交易金额', trading_status:'交易状态', not_submitted:'未提交', successful_trade:'交易成功', refund_completed:'退款完成', order_cancelled:'订单已撤销', unknown_state:'未知状态', date_trade:'交易时间', membership_number:'会员编号', member_name:'会员名称', member:'会员', contact_information:'联系方式', investment_amount:'投资金额($)', current_balance:'当前余额($)', team_number:'团队人数(人)', team_jg:'人员结构图', user_name:'用户名称', account_level:'账户等级', phone_number:'手机号码', user_email:'用户邮箱', subordinate_departments:'所属部门', date_of_creation:'创建日期', security_setting:'安全设置', change_password:'修改密码', modify_mailbox:'修改邮箱', old_password:'旧密码', new_password:'新密码', confirm_password:'确认密码', place_old:'请输入旧密码', place_new:'请输入新密码', place_new_again:'请再次输入新密码', place_email_new:'请输入新的邮箱', place_pass:'请输入密码', level_description:'等级说明', ordinary_member:'普通会员', gold_member:'黄金会员', platinum_members:'铂金会员', diamond_member:'钻石会员', transaction_amount1:'交易金额', transaction_type:'交易类型', trading_status:'交易状态', input_amount:'输入金额', cash_time:'提现时间', audit_time:'审核时间', p_info:'个人信息', operation_log:'操作日志', behavior:'行为', request_time_consuming:'请求耗时', date_of_creation:'创建日期', logout:'退出' }, route:{ home:'首页' } } export default cn;
const app = require('./app'); const express = require('@feathersjs/express'); const proxyApp = express(); const http = require('http'); proxyApp.use('/api/v1', app); const server = http.createServer(proxyApp); app.setup(server); module.exports = server;
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import Home from '../src/home/Home'; import Tweet from '../src/components/Tweets'; import Menu from '../src/components/Menu'; storiesOf('Home', module) .add('Loading', () => <Home />) .add('Git Hub', () => <Home timeline={{ name: 'Git Hub', profile: 'github' }} onClick={action('clicked')}/>); storiesOf('Tweets', module) .add('Git Hub', () => <Tweet profile='github'/>); storiesOf('Menu', module) .add('Default', () => <Menu />) .add('Text & click', () => <Menu timeline={{ name: 'Text', profile: 'Tester' }} onClick={action('clicked')}/>); /* eslint-disable */
function randomColor() { const ColorKey = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"]; var colorHex = "#"; for (var i = 0; i < 6; i++) { const randomKey = Math.floor(Math.random() * 15); colorHex += ColorKey[randomKey]; } return colorHex; } class Circle { constructor({ origin, speed, color, angle, context }) { this.origin = origin; this.position = { ...this.origin }; this.color = color; this.speed = speed; this.angle = angle; this.context = context; this.renderCount = 0; } draw() { this.context.fillStyle = this.color; this.context.beginPath(); this.context.arc(this.position.x, this.position.y, 6, 0, Math.PI * 2); this.context.fill(); } move() { this.position.x = Math.sin(this.angle) * this.speed + this.position.x; this.position.y = Math.cos(this.angle) * this.speed + this.position.y + this.renderCount * 0.3; this.renderCount++; } } class Firework { constructor({ origin, speed, color, angle, context }) { this.origin = origin; this.position = { ...this.origin }; this.color = color; this.speed = speed; this.angle = angle; this.context = context; this.renderCount = 0; } draw() { for (var i = 0; i < 6; i++) { const isOdd = i % 2 === 0; const x = isOdd ? this.position.x - (8 - i) * i : this.position.x + (8 - i) * 5; const y = isOdd ? this.position.y - (8 - i) * 5 : this.position.y - i * i; this.context.strokeStyle = randomColor(); this.context.beginPath(); this.context.moveTo( this.position.x + Math.random() * 7, this.position.y - Math.random() * 7 ); this.context.quadraticCurveTo( x, isOdd ? y - 10 : y - 10, isOdd ? x - i * 15 : x + 10, y ); this.context.stroke(); } } move() { this.position.x = Math.sin(this.angle) * this.speed + this.position.x; this.position.y = Math.cos(this.angle) * this.speed + this.position.y + this.renderCount * 0.3; this.renderCount++; } } class WaterMelon { constructor({ context, origin, speed, color, angle }) { this.origin = origin; this.position = { ...this.origin }; this.ctx = context; this.color = color; this.renderCount = 0; this.speed = speed; this.angle = angle; } draw() { // 西瓜皮 this.ctx.fillStyle = "green"; this.ctx.beginPath(); this.ctx.arc( this.position.x, this.position.y, 30, (Math.PI * 2) / 8, (Math.PI * 2) / 2, false ); this.ctx.fill(); // 西瓜瓤 this.ctx.fillStyle = "white"; this.ctx.beginPath(); this.ctx.arc( this.position.x, this.position.y, 28, (Math.PI * 2) / 8, (Math.PI * 2) / 2, false ); this.ctx.fill(); // 西瓜肉 this.ctx.fillStyle = "#e65555"; this.ctx.beginPath(); this.ctx.arc( this.position.x, this.position.y, 26, (Math.PI * 2) / 8, (Math.PI * 2) / 2, false ); this.ctx.fill(); // 西瓜籽 this.ctx.fillStyle = "black"; for (var i = 1; i < 4; i++) { this.ctx.beginPath(); this.ctx.moveTo( this.position.x - 20 + i * 6, this.position.y + 8 + i * 4 ); this.ctx.lineTo( this.position.x - 24 + i * 6, this.position.y + 9 + i * 4 ); this.ctx.lineTo( this.position.x - 22 + i * 6, this.position.y + 6 + i * 4 ); this.ctx.closePath(); this.ctx.fill(); } } move() { this.position.x = Math.sin(this.angle) * this.speed + this.position.x; this.position.y = Math.cos(this.angle) * this.speed + this.position.y + this.renderCount * 0.3; this.renderCount++; } } class Boom { constructor({ origin, context, circleCount = 10, area }) { this.origin = origin; this.context = context; this.circleCount = circleCount; this.area = area; this.stop = false; this.circles = []; } randomRange(start, end) { return (end - start) * Math.random() + start; } renderCircle() { // 实心圆 const circle = new Circle({ context: this.context, origin: this.origin, color: randomColor(), angle: this.randomRange(Math.PI - 1, Math.PI + 1), speed: this.randomRange(1, 6), }); this.circles.push(circle); } renderWaterMelon() { // 西瓜 const watermelon = new WaterMelon({ context: this.context, origin: this.origin, color: randomColor(), angle: this.randomRange(Math.PI - 1, Math.PI + 1), speed: this.randomRange(1, 8), }); this.circles.push(watermelon); } renderFirework() { // 烟花 const firework = new Firework({ context: this.context, origin: this.origin, color: randomColor(), angle: this.randomRange(Math.PI - 1, Math.PI + 1), speed: this.randomRange(1, 6), }); this.circles.push(firework); } init() { for (let i = 0; i < this.circleCount; i++) { if (i % 3 === 0) { this.renderWaterMelon(); } else if (i % 2 === 0) { this.renderCircle(); } else { this.renderFirework(); } } } move() { this.circles.forEach((circle, index) => { if ( circle.position.x > this.area.width || circle.position.y > this.area.height ) { return this.circles.splice(index, 1); } circle.move(); }); if (this.circles.length == 0) { this.stop = true; } } draw() { this.circles.forEach((circle) => circle.draw()); } } class CursorSpecialEffects { constructor() { this.computerCanvas = document.createElement("canvas"); this.renderCanvas = document.createElement("canvas"); this.computerContext = this.computerCanvas.getContext("2d"); this.renderContext = this.renderCanvas.getContext("2d"); this.globalWidth = window.innerWidth; this.globalHeight = window.innerHeight; this.booms = []; this.running = false; } handleMouseDown(e) { const boom = new Boom({ origin: { x: e.clientX, y: e.clientY }, context: this.computerContext, area: { width: this.globalWidth, height: this.globalHeight, }, }); boom.init(); this.booms.push(boom); this.running || this.run(); } handlePageHide() { this.booms = []; this.running = false; } init() { const style = this.renderCanvas.style; style.position = "fixed"; style.top = style.left = 0; style.zIndex = "999999999999999999999999999999999999999999"; style.pointerEvents = "none"; style.width = this.renderCanvas.width = this.computerCanvas.width = this.globalWidth; style.height = this.renderCanvas.height = this.computerCanvas.height = this.globalHeight; document.body.append(this.renderCanvas); window.addEventListener("mousedown", this.handleMouseDown.bind(this)); window.addEventListener("pagehide", this.handlePageHide.bind(this)); } run() { this.running = true; if (this.booms.length == 0) { return (this.running = false); } requestAnimationFrame(this.run.bind(this)); this.computerContext.clearRect(0, 0, this.globalWidth, this.globalHeight); this.renderContext.clearRect(0, 0, this.globalWidth, this.globalHeight); this.booms.forEach((boom, index) => { if (boom.stop) { return this.booms.splice(index, 1); } boom.move(); boom.draw(); }); this.renderContext.drawImage( this.computerCanvas, 0, 0, this.globalWidth, this.globalHeight ); } } const cursorSpecialEffects = new CursorSpecialEffects(); cursorSpecialEffects.init(); console.log("click.....");
// express const express = require('express') const app = express() // mongoose const mongoose = require('mongoose') // handlebars const exphbs = require('express-handlebars') // dateformat const dateFormat = require("dateformat") // body-parser const bodyParser = require('body-parser') // port const PORT = 3000 // record const Record = require('./models/Record') const Category = require('./models/Category') const { collection } = require('./models/Record') // static files app.use(express.static('public')) // connection mongoose.connect('mongodb://localhost/expense', { useNewUrlParser: true, useUnifiedTopology: true }) const db = mongoose.connection db.on('error', () => { console.log('mongodb error') }) db.once('open', () => { console.log('mongodb connected') }) // view app.engine('handlebars', exphbs({ defaultLayout: 'main', extname: '.handlebars' })) app.set('view engine', 'handlebars') // use body-parser app.use(bodyParser.urlencoded({ extended: true })) // route // index app.get('/', (req, res) => { const catNames = [] Category.find() .lean() .then(categories => { let totalAmount = 0 categories.forEach(item => { catNames.push(item.category) }) }) Record.find() .lean() .then(records => { let totalAmount = 0 records.forEach(item => { const formatDate = dateFormat(item.date, "mmmm dS, yyyy") item.date = formatDate totalAmount += item.amount }) res.render('index', { records, totalAmount, catNames }) }) .catch(error => console.error(error)) }) // new app.get('/records/new', (req, res) => { Category.find() .lean() .then(categories => { res.render('new', { categories }) }) .catch(error => console.error(error)) }) app.post('/records', (req, res) => { const { name, date, category, amount } = req.body const categoryIcon = Category.find() .lean() .then(categories => { categories.forEach(item => { if (item.category === category) { return item.categoryIcon } }) }) console.log(categoryIcon) if (Object.values(req.body).indexOf('') === -1) { return Record.create({ name: name, date: date, category: category, categoryIcon: '', amount: amount }) .then(() => res.redirect('/')) .catch(error => console.log(error)) } else { res.render('new', { name, date, category, amount }) } }) app.listen(PORT, () => { console.log(`App is running on http://localhost:${PORT}`) })
'use strict'; const config = require('config'); const util = require('util'); const banks = require('../banks'); const tools = require('../tools'); const db = require('../db'); const fetchUrl = require('fetch').fetchUrl; module.exports = IPAYServlet; function IPAYServlet(bank, fields, charset) { this.bank = (typeof bank === 'string' ? banks[bank] || banks.ec || {} : bank) || {}; this.fields = fields || {}; this.normalizeValues(); this.version = IPAYServlet.detectVersion(this.bank, this.fields); this.language = IPAYServlet.detectLanguage(this.bank, this.fields); this.charset = charset || IPAYServlet.detectCharset(this.bank, this.fields); } IPAYServlet.samplePayment = function (req, project, urlPrefix, options, callback) { let bank = banks[project.bank] || banks.ipizza, charsetValue, charsetKey; charsetValue = ((bank.allowedCharsets || []).indexOf('UTF-8') >= 0 ? 'UTF-8' : (bank.allowedCharsets || [])[0] || 'ISO-8859-1').toLowerCase(); charsetKey = bank.charset || 'charEncoding'; let testFields = { action: 'gaf', ver: '004', id: project.uid, ecuno: '1392644629', eamount: (options.amount && Math.round((Number(options.amount.replace(/[^\d.,]/g, '').replace(/,/g, '.')) || 0) * 100).toString()) || '1336', cur: 'EUR', datetime: '20140217154349', feedBackUrl: urlPrefix + '/project/' + project._id + '?payment_action=success', delivery: 'S', lang: 'en' }; if (charsetKey) { testFields[charsetKey] = charsetValue; } let payment = new IPAYServlet(project.bank, testFields, charsetValue); payment.editable = { amount: { field: 'eamount', name: 'Summa', value: options.amount || '13.36' } }; payment.record = project; payment.signClient(err => { if (err) { return callback(err); } callback(null, payment, charsetValue); }); }; IPAYServlet.detectVersion = function (bank, fields) { return (fields.ver || '2').lpad(3); }; IPAYServlet.detectLanguage = function (bank, fields) { bank = (typeof bank === 'string' ? banks[bank] || banks.ec || {} : bank) || {}; let language = IPAYServlet.languageCodes[(fields.lang || 'ET').toUpperCase().trim()]; if (IPAYServlet.languages.indexOf(language) < 0) { language = IPAYServlet.defaultLanguage; } return language; }; IPAYServlet.detectCharset = function (bank, fields) { let version = IPAYServlet.detectVersion(bank, fields); let defaultCharset = bank.defaultCharset; if (version === '004') { return fields.charEncoding || defaultCharset; } return defaultCharset; }; IPAYServlet.languages = ['ET', 'EN', 'FI', 'DE']; IPAYServlet.languageCodes = { ET: 'EST', EN: 'ENG', FI: 'FIN', DE: 'GER' }; IPAYServlet.defaultLanguage = 'EST'; IPAYServlet.actionFields = { gaf: ['action', 'ver', 'id', 'ecuno', 'eamount', 'cur', 'datetime', 'mac', 'lang', 'charEncoding', 'feedBackUrl', 'delivery'], afb: ['action', 'ver', 'id', 'ecuno', 'receipt_no', 'eamount', 'cur', 'respcode', 'datetime', 'msgdata', 'actiontext', 'mac', 'charEncoding', 'auto'] }; IPAYServlet.signatureOrder = { '002': { gaf: ['ver', 'id', 'ecuno', 'eamount', 'cur', 'datetime'], afb: ['ver', 'id', 'ecuno', 'receipt_no', 'eamount', 'cur', 'respcode', 'datetime', 'msgdata', 'actiontext'] }, '004': { gaf: ['ver', 'id', 'ecuno', 'eamount', 'cur', 'datetime', 'feedBackUrl', 'delivery'], afb: ['ver', 'id', 'ecuno', 'receipt_no', 'eamount', 'cur', 'respcode', 'datetime', 'msgdata', 'actiontext'] } }; IPAYServlet.signatureLength = { action: -3, ver: 3, id: -10, ecuno: 12, eamount: 12, cur: -3, lang: -2, datetime: -14, receipt_no: 6, respcode: 3, msgdata: -40, actiontext: -40, charEncoding: -16, feedBackUrl: -128, delivery: -1, auto: -1 }; // ++ kohustuslikud meetodid IPAYServlet.prototype.validateClient = function (callback) { db.findOne( 'project', { uid: this.fields.id }, (err, record) => { if (err) { return callback(err); } if (!record) { return callback(null, { success: false, errors: [ { field: 'id', value: (this.fields.id || '').toString(), error: 'Sellise kliendi tunnusega makselahendust ei leitud. Juhul kui sertifikaat on aegunud, tuleks see uuesti genereerida' } ], warnings: false }); } if (this.bank.key !== record.bank) { return callback(null, { success: false, errors: [ { field: 'id', value: (this.fields.id || '').toString(), error: util.format( 'Valitud kliendi tunnus kehtib ainult "%s" makselahenduse jaoks, hetkel on valitud "%s"', banks[record.bank].name, this.bank.name ) } ], warnings: false }); } this.record = record; callback(null, { success: true, errors: false, warnings: false }); } ); }; IPAYServlet.prototype.validateSignature = function (callback) { this.calculateHash(); tools.opensslVerify( this.sourceHash, this.fields.mac, this.record.userCertificate.certificate.toString('utf-8').trim(), this.charset, 'hex', (err, success) => { if (err) { return callback(err); } callback(null, { success: !!success, errors: !success ? [ { field: 'mac', error: util.format('Allkirja parameetri %s valideerimine ebaõnnestus.', 'mac'), download: true } ] : false, warnings: false }); } ); }; IPAYServlet.prototype.sign = function (callback) { this.calculateHash(); tools.opensslSign(this.sourceHash, this.record.bankCertificate.clientKey.toString('utf-8').trim(), this.charset, 'hex', (err, signature) => { if (err) { return callback(err); } this.fields.mac = signature.toUpperCase(); callback(null, true); }); }; IPAYServlet.prototype.signClient = function (callback) { this.calculateHash(); tools.opensslSign(this.sourceHash, this.record.userCertificate.clientKey.toString('utf-8').trim(), this.charset, 'hex', (err, signature) => { if (err) { return callback(err); } this.fields.mac = signature.toUpperCase(); callback(null, true); }); }; IPAYServlet.prototype.validateRequest = function (callback) { let validator = new IPAYServletValidator(this.bank, this.fields); validator.validateFields(); this.errors = validator.errors; this.warnings = validator.warnings; callback(null, { success: !this.errors.length, errors: (this.errors.length && this.errors) || false, warnings: (this.warnings.length && this.warnings) || false }); }; IPAYServlet.prototype.getUid = function () { return this.fields.id; }; IPAYServlet.prototype.getCharset = function () { return this.charset; }; IPAYServlet.prototype.getLanguage = function () { return tools.languages[this.language] || 'et'; }; IPAYServlet.prototype.getSourceHash = function () { return this.sourceHash || false; }; IPAYServlet.prototype.getType = function () { return 'PAYMENT'; }; IPAYServlet.prototype.getAmount = function () { return ((Number(this.fields.eamount) || 0) / 100).toString() || '0'; }; IPAYServlet.prototype.getReferenceCode = function () { return false; }; IPAYServlet.prototype.getMessage = function () { return false; }; IPAYServlet.prototype.getCurrency = function () { return (this.fields.cur || 'EUR').toUpperCase().trim(); }; IPAYServlet.prototype.getReceiverName = function () { return false; }; IPAYServlet.prototype.getReceiverAccount = function () { return false; }; IPAYServlet.prototype.editSenderName = function () { return true; }; IPAYServlet.prototype.showSenderName = function () { return false; }; IPAYServlet.prototype.editSenderAccount = function () { return false; }; IPAYServlet.prototype.showSenderAccount = function () { return false; }; IPAYServlet.prototype.showReceiverName = function () { return false; }; IPAYServlet.prototype.showReceiverAccount = function () { return false; }; IPAYServlet.prototype.getSuccessTarget = function () { if (this.version === '004') { return this.fields.feedBackUrl || this.record.ecUrl || ''; } return this.record.ecUrl || ''; }; IPAYServlet.prototype.getCancelTarget = function () { return this.getSuccessTarget(); }; IPAYServlet.prototype.getRejectTarget = function () { return this.getSuccessTarget(); }; // -- kohustuslikud meetodid IPAYServlet.prototype.calculateHash = function () { let list = [], key, value, pad, signatureOrders = IPAYServlet.signatureOrder[this.version] && IPAYServlet.signatureOrder[this.version][this.fields.action]; if (!signatureOrders) { this.sourceHash = false; return; } for (let i = 0, len = signatureOrders.length; i < len; i++) { key = signatureOrders[i]; value = String(this.fields[key]); pad = IPAYServlet.signatureLength[key] || 0; if (pad < 0) { value = value.rpad(pad, ' '); } else { value = value.lpad(pad); } list.push(value); } this.sourceHash = list.join(''); return this.sourceHash; }; IPAYServlet.prototype.normalizeValues = function () { let keys = Object.keys(this.fields); for (let i = 0, len = keys.length; i < len; i++) { if (this.fields[keys[i]] || this.fields[keys[i]] === 0) { this.fields[keys[i]] = this.fields[keys[i]].toString().trim(); } else { this.fields[keys[i]] = ''; } } }; function IPAYServletValidator(bank, fields) { this.bank = (typeof bank === 'string' ? banks[bank] || banks.ec || {} : bank) || {}; this.fields = fields || {}; this.version = IPAYServlet.detectVersion(this.bank, this.fields); this.errors = []; this.warnings = []; } IPAYServletValidator.prototype.validateFields = function () { let action = (this.fields.action || '').toString(), versionResponse, actionResponse; this.errors = []; this.warnings = []; versionResponse = this.validate_ver(true); if (typeof versionResponse === 'string') { this.errors.push({ field: 'ver', value: this.version, error: versionResponse }); return; } actionResponse = this.validate_action(); if (typeof actionResponse === 'string') { this.errors.push({ field: 'action', value: action, error: actionResponse }); return; } IPAYServlet.actionFields[action].forEach(field => { let response = this['validate_' + field](), value = (this.fields[field] || '').toString(); if (typeof response === 'string') { this.errors.push({ field, value, error: response }); } else if (this.bank.fieldLength && this.bank.fieldLength[field] && value.length > this.bank.fieldLength[field]) { this.warnings.push({ field, value, warning: util.format('Välja %s pikkus on %s sümbolit, lubatud on %s', field, value.length, this.bank.fieldLength[field]) }); } }); }; IPAYServletValidator.prototype.validate_ver = function (initial) { let value = (this.fields.ver || '').toString(); if (!value) { return util.format('Protokolli versiooni %s väärtust ei leitud', 'action'); } if (!IPAYServlet.signatureOrder[value]) { return util.format( 'Protokolli versiooni %s ("%s") väärtus peab olema üks järgmistest: %s', 'ver', value, Object.keys(IPAYServlet.signatureOrder).join(', ') ); } if (initial && value === '002') { return util.format('Kaardikeskuse versioon 002 on aegunud, selle asemel tuleb kasutada versiooni 004'); } return true; }; IPAYServletValidator.prototype.validate_action = function () { let value = (this.fields.action || '').toString(); if (!value) { return util.format('Teenuskoodi %s väärtust ei leitud', 'action'); } if (!IPAYServlet.signatureOrder[this.version][value]) { return util.format( 'Teenuskoodi %s ("%s") väärtus ei ole toetatud. Kasutada saab järgmisi väärtuseid: ', 'action', value, Object.keys(IPAYServlet.signatureOrder[this.version]).join(', ') ); } return true; }; IPAYServletValidator.prototype.validate_id = function () { let value = (this.fields.id || '').toString(); if (!value) { return util.format('Päringu koostaja tunnus %s peab olema määratud', 'id'); } return true; }; IPAYServletValidator.prototype.validate_ecuno = function () { let value = (this.fields.ecuno || '').toString(); if (!value) { return util.format('Tehingu unikaalse numbri %s kasutamine on kohustuslik', 'ecuno'); } if (Number(value) < 100000) { return util.format('Tehingu unikaalse numbri %s numbriline väärtus peab olema vähemalt 100000', 'ecuno'); } if (String(value).length > 12) { return util.format('Tehingu unikaalne number %s on liiga pikk (maksimaalselt 12 numbrikohta)', 'ecuno'); } return true; }; IPAYServletValidator.prototype.validate_eamount = function () { let value = (this.fields.eamount || '').toString(); if (!value) { return util.format('Tehingu summa %s kasutamine on kohustuslik', 'eamount'); } if (!String(value).match(/^\d{1,}$/)) { return util.format('Makse summa %s peab olema numbriline (täisarv) sendiväärtus', 'eamount'); } return true; }; IPAYServletValidator.prototype.validate_cur = function () { let value = (this.fields.cur || '').toString(); if (!value) { return util.format('Valuuta %s väärtus on seadmata', 'cur'); } if (!value || !value.match(/^[A-Z]{3}$/i)) { return util.format('Valuuta %s ei ole korrektses formaadis', 'cur'); } return true; }; IPAYServletValidator.prototype.validate_datetime = function () { let value = (this.fields.datetime || '').toString(); if (!value) { return util.format('Tehingu sooritamise aeg %s on seadmata', 'datetime'); } if (value.length !== 14 || !String(value).match(/^\d{1,}$/)) { return util.format('Tehingu sooritamise aeg %s on vigasel kujul, peab olema formaadis "AAAAKKPPTTmmss"', 'datetime'); } return true; }; IPAYServletValidator.prototype.validate_lang = function () { let value = (this.fields.lang || '').toString(); if (value && IPAYServlet.languages.indexOf(value.toUpperCase()) < 0) { return util.format('Tundmatu keelekoodi %s väärtus', 'lang'); } return true; }; IPAYServletValidator.prototype.validate_mac = function () { let value = (this.fields.mac || '').toString(); if (!value) { return util.format('Allkirja parameeter %s puudub', 'mac'); } if (!value.match(/^[0-9a-f]+$/i)) { return util.format('Allkirja parameeter %s peab olema HEX formaadis', 'mac'); } if (Buffer.from(value, 'hex').length % 128) { return util.format( 'Allkirja parameeter %s on vale pikkusega, väärtus vastab %s bitisele võtmele, lubatud on 1024, 2048 ja 4096 bitised võtmed', 'mac', Buffer.from(value, 'hex').length * 8 ); } return true; }; IPAYServletValidator.prototype.validate_charEncoding = function () { let value = (this.fields.charEncoding || '').toString(), allowedCharsets = this.bank.allowedCharsets || [this.bank.defaultCharset], defaultCharset = this.bank.defaultCharset; if (!value) { return true; } if (value && this.version === '002') { return util.format('Teksti kodeeringu parameetri %s kasutamine ei ole protokolli versiooni %s puhul lubatud', 'charEncoding', this.version); } if (allowedCharsets.indexOf(value.toUpperCase()) < 0) { return util.format( 'Teksti kodeeringu parameeter %s võib olla %s', 'charEncoding', tools.joinAsString(allowedCharsets, ', ', ' või ', defaultCharset, ' (vaikimisi)') ); } return true; }; IPAYServletValidator.prototype.validate_feedBackUrl = function () { let value = (this.fields.feedBackUrl || '').toString(); if (value && this.version === '002') { return util.format('Tagasisuunamise aadressi %s kasutamine ei ole protokolli versiooni %s puhul lubatud', 'feedBackUrl', this.version); } if (!value && this.version === '004') { return util.format('Tagasisuunamise aadress %s kasutamine on protokolli versiooni %s puhul kohustuslik', 'feedBackUrl', this.version); } return true; }; IPAYServletValidator.prototype.validate_delivery = function () { let value = (this.fields.delivery || '').toString(); if (value && this.version === '002') { return util.format('Transpordimeetodi %s kasutamine ei ole protokolli versiooni %s puhul lubatud', 'delivery', this.version); } if (!value && this.version === '004') { return util.format('Transpordimeetodi %s kasutamine on protokolli versiooni %s puhul kohustuslik', 'delivery', this.version); } if (value && ['S', 'T'].indexOf(value.toUpperCase().trim()) < 0) { return util.format('Transpordimeetodi %s väärtus on vigasel kujul, peab olema üks järgmistest: %s', 'delivery', '"S" või "T"'); } return true; }; IPAYServlet.generateForm = function (payment, project, callback) { tools.incrTransactionCounter(project.uid, (err, transactionId) => { if (err) { return callback(err); } let paymentFields = {}; payment.fields.forEach(field => { paymentFields[field.key] = field.value; }); let fields = { action: 'afb', ver: paymentFields.ver.replace(/^0+/, ''), id: paymentFields.id, ecuno: paymentFields.ecuno, receipt_no: payment.state === 'PAYED' ? transactionId : '0', eamount: paymentFields.eamount, cur: paymentFields.cur, respcode: payment.state === 'PAYED' ? '000' : '111', datetime: paymentFields.datetime, msgdata: payment.payment.senderName || '', actiontext: payment.state === 'PAYED' ? 'OK, tehing autoriseeritud' : 'Tehing katkestatud' }; let transaction = new IPAYServlet(project.bank, fields, payment.charset); transaction.record = project; if (paymentFields.charEncoding) { fields.charEncoding = paymentFields.charEncoding; } transaction.sign(err => { if (err) { return callback(err); } fields.auto = 'Y'; let method = 'POST'; let payload = tools.stringifyQuery(fields, payment.charset); let url = payment.state === 'PAYED' ? payment.successTarget : payment.cancelTarget; if (payment.state === 'PAYED') { fetchUrl( url, { method, payload: payload ? payload : undefined, agent: false, maxResponseLength: 100 * 1024 * 1024, timeout: 10000, disableRedirects: true, userAgent: config.hostname + ' (automaatsed testmaksed)', headers: { 'content-type': 'application/x-www-form-urlencoded' }, rejectUnauthorized: false }, (err, meta, body) => { if (err) { payment.autoResponse = { status: false, error: err.message }; } else { payment.autoResponse = { statusCode: meta.status, headers: meta.responseHeaders, body: body && body.toString() }; } fields.auto = 'N'; payment.responseFields = fields; payment.responseHash = transaction.sourceHash; payment.returnMethod = method; callback(null, { method, url, payload }); } ); } else { fields.auto = 'N'; payment.responseFields = fields; payment.responseHash = transaction.sourceHash; payment.returnMethod = method; return callback(null, { method, url, payload }); } }); }); };
(function(){ 'use strict'; angular .module('everycent.transactions.importers') .factory('FcbImporter', FcbImporter); FcbImporter.$inject = ['DateService']; function FcbImporter(DateService){ var service = { convertFromBankFormat: _convertFromFCBankFormat, convertFromCreditCardFormat: _convertFromCreditCardFormat }; return service; function _convertFromCreditCardFormat() { throw new Error('not implemented yet'); } function _convertInputToLines(input) { if (!input) return []; return input.split(/[\n]/); } function _convertFromFCBankFormat(input, startDate, endDate) { // SAMPLE DATA // 2017-09-10 SAVINGS WITHDRAWAL - ATM $500.00 $0.00 $1,819.61 // 2017-09-08 SAVINGS WITHDRAWAL - ATM $500.00 $0.00 $2,319.61 // 2017-09-06 ACH CREDIT MEMO $0.00 $250.00 $2,819.61 // 2017-09-02 SAVINGS WITHDRAWAL - ATM $1,000.00 $0.00 $2,569.61 // 2017-09-01 ABM Withdrawal Fee - SAV $3.00 $0.00 $3,569.61 // first split into lines var lines = _convertInputToLines(input); // then split each line into its parts return lines.map(function(line){ return _convertFCBankLineDataToTransaction(line, startDate, endDate); }); } function _convertFCBankLineDataToTransaction(line, startDate, endDate) { var transaction = {}; var parts = line.split('\t'); transaction.transaction_date = new Date(parts[0]); transaction.description = parts[1]; var withdrawalAsStringWithDollarSign = parts[2]; var depositAsStringWithDollarSign = parts[3]; transaction.withdrawal_amount = extractNumberFromDollarString(withdrawalAsStringWithDollarSign); transaction.deposit_amount = extractNumberFromDollarString(depositAsStringWithDollarSign); var start = DateService.toDate(startDate); var end = DateService.toDate(endDate); // confirm that the transaction date is within the period if(transaction.transaction_date < start || transaction.transaction_date > end){ transaction.deleted = true; } // also remove any transactions with 0 amounts if(transaction.withdrawal_amount === 0 && transaction.deposit_amount === 0){ transaction.deleted = true; } return transaction; } function extractNumberFromDollarString(dollarString) { if(!dollarString) { return 0; } var amountWithCommas = dollarString.replace(/\$/g, ''); var amountAsNumberInDollars = Number(amountWithCommas.replace(/,/g, '')); return amountAsNumberInDollars * 100; } } })();
const Discord = require('discord.js'); const client = new Discord.Client(); client.once('ready', () => { console.log('joy ♡ is online!'); }); client.login('NDg3MDQ3NTM2OTEwMDA4MzMw.W5BsXQ.PpVgDQcEVkVVO5QrpbqH8FJ98SE');
import React, {useState} from 'react'; import './App.scss'; import Sidebar from "./components/Sidebar"; import Chat from "./components/Chat"; import {Provider} from "react-redux"; import {PersistGate} from "redux-persist/integration/react"; import {store, persistor} from "./store"; import Notification from "./components/Notification"; const App = () => { const [isVisible, toggleIsVisible] = useState(false); return ( <div className="App"> <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <Sidebar isVisible={isVisible} toggleIsVisible={toggleIsVisible}/> <Chat isVisible={isVisible} toggleIsVisible={toggleIsVisible}/> <Notification/> </PersistGate> </Provider> </div> ); } export default App;
import React from 'react'; import "./ProjectCard.css" import { useState } from 'react'; import { render } from 'react-dom'; import Project from "../Project/Project" /*localStorage.setItem('projects', JSON.stringify([ { projectTitle: "Black Box", projectDeadline: 87, projectTeam: ["Justin Kessler", "Jimmy Kessler", "Raymond Harmer", "Trevor Allison", "Kelsey Jones"], projectDescription: "Project Black Box is dedicated towards testing new Nano materials to go inside our cutting edge prosthetics.", projectTaskProgress: 70, projectID: 1, project_todos: [ { todo_title: "Take out the Trash", todo_description: "Really understandable", category: "Life", time: "4h 56m", taskID: 1 }, { todo_title: "Build API", todo_description: "create a useful api for everyone to be good at", category: "Development", taskID: 2 } ], project_inProgress: [ { inProgress_title: "Build super moon", inProgress_description: "Really hard to do but im sure you can get it done", category: "Design", time: "1h 2m", taskID: 3 } ], project_stuck: [ { stuck_title: "Just really here being stuck", stuck_description: "Can't really see it getting much worse than this", category: "Development", time: "22m", taskID: 4 } ], project_complete: [ { complete_title: "Smoking that phat gas", complete_description: "I always knew I could do it", category: "Engineering", time: "59m", taskID: 5 } ] } ]))*/ const ProjectCard = (props) => { const [projectRender, setRender] = useState(0); function renderHandler() { props.projectRender(props.projectID); } function teamDisplay() { let number = props.projectTeam.length; if (props.projectTeam.length > 3) { return ("+" + number) } else { return null } } return ( <div className="project-card-container" onClick={renderHandler}> <div className="project-card-title">{props.projectTitle}</div> <div className="project-card-deadline">{props.projectDeadline} Days Left</div> <div className="project-card-team-members"><p>Team :</p> <div className="card-member-icon icon1"></div> <div className="card-member-icon icon2"></div> <div className="card-member-icon icon3"></div> <p className="team-expand-number">{teamDisplay()}</p> </div> <div className="project-card-description">{props.projectDescription}</div> <div className="project-card-task-progress"> <div className="task-completion">Tasks : 7/13</div> <div className="task-progress-bar"> <div className="task-progress"></div> </div> </div> </div> ); } export default ProjectCard;
class AppService{ constructor($http){ 'ngInject'; this.http = $http; this.jquerry = $; this.callback; } getXmlAsObject(str){ var xml = this.jquerry.parseXML(str); var json = this.xmlToJson(xml); var json = json.Children[0]; return json; } isPercentValue(strValue){ if(strValue != null){ var arrValues = strValue.split("%"); if(arrValues.length > 1){ return true; }else{ return false; } }else{ return false; } } convertPercentToNumeric(strPercent, fullValue){ var returnValue = 0; var intPercent = Number( strPercent.replace("%", "")) ; returnValue = Math.round( (fullValue * intPercent ) / 100 ); return returnValue; } // Changes XML to JSON xmlToJson (xml) { // Create the return object var obj = {}; if(xml.nodeName && xml.nodeName != "#text"){ obj["type"] = xml.nodeName; obj.Children = []; } if (xml && xml.nodeType == 1) { // element // do attributes if (xml.attributes.length > 0) { for (var j = 0; j < xml.attributes.length; j++) { var attribute = xml.attributes.item(j); obj[attribute.nodeName] = attribute.nodeValue; } } } // do children if (xml && xml.hasChildNodes() ) { for(var i = 0; i < xml.childNodes.length; i++) { var item = xml.childNodes.item(i); var nodeName = item.nodeName; if( obj["type"] ){ var aaa = this.xmlToJson(item); if( aaa["type"] ){ obj.Children.push ( aaa ); } } } } return obj; } } export default AppService;
Function.prototype.inherits = function(superclass) { var Surrogate = function() {}; Surrogate.prototype = superclass.prototype; this.prototype = new Surrogate(); }; function MovingObject () {}; MovingObject.prototype.move = function() { console.log("moving!"); }; function Ship () {} Ship.inherits(MovingObject); function Asteroid () {}; Asteroid.inherits(MovingObject); Asteroid.prototype.blast = function() { console.log("outerspace blasting peew!"); }; Ship.prototype.newMethod = function() { console.log("a method only for ships"); }; var ship = new Ship(); var asteroid = new Asteroid(); var mo = new MovingObject(); ship.move(); asteroid.move(); asteroid.blast(); // ship.blast(); // error // mo.newMethod(); // error
$(function(){ // 获取当前位置 getLocationFun(); /* 微信中不隐去.header */ var ua = window.navigator.userAgent.toLowerCase(); /*if(ua.match(/MicroMessenger/i) == 'micromessenger'){ $(".header").show(); }*/ $(".header .returnBtn").click(function(){ if(ua.match(/MicroMessenger/i) == 'micromessenger'){ location.href = wechatUrl + "/syOauth2Login.html?r=/index.html"; }else{ location.href = "index.html"; } }) var logininf = JSON.parse(localStorage.getItem("logininf")); var myDate = new Date(); var year= myDate.getFullYear(); var month= myDate.getMonth()+1 < 10 ? '0'+(myDate.getMonth()+1) : (myDate.getMonth()+1); var date = myDate.getDate() < 10 ? '0'+ myDate.getDate() : myDate.getDate(); var nowDate = year +'-'+ month +"-"+date; $("#startTime").val(nowDate); var pageNumVal = 1; $(".main").scroll(function(){ var scrollNum = document.documentElement.clientWidth / 7.5; if($(".main .carList").outerHeight() - $(".main").scrollTop() - $(".main").height() < 20){ if($(".ajax-loder-wrap").length > 0){ return false; } if(pageNumVal < totalNum){ pageNumVal = parseInt(pageNumVal) + parseInt(1) pageInf.pageInfo.pageNum = pageNumVal; getVehicleList(); } } }) $(".header .txt").html("应收费用 &nbsp" + nowDate); var ua = window.navigator.userAgent.toLowerCase(); /*if(ua.match(/MicroMessenger/i) == 'micromessenger'){ $(".header").show(); }*/ //获取列表 var pageInf = { endCompleteTime:nowDate, startCompleteTime:nowDate, pageInfo:{ pageNum:pageNumVal, pageSize:25 } } getVehicleList(); function getVehicleList(){ $.ajax({ url: tmsUrl + '/wx/query/transportCostStatistics?token=' + logininf.token + '&timeStamp=' + logininf.timeStamp, type: "post", contentType: 'application/json', data: JSON.stringify(pageInf), beforeSend:function(){ $(".main").append('<div class="ajax-loder-wrap"><img src="../images/ajax-loader.gif" class="ajax-loader-gif"/><p class="loading-text">加载中...</p></div>'); }, success:function(data){ $(".ajax-loder-wrap").remove(); totalNum = data.result.pageModel.pageInfo.pages; var datas = data.result.pageModel.data; if(datas.length == 0){ var timer1 = setTimeout(function(){ $(".listCon").append('<p class="noContent" style="width: 3rem; height: auto; margin: 0 auto; padding-top: 0.36rem;">'+ '<img src="images/noContent.png" alt="" style="width: 3rem; height: auto; display: block;"/>'+ '</p>'); },600) $(".carAmountInf").empty(); }else{ // vehicleHtml(datas,data.result.spotPayAmountSum,data.result.collectPayAmountSum,data.result.monthlyPayAmountSum); vehicleHtml(datas,data.result.spotPayAmountSum,data.result.collectPayAmountSum); } } }) function vehicleHtml(vehicleData,spotPayAmountSum,collectPayAmountSum){ // var vehicleItem = "",spotPayAmountAll = 0,collectPayAmountAll = 0,monthlyPayAmountAll = 0,carAmountInfHtml = ''; var vehicleItem = "",spotPayAmountAll = 0,collectPayAmountAll = 0,carAmountInfHtml = ''; if(spotPayAmountSum != undefined && spotPayAmountSum != null){ spotPayAmountAll = spotPayAmountSum; } if(collectPayAmountSum != undefined && collectPayAmountSum != null){ collectPayAmountAll = collectPayAmountSum; } /*if(monthlyPayAmountSum != undefined && monthlyPayAmountSum != null){ monthlyPayAmountAll = monthlyPayAmountSum; }*/ var time = $("#startTime").val(); for(var i = 0; i < vehicleData.length; i ++ ){ vehicleItem += '<ul class="listItem" spot="'+vehicleData[i].spotPayAmount+'" col="'+vehicleData[i].collectPayAmount+'" eqpNo="'+vehicleData[i].eqpNo+'" time="'+time+'">'+ '<li>'+vehicleData[i].contactName+'-'+vehicleData[i].eqpNo+'</li>'+ '<li style="color: #00b050;">'+vehicleData[i].spotPayAmount+'</li>'+ '<li style="color: #007aff">'+vehicleData[i].collectPayAmount+' </li>'+ // '<li>'+vehicleData[i].monthlyPayAmount+'</li>'+ '</ul>' } // carAmountInfHtml = '<span>现付:'+spotPayAmountAll+'元;到付:'+collectPayAmountAll+'元;月结:'+monthlyPayAmountAll+'元</span>'; carAmountInfHtml = '<span>现付:'+spotPayAmountAll+'元;到付:'+collectPayAmountAll+'元;</span>'; $(".orderList .listCon").append(vehicleItem); $(".carAmountInf").html(carAmountInfHtml); } } $(".carList .listCon").on("click",".listItem",function(){ var spot = $(this).attr("spot"); var col = $(this).attr("col"); var eqpNo = $(this).attr("eqpNo"); var time = $(this).attr("time"); // var mon = $(this).attr("mon"); location.href = "orderCostListDj0.html?spot="+spot+"&col="+col+"&eqpNo="+eqpNo+"&time="+time; }) $(".header .right").click(function(){ $(".searchLayer").toggle(); }) $(".searchBox .searchbtn").click(function(){ if($("#startTime").val().trim() == ""){ $(".searchLayer").hide(); }else{ $(".main .orderList .listCon").html(""); totalNum = 1; pageInf.pageInfo.pageNum = 1; pageInf.endCompleteTime = $("#startTime").val(); pageInf.startCompleteTime = $("#startTime").val(); getVehicleList(); $(".searchLayer").hide(); $(".header .txt").html("应收费用 &nbsp" + $("#startTime").val()); } }) })
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom' import { useSelector } from 'react-redux'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead' import TableRow from '@material-ui/core/TableRow' import Paper from '@material-ui/core/Paper' import Button from '@material-ui/core/Button' // helpers import get from '../../Helpers/Request/get' import post from '../../Helpers/Request/post' // components import Notification from '../../Components/Notification/Notification'; const useStyles = makeStyles({ table: { minWidth: 500, }, }); /** * @package add people in team with teamId = id (from url parameter) */ export default function BasicTable() { const classes = useStyles(); const [fetched, setFetched] = useState(false) const [rows, setRows] = useState([]) const user = useSelector((state)=>state.user) const { id } = useParams() useEffect(async () => { const response = await get('contactlist') console.log(response.data) if (response.data) { setRows(response.data) setFetched(true) } else { Notification('Error', 'Cannot fetch Users', 'warning') } }, []) const handleAdd = async (userId)=>{ console.log(userId) const reponse = await post('addinroom', { myId: user, userId: userId, roomId: id }) if(reponse.data){ Notification('Success', 'User Added to Meet', 'success') } else{ Notification('Error', 'Cannot Add!!', 'warning') } } return ( <> { fetched ? ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell><b>Email Id</b></TableCell> <TableCell align="center"><b>Add</b></TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.email}> <TableCell component="th" scope="row"> {row.email} </TableCell> <TableCell align="center"><Button variant="contained" color="primary" name={row.id} onClick={()=>handleAdd(row.id)}> Add </Button></TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ) : (null) } </> ); }
"use strict"; var core_1 = require('@angular/core'); var FooDirective = (function () { function FooDirective() { } FooDirective.decorators = [ { type: core_1.Directive, args: [{ selector: '[foo]' },] }, ]; /** @nocollapse */ FooDirective.ctorParameters = []; return FooDirective; }()); exports.FooDirective = FooDirective;
import React, { Component } from 'react'; // BackgroundColor import { AnimatedBg, Transition } from 'scroll-background'; // SlideShow import HomeSlideShow from './HomeSlideShow.js'; import "../node_modules/react-image-gallery/styles/css/image-gallery.css"; // Particles import { DawnParticles, NightParticles } from './BaseParticles.js'; // Plane import Plane from './Plane.js'; import "./css/plane.css"; const dawnRgb = "#EDADAB" const dayRgb = "#33B2F5" const sunsetRgb = "#FF8021" const nightRgb = "#232741" function HomeCard(props) { return <div className="row"> <div className="homeCard mx-auto"> <img src={require('./files/mrlicorne_logo.jpg')} style= {{width: "215px"}} alt="MrLicorne logo"/> </div> </div> } function PageSection(props) { return <section style={{padding: '2vh 0', border: "1px solid black", height: '100vh'}} className='pageSection'> {props.children} </section> } class SectionComponent extends Component { render() { return ( <div className="container-fluid" style= {{padding: '0'}}> <AnimatedBg> <PageSection id="dawnSection"> <div className="particlesSky"> <DawnParticles /> </div> </PageSection> <Transition height="170px" from={dawnRgb} to={dayRgb} position={0.75} /> <PageSection id="daySection"/> <Transition height="170px" from={dayRgb} to={sunsetRgb} position={0.75} /> <PageSection id="sunsetSection" /> <Transition height="170px" from={sunsetRgb} to={nightRgb} position={0.75} /> <PageSection id="nightSection"> <div className="particlesSky"> <Plane /> <NightParticles /> </div> </PageSection> </AnimatedBg> </div> ); } } class App extends Component { render() { return ( <div className="container-fluid App"> <HomeCard/> <div className="row" style= {{marginTop: "-75px"}}> <HomeSlideShow/> <SectionComponent style= {{width: '100%'}}/> </div> </div> ); } } export default App;
import Html from "../../Html/Html"; import Api from "../../Api/Api"; export default class UnknownBlock { constructor() { this.rootDataURL = Api().getRootURL() + "unknown"; console.log(this.rootDataURL); } renderContent(requestedData) { const main = Html().select(".main"); const content = this.generateContent(); main.replace(content); } generateContent() { const pageTitle = Html() .create("h1") .text("Unknown Endpoint."); const pageSubTitle = Html() .create("h2") .text("Welcome to the Void."); const content = Html() .create("div") .addChild(pageTitle) .addChild(pageSubTitle); return content; } }
'use strict'; function render_nomenclature(parent = 'render', data) { var div = $('#'+parent); div.empty(); div.append('' + '<div class="table-responsive">\n' + '<table class="table">\n' + '<thead>\n' + '<tr>\n' + '<th>Название</th>\n' + '<th class="text-right">Действия</th>\n' + '</tr>\n' + '</thead>\n' + '<tbody id="nomenclature-table-body">\n' + '</tbody>\n' + '</table>\n' + '</div>'); $.each(data, function(k,v){ if (v.parent == 0) { $('#nomenclature-table-body').append('' + '<tr>\n' + '<td class="" style="width: 90%;"><i class="fas fa-plus-circle"></i> '+ v.title +'</td>\n' + '<td class="co1l-2 text-right">\n' + '<div class="btn-group" role="group" aria-label="Basic example">\n' + '<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#edit-section" data-id="'+v.id+'">\n' + '<i class="fas fa-pencil-alt"></i>\n' + '</button>\n' + '<button type="button" class="btn btn-primary btn-sm delete-nomenclature" data-id="'+ v.id +'">\n' + '<i class="fas fa-trash-alt"></i>\n' + '</button>\n' + '</div>\n' + '</td>\n' + '</tr>\n' ); } }); } function deleteRequestNomenclature(id, item, delete_route) { $.ajax({ type: 'POST', data: {"id":id}, url: delete_route, success: function(success) { //render table if ($.isEmptyObject(success)) { render_empty_result('render','Раздел пуст'); console.log('sss'); } else render_nomenclature('render', success); // $(item).closest('tr').remove(); // console.log(success); showToastPosition('top-right','Успех', 'Удалено'); }, error: function (error) { $.each(error.responseJSON.errors, function (index, value) { showDangerToast('top-right','Ошибка', value); }); }, beforeSend: function(xhr) { if (token) xhr.setRequestHeader('X-CSRF-TOKEN', token); }, }).done(function(success){ $('#loader').fadeOut(1000); }) } function deleteRequest(id, item, delete_route, render, modal=false) { var render_block = $('#'+render); var hide_modal = $('#'+modal); $.ajax({ type: 'POST', data: {"id":id}, url: delete_route, success: function(success) { if (render) $(render_block).empty(); showToastPosition('top-right','Успех', 'Удалено!'); }, error: function (error) { $.each(error.responseJSON.errors, function (index, value) { showDangerToast('top-right','Ошибка', value); }); }, beforeSend: function(xhr) { if (token) xhr.setRequestHeader('X-CSRF-TOKEN', token); }, }).done(function(success){ if (render) $(render_block).html(success); $('#loader').fadeOut(1000); }) } function delete_item(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-nomenclature',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route, render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_specification(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete_specification',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_specification_value(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-value',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_specification_group_value(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-group-value',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_implementation(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-implementation',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_currency(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-currency',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_procurement(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-procurement',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } //products function delete_product(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-product',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_percents(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-percents',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_types(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-types',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_range(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-range',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); } function delete_provider(title, text, cancel_btn,delete_btn, delete_txt, cancel_txt, delete_route, render){ $(document).on('click','.delete-user',function(e){ e.preventDefault(); var item = $(this); var id = $(this).data('id'); swal({ title: title, text: text, buttons: { cancel: { text: cancel_btn, value: null, visible: true, className: "btn btn-primary", closeModal: true, }, confirm: { text: delete_btn, value: true, visible: true, className: "btn btn-danger", closeModal: true } }, }).then((value) => { switch (value) { case true: swal({ text: delete_txt, timer: 1000, button: false }); deleteRequest(id, item, delete_route,render); break; default: swal({ text: cancel_txt, timer: 1000, button: false }) } }); }); }
import { createUseStyles } from "react-jss"; import sizes from "../utils/breakpoints"; const useStyles = createUseStyles({ main: { width: "80%", margin: "0 auto", paddingTop: "5rem", [sizes.down("laptopSm")]: { width: "90%", }, [sizes.down("mobileLg")]: { width: "100%", }, }, container: { display: "flex", [sizes.down("tablet")]: { flexDirection: "column", alignItems: "center", }, }, imgContainer: { width: "65%", display: "flex", alignItems: "center", justifyContent: "center", }, img: { [sizes.down("mobileLg")]: { width: "200px", }, }, infoSide: { width: "35%", [sizes.down("tablet")]: { width: "100%", display: "flex", marginTop: "4rem", justifyContent: "space-between", alignItems: "center", }, [sizes.down("mobileLg")]: { display: "flex", flexDirection: "column", }, }, info: { [sizes.down("tablet")]: { width: "45%", }, [sizes.down("mobileLg")]: { width: "80%", margin: "0 auto", textAlign: "center", }, }, planetName: { marginTop: "4rem", textTransform: "uppercase", fontSize: "5rem", letterSpacing: "1rem", [sizes.down("laptopSm")]: { fontSize: "4rem", }, [sizes.down("tablet")]: { marginTop: 0, }, [sizes.down("mobileLg")]: { fontSize: "2.5rem", }, }, content: { paddingTop: "2rem", paddingBottom: "2rem", }, sourceLink: { color: "rgba(255,255,255,0.6)", "& span": { textDecoration: "underline", }, }, buttons: { marginTop: "3rem", [sizes.down("tablet")]: { marginTop: 0, width: "45%", }, [sizes.down("mobileLg")]: { display: "none", }, }, geologyContainer: { display: "flex", flexDirection: "column", alignItems: "center", }, geologyImg: { width: "200px", height: "auto", marginTop: "-8rem", [sizes.down("mobileLg")]: { width: "100px", }, }, bigGeologyImg: { width: "200px", height: "auto", marginTop: "-15.5rem", [sizes.down("mobileLg")]: { width: "100px", marginTop: "-8rem", }, }, }); export default useStyles;
define([ "dojo/_base/declare", "dojo/date/locale", // locale.format "dojo/date/stamp", // stamp.fromISOString stamp.toISOString "dijit/_CssStateMixin", "dijit/_Widget", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "dijit/form/TimeTextBox", "epi/shell/widget/_ValueRequiredMixin" ], function (declare, locale, stamp, _CssStateMixin, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, TimeTextBox, _ValueRequiredMixin ) { var a = declare([TimeTextBox], { _setValueAttr: function (value, priorityChange, formattedValue) { if (value instanceof Date || !value) { this.inherited(arguments); return; } var date = new Date(); date.setSeconds(0); var timeSpan = value.split(":"); date.setMinutes(parseInt(timeSpan[1])); date.setHours(parseInt(timeSpan[0])); this.set("value", date); }, _getValueAttr: function () { var result = this.inherited(arguments); if (result === null) { return null; } var hours = result.getHours() + ""; if (hours.length < 2) { hours = "0" + hours; } var minutes = result.getMinutes() + ""; if (minutes.length < 2) { minutes = "0" + minutes; } return hours + ":" + minutes + ":00"; }, serialize: function (/*anything*/ val, /*Object?*/ options) { return val; } }); return declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, _CssStateMixin, _ValueRequiredMixin], { templateString: "<div class='dijitInline' tabindex='-1' role='presentation'>\ <div data-dojo-attach-point='stateNode, tooltipNode'>\ </div>\ </div>", baseClass: "epiTimePicker", value: null, onChange: function (value) { // Event }, postCreate: function () { this.inherited(arguments); this.timePicker = new TimeTextBox(this.params); this.timePicker.placeAt(this.stateNode); if (this._value) { this.timePicker.set("value", this._value); } this.connect(this.timePicker, "onChange", this._onTimePickerChanged); }, isValid: function () { // summary: // Check if widget's value is valid. // tags: // protected, override return !this.required || this.timePicker.isValid(); }, // Setter for value property _setValueAttr: function (value) { this._setValue(value, true); }, _getValueAttr: function () { // summary: // Returns the textbox value as array. // tags: // protected, override var val = this.timePicker && this.timePicker.get("value"); return this._getTimeSpanValue(val); }, _setReadOnlyAttr: function (value) { this._set("readOnly", value); if (this.timePicker) { this.timePicker.set("readOnly", value); } }, _onTimePickerChanged: function (value) { this._setValue(value, false); }, _setValue: function (value, updateTimePicker) { // Assume value is an array var timeSpanValue = value; if (value instanceof Date) { // Split list timeSpanValue = this._getTimeSpanValue(value); } else if (!value) { // use empty array for empty value timeSpanValue = null; } if (this._started && epi.areEqual(this.value, timeSpanValue)) { return; } // set value to this widget (and notify observers) this._set("value", timeSpanValue); if (updateTimePicker) { var parsedValue = this._parseDateValue(timeSpanValue); if (parsedValue) { this._value = parsedValue; this.timePicker && this.timePicker.set("value", parsedValue); } } if (this._started && this.validate()) { // Trigger change event this.onChange(timeSpanValue); } }, _getTimeSpanValue: function (date) { if (!date) { return null; } var hours = date.getHours() + ""; if (hours.length < 2) { hours = "0" + hours; } var minutes = date.getMinutes() + ""; if (minutes.length < 2) { minutes = "0" + minutes; } return hours + ":" + minutes + ":00"; }, _parseDateValue: function (str) { if (!str) { return null; } var date = new Date(); date.setSeconds(0); var timeSpan = str.split(":"); date.setMinutes(parseInt(timeSpan[1])); date.setHours(parseInt(timeSpan[0])); return date; } }); });
import React from 'react'; import { View, } from 'react-native'; import { LogoTitle } from '../../../components/header'; import Gallery from 'react-native-image-gallery'; import { FilePicturePath } from '../../../utilities/index'; import Strings from '../../../language/fr'; export class ArchiveGalleryScreen extends React.Component { static navigationOptions = ({ navigation }) => { return { headerTitle: <LogoTitle HeaderText={Strings.GALLERY} />, }; }; constructor(props) { super(props); this.state = { images: [], index: this.props.navigation.state.params.index, }; } render() { let pictures = this.props.navigation.state.params.pictures; var images = []; pictures.map(row => { images.push({ caption: row.date, source: { uri: FilePicturePath() + row.source } }); }); return ( <View style={{ flex: 1 }} > <Gallery style={{ flex: 1, backgroundColor: 'black' }} images={images} initialPage={this.state.index} /> </View> ); } }
/* Write a function that accepts a number as a parameter and checks if the number is prime or not. Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. */ "use strict" function primeNum(number){ for(var i = 2; i < number; i++){ if(number % 2 === 0){ return false; } } return number > 1; } console.log(primeNum(2));
const express = require("express"); const bodyParser = require("body-parser"); const date = require(__dirname+"/date.js"); const app = express(); let list=[]; app.use(bodyParser.urlencoded({extended:true})); app.use(express.static("public")); app.set('view engine', 'ejs'); app.listen(8080,function(){ console.log("server on port 8080 is started"); }) app.get("/",function(req,res){ //res.send("hello world"); let today =date.getDate(); res.render("home",{day:today,item:list}); }); app.post("/",function(req,res) { let listValue = req.body.listValue; //console.log(req.body.buttonadd); console.log(listValue); if (req.body.buttonadd ==="1") { list.push(listValue); } else { list.pop(listValue); } res.redirect("/"); }); app.get("/about",function(req,res){ res.render("about"); })
export default from './OrderTable';
import React from "react"; import { Parallax } from "react-scroll-parallax"; const ParallaxImage1 = () => { return ( <Parallax className="custom-class" y={[-20, 20]}> <img src="https://picsum.photos/420/380" alt="" /> <img src="https://picsum.photos/420/380" alt="" /> <img src="https://picsum.photos/420/380" alt="" /> </Parallax> ); }; export default ParallaxImage1;
"use strict" import React from 'react'; import {connect} from 'react-redux'; //smart component import {bindActionCreators} from 'redux'; import {Modal, Panel, Well, Row, Col, Button, ButtonGroup, Label} from 'react-bootstrap'; import {deleteCartItem, updateCart, getCart} from '../../actions/cartActions'; class Cart extends React.Component{ constructor(){ super(); this.state = {showModal: false}; } componentDidMount(){ this.props.getCart(); } handleCloseModal(){ this.setState({showModal: false}); } handleOpenModal(){ this.setState({showModal: true}); } deleteHandler(_id){ const indexToDelete = this.props.cart.findIndex( function(cartItem){ return _id === cartItem._id; } ); const cartAfterDelete = [...this.props.cart.slice(0, indexToDelete), ...this.props.cart.slice(indexToDelete+1)] this.props.deleteCartItem(cartAfterDelete); } onIncrement(_id){ this.props.updateCart(_id, 1, this.props.cart); } onDecrement(_id, qty){ if(qty > 1){ this.props.updateCart(_id, -1, this.props.cart); } } render(){ if(this.props.cart[0]){ return this.renderCart(); }else{ return this.renderEmpty(); } } renderEmpty(){ return(<div></div>); } renderCart(){ const cartItemsList = this.props.cart.map((cartItem)=>{ return( <Panel key={cartItem._id}> <Row componentClass="h4"> <Col xs={12} sm={4}> <h6>{cartItem.title}</h6><span> </span> </Col> <Col xs={12} sm={2}> <h6>usd. {cartItem.price}</h6> </Col> <Col xs={12} sm={2}> <h6>qty. <Label bsStyle="success">{cartItem.qty}</Label></h6> </Col> <Col xs={6} sm={4}> <ButtonGroup style={{minWidth: '300px'}}> <Button onClick={this.onDecrement.bind(this, cartItem._id, cartItem.qty)} bsStyle="default" bsSize="small">-</Button> <Button onClick={this.onIncrement.bind(this, cartItem._id)} bsStyle="default" bsSize="small">+</Button> <span> </span> <Button onClick={this.deleteHandler.bind(this, cartItem._id)} bsStyle="danger" bsSize="small">DELETE</Button> </ButtonGroup> </Col> </Row> </Panel> ); }, this); return( <Panel bsStyle="primary"> <Panel.Heading> <Panel.Title componentClass="h3">Cart</Panel.Title> </Panel.Heading> <Panel.Body > {cartItemsList} </Panel.Body> <Panel.Footer> <Row> <Col xs={6}> <h6>Total amount:{this.props.totalAmount} usd.</h6> <Button onClick={this.handleOpenModal.bind(this)} bsStyle="success" bsSize="small">PROCESS TO CHECKOUT</Button> </Col> <Col xs={6}> <Button bsStyle="primary" bsSize="small">CART DITAILS</Button> </Col> </Row> </Panel.Footer> <Modal show={this.state.showModal} onHide={this.handleCloseModal.bind(this)}> <Modal.Header closeButton> <Modal.Title>Thank You!</Modal.Title> </Modal.Header> <Modal.Body> <h6>Your order has beeg saved.</h6> <p>You will recive the confirmation email.</p> </Modal.Body> <Modal.Footer> <Col xs={6}> <h6>Total amount:{this.props.totalAmount} usd.</h6> </Col> <Button onClick={this.handleCloseModal.bind(this)}>Close</Button> </Modal.Footer> </Modal> </Panel> ); } } function mapStateToProps(state){ return{ cart: state.cart.cart, totalAmount: state.cart.totalAmount } } function mapDispatchToProps(dispatch){ return bindActionCreators({ deleteCartItem: deleteCartItem, updateCart: updateCart, getCart: getCart }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Cart);
import caseApi from '@/api/case' import clientApi from '@/api/client' import commonJS from '@/common/common' import candidateForCaseApi from '@/api/candidateForCase' import selectCase from '@/components/main/dialog/selectCase/selectCase.vue' import selectCandidate from '@/components/main/dialog/selectCandidate/selectCandidate.vue' import selectUser from '@/components/main/dialog/selectUser/selectUser.vue' import selectHr from '@/components/main/dialog/selectHr/selectHr.vue' import uploadFileApi from '@/api/uploadFile' import uploadFile from '@/components/main/dialog/uploadFile/uploadFile.vue' import downloadFile from '@/components/main/dialog/downloadFile/downloadFile.vue' import userApi from '@/api/user' export default { components: { 'selectCandidate': selectCandidate, 'selectCase': selectCase, 'uploadFile': uploadFile, 'downloadFile': downloadFile, 'selectUser': selectUser, 'selectHr': selectHr }, data () { return { mode: 'add', // 默认操作模式为新建 form: { id: null, clientId: '', hrId: '', hrChineseName: '', hrEnglishName: '', title: '', level: '', department: '', lineManager: '', subordinates: '', english: '', age: '', experience: '', school: '', status: 'PREPARE', description: '', location: '', salaryScope: '', cwUserName: '', headCount: null, pipeline: '', show4JobType: [], question: '', sourcingMap: '' }, attention: false, rules: { clientId: [{ required: true, message: '客户必填', trigger: 'blur' }], title: [{ required: true, message: '职位名称必填', trigger: 'blur' }, { max: 200, message: '职位名称长度不能大于200个字符', trigger: 'blur' } ], status: [{ required: true, message: '职位状态必填', trigger: 'blur' }], level: [{ max: 50, message: '职级长度不能大于25', trigger: 'blur' }], department: [{ max: 50, message: '部门长度不能大于25', trigger: 'blur' }], lineManager: [{ max: 50, message: '汇报对象长度不能大于25', trigger: 'blur' }], subordinates: [{ max: 50, message: '是否带人长度不能大于25', trigger: 'blur' }], english: [{ max: 50, message: '英语要求长度不能大于25', trigger: 'blur' }], age: [{ max: 50, message: '年龄要求长度不能大于25', trigger: 'blur' }], school: [{ max: 50, message: '学历要求长度不能大于25', trigger: 'blur' }], experience: [{ max: 50, message: '经验要求长度不能大于25', trigger: 'blur' }], location: [{ max: 200, message: '工作地点长度不能大于100', trigger: 'blur' }] }, clients: [], // 职位候选人集合 candidateForCaseList: [], // 候选人列表加载中 candidateTableLoading: false, // 当前选中职位对应候选人 curCandidateForCase: null, // 选择候选人对话框是否显示 selectCandidateDialogShow: false, // 选择hr对话框是否显示 selectHRDialogShow: false, // 选择职位对话框是否显示 selectCaseDialogShow: false, showUploadFileDialog: false, // 上传文件对话框 uploadFileData: null, // 上传文件附加数据 uploadFiles: [], // 上传文件集合 selectCWDialogShow: false, roles: [], jobType: '', jobTypeList: commonJS.jobTypeList } }, methods: { // 设置行样式 setCandidateRowClassName ({ row, index }) { if (row.farthestPhase === 'Successful' || row.farthestPhase === 'Payment' || row.farthestPhase === 'Invoice' || row.farthestPhase === 'On Board' || row.farthestPhase === 'Offer Signed') { return 'rowGreen' } else if (row.farthestPhase === 'Offer Signed' || row.farthestPhase === 'Final Interview' || row.farthestPhase === '4th Interview' || row.farthestPhase === '3rd Interview' || row.farthestPhase === '2nd Interview' || row.farthestPhase === '1st Interview' || row.farthestPhase === 'CVO') { return 'rowBlue' } }, // 获取YYYY-MM-dd格式的年月日 formatDate (d) { if (typeof (d) !== 'undefined' && d !== null && d !== '') { return d.substr(0, 10) } return '' }, openSelectCWDialog () { this.selectCWDialogShow = true }, // 显示控制 showControl (key) { if (key === 'deleteRecommend' || key === 'delete') { // 只有管理员才能删除 return commonJS.isAdminInArray(this.roles) } else if (key === 'visibility') { // 管理员和公司管理员可以操作 return commonJS.isAdminInArray(this.roles) || commonJS.isAdminCompanyInArray(this.roles) } // 没有特殊要求的不需要角色 return true }, // 是否关注 isAttention (row) { return row.attention }, // 更新候选人职位关注信息 updateCandidateForCaseAttention (row, attention) { let params = { id: row.id, attention: attention } candidateForCaseApi.updateAttention(params).then(res => { if (res.status !== 200) { this.$message.error({ message: '系统异常,请联系管理员!' }) } else { this.$message({ message: '更新成功!', type: 'success', showClose: true }) // 刷新推荐列表 this.queryCandidateForCaseList() } }) }, // 更新关注列表 updateCaseAttention () { let params = { attention: this.attention, caseId: this.form.id } caseApi.updateCaseAttention(params).then(res => { if (res.status !== 200) { this.$message.error({ message: '系统异常,请联系管理员!' }) } else { this.$message({ message: '更新成功!', type: 'success', showClose: true }) } }) }, // 编辑候选人 editCandidate (index, row) { this.$router.push({ path: '/candidate/candidate', query: { mode: 'modify', candidateId: row.candidateId } }) }, // 删除推荐 deleteRecommend (index, row) { this.$confirm('确认要删除推荐吗?', '确认信息', { distinguishCancelAndClose: true, confirmButtonText: '确定', cancelButtonText: '取消' }) .then(() => { candidateForCaseApi.deleteById(row.id).then(res => { if (res.status !== 200) { this.$message.error({ message: '删除失败,请联系管理员!' }) } else { this.$message({ message: '删除成功!', type: 'success', showClose: true }) this.queryCandidateForCaseList() } }) }) }, // 取消 cancel () { if (typeof (this.$route.query.mode) !== 'undefined') { this.mode = this.$route.query.mode if (typeof (this.$route.query.case) !== 'undefined') { this.form = this.$route.query.case } } else { this.form.id = '' this.form.clientId = '' this.form.clientName = '' this.form.hrId = '' this.form.hrChineseName = '' this.form.hrEnglishName = '' this.form.title = '' this.form.level = '' this.form.department = '' this.form.lineManager = '' this.form.subordinates = '' this.form.english = '' this.form.age = '' this.form.experience = '' this.form.school = '' this.form.status = '' this.form.description = '' this.form.salaryScope = '' this.form.location = '' this.form.cwUserName = '' this.form.headCount = null this.form.pipeline = '' this.form.show4JobType = [] this.form.sourcingMap = '' } }, // 保存 save () { this.$refs['form'].validate((valid) => { if (valid) { // 如果校验通过就调用后端接口 caseApi.save(this.form).then( res => { if (res.status === 200) { // 将从服务端获取的id赋值给前端显示 this.form = res.data this.$message({ message: '保存成功!', type: 'success', showClose: true }) } else { this.$message.error('保存失败!') } }) } else { // 如果检查不通过就给出提示 this.$message({ message: '有错误,请检查!', type: 'warning', showClose: true }) } }) }, // 为Case添加候选人 addCandidateForCase () { if (this.form.id == null) { this.$message({ message: '请先保存职位信息!', type: 'warning', showClose: true }) } }, // 职位候选人变化 rowChange (val) { this.curCandidateForCase = val }, // “选择候选人”对话框返回 sureSelectCandidateDialog (val) { // 首先关闭对话框 this.selectCandidateDialogShow = false // 然后变量当前所有候选人id,判断新选中的候选人是否已经在当前职位的候选人列表中 let include = false for (let index in this.candidateForCaseList) { if (this.candidateForCaseList[index].candidateId === val.id) { include = true break } } if (include) { // 如果选中的候选人重复,就给出提示 this.$message({ message: '该候选人已在该职位上!', type: 'warning', showClose: true }) } else { // 添加候选人到职位 let candidate = { 'candidateId': val.id, 'caseId': this.form.id, 'clientId': this.form.clientId, 'title': this.form.title } candidateForCaseApi.save(candidate).then(res => { if (res.status === 200) { // 获取该职位所有候选人信息 candidateForCaseApi.findByCaseId(this.form.id).then(res => { if (res.status === 200) { this.candidateForCaseList = res.data } }) } }) } }, // “选择职位”对话框返回 sureSelectCaseDialog (val) { // 首先关闭对话框 this.selectCaseDialogShow = false // 添加候选人到职位 let o = { 'curCaseId': this.form.id, 'oldCaseId': val.id } // 显示加载中 this.candidateTableLoading = true candidateForCaseApi.copyFromOldCase(o).then(res => { if (res.status === 200) { // 获取该职位所有候选人信息 candidateForCaseApi.findByCaseId(this.form.id).then(res => { if (res.status === 200) { this.candidateForCaseList = res.data this.$message({ message: '候选人列表已更新', type: 'success', showClose: true }) } // 隐藏加载中 this.candidateTableLoading = false }) } }) }, // 打开选择候选人对话框 openSelectCandidateDialog () { if (this.form.id === null) { this.$message({ message: '请先保存职位信息!', type: 'warning', showClose: true }) } else { this.selectCandidateDialogShow = true } }, // 打开选择职位对话框 openSelectCaseDialog () { if (this.form.id === null) { this.$message({ message: '请先保存职位信息!', type: 'warning', showClose: true }) } else { this.selectCaseDialogShow = true } }, // 打开上次文件对话框 openUploadFileDialog () { if (this.form.id == null) { this.$message({ message: '请先保存职位信息!', type: 'warning', showClose: true }) } else { this.uploadFileData = { 'tableId': this.form.id, 'tableName': 'case' } this.showUploadFileDialog = true } }, // 查询上传文件集合 queryUploadFiles () { if (this.form.id !== null) { let params = { 'relativeTableId': this.form.id, 'relativeTableName': 'case' } uploadFileApi.findByRelativeTableIdAndRelativeTableName(params).then(res => { if (res.status === 200) { this.uploadFiles = res.data } }) } }, // 查询推荐候选人列表 queryCandidateForCaseList () { // 获取该职位所有候选人信息 if (this.form.id !== null) { // 显示加载中 this.candidateTableLoading = true candidateForCaseApi.findByCaseId(this.form.id).then(res => { if (res.status === 200) { // 隐藏加载中 this.candidateTableLoading = false this.candidateForCaseList = res.data } }) } }, // 查询其他数据 queryOthers () { // 查询推荐候选人列表 this.queryCandidateForCaseList() }, // 查询职位关注情况 queryCaseAttentionByCaseId () { if (this.form.id !== null) { caseApi.queryCaseAttentionByCaseId(this.form.id).then(res => { if (res.status === 200) { this.attention = res.data } }) } }, // “选择CW”对话框返回 sureSelectCWDialog (val) { // 首先关闭对话框 this.selectCWDialogShow = false this.form.cwUserName = val.username }, // “选择hr”对话框返回 sureSelectHRDialog (val) { // 首先关闭对话框 this.selectHRDialogShow = false this.form.hrId = val.id this.form.hrChineseName = val.chineseName this.form.hrEnglishName = val.englishName }, // 通过id删除职位 deleteById () { this.$confirm('确认要删除职位 ' + this.form.title + ' 吗?', '确认信息', { distinguishCancelAndClose: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => { let params = { 'id': this.form.id } caseApi.deleteById(params).then(res => { if (res.status === 200) { this.$router.push({ path: '/case/caselist' }) } else { this.$message.error('删除失败!') } }) }) } }, created () { // 获取当前用户的角色列表 userApi.findSelf().then(res => { if (res.status === 200) { this.roles = res.data.roles this.jobType = res.data.jobType } }) // 通过入参获取当前操作模式 if (typeof (this.$route.query.mode) !== 'undefined') { // 接收list传入的参数 this.mode = this.$route.query.mode if (typeof (this.$route.query.case) !== 'undefined') { this.form = this.$route.query.case this.queryOthers() this.queryCaseAttentionByCaseId() } else if (typeof (this.$route.query.caseId) !== 'undefined') { let params = { 'id': this.$route.query.caseId } caseApi.queryById(params).then(res => { if (res.status === 200) { this.form = res.data this.queryOthers() this.queryCaseAttentionByCaseId() } }) } } // 获取所有“客户”信息 clientApi.findAllOrderByChineseName().then(res => { if (res.status === 200) { this.clients = res.data } }) // 查询上传文件 this.queryUploadFiles() } }
import React, { Component } from "react" class File extends Component{ constructor(props){ super(props) this.state = { drag: false, } this.fileUpload = React.createRef(); this.dropRef = React.createRef() } handleDrag = (e) => { e.preventDefault() e.stopPropagation() } handleDragIn = (e) => { e.preventDefault() e.stopPropagation() this.dragCounter++ if (e.dataTransfer.items && e.dataTransfer.items.length > 0) { this.setState({drag: true}) } } handleDragOut = (e) => { e.preventDefault() e.stopPropagation() this.dragCounter-- if (this.dragCounter === 0) { this.setState({drag: false}) } } handleDrop = (e) => { e.preventDefault() e.stopPropagation() this.setState({drag: false}) if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { this.props.onChange(e, this.props.keyName, "single", this.props.videoKey ? this.props.videoKey : "file",this.props.m) e.dataTransfer.clearData() this.dragCounter = 0 } } componentDidMount() { let div = this.dropRef.current if(div){ div.addEventListener('dragenter', this.handleDragIn) div.addEventListener('dragleave', this.handleDragOut) div.addEventListener('dragover', this.handleDrag) div.addEventListener('drop', this.handleDrop) } } componentWillUnmount() { let div = this.dropRef.current if(div){ div.removeEventListener('dragenter', this.handleDragIn) div.removeEventListener('dragleave', this.handleDragOut) div.removeEventListener('dragover', this.handleDrag) div.removeEventListener('drop', this.handleDrop) } } clickUploadImage = () => { this.fileUpload.current.click(); } render(){ return ( <div className="filesinput" ref={this.dropRef}> <div className="file_input uploadicn" style={{"outline":this.state.drag ? "2px dashed white" : ""}} onClick={this.clickUploadImage}><i className="fa fa-upload" aria-hidden="true"></i>{this.props.defaultText ? this.props.defaultText : this.props.t("Drag & Drop Image Here")}</div> <input {...this.props.data} style={{ "display":"none" }} className="form-control" ref={this.fileUpload} type="file" key={this.props.keyName} //accept={this.props.type+"/*"} id={this.props.keyName} name={this.props.name} onChange={(e) => this.props.onChange(e, this.props.target,"single",this.props.type,this.props.m)} /> </div> ) } } export default File
const { ObjectType } = require('database').models; const updateObjectTypes = require('utilities/operations/objectType/updateTopWobjects'); /** * Make any changes you need to make to the database here */ exports.up = async function up(done) { await updateObjectTypes(true); done(); }; /** * Make any changes that UNDO the up function side effects here (if possible) */ exports.down = async function down(done) { await ObjectType.update({}, { $unset: { top_wobjects: '' } }); console.log('Deleted field "top_wobjects" from all of ObjectTypes!'); done(); };
import ruleParser from '../utils/ruleParser' describe('ruleParser tests', () => { it('Parses correct file format', () => { try { ruleParser('testData.txt') expect(true).toBe(true) } catch { expect(true).toBe(false) } }) it('Doesn`t parse an incorrect file', () => { try { ruleParser('testData') expect(true).toBe(false) } catch { expect(true).toBe(true) } }) it('Returns correct objects', async () => { const { dict, ruleSet, date } = await ruleParser('testData.txt').then((res) => res) expect(Object.keys(dict).length).toBe(2) expect(ruleSet.size).toBe(13) expect(date).toEqual('April 22, 2021') }) it('Returns correct indexes', async () => { const { dict } = await ruleParser('testData.txt').then((res) => res) const correct = (dict['1'].topic === 'Index A' && dict['2'].topic === 'Index B') expect(correct).toBe(true) }) it('Returns correct sections', async () => { const { dict } = await ruleParser('testData.txt').then((res) => res) const correct = (dict['1'].sections['100'].topic === 'Section of A' && dict['1'].sections['101'].topic === 'Another section of A') expect(correct).toBe(true) }) it('Returns correct rules for a section', async () => { const { dict } = await ruleParser('testData.txt').then((res) => res) const { topic } = dict['1'].sections['100'].rules['100.1'] expect(topic).toEqual('Rule of section A. See rule 101 and also see rule 200.1b.') }) it('Returns correct notion for a rule', async () => { const { dict } = await ruleParser('testData.txt').then((res) => res) const { topic } = dict['1'].sections['100'].rules['100.1'].subrules['100.1a'] expect(topic).toEqual('Notion of Rule 100.1') }) })
var Objects = []; var canvas = document.getElementById("main"); canvas.width = 700; canvas.height = 500; canvas.style.width = canvas.width + "px"; canvas.style.height = canvas.height + "px"; var ctx = canvas.getContext('2d'); Game = {}; Game.paused = false; Game.fps = 60; Game.Gravity = 10; Art = {}; KeysDown = { a: false, d: false, s: false, y: false }; var EscapeHit = false; $(document).keydown(function(key){ if(key.keyCode == 32){ KeysDown.s = true; }; if(key.keyCode == 65){ KeysDown.a = true; }; if(key.keyCode == 68){ KeysDown.d = true; }; if(key.keyCode == 89){ KeysDown.y = true; }; if(key.keyCode == 27 && !EscapeHit){ EscapeHit = true; if(Game.paused){ $("title").text("-:TEST:-"); Game.paused = false; } else{ $("title").text("-:PAUSED:-"); Game.paused = true; ctx.rect((canvas.width/2)-150,(canvas.height/2)-50,300,100); ctx.fillStyle = "Black"; ctx.fill(); ctx.stroke(); ctx.font = "20px Georgia"; ctx.fillStyle = "White"; ctx.fillText("GAME PAUSED",(canvas.width/2)-75,(canvas.height/2)+12.5); } }; }); $(document).keyup(function(key){ if(key.keyCode == 32){ KeysDown.s = false; }; if(key.keyCode == 65){ KeysDown.a = false; }; if(key.keyCode == 68){ KeysDown.d = false; }; if(key.keyCode == 89){ KeysDown.y = false; }; if(key.keyCode == 27){ EscapeHit = false; } }); Art.Circle = function(x,y,r,canCollide){ this.x = x; this.y = y; this.r = r; this.canCollide = canCollide; this.Type = "Circle" this.yv = null; if(!this == Player){ Objects.push(this); } }; Art.DrawCircle = function(c){ ctx.beginPath(); ctx.arc(c.x,c.y,c.r,0,Math.PI*2); }; Art.Rect = function(x,y,w,h,canCollide){ this.x = x; this.y = y; this.w = w; this.h = h; this.canCollide = canCollide; this.Type = "Rect"; Objects.push(this); } Art.DrawRect = function(c){ ctx.rect(c.x,c.y,c.w,c.h); } Art.DrawObjects = function(){ for(var i = 0; i < Objects.length; i++){ if(Objects[i].Type == "Rect") Art.DrawRect(Objects[i]); if(Objects[i].Type == "Cirlce") Art.DrawCircle(Objects[i]); } } var Player = new Art.Circle(100,0,40,true); Player.Jumping = false; Player.Standing = false; Player.MaxJump = 25; Player.Jump = 0; Player.Morphing = false; Player.Change = 0; Player.minSize = 5; //Both should be divisible by 5 Player.maxSize = 120; Player.requestJump = function(){ if (Player.Standing){ Player.Standing = false; Player.Jump = Player.MaxJump; Player.Jumping = true; }; }; Player.requestMorph = function(){ if(!Player.Morphing){ Player.Morphing = true; if(Player.r == Player.minSize){ Player.Change = 5; }else{ Player.Change = -5; } } } //CreateObjects var Platform = new Art.Rect(0,(canvas.height-25), 800, 50,true); Platform.min = 0; Platform.max = Platform.w; Platform.Speed = -1; var P1 = new Art.Rect(200,Platform.y-50,150,50,true); for(var i = 100;i < 475; i += 25){ var P2 = new Art.Rect(i,i,25,25,true); }; //EndCreation Player.isStanding = function(){ for(var i = 0; i < Objects.length; i++){ if(Objects[i].canCollide){ if((Player.y+Player.r)>=(Objects[i].y) && !((Player.y)>(Objects[i].y)) && (Player.x+Player.r > (Objects[i].x)) && (Player.x-Player.r < (Objects[i].x + Objects[i].w)) ){ Player.y = Objects[i].y-Player.r return true; } } } } Player.isOnLeft = function(){ for(var i = 0; i < Objects.length; i++){ if(Objects[i].canCollide){ if((Player.x + Player.r) >= (Objects[i].x) && (Player.x - Player.r) <= (Objects[i].x) && !((Player.y - Player.r) >= (Objects[i].y + Objects[i].h)) && !((Player.y + Player.r) <= (Objects[i].y))){ Player.x = Objects[i].x - Player.r return true; } } } } Player.isOnRight = function(){ for(var i = 0; i < Objects.length; i++){ if(Objects[i].canCollide){ if((Player.x - Player.r <= (Objects[i].x + Objects[i].w)) && !(Player.x + Player.r < Objects[i].x) && !((Player.y - Player.r) >= (Objects[i].y + Objects[i].h)) && !((Player.y + Player.r) <= (Objects[i].y))){ Player.x = Objects[i].x + Objects[i].w + Player.r; return true; } } } } Player.isUnder = function(){ for(var i = 0; i < Objects.length; i++){ if(Objects[i].canCollide){ if((Player.y-Player.r)<=(Objects[i].y + Objects[i].h) && !((Player.y)<(Objects[i].y)) && (Player.x+Player.r > (Objects[i].x)) && (Player.x-Player.r < (Objects[i].x + Objects[i].w)) ){ return true; } } } } Game.main = function(){ if(!Game.paused){ ctx.clearRect(0, 0, canvas.width, canvas.height); if(Platform.w == Platform.min){ Platform.Speed = 1; } if(Platform.w == Platform.max){ Platform.Speed = -1; } Platform.w += Platform.Speed; if(Player.Jumping){ if(!Player.isUnder()){ Player.y += -Player.Jump; Player.Jump = Player.Jump - 1; if(Player.Jump == 0){ Player.Jumping = false; } }else{ Player.Jumping = false; } }else{ if(Player.isStanding()){ Player.yv = 0; Player.Standing = true; } else{ Player.yv = Game.Gravity; Player.Standing = false; } }; if(Player.Morphing){ if(Player.Change == 5){ Player.r += Player.Change if(Player.r == Player.maxSize){ Player.Morphing = false; } }else{ Player.r += Player.Change if(Player.r == Player.minSize){ Player.Morphing = false; } } } if(KeysDown.a && !Player.isOnRight()){ Player.x += -6; } if(KeysDown.d && !Player.isOnLeft()){ Player.x += 6; } if(KeysDown.y){ Player.requestMorph(); } if(KeysDown.s){ Player.requestJump(); } Player.y += Player.yv; Art.DrawCircle(Player); Art.DrawObjects(); ctx.stroke(); } }; Game._intervalId = setInterval(Game.main, (1000/Game.fps))
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { buildStepDocuments, jsSearchIndex } from '@cucumber/suggest' import { ExpressionFactory, ParameterTypeRegistry } from '@cucumber/cucumber-expressions' import { configure } from '../dist/src/index' (function () { // create div to avoid needing a HtmlWebpackPlugin template const div = document.createElement('div'); div.id = 'root'; // @ts-ignore div.style = 'width:800px; height:600px; border:1px solid #ccc;'; document.body.appendChild(div); })(); // Build some sample step texts and cucumber expressions. These would typically come from a stream // of Cucumber Messages. const ef = new ExpressionFactory(new ParameterTypeRegistry()) const expressions = [ ef.createExpression('I have {int} cukes in my belly'), ef.createExpression('there are {int} blind mice') ]; const docs = buildStepDocuments( [ 'I have 42 cukes in my belly', 'I have 96 cukes in my belly', 'there are 38 blind mice', ], expressions ) const index = jsSearchIndex(docs) const editor = monaco.editor.create(document.getElementById('root'), { value: `@foo Feature: Hello Scenario: Hi Given I have 58 cukes in my belly And this is an undefined step | some | poorly | | formatted | table | `, language: 'gherkin', theme: 'vs-dark', // semantic tokens provider is disabled by default 'semanticHighlighting.enabled': true }) configure(monaco, editor, index, expressions)
/** * * @type {DataTable|Component} */ var dtc = Component.factory('DataTable', 'dtc'); var data = randomData(); dtc.option({ source: { url: '/data.json', dataSrc: 'items' }, useSelectCheckbox: true }); function randomData() { var result = [], ids = _.range(1, _.random(30, 50)); _.each(ids, function (id) { result.push({ id: id, name: faker.name.findName(), phone: faker.phone.phoneNumberFormat(), email: faker.internet.email(), address: faker.address.streetAddress(), state: faker.address.state() }); }); return result; } App.onInit(function () { dtc.addFields([ {title: 'ID', name: 'value', data: 'value'}, {title: 'Name', name: 'text', data: 'text'} // {title: 'Email', name: 'email', data: 'email'}, // {title: 'Phone', name: 'phone', data: 'phone'}, // {title: 'State', name: 'state', data: 'state'}, // {title: 'Address', name: 'address', data: 'address'} ]); dtc.render('#dtc'); });
import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import {Link} from "react-router-dom" function NavBar(){ return( <div> <nav className="navbar navbar-dark bg-dark"> <Link class="badge badge-dark" to="/">Home</Link> <Link class="badge badge-dark" to="/dice">Dice Roll Simulator</Link> <Link class="badge badge-dark" to="/scenario">Scenario Generator</Link> <Link class="badge badge-dark" to="/roster">Roster Builder</Link> </nav> </div> ); } export default NavBar;
const playlistModel = require("../../models/playlists") const playlistVideoModel = require("../../models/playlistvideos"), dateTime = require('node-datetime'), fieldErrors = require('../../functions/error'), errorCodes = require("../../functions/statusCodes"), constant = require("../../functions/constant"), globalModel = require("../../models/globalModel"), uniqid = require('uniqid'), socketio = require("../../socket"), { validationResult } = require('express-validator'), commonFunction = require("../../functions/commonFunctions"), videoModel = require("../../models/videos"), userModel = require("../../models/users"), privacyModel = require("../../models/privacy"), notificationModel = require("../../models/notifications"), privacyLevelModel = require("../../models/levelPermissions") exports.delete = async (req, res) => { if (!req.item) { return res.send({ error: fieldErrors.errors([{ msg: constant.general.PERMISSION_ERROR }], true), status: errorCodes.invalid }).end(); } await playlistModel.delete(req.item.playlist_id, req).then(result => { if (result) { commonFunction.deleteImage(req, res, "", "playlist", req.item) socketio.getIO().emit('playlistDeleted', { "playlist_id": req.item.playlist_id, "message": constant.playlist.DELETED, }); } }) res.send({}) } exports.view = async(req,res) => { let LimitNum = 21; let page = "" if (req.body.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * LimitNum let playlist = {} playlist = { pagging: false, items: [] } await videoModel.getVideos(req,{playlist_id:req.body.playlist_id,limit:LimitNum,offset:offset}).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } res.send( { 'pagging': pagging, items: result }) } }) res.send(playlist) } exports.browse = async (req, res) => { const queryString = req.query const limit = 17 let page = 1 if (req.body.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } req.query.search = {} let offset = (page - 1) * (limit - 1) const data = { limit: limit, offset: offset } data['type'] = queryString.type if (queryString.q && !queryString.tag) { data['title'] = queryString.q } if (queryString.sort == "latest") { data['orderby'] = "playlists.playlist_id desc" } else if (queryString.sort == "favourite" && req.appSettings['playlist_favourite'] == 1) { data['orderby'] = "playlists.favourite_count desc" } else if (queryString.sort == "view") { data['orderby'] = "playlists.view_count desc" } else if (queryString.sort == "like" && req.appSettings['playlist_like'] == "1") { data['orderby'] = "playlists.like_count desc" } else if (queryString.sort == "dislike" && req.appSettings['playlist_dislike'] == "1") { data['orderby'] = "playlists.dislike_count desc" } else if (queryString.sort == "rated" && req.appSettings['playlist_rating'] == "1") { data['orderby'] = "playlists.rating desc" } else if (queryString.sort == "commented" && req.appSettings['playlist_comment'] == "1") { data['orderby'] = "playlists.comment_count desc" } if (queryString.type == "featured" && req.appSettings['playlist_featured'] == 1) { data['is_featured'] = 1 } else if (queryString.type == "sponsored" && req.appSettings['playlist_sponsored'] == 1) { data['is_sponsored'] = 1 } else if (queryString.type == "hot" && req.appSettings['playlist_hot'] == 1) { data['is_hot'] = 1 } //get all playlists await playlistModel.getPlaylists(req, data).then(result => { if (result) { let pagging = false let items = result if (result.length > limit - 1) { items = result.splice(0, limit - 1); pagging = true } res.send({ playlists: items, pagging: pagging }) } }).catch(err => { res.send({}) }) } exports.getPlaylist = async (req, res, next) => { const video_id = req.body.video_id let send = false //owner plans await privacyLevelModel.findBykey(req,"member",'allow_create_subscriptionplans',req.user.level_id).then(result => { req.query.planCreate = result == 1 ? 1 : 0 }) if(req.query.planCreate == 1){ //get user plans await userModel.getPlans(req, { owner_id: req.user.user_id }).then(result => { if (result) { req.query.plans = result } }) } await playlistModel.getPlaylist(video_id, req, res).then(result => { if (result) { send = true return res.send({ playlists: result,plans:req.query.plans ? req.query.plans : [] }) } }) if (!send) res.send({ playlists: [],plans:req.query.plans ? req.query.plans : [] }) } exports.create = async (req, res) => { if (req.quotaLimitError) { return res.send({ error: fieldErrors.errors([{ msg: constant.playlist.QUOTAREACHED }], true), status: errorCodes.invalid }).end(); } if (req.imageError) { return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end(); } const video_id = req.body.video_id const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } // all set now let insertObject = {} let playlistId = req.body.playlist_id let playlistObject = {} if (parseInt(playlistId) > 0) { //uploaded await globalModel.custom(req, "SELECT * FROM playlists WHERE playlist_id = ?", playlistId).then(async result => { if (result) { playlistObject = JSON.parse(JSON.stringify(result))[0]; await privacyModel.permission(req, 'playlist', 'edit', playlistObject).then(result => { if(!result){ playlistId = null playlistObject = null } }).catch(err => { playlistId = null }) } }).catch(err => { playlistId = null }) } else { insertObject["owner_id"] = req.user.user_id; insertObject["custom_url"] = uniqid.process('b') } insertObject["title"] = req.body.title if(req.body.privacy) insertObject["view_privacy"] = req.body.privacy ? req.body.privacy : "" insertObject["description"] = req.body.description ? req.body.description : "" insertObject["adult"] = req.body.adult ? req.body.adult : 0 insertObject["search"] = req.body.search ? req.body.search : 1 insertObject["private"] = req.body.private ? req.body.private : '0' if(typeof req.body.comments != "undefined"){ insertObject['autoapprove_comments'] = parseInt(req.body.comments) } if (req.fileName) { insertObject['image'] = "/upload/images/playlists/" + req.fileName; if(Object.keys(playlistObject).length && playlistObject.image) commonFunction.deleteImage(req, res, playlistObject.image, 'playlist/image'); }else if(!req.body.playlistImage){ insertObject['image'] = ""; if(Object.keys(playlistObject).length && playlistObject.image) commonFunction.deleteImage(req, res, playlistObject.image, 'playlist/image'); } var dt = dateTime.create(); var formatted = dt.format('Y-m-d H:M:S'); if (!playlistId) { insertObject["is_sponsored"] = req.levelPermissions['playlist.sponsored'] == "1" ? 1 : 0 insertObject["is_featured"] = req.levelPermissions['playlist.featured'] == "1" ? 1 : 0 insertObject["is_hot"] = req.levelPermissions['playlist.hot'] == "1" ? 1 : 0 if (req.levelPermissions["playlist.auto_approve"] && req.levelPermissions["playlist.auto_approve"] == "1") insertObject["approve"] = 1 else insertObject["approve"] = 0 insertObject["creation_date"] = formatted } insertObject["modified_date"] = formatted if (playlistId) { if (parseInt(video_id) > 0) { let insertVideoObject = {} insertVideoObject.video_id = video_id insertVideoObject.creation_date = formatted insertVideoObject.playlist_id = playlistId playlistVideoModel.insert(insertVideoObject, req, res).then(result => { //update video_count globalModel.custom(req, "UPDATE playlists SET total_videos = total_videos + 1 WHERE playlist_id = " + playlistId).then(result => { }).catch(err => { }) }).catch(err => { }) return res.send({ playlistId: playlistId, message: constant.playlist.VIDEOSUCCESS, custom_url: playlistObject['custom_url'] }); } //update existing video await globalModel.update(req, insertObject, "playlists", 'playlist_id', playlistId).then(async result => { res.send({ playlistId: playlistId, message: constant.playlist.EDIT, custom_url: playlistObject.custom_url }); }).catch(err => { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); }) } else { //create new playlist await globalModel.create(req, insertObject, "playlists").then(async result => { if (result) { if (parseInt(video_id) > 0) { let insertVideoObject = {} insertVideoObject.video_id = video_id insertVideoObject.creation_date = formatted insertVideoObject.playlist_id = result.insertId playlistVideoModel.insert(insertVideoObject, req, res).then(result1 => { globalModel.custom(req, "UPDATE playlists SET total_videos = total_videos + 1 WHERE playlist_id = " + result.insertId).then(result => { }).catch(err => { }) }).catch(err => { }) } let dataNotification = {} dataNotification["type"] = "playlists_create" dataNotification["owner_id"] = req.user.user_id dataNotification["object_type"] = "playlists" dataNotification["object_id"] = result.insertId notificationModel.sendPoints(req,dataNotification,req.user.level_id); notificationModel.insertFollowNotifications(req,{subject_type:"users",subject_id:req.user.user_id,object_type:"playlists",object_id:result.insertId,type:"members_followed"}).then(result => { }).catch(err => { }) res.send({ playlistId: result.insertId, message: constant.playlist.SUCCESS, custom_url: insertObject['custom_url'] }); } else { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); } }).catch(err => { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); }) } }
'use strict'; function authService($rootScope, $http, $q, $localStorage, Constants) { var serviceBase = Constants.AuthenticationService; var authServiceFactory = {}; var _authentication = { isAuth: false, userName: "", firstName: "", lastName: "", token: "" }; var _saveRegistration = function (registration) { _logOut(); return $http.post(serviceBase + 'api/account/register', registration).then(function (response) { return response; }); }; var _isAuthenticated = function() { if($localStorage.authorizationData != null && $localStorage.authorizationData.isAuth) { return true; } return false; } var _login = function (loginData) { var data = "grant_type=password&username=" + loginData.userNameOrEmail + "&password=" + loginData.password; var deferred = $q.defer(); $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) { _authentication = { token: response.access_token, userName: loginData.userNameOrEmail, firstName: response.firstName, lastName: response.lastName, isAuth: true }; $localStorage.authorizationData = _authentication; $rootScope.$broadcast('authorized', {user: _authentication}); deferred.resolve(response); }).error(function (err, status) { _logOut(); deferred.reject(err); }); return deferred.promise; }; var _logOut = function () { //$localStorage.$remove('authorizationData'); $localStorage.authorizationData = ''; _authentication = {}; $rootScope.$broadcast('unauthorized', { user: _authentication }); }; var _checkAuthenticated = function () { $http.get(Constants.WebApi.Accounts.IsAuthenticated).then(function (response) { return true; }); return false; } var _fillAuthData = function () { var authData = $localStorage.authorizationData; if (authData) { _authentication.isAuth = true; _authentication.userName = authData.userName; } } authServiceFactory.saveRegistration = _saveRegistration; authServiceFactory.login = _login; authServiceFactory.logOut = _logOut; authServiceFactory.fillAuthData = _fillAuthData; authServiceFactory.authentication = _authentication; authServiceFactory.isAuthenticated = _isAuthenticated; authServiceFactory.checkAuthenticated = _checkAuthenticated; return authServiceFactory; }
class Pong { constructor(mode) { this._mode = mode; this._gameObjects = []; this._scoreP1 = this._scoreP2 = 0; this._speedMultiplier = 1; this._speedIncrement = 0.07; } preload() { this._soundWall = loadSound('assets/wall.wav'); this._soundPaddle = loadSound('assets/paddle.wav'); this._soundScore = loadSound('assets/score.wav'); } setup() { createCanvas(window.innerWidth, window.innerHeight); frameRate(60); this._paddleP1 = new Paddle(0,0); this._paddleP2 = new Paddle(0,0); this._ball = new Ball(0,0); this._paddleP1.initialPosition = { x: 30, y: window.innerHeight/2 - this._paddleP1.height/2 } this._paddleP2.initialPosition = { x: window.innerWidth - 30 - this._paddleP2.width, y: window.innerHeight/2 - this._paddleP2.height/2 } this._ball.initialPosition = { x: window.innerWidth/2 - this._ball.radius, y: window.innerHeight/2 - this._ball.radius } this._gameObjects.push(this._paddleP1, this._paddleP2, this._ball); this._paddleP1.controller = new PlayerController(this._paddleP1, 'P1'); if (this._mode === 'vs') { this._paddleP2.controller = new PlayerController(this._paddleP2, 'P2'); } else { this._paddleP2.controller = new ComputerController(this._paddleP2, this._ball); } } draw() { this._gameObjects.forEach(function(gameObject) { gameObject.update(); }); /* Ball collision with P1 and P2 paddles */ if (this._ball.isColliding(this._paddleP1)) { angleMode(DEGREES); let angle = map(this._ball.position.y, this._paddleP1.position.y, this._paddleP1.position.y + this._paddleP1.height, -45, 45); this._speedMultiplier += this._speedIncrement; this._ball.speed = { x: cos(angle), y: sin(angle), multiplier: this._ball.speedMagnitude * this._speedMultiplier } this._soundPaddle.play(); } else if (this._ball.isColliding(this._paddleP2)) { angleMode(DEGREES); let angle = map(this._ball.position.y, this._paddleP2.position.y, this._paddleP2.position.y + this._paddleP2.height, 225, 135); this._speedMultiplier += this._speedIncrement; this._ball.speed = { x: cos(angle), y: sin(angle), multiplier: this._ball.speedMagnitude * this._speedMultiplier } this._soundPaddle.play(); } /* Ball collision with top and bottom window borders */ if (this._ball.position.y < 0 || this._ball.position.y + this._ball.diameter > window.innerHeight) { this._ball.invertSpeedY(); this._soundWall.play(); } /* Ball collision with left border */ if (this._ball.position.x + this._ball.diameter < 0) { this._scoreP1++; this._speedMultiplier = 1; this._ball.resetPosition(); this._soundScore.play(); } /* Ball collision with right border */ if (this._ball.position.x > window.innerWidth) { this._scoreP2++; this._speedMultiplier = 1; this._ball.resetPosition(); this._soundScore.play(); } clear(); this._gameObjects.forEach(function(gameObject) { gameObject.draw(); }); } }
import React, { Component } from 'react'; import '../style/1.css'; import{ Link } from "react-router-dom"; import {connect} from "unistore/react"; import {actions} from './store'; import {withRouter} from "react-router-dom"; import {Redirect} from "react-router-dom"; import axios from 'axios'; class ProductDetail extends Component{ constructor (props){ super(props); this.state = { search:"", product_id:"", qty:0 } } handleClick=(e)=>{ e.preventDefault(); console.log("event",e.target.value) this.props.handleClick(e.target.value); this.props.postCart(); } render() { return ( <div> <div className="container-fluid"> <div className="row justify-content-Start"> <h2 className="margin20px"></h2> </div> </div> <div className="container-fluid justify-content-center"> <div className="row justify-content-center"> <div className="col-md-6 col-12 borderproduct marginauto detailprod textcenter margin20"> <a href="#"><img src={this.props.urlimage} className="imgproduct" alt=""/></a> <table className="marginauto"> <tr> <td><span>Name</span></td> <td><span>:</span></td> <td><a href="#"><span>{this.props.name}</span></a></td> </tr> <tr> <td><span>Vendor</span></td> <td><span>:</span></td> <td><span>{this.props.vendor}</span></td> </tr> <tr> <td><span>Status</span></td> <td><span>:</span></td> <td><span>{this.props.status}</span></td> </tr> <tr> <td><span>Price</span></td> <td><span>:</span></td> <td><span>{this.props.price}</span></td> </tr> <tr> <td><span>seller</span></td> <td><span>:</span></td> <td><span>{this.props.seller}</span></td> </tr> <tr> <td><span>Processor</span></td> <td><span>:</span></td> <td><span>{this.props.processor}</span></td> </tr> <tr> <td><span>RAM</span></td> <td><span>:</span></td> <td><span>{this.props.ram}</span></td> </tr> <tr> <td><span>Memory</span></td> <td><span>:</span></td> <td><span>{this.props.memory}</span></td> </tr> <tr> <td><span>Camera</span></td> <td><span>:</span></td> <td><span>{this.props.camera}</span></td> </tr> <tr> <td><span>Other Description</span></td> <td><span>:</span></td> <td><span>{this.props.other_description}</span></td> </tr> <tr> <td><span>Stock</span></td> <td><span>:</span></td> <td><span>{this.props.stock}</span></td> </tr> </table> </div> </div> <span>Input Qty </span><br/><br/> <input type="number" onChange={e => this.props.changeInput(e)} name="qtyorder"/><br/><br/> <button className="btn btn-primary pb20" onClick={e => {this.handleClick(e);}} value={this.props.id} style={{backgroundColor:"blue", marginBottom:"30px"}} >Add to Cart</button> </div> </div> ); }} export default connect("productid, token, qtyorder", actions)(withRouter(ProductDetail));
const log = require("metalogger")(); // eslint-disable-line no-unused-vars const _ = require("lodash"); const hutil = require("../hutil"); class SirenPlugin { constructor(message) { if (typeof message !== 'object') { this.doc = JSON.parse(message); } else { this.doc = _.clone(message); } this.newDoc = {}; } translate() { this.preprocess(); this.processProperties(); this.processTopHref(); this.processTopLink(); this.processEntities(); return this.newDoc; } preprocess() { this.doc["h:pvt"] = {}; if (!this.doc["h:pvt"].globalCuries) { if (this.doc["h:head"]) { this.doc["h:pvt"].globalCuries = this.doc["h:head"].curies; } } } processProperties() { const body = this.doc; if (!this.newDoc.properties) this.newDoc.properties = {}; for (const prop in body) { if (body[prop] === null) { this.newDoc.properties[prop] = null; continue; } if (!hutil.skipProps.includes(prop) && (typeof body[prop] !== 'object')) { this.newDoc.properties[prop] = body[prop]; } if (prop === 'h:type') { this.newDoc.class = []; const types = body[prop]; if (!Array.isArray(types)) { throw new Error ("In Hyper messages h:type must be an array"); } for (let type of types) { type = hutil.removePrefixIfCURIE(type, this.doc); this.newDoc.class.push(type); } if (this.newDoc.class.length <1) { delete this.newDoc['class']; } } } if (_.isEqual(this.newDoc.properties, {})) { delete this.newDoc['properties']; } } processTopHref() { const hrefs = (this.doc["h:ref"]) ? this.doc["h:ref"] : {}; if (!this.newDoc.links) this.newDoc.links = []; for (const href in hrefs) { // {"rel": ["self"], "href": "http://api.x.io/orders/42"}, const link = {}; link.rel = [href]; link.href = hrefs[href]; this.newDoc.links.push(link); } } processTopLink() { const hlinks = (this.doc["h:link"]) ? this.doc["h:link"] : []; if (!this.newDoc.actions) this.newDoc.actions = []; for (const hlink of hlinks) { const action = {}; if (hlink["rel"]) { const rel = hlink["rel"][0]; // Siren actions only have one rel. Data loss may occur. action.name = hutil.removePrefixIfCURIE(rel, this.doc); } if (hlink["h:label"]) action.title = hlink["h:label"]; if (hlink["uri"]) action.href = hlink["uri"]; if (hlink["template"]) { if (hlink["template"]["contentType"]) action.type = hlink["template"]["contentType"]; if (hlink["template"]["fields"]) { action.fields = []; for (const fieldname in hlink["template"]["fields"]) { const fieldvalue = hlink["template"]["fields"][fieldname]; const field = {}; field.name = fieldname; field.type = fieldvalue["type"] ? fieldvalue["type"] : "text"; if (fieldvalue["default"]) { field.value = fieldvalue["default"]; } action.fields.push(field); } } } if (hlink["action"]) action.method = hutil.actionToHTTP(hlink["action"]); this.newDoc.actions.push(action); } // No need for empty actions property if (this.newDoc.actions.length <1) { delete this.newDoc['actions']; } } processEntities() { const body = this.doc; for (const prop in body) { if (body[prop] === null) { // not an entity continue; } if (!hutil.skipProps.includes(prop) && (typeof body[prop] === 'object')) { if (!this.newDoc.entities || !Array.isArray(this.newDoc.entities)) { this.newDoc.entities = []; } if (Array.isArray(body[prop])) { for (const obj of body[prop]) { if (this.isEmbeddedLink(obj)) { this.convertEmbeddedLink(obj); this.newDoc.entities.push(obj); } else { const representor = new SirenPlugin(obj); representor.translate(); // Embeded Entities require `rel` property, but we only have // enough info, in Hyper, for `class. So we make rel and class // be the same. Reasonable middleground. representor.newDoc.rel = representor.newDoc.class; this.newDoc.entities.push( representor.newDoc ); } } } else { if (this.isEmbeddedLink(body[prop])) { this.convertEmbeddedLink(body[prop]); this.newDoc.entities.push(body[prop]); } else { const representor = new SirenPlugin(body[prop]); representor.translate(); // Making rel = class, for the same reasons as above. representor.newDoc.rel = representor.newDoc.class; this.newDoc.entities.push( representor.newDoc ); } } } } } /** * Siren has notion of a "regular" sub-entity and a sub-entity that is just an * embedded link. The latter gets formatted very differently, unfortunately, * so it needs to be processed separately. This method checks whether * a Hyper object should be treated as an embedded link. * * @param obj is modified by reference */ isEmbeddedLink(obj) { if (!obj) return false; if (typeof obj !== 'object' && Array.isArray(obj) ) return false; if ((!obj["h:link"] && !obj["h:ref"]) || !obj["h:type"]) return false; const allowedProps = ["h:type", "h:link", "h:ref", "h:label", "name"]; const keys = _.keys(obj); for (const key of keys ) { if (!allowedProps.includes(key)) { return false; } } if (obj["h:ref"]) { if (_.keys(obj["h:ref"]).length !== 1) return false; } if (obj["h:link"]) { if (obj["h:link"].length !== 1) return false; } return true; /* * EXAMPLEs: * { * "h:type": ["items", "collection"], * "h:ref": { * "http://x.io/rels/order-items": "http://api.x.io/orders/42/items" * } * } * * { * "h:type": ["items", "collection"], * "h:link": [{ * "rel" : ["http://x.io/rels/order-items"], * "uri" : "http://api.x.io/orders/42/items" * }] * } */ } /** * Siren has notion of a "regular" sub-entity and a sub-entity that is just an * embedded link. The latter gets formatted very differently, unfortunately, * so it needs to be processed separately. This method modifies the object. * * @param obj is modified by reference */ convertEmbeddedLink(obj) { obj.class = obj["h:type"]; delete obj["h:type"]; if (obj["h:ref"]) { for (const prop in obj["h:ref"]) { obj.rel = [prop]; obj.href = obj["h:ref"][prop]; } } delete obj["h:ref"]; if (obj["h:link"]) { const link = obj["h:link"][0]; obj.rel = link.rel; obj.href = link.uri; if (link.label) { obj.title = link.label; } } delete obj["h:link"]; /* "class": ["items", "collection"], "rel": ["http://x.io/rels/order-items"], "href": "http://api.x.io/orders/42/items" */ } } module.exports = (doc) => { const representor = new SirenPlugin(doc); return representor; };
var mongoose = require('mongoose') var Message = mongoose.model('Message') var Comment = mongoose.model('Comment') module.exports = { show: function(req, res) { Message.find({}, function(err, data) { res.json({posts: data}) }) }, create: function(req, res) { var message = new Message(req.body) message.save(function(err) { (err) ? console.log(err) : res.redirect('/messages') }) } }
/* Copyright (c) 2010 Mike Desjardins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ Components.utils.import("resource://app/chrome/content/js/global.js"); function toggleFollow(myUsername,myPassword,hisUserId) { var check = document.getElementById('check-' + myUsername); if (check.checked) { follow(myUsername,myPassword,hisUserId); } else { unfollow(myUsername,myPassword,hisUserId); } } function unfollow(myUsername,myPassword,hisScreenName) { jsdump(myUsername + ' is unfollowing ' + hisUserId); var throb = document.getElementById('throb-' + myUsername); throb.style.display='inline'; var check = document.getElementById('check-' + myUsername); check.style.display='none'; var am = new AccountManager(); account = am.getAccount(myUsername,Ctx.service); Social.service(Ctx.service).unfollow({ "username": account.username, "password": account.password, "token": account.token, "tokenSecret": account.tokenSecret, "screenName": hisScreenName, "onSuccess": function(result) { friendshipCallback(result,myUsername); }, "onError": function(status) { jsdump("Error w/ unfollow, HTTP Status: " + status); var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); prompts.alert(window, "Sorry.", "There was an error processing your unfollow request (Error Code" + status + ")."); var check = document.getElementById('check-' + myUsername); check.checked=true; check.style.display='inline'; document.getElementById('throb-' + myUsername).style.display='none'; } }); } function follow(myUsername,myPassword,hisUserId) { jsdump(myUsername + ' is following ' + hisUserId); var throb = document.getElementById('throb-' + myUsername); throb.style.display='inline'; var check = document.getElementById('check-' + myUsername); check.style.display='none'; var hisUsername = document.getElementById('hisUsername').value; var am = new AccountManager(); account = am.getAccount(myUsername,Ctx.service); Social.service(Ctx.service).follow({ "username": account.username, "password": account.password, "token": account.token, "tokenSecret": account.tokenSecret, "screenName": hisUserId, "onSuccess": function(result) { friendshipCallback(result,myUsername); }, "onError": function(status) { jsdump('Error w/ follow: HTTP status: ' + status) var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); prompts.alert(window, "Sorry.", "There was an error processing your follow request (Error Code " + status + ")."); check.checked=false; check.style.display='inline'; document.getElementById('throb-' + myUsername).style.display='none'; } }); } function friendshipCallback(transport,myUsername) { var throb = document.getElementById('throb-' + myUsername); throb.style.display='none'; var check = document.getElementById('check-' + myUsername); check.style.display='inline'; }
function solve(arr){ let bestNumber = 0; let counter = 1; let bestSequence = 0; for (let i = 0; i < arr.length - 1; i++) { if (arr[i] === arr[i + 1]) { counter++; }else{ counter = 1; } if (counter > bestSequence) { bestSequence = counter; bestNumber = arr[i]; } } let result = ''; for (let i = 0; i < bestSequence; i++) { result += bestNumber + ' '; } console.log(result); } solve([2, 1, 1, 2, 3, 3, 2, 2, 2, 1]);
import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Route, Switch, Redirect, useParams, useRouteMatch } from 'react-router-dom'; import 'chartjs-plugin-annotation'; import { isEmpty } from 'underscore'; //css import 'assets/css/device-view.css'; // others import { DeviceToolBar, DeviceToolBarContainer } from './DeviceToolBar'; import DeviceEdit from './DeviceEdit'; import DeviceLogs from './DeviceLogs'; import DevicePhotos from './DevicePhotos'; import DeviceOverview from './DeviceOverview/DeviceOverview'; import { useInitScrollTop } from 'utils/customHooks'; import { withPermission } from '../../../containers/PageAccess'; import { getOrgDevices, updateDeviceDetails } from '../../../../redux/DeviceOverview/OverviewSlice'; const activeNetwork = JSON.parse(localStorage.getItem('activeNetwork')); const DeviceView = () => { useInitScrollTop(); const dispatch = useDispatch(); const match = useRouteMatch(); const params = useParams(); const devices = useSelector((state) => state.deviceOverviewData.devices); let deviceData = {}; const selectedDevice = devices.filter((device) => device.name === params.deviceName); selectedDevice.forEach((device) => { deviceData = { ...device }; }); useEffect(() => { if (isEmpty(devices)) { dispatch(getOrgDevices(activeNetwork.net_name)); dispatch(updateDeviceDetails(deviceData)); } }, []); return ( <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap' }}> <DeviceToolBar deviceName={deviceData.name} /> <DeviceToolBarContainer> <Switch> <Route exact path={`${match.url}/overview`} component={() => <DeviceOverview deviceData={deviceData} />} /> <Route exact path={`${match.url}/edit`} component={() => <DeviceEdit deviceData={deviceData} />} /> <Route exact path={`${match.url}/maintenance-logs`} component={() => ( <DeviceLogs deviceName={deviceData.name} deviceLocation={deviceData.locationID} /> )} /> <Route exact path={`${match.url}/photos`} component={() => <DevicePhotos deviceData={deviceData} />} /> <Redirect to={`${match.url}/overview`} /> </Switch> </DeviceToolBarContainer> </div> ); }; export default withPermission(DeviceView, 'CREATE_UPDATE_AND_DELETE_NETWORK_DEVICES');
fabrikAdminForm = new Class({ Extends: PluginManager, initialize:function(plugins, lang){ this.parent(plugins, lang); this.opts.actions = [{'value':'front','label':Joomla.JText._('COM_FABRIK_FRONT_END')},{'value':'back','label':Joomla.JText._('COM_FABRIK_BACK_END')},{'value':'both','label':Joomla.JText._('COM_FABRIK_BOTH')}]; this.opts.when = [{'value':'new','label':Joomla.JText._('COM_FABRIK_NEW')}, {'value':'edit','label':Joomla.JText._('COM_FABRIK_EDIT')},{'value':'both','label':Joomla.JText._('COM_FABRIK_BOTH')}]; this.opts['type'] = 'form'; }, getPluginTop:function(plugin, loc, when){ var s = this._makeSel('inputbox events', 'jform[plugin_events][]', this.opts.when, when); return new Element('tr').adopt( new Element('td').adopt([ new Element('input', {'value':Joomla.JText._('COM_FABRIK_SELECT_DO'), 'size':1,'readonly':true, 'class':'readonly'}), this._makeSel('inputbox elementtype', 'jform[plugin][]', this.plugins, plugin), new Element('input', {'value':Joomla.JText._('COM_FABRIK_IN'), 'size':1,'readonly':true, 'class':'readonly'}), this._makeSel('inputbox elementtype', 'jform[plugin_locations][]', this.opts.actions, loc), new Element('input', {'value':Joomla.JText._('COM_FABRIK_ON'), 'size':1,'readonly':true, 'class':'readonly'}), s ]) ); } });
import React from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import firebase from "firebase/app"; import "firebase/firestore"; class Users extends React.Component { constructor(props) { super(props); this.state = { users: [] }; this.followButtonClicked = async uid => { const { myId } = this.props; const db = firebase.firestore(); const docSnapshot = await db .collection("users") .doc(myId) .get(); if (docSnapshot.exists) { await db .collection("users") .doc(myId) .update({ followee: firebase.firestore.FieldValue.arrayUnion(uid) }); await db .collection("users") .doc(uid) .update({ follower: firebase.firestore.FieldValue.arrayUnion(myId) }); } else { await db .collection("users") .doc(myId) .set({ followee: [uid] }); } }; this.unfollowButtonClicked = async uid => { const { myId } = this.props; const db = firebase.firestore(); const docSnapshot = await db .collection("users") .doc(myId) .get(); if (docSnapshot.exists) { await db .collection("users") .doc(myId) .update({ followee: firebase.firestore.FieldValue.arrayRemove(uid) }); await db .collection("users") .doc(uid) .update({ follower: firebase.firestore.FieldValue.arrayRemove(myId) }); } else { await db .collection("users") .doc(myId) .set({ followee: [] }); } }; } componentDidMount = async () => { const db = firebase.firestore(); const documentSnapshots = await db.collection("users").get(); const { myId } = this.props; const users = []; documentSnapshots.forEach(doc => { if (doc.id !== myId) { users.push(doc.id); } }); this.setState({ users }); }; render() { const { users } = this.state; return ( <div> <p>hoge</p> {users.map((uid, index) => ( <ul key={uid + "-" + index}> <li>NO_NAME</li> <li> <button onClick={() => this.followButtonClicked(uid)}> follow </button> </li> <li> <button onClick={() => this.unfollowButtonClicked(uid)}> unfollow </button> </li> </ul> ))} <style jsx>{` ul { display: flex; list-style: none; } li { margin: 0 0.5rem; } `}</style> </div> ); } } const mapStateToProps = state => { const { userCredential } = state.user; return { myId: userCredential ? userCredential.uid : null }; }; Users.defaultProps = { myId: "" }; Users.propTypes = { myId: PropTypes.string }; export default connect( mapStateToProps, null )(Users);
const {Command} = require('discord.js-commando'); const low = require('lowdb'); const FileSync = require('lowdb/adapters/FileSync'); const adapter = new FileSync('storage/bot.json'); const db = low(adapter); const trelloYello = require('trello-yello'); const key = require('../../key'); module.exports = class extends Command { constructor(client) { super(client, { name: 'boards', group: 'boards', memberName: 'boards', description: 'Lists available boards', examples: ['boards'] }); } async run(message) { const prefix = message.guild === null ? this.client.commandPrefix : message.guild.commandPrefix; if (!db.get('users').find({id: message.author.id}).value()) { return message.say('You\'re not signed in! Please run `' + prefix + 'auth`.'); } const {token} = db.get('users').find({id: message.author.id}).value(); const trello = trelloYello({key, token}); const boards = await trello.getCurrentUser().getBoards(); let toSend = 'Run `' + prefix + 'board <id>` to choose a board.\n\nBoards:'; let name; let id; for (const board of boards) { name = await board.getName(); // eslint-disable-line no-await-in-loop id = await board.getId(); // eslint-disable-line no-await-in-loop toSend += '\n - `' + id + '` ' + name; } return message.say(toSend); } };
var gameData = require("gameData"); var confige = require("confige"); var ZhaJinHuaLogic = require("ZhaJinHuaLogic"); cc.Class({ extends: cc.Component, properties: { }, onDestory:function(){ console.log("gameScene onDestory!!!!!!") if(confige.curUsePlatform == 1) jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "gameScene onDestory!!!!!!"); }, onLoad: function () { this.resNode = this.node.getChildByName("resNode"); confige.h5RoomID = "0"; this.oldPlayer = this.node.getChildByName("oldPlayer"); this.oldPlayer.getChildByName("name").getComponent("cc.Label").string = confige.userInfo.nickname; this.oldPlayer.getChildByName("score").getComponent("cc.Label").string = ""; cc.loader.onProgress = function(){}; confige.loadNode.hideNode(); if(cc.sys.platform == cc.sys.IPAD) cc.view.setDesignResolutionSize(1280,720,cc.ResolutionPolicy.EXACT_FIT); if(cc.sys.platform == cc.sys.MOBILE_BROWSER) cc.view.setDesignResolutionSize(1280,790,cc.ResolutionPolicy.EXACT_FIT); this.gameBGNode = this.node.getChildByName("gameBGNode").getComponent("gameBGNode"); this.gameBGNode.onInit(); this.playerNode = this.node.getChildByName("playerNode"); this.infoNode = this.node.getChildByName("infoNode"); this.playerLoadOK = false; this.infoLoadOK = false; this.doLaterLoad = false; var self = this; cc.loader.loadRes("prefabs/game/gameInfoNode", cc.Prefab, function (err, prefabs) { console.log("gameInfoNode load!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); var newLayer = cc.instantiate(prefabs); self.infoNode.addChild(newLayer); self.gameInfoNode = newLayer.getComponent("gameInfoNode"); self.gameInfoNode.onInit(); self.infoLoadOK = true; if(self.playerLoadOK == true && self.infoLoadOK == true) { if(self.doLaterLoad == false) { self.doLaterLoad = true; self.loadRes1(); // self.loadLater(); // self.startLater(); // self.loadRes2(); } } }); cc.loader.loadRes("prefabs/game/sanKung/sanKungPlayerNode", cc.Prefab, function (err, prefabs) { console.log("gamePlayerNode load!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); var newLayer = cc.instantiate(prefabs); self.playerNode.addChild(newLayer); self.gamePlayerNode = newLayer.getComponent("gamePlayerNode"); self.gamePlayerNode.onInit(); self.playerLoadOK = true; if(self.playerLoadOK == true && self.infoLoadOK == true) { if(self.doLaterLoad == false) { self.doLaterLoad = true; self.loadRes1(); // self.loadLater(); // self.startLater(); // self.loadRes2(); } } self.oldPlayer.active = false; }); // this.gameInfoNode = this.node.getChildByName("gameInfoNode").getComponent("gameInfoNode"); // this.gameInfoNode.onInit(); // this.gamePlayerNode = this.node.getChildByName("gamePlayerNode").getComponent("gamePlayerNode"); // this.gamePlayerNode.onInit(); console.log("gameScene Load!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); }, start: function () { }, loadLater:function(){ console.log("loadLater!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); pomelo.clientScene = this; confige.curGameScene = this; gameData.gameMainScene = this; this.sceneLoadOver = false; this.timeCallFunc = -1; this.waitForSettle = false; this.time_rob = 10; this.time_betting = 10; this.time_settlement = 10; this.meChair = 0; this.curBankerChair = -1; this.isJinHua = true; this.curBet = confige.roomData.curBet; this.jinHuaMaxBet = confige.roomData.maxBet; this.jinHuaMaxRound = confige.roomData.maxRound; this.jinHuaStuffyRound = confige.roomData.stuffyRound; this.scorePoolNew = this.node.getChildByName("gameBGNode").getChildByName("mainNode").getChildByName("scorePoolNew"); this.scoreRoundLabel = this.scorePoolNew.getChildByName("scoreRound").getComponent("cc.Label"); this.scoreAllLabel = this.scorePoolNew.getChildByName("scoreAll").getComponent("cc.Label"); this.roundLabel = this.scorePoolNew.getChildByName("round").getComponent("cc.Label"); this.joinState = confige.roomData.state; this.gameBegin = false; //本房间游戏开始 this.gameStart = false; //当前局游戏开始 this.joinLate = false; this.timerItem = this.node.getChildByName("timerItem").getComponent("timerItem"); this.timerItem.onInit(); this.zhajinniuRoundTime = Math.ceil(confige.roomData.TID_ZHAJINHUA/1000); this.allBetNum = 0; this.myBetNum = 0; this.readyBtn = this.node.getChildByName("btn_ready"); this.showCardBtn = this.node.getChildByName("btn_showMyCard"); this.betNumMax = 20; this.niuniuBetType = 1; this.gameStatus = this.node.getChildByName("gameStatus"); this.gameStatusList = {}; for(var i=1;i<=5;i++) { this.gameStatusList[i] = this.gameStatus.getChildByName("tips" + i); } this.btnCanSend = true; this.openCardBox = this.node.getChildByName("openCardBox"); this.openCardBtn1 = this.openCardBox.getChildByName("btn1"); this.openCardBtn2 = this.openCardBox.getChildByName("btn2"); this.openCardImg1 = this.openCardBox.getChildByName("btnImg1"); this.openCardImg2 = this.openCardBox.getChildByName("btnImg2"); }, startLater: function () { this.gamePlayerNode.onStart(); if(this.isJinHua == true) { this.initZhajinniuLayer(); } if(confige.curReconnectData == -1) //是否属于重连状态 { if(this.joinState == 1005) { for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { this.gamePlayerNode.cardItemList.activePlayer(confige.getCurChair(i)); } } } if(this.joinState != 1001) //本局游戏已经开始才加入 { this.gameBegin = true; this.gameInfoNode.btn_inviteFriend.active = false; // this.gameInfoNode.btn_close.interactable = false; console.log("本局游戏已经开始才加入,进入观战模式"); console.log("当前参与游戏的人数===" + this.gamePlayerNode.playerCount); var watchPlayer = 0; // for(var i=0;i<this.playerCount;i++) for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == false) { watchPlayer ++; console.log("有一个观战的玩家"); } if(confige.roomPlayer[i].isBanker == true) { this.curBankerChair = i; this.gamePlayerNode.playerList[confige.getCurChair(this.curBankerChair)].getChildByName("banker").active = true; this.gamePlayerNode.lightBgList[confige.getCurChair(this.curBankerChair)].active = true; } } this.gamePlayerNode.playerCount -= watchPlayer; this.readyBtn.active = false; this.gameStart = true; this.joinLate = true; if(this.joinState == 1003) { for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { this.gamePlayerNode.playerCardList[i] = confige.roomData.player[i].handCard; this.gamePlayerNode.playerHandCardList[confige.getCurChair(i)].initCardWithBack(); var curChair = confige.getCurChair(i); if(curChair != 0 && confige.roomPlayer[i].isShowCard == true) this.gamePlayerNode.showOneCard(i); this.gamePlayerNode.playerHandCardList[curChair].showCardBackWithCount(5); } } } if(this.joinState != 1005) //非抢庄阶段,显示分数和庄家 { var curBetCount = 0; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); curBetCount += confige.roomData.betList[i]; this.gamePlayerNode.curBetNumList[curChair] = confige.roomData.betList[i]; // this.playerScoreList[parseInt(i)] -= confige.roomData.betList[i]; // this.playerInfoList[curChair].setScore(this.playerScoreList[parseInt(i)]); console.log(this.gamePlayerNode.betNumLabelList); this.gamePlayerNode.betNumLabelList[curChair].string = this.gamePlayerNode.curBetNumList[curChair] + "分"; if(confige.roomPlayer[i].isBanker == false) this.gamePlayerNode.betNumNodeList[curChair].active = true; } } this.allBetNum = curBetCount; this.showScorePool(this.allBetNum); this.gameBGNode.betItemListAddBet(confige.getCurChair(this.curBankerChair),this.allBetNum); } if(this.isJinHua == true) { this.curBet = confige.roomData.curBet; this.changeBetNum(this.curBet); this.curRound = confige.roomData.curRound; if(this.curRound > this.jinHuaStuffyRound) this.btnWatchCard.getComponent("cc.Button").interactable = true; this.setRoundTime(this.curRound); this.scoreRoundLabel.string = this.curBet; this.roundLabel.string = this.curRound; var curBetCount = 0; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); this.gamePlayerNode.playerHandCardList[curChair].resetCard(); for(var j=0;j<3;j++) this.gamePlayerNode.playerHandCardList[curChair].showCardBackWithIndex(j); if(confige.roomData.player[i].isShowCard == true) { this.lookCardList[curChair] = true; this.gamePlayerNode.watchCardImgList[curChair].active = true; } if(confige.roomData.player[i].state == 1) { this.loseList[curChair] = true; this.loseNodeList[curChair].active = true; this.giveUpList[curChair] = true; this.gamePlayerNode.discardImgList[curChair].active = true; this.gamePlayerNode.watchCardImgList[curChair].active = false; } if(confige.curReconnectData.roomInfo.player[i].state == 2) { this.loseList[curChair] = true; this.loseNodeList[curChair].active = true; this.gamePlayerNode.watchCardImgList[curChair].active = false; this.gamePlayerNode.failureImgList[curChair].active = true; this.gamePlayerNode.cardItemList.deActivePlayer(curChair); } curBetCount += confige.roomData.betList[i]; this.gamePlayerNode.curBetNumList[curChair] = confige.roomData.betList[i]; this.gamePlayerNode.betNumLabelList[curChair].string = this.gamePlayerNode.curBetNumList[curChair] + "分"; this.gamePlayerNode.betNumNodeList[curChair].active = true; } } this.allBetNum = curBetCount; this.showScorePool(this.allBetNum); var curPlayerChair = confige.getCurChair(confige.roomData.curPlayer); this.changeArrow(curPlayerChair); } } }else{ this.recoverGame(); confige.curReconnectData = -1; } console.log("roomId + meChair === " + (confige.roomData.roomId*10 + this.meChair)); this.sceneLoadOver = true; //处理缓存的服务器消息 confige.gameSceneLoadOver = true; confige.curSceneIndex = 2; var infoCount = confige.gameSceneLoadData.length; console.log(confige.gameSceneLoadData); for(var i=0;i<infoCount;i++) { console.log("deal once!!!!!!!!"); var curInfo = confige.gameSceneLoadData.shift(); pomelo.dealWithOnMessage(curInfo); console.log(curInfo); } confige.gameSceneLoadData = []; console.log(confige.gameSceneLoadData); }, setBanker:function(chair){ this.curBankerChair = chair; }, showScorePool:function(score,type,bankerScore,change){ console.log("show fuck score pool!!!!!!"); this.scorePoolNew.active = true; this.scoreAllLabel.string = score; this.gameBGNode.scorePoolNum = parseInt(score); if(change === true) { // this.gameBGNode.betItemRemoveToBanker(confige.getCurChair(this.curBankerChair)); var callFunc = function(){ this.gameBGNode.betItemListClean(); console.log("fuck you scorePool 丢钱出去!!!!!!!!!!!!!!") this.gameBGNode.betItemListAddBet(confige.getCurChair(this.curBankerChair),callFunc.score); }; callFunc.score = score; this.scheduleOnce(callFunc,1); } }, showGameStatus:function(index){ this.gameStatus.active = true; for(var i=1;i<=5;i++) this.gameStatusList[i].active = false; if(index == 2) { this.gameStatus.active = false; }else{ this.gameStatusList[index].active = true; } }, hideGameStatus:function(){ this.gameStatus.active = false; }, compareBet:function(betNum, chair){ this.gameBGNode.betItemListAddBet(chair,betNum); if(this.isJinHua) { this.allBetNum += betNum; this.gamePlayerNode.curBetNumList[chair] += betNum; this.gamePlayerNode.betNumLabelList[chair].string = this.gamePlayerNode.curBetNumList[chair].toString() + "分"; this.showScorePool(this.allBetNum,1); return; } this.allBetNum = this.allBetNum + betNum; if(chair == 0) this.myBetNum = this.myBetNum + betNum; this.showScorePool(this.allBetNum,1); this.gamePlayerNode.curBetNumList[chair] += betNum; this.gamePlayerNode.betNumLabelList[chair].string = this.gamePlayerNode.curBetNumList[chair].toString() + "分"; }, addBet:function(betNum, chair){ if(confige.soundEnable == true) { var oriChair = confige.getOriChair(chair); var betNumNew = betNum; if(this.lookCardList[oriChair] == true) betNumNew = betNumNew/2; if(betNumNew <= this.curBet) { console.log("play@@@@@fffflooooowww!!!!!!") var curSex = 0; curSex = parseInt(confige.roomPlayer[oriChair].playerInfo.sex); var curMusicIndex = 1; if(this.curRound != 1) curMusicIndex += parseInt(Math.random()*2); console.log("curMusicIndex===="+curMusicIndex); if(curSex == 2) confige.playSoundByName("f_follow"+curMusicIndex); else confige.playSoundByName("m_follow"+curMusicIndex); }else{ console.log("play@@@@@addddddddd!!!!!!") var curSex = 0; curSex = parseInt(confige.roomPlayer[oriChair].playerInfo.sex); if(curSex == 2) confige.playSoundByName("f_add"); else confige.playSoundByName("m_add"); } confige.playSoundByName("sendBet"); } this.gameBGNode.betItemListAddBet(chair,betNum); if(this.isJinHua) { this.allBetNum += betNum; this.gamePlayerNode.curBetNumList[chair] += betNum; this.gamePlayerNode.betNumLabelList[chair].string = this.gamePlayerNode.curBetNumList[chair].toString() + "分"; this.showScorePool(this.allBetNum,1); return; } // this.allBetNum = this.allBetNum + betNum; // if(chair == 0) // this.myBetNum = this.myBetNum + betNum; // this.showScorePool(this.allBetNum,1); // this.gamePlayerNode.curBetNumList[chair] += betNum; // this.gamePlayerNode.betNumLabelList[chair].string = this.gamePlayerNode.curBetNumList[chair].toString() + "分"; }, onBtnReadyClicked:function(){ if(this.btnCanSend) { this.btnCanSend = false; pomelo.request("connector.entryHandler.sendData", {"code" : "ready"}, function(data) { console.log("flag is : "+ data.flag); if(data.flag == true) { if(this.isJinHua) { this.scorePoolNew.active = false; this.readyBtn.active = false; for(var i=0;i<6;i++) { this.lookCardList[i] = false; this.giveUpList[i] = false; this.loseList[i] = false; this.loseNodeList[i].active = false; this.gamePlayerNode.watchCardImgList[i].active = false; this.gamePlayerNode.failureImgList[i].active = false; this.gamePlayerNode.discardImgList[i].active = false; // this.isTurnImgList[i].active = false; } }else{ console.log("fuck onBtnReadyClicked !!!!!!!!!"); this.readyBtn.active = false; } } this.btnCanSend = true; }.bind(this)); } }, onBtnBetClicked:function(event, customEventData){ }, onBtnPushBankerClicked:function(event,customEventData){ }, onBtnPopBankerClicked:function(){ }, downBanker:function(data){ }, onServerRobBanker:function(){ }, onServerRobBankerReturn:function(data){ }, statusChange:function(index){ if(this.isJinHua) { return; } else if(index === 1) { this.timerItem.setTime(this.time_betting); } else if(index === 2) { this.timerItem.setTime(this.time_settlement); } }, onServerReady:function(chair){ confige.roomPlayer[confige.getOriChair(chair)].isReady = true; console.log(confige.getOriChair(chair) + "号玩家准备"); this.onReConnect = false; this.gamePlayerNode.playerList[chair].getChildByName("isReady").active = true; this.gamePlayerNode.failureImgList[chair].active = false; this.gamePlayerNode.watchCardImgList[chair].active = false; this.gamePlayerNode.discardImgList[chair].active = false; if(chair == 0) //当前玩家自己 { console.log("000000000号玩家准备"); this.showCardBtn.active = false; this.joinLate = false; this.gameBGNode.betItemListClean(); this.showGameStatus(5); this.gameBGNode.scorePool.active = false; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { var curChair = confige.getCurChair(i); this.gamePlayerNode.playerHandCardList[curChair].resetCard(); this.gamePlayerNode.niuTypeBoxList[curChair].active = false; this.gamePlayerNode.playerList[curChair].getChildByName("banker").active = false; this.gamePlayerNode.betNumNodeList[curChair].active = false; this.gamePlayerNode.betNumLabelList[curChair].string = "0" + "分"; this.gamePlayerNode.curBetNumList[curChair] = 0; this.gamePlayerNode.lightBgList[curChair].active = false; this.gamePlayerNode.isRobImgList[curChair].active = false; this.gamePlayerNode.noRobImgList[curChair].active = false; this.gamePlayerNode.robNumNodeList[curChair].active = false; } } } }, onServerBeginBetting:function(data){ var bankerChair = data.banker; this.allBetNum = 0; this.myBetNum = 0; console.log("fuck joinLate =====!!!!!!!!!" + this.joinLate); this.statusChange(1); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curIndex = confige.getCurChair(i); this.gamePlayerNode.isRobImgList[curIndex].active = false; this.gamePlayerNode.noRobImgList[curIndex].active = false; if(i != bankerChair) //庄家不显示分数框 { this.gamePlayerNode.betNumNodeList[curIndex].active = true; } if(this.isJinHua == false) { if(i != bankerChair) { this.gamePlayerNode.betNumLabelList[curIndex].string = "0" + "分"; this.gamePlayerNode.curBetNumList[curIndex] = 0; } } } } console.log("onServerBeginBetting111111"); this.curBankerChair = bankerChair; if(bankerChair == this.meChair) this.showGameStatus(4); else this.showGameStatus(2); this.showScorePool(this.allBetNum); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { this.gamePlayerNode.playerList[confige.getCurChair(i)].getChildByName("banker").active = false; this.gamePlayerNode.lightBgList[confige.getCurChair(i)].active = false; } } console.log("onServerBeginBetting222222"); if(bankerChair != -1) { this.gamePlayerNode.playerList[confige.getCurChair(bankerChair)].getChildByName("banker").active = true; this.gamePlayerNode.lightBgList[confige.getCurChair(bankerChair)].active = true; // this.curBankerChair = confige.getCurChair(bankerChair); } console.log("onServerBeginBetting333333"); }, onServerDealCard:function(handCards){ }, btn_showMyCard:function(){ }, showMingCard:function(cards){ }, onServerSettlement:function(data){ if(this.timeCallFunc != -1) { this.timerItem.hideTimer(); this.unschedule(this.timeCallFunc); } this.hideOpenCard(1); this.hideOpenCard(2); this.hideGameStatus(); console.log("onServerSettlement 1111111"); if(this.isJinHua) { for(var i in confige.roomPlayer) { if(confige.roomPlayer.hasOwnProperty(i)) { if(confige.roomPlayer[i] && confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { this.gamePlayerNode.playerCardList[i] = data.player[i].handCard; } } } this.hideDoBtnLayer(); this.hideArrow(); this.btnWatchCard.active = false; this.setRoundTime(0); } this.statusChange(0); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { confige.roomPlayer[i].isReady = false; } this.gamePlayerNode.isTurnImgList[i].active = false; } console.log("onServerSettlement 222222222"); //第一步显示玩家手牌 if(this.isJinHua) { this.gamePlayerNode.showOneCard(this.meChair); if(data.compareList[this.meChair] != null) { console.log("compareList 存在队列@@@@@"); for(var p in data.compareList[this.meChair]) this.gamePlayerNode.showOneCard(data.compareList[this.meChair][p]); } } console.log("onServerSettlement 33333333"); this.waitForSettle = true; this.showCardBtn.active = false; this.gameStart = false; this.joinLate = false; this.gameInfoNode.btn_close.interactable = true; this.timerItem.hideTimer(); //分割筹码 console.log("分割筹码"); console.log(data.curScores); if(this.isJinHua == true) { for(var i in data.curScores) { if(data.curScores[i] > 0){ this.gameBGNode.betItemRemove(confige.getCurChair(i),data.curScores[i] + this.gamePlayerNode.curBetNumList[confige.getCurChair(i)]); if(confige.soundEnable == true) confige.playSoundByName("getBet"); } } for(var i=0;i<this.gameBGNode.betItemCount;i++) this.gameBGNode.betItemListAll[i].opacity = 0; } console.log("onServerSettlement 4444444"); //第二步延迟显示结算界面 var self = this; var showSettleFunc1 = function(){ self.gameInfoNode.settleLayer.show(data.curScores[self.meChair]); for(var i in data.result) { if(data.result.hasOwnProperty(i)) { var isDiscard = false; var isFailure = false; var isShow = false; var niuType = 100; if(self.isJinHua) { if(data.player[i]) { if(data.player[i].state == 1) { console.log(i + "号玩家弃牌了"); niuType = 100; isDiscard = true; } if(data.player[i].state == 2) { console.log(i + "号玩家比牌失败"); niuType = 100; isFailure = true; } } if(data.compareList[self.meChair] != null) { console.log("compareList 存在队列@@@@@"); for(var p in data.compareList[self.meChair]){ if(data.compareList[self.meChair][p] == i) { isShow = true; niuType = data.result[i].type; } } } if(i == self.meChair) { isShow = true; niuType = data.result[i].type; } } self.gameInfoNode.settleLayer.addOneSettleJinHua(confige.roomData.player[i].playerInfo.nickname, niuType, data.curScores[i],data.player[i].handCard,isDiscard,isFailure,isShow); self.gamePlayerNode.playerScoreList[i] = data.realScores[i]; self.gamePlayerNode.playerInfoList[confige.getCurChair(i)].setScore(self.gamePlayerNode.playerScoreList[i]); } } console.log("onServerSettlement 55555555"); // if(self.gameInfoNode.roomCurTime < self.gameInfoNode.roomMaxTime) // self.gameInfoNode.roomCurTime ++; // self.gameInfoNode.roomTime.string = "第" + self.gameInfoNode.roomCurTime + "/" + self.gameInfoNode.roomMaxTime + "局"; self.waitForSettle = false; }; var showSettleFunc2 = function(){ if(this.gameInfoNode.settleLayer == -1){ cc.loader.loadRes("prefabs/game/settleLayer", cc.Prefab, function (err, prefabs) { var newLayer = cc.instantiate(prefabs); self.gameInfoNode.layerNode1.addChild(newLayer,10); self.gameInfoNode.settleLayer = newLayer.getComponent("settleLayer"); self.gameInfoNode.settleLayer.showLayer(); self.gameInfoNode.settleLayer.parent = self; showSettleFunc1(); }); }else{ self.gameInfoNode.settleLayer.showLayer(); showSettleFunc1(); } }; if(this.isJinHua) this.scheduleOnce(showSettleFunc2,2.5); }, resetScene:function(){ this.readyBtn.active = true; this.showCardBtn.active = false; this.timerItem.active = false; }, //根据重连数据重现游戏状态 recoverGame:function(){ this.onReConnect = true; console.log("处理重连数据"); console.log("当前参与游戏的人数===" + this.gamePlayerNode.playerCount); var watchPlayer = 0; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == false) { watchPlayer ++; if(i == this.meChair) this.joinLate = true; console.log("有一个观战的玩家"); } } this.gamePlayerNode.playerCount -= watchPlayer; if(confige.curReconnectData.freeState && confige.curReconnectData.freeState != false) this.gameInfoNode.onServerShowFinish(confige.curReconnectData.freeState); console.log("on recoverGame() !!!!!!!!!!!!!"); this.gameInfoNode.roomMaxTime = confige.curReconnectData.roomInfo.maxGameNumber; this.curBet = confige.curReconnectData.roomInfo.curBet; this.changeBetNum(this.curBet); this.curRound = confige.curReconnectData.roomInfo.curRound; if(this.curRound > this.jinHuaStuffyRound) this.btnWatchCard.getComponent("cc.Button").interactable = true; this.setRoundTime(this.curRound); this.scoreRoundLabel.string = this.curBet; this.roundLabel.string = this.curRound; //重置场景 this.resetScene(); console.log(confige.roomPlayer); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { if(confige.roomPlayer[i].isReady == true) this.gamePlayerNode.cardItemList.activePlayer(confige.getCurChair(i)); if(confige.roomPlayer[i].isOnline == false) this.gamePlayerNode.leaveNodeList[confige.getCurChair(i)].active = true; else this.gamePlayerNode.leaveNodeList[confige.getCurChair(i)].active = false; } } //重现当前玩家分数和显示庄家 // console.log(confige.roomPlayer); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { if(this.gamePlayerNode.playerActiveList[confige.getCurChair(i)] == false) { console.log("this.playerActiveList === addone"); this.gamePlayerNode.addOnePlayer(confige.roomPlayer[i]); } this.gamePlayerNode.playerScoreList[i] = confige.curReconnectData.roomInfo.player[i].score;// - confige.curReconnectData.betList[i]; // if(this.isJinHua) // this.playerScoreList[i] -= this.zhajinniuBasic; this.gamePlayerNode.playerInfoList[confige.getCurChair(i)].setScore(this.gamePlayerNode.playerScoreList[i]); if(confige.curReconnectData.roomInfo.player[i].isBanker == true) { this.gamePlayerNode.playerList[confige.getCurChair(i)].getChildByName("banker").active = true; this.gamePlayerNode.lightBgList[confige.getCurChair(i)].active = true; this.curBankerChair = i;//confige.getCurChair(i); console.log("重连时庄家==="+this.curBankerChair); } } } //重现下注金额 this.gameInfoNode.roomCurTime = confige.curReconnectData.roomInfo.gameNumber; this.gameInfoNode.roomTime.string = "第" + this.gameInfoNode.roomCurTime + "/" + this.gameInfoNode.roomMaxTime + "局"; if(confige.curReconnectData.state != 1001) { var curBetCount = 0; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); if(curChair == 0) { this.myBetNum = confige.curReconnectData.betList[i]; } curBetCount += confige.curReconnectData.betList[i]; this.gamePlayerNode.curBetNumList[curChair] = confige.curReconnectData.betList[i]; this.gamePlayerNode.betNumLabelList[curChair].string = this.gamePlayerNode.curBetNumList[curChair] + "分"; if(confige.roomPlayer[i].isBanker == false) this.gamePlayerNode.betNumNodeList[curChair].active = true; } } this.readyBtn.active = false; //重现当前局数显示 // this.gameInfoNode.roomCurTime = confige.curReconnectData.roomInfo.gameNumber; // this.gameInfoNode.roomTime.string = "第" + this.gameInfoNode.roomCurTime + "/" + this.gameInfoNode.roomMaxTime + "局"; console.log("重连"+ this.gameInfoNode.roomTime.string); this.gameBegin = true; // this.gameInfoNode.btn_close.interactable = false; this.gameInfoNode.btn_inviteFriend.active = false; }else{ //重现当前局数显示 // this.gameInfoNode.roomCurTime = confige.curReconnectData.roomInfo.gameNumber + 1; // this.gameInfoNode.roomTime.string = "第" + this.gameInfoNode.roomCurTime + "/" + this.gameInfoNode.roomMaxTime + "局"; console.log("重连"+ this.gameInfoNode.roomTime.string); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { this.gamePlayerNode.playerList[confige.getCurChair(i)].getChildByName("isReady").active = true; if(i == this.meChair) this.readyBtn.active = false; } } } switch(confige.curReconnectData.state){ case 1001: //空闲阶段 // this.statusChange(0); if(this.curBankerChair != -1){ this.gamePlayerNode.playerList[this.curBankerChair].getChildByName("banker").active = false; this.gamePlayerNode.lightBgList[this.curBankerChair].active = false; } break; case 1002: //下注阶段 break; case 1003: //发牌阶段 // this.statusChange(2); console.log("case 1003:!!!!!!!!"); // console.log(confige.roomPlayer); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { this.gamePlayerNode.playerCardList[i] = confige.curReconnectData.roomInfo.player[i].handCard; console.log("取出玩家的牌数据" + i) console.log(this.gamePlayerNode.playerCardList[i]); this.gamePlayerNode.playerHandCardList[confige.getCurChair(i)].initCardWithBack(); if(confige.roomPlayer[i].isShowCard == true) this.gamePlayerNode.showOneCard(i); } } if(this.joinLate == false) { this.gamePlayerNode.showOneCard(this.meChair,-1); this.btn_showMyCard(); } //this.showCardBtn.active = true; break; case 1004: //结算阶段 // this.statusChange(0); break; case 1005: //抢庄阶段 // this.statusChange(1); break; case 1006: break; } if(this.gameInfoNode.roomCurTime != 0) { this.gameInfoNode.btn_inviteFriend.active = false; this.gameBegin = true; }else{ console.log("fuck roomCurTime === " + this.roomCurTime); } console.log("this.gameBegin======??????" + this.gameBegin); if(this.isJinHua) { if(confige.curReconnectData.state == 1001) { confige.curReconnectData = -1; return; } console.log("特殊处理炸金牛的重连"); console.log("this.playerCount ===== " + this.gamePlayerNode.playerCount); if(this.isJinHua == true) { this.hideDoBtnLayer(); this.curRound = confige.curReconnectData.roomInfo.curRound; this.setRoundTime(this.curRound); var curBetCount = 0; var meGiveUp = false; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); this.gamePlayerNode.playerHandCardList[curChair].resetCard(); for(var j=0;j<3;j++) this.gamePlayerNode.playerHandCardList[curChair].showCardBackWithIndex(j); if(confige.curReconnectData.roomInfo.player[i].isShowCard == true) { this.lookCardList[curChair] = true; this.gamePlayerNode.watchCardImgList[curChair].active = true; if(curChair == 0){ this.isWatchCard = true; } } if(confige.curReconnectData.roomInfo.player[i].state == 1) { this.loseList[curChair] = true; this.loseNodeList[curChair].active = true; this.giveUpList[curChair] = true; this.gamePlayerNode.discardImgList[curChair].active = true; this.gamePlayerNode.watchCardImgList[curChair].active = false; if(curChair == 0 && this.joinLate == false) meGiveUp = true; } if(confige.curReconnectData.roomInfo.player[i].state == 2) { this.loseList[curChair] = true; this.loseNodeList[curChair].active = true; this.gamePlayerNode.watchCardImgList[curChair].active = false; this.gamePlayerNode.failureImgList[curChair].active = true; this.gamePlayerNode.cardItemList.deActivePlayer(curChair); } if(confige.curReconnectData.roomInfo.player[i].state == 1 || confige.curReconnectData.roomInfo.player[i].state == 2) { if(i == this.meChair && this.joinLate == false) { if(confige.curReconnectData.roomInfo.player[i].handCard) { this.gamePlayerNode.playerCardList[this.meChair] = confige.curReconnectData.roomInfo.player[i].handCard; this.gamePlayerNode.showOneCard(this.meChair); } } } curBetCount += confige.curReconnectData.betList[i]; this.gamePlayerNode.curBetNumList[curChair] = confige.curReconnectData.betList[i]; this.gamePlayerNode.betNumLabelList[curChair].string = this.gamePlayerNode.curBetNumList[curChair] + "分"; } } if(this.isWatchCard == true) { this.btnWatchCard.active = false; }else{ if(confige.roomPlayer[this.meChair].isActive == true && confige.roomPlayer[this.meChair].isReady == true) { if(meGiveUp == true) { this.btnWatchCard.active = false; } else{ this.btnWatchCard.active = true; } }else{ this.btnWatchCard.active = false; } } this.allBetNum = curBetCount; this.showScorePool(this.allBetNum); this.gameBGNode.betItemListAddBet(confige.getCurChair(this.curBankerChair),this.allBetNum); var curPlayerChair = confige.getCurChair(confige.curReconnectData.roomInfo.curPlayer); this.changeArrow(curPlayerChair); if(this.curRound > this.jinHuaStuffyRound) this.btnWatchCard.getComponent("cc.Button").interactable = true; else this.btnWatchCard.getComponent("cc.Button").interactable = false; if(this.isWatchCard == true) { this.changeBetNum(this.curBet); var curCardData = confige.curReconnectData.roomInfo.player[this.meChair].handCard; for(var k in curCardData) { var index = parseInt(k); this.gamePlayerNode.playerHandCardList[0].setCardWithIndex(index, curCardData[index].num, curCardData[index].type); } } if(curPlayerChair == 0) { if(this.curRound == this.jinHuaMaxRound) this.showDoBtnLayer(0,true); else this.showDoBtnLayer(); if(this.curRound < 3) this.hideBtnCompare(); }else{ this.hideDoBtnLayer(); this.showGameStatus(4); } } } confige.curReconnectData = -1; }, connectCallBack:function(){ }, //炸金牛模式的处理 initZhajinniuLayer:function(){ console.log("炸金牛模式的处理 !!!!!!!!!!!"); this.zhajinniuLayer = this.node.getChildByName("zhajinniuLayer"); this.doBtnLayer = this.zhajinniuLayer.getChildByName("doBtnLayer"); this.zhaBetBtnBox = this.doBtnLayer.getChildByName("betBtnBox"); this.btnAbandonCard = this.doBtnLayer.getChildByName("abandonCard"); this.btnCompareCard = this.doBtnLayer.getChildByName("compareCard"); this.btnWatchCard = this.zhajinniuLayer.getChildByName("watchCard"); this.compareBtnBox = this.zhajinniuLayer.getChildByName("compareBtnBox"); this.zhaBetList = {}; this.zhaBetList[1] = this.zhaBetBtnBox.getChildByName("bet1"); this.zhaBetList[2] = this.zhaBetBtnBox.getChildByName("bet2"); this.zhaBetList[3] = this.zhaBetBtnBox.getChildByName("bet3"); this.zhaBetList[4] = this.zhaBetBtnBox.getChildByName("bet4"); this.zhaBetList[5] = this.zhaBetBtnBox.getChildByName("bet5"); this.zhajinniuLayer.active = true; this.curRound = 0; this.isWatchCard = false; this.meGiveUp = false; this.lookCardList = {}; this.giveUpList = {}; this.loseList = {}; for(var i=0;i<6;i++) { this.lookCardList[i] = false; this.giveUpList[i] = false; this.loseList[i] = false; } this.compareBtnList = {}; this.compareBtnList[1] = this.compareBtnBox.getChildByName("compare1"); this.compareBtnList[2] = this.compareBtnBox.getChildByName("compare2"); this.compareBtnList[3] = this.compareBtnBox.getChildByName("compare3"); this.compareBtnList[4] = this.compareBtnBox.getChildByName("compare4"); this.compareBtnList[5] = this.compareBtnBox.getChildByName("compare5"); this.loseNodeList = {}; this.loseNodeList[0] = this.zhajinniuLayer.getChildByName("lose0"); this.loseNodeList[1] = this.zhajinniuLayer.getChildByName("lose1"); this.loseNodeList[2] = this.zhajinniuLayer.getChildByName("lose2"); this.loseNodeList[3] = this.zhajinniuLayer.getChildByName("lose3"); this.loseNodeList[4] = this.zhajinniuLayer.getChildByName("lose4"); this.loseNodeList[5] = this.zhajinniuLayer.getChildByName("lose5"); this.zhajinniuBasic = confige.roomData.basic; console.log("fuck 炸金牛基础分数"+this.zhajinniuBasic); this.gameInfoNode.roomTimeNode.active = false; this.roundTime = this.gameInfoNode.roomInfo.getChildByName("nowRound").getComponent("cc.Label"); this.pkLayer = this.zhajinniuLayer.getChildByName("pkLayer"); this.pk1 = this.pkLayer.getChildByName("pk1"); this.pk2 = this.pkLayer.getChildByName("pk2"); this.pk1Head = this.pk1.getChildByName("head").getComponent("cc.Sprite"); this.pk1Name = this.pk1.getChildByName("name").getComponent("cc.Label"); this.pk1Win = this.pk1.getChildByName("pkWin"); this.pk1Lose = this.pk1.getChildByName("pkLose"); this.pk2Head = this.pk2.getChildByName("head").getComponent("cc.Sprite"); this.pk2Name = this.pk2.getChildByName("name").getComponent("cc.Label"); this.pk2Win = this.pk2.getChildByName("pkWin"); this.pk2Lose = this.pk2.getChildByName("pkLose"); this.pkImg = this.pkLayer.getChildByName("pkImg"); }, setRoundTime:function(number){ if(number == 0) { this.roundTime.string = ""; }else{ this.roundTime.string = "第"+number+"轮"; } }, changeArrow:function(index){ this.hideArrow(); this.gamePlayerNode.isTurnImgList[index].active = true; this.gamePlayerNode.isTurnImgList[index].opacity = 255; this.gamePlayerNode.isTurnImgList[index].runAction(cc.repeatForever(cc.sequence(cc.fadeTo(0.3,100),cc.fadeTo(0.3,255)))); }, hideArrow:function(){ for(var i=0;i<6;i++) { this.gamePlayerNode.isTurnImgList[i].stopAllActions(); this.gamePlayerNode.isTurnImgList[i].active = false; } }, showDoBtnLayer:function(curBet,hideBet){ this.doBtnLayer.active = true; if(hideBet == true){ for(var i=1;i<=3;i++) this.zhaBetList[i].getComponent("cc.Button").interactable = false; } return; }, hideDoBtnLayer:function(){ this.doBtnLayer.active = false; this.btnCompareCard.active = true; for(var i=1;i<=3;i++) { this.zhaBetList[i].getComponent("cc.Button").interactable = true; } }, hideBtnCompare:function(){ this.btnCompareCard.active = false; }, showCompareLayer:function(){ console.log("showCompareLayer begin"); this.compareBtnBox.active = true; var compareCount = 0; var compareChair = {}; for(var i in confige.roomPlayer) { if(confige.roomPlayer.hasOwnProperty(i)){ if(confige.roomPlayer[i] && confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curIndex = confige.getCurChair(i); if(curIndex != 0 && this.giveUpList[curIndex] == false && this.loseList[curIndex] == false) { compareChair = curIndex; compareCount ++; console.log("compare +++++++++@@@@@@@@@ =====") } } } } if(compareCount == 1) { console.log("compare with chair 123123123123===== " + confige.getOriChair(compareChair)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(compareChair)}); this.hideCompareLayer(); this.hideDoBtnLayer(); }else{ for(var i in confige.roomPlayer) { if(confige.roomPlayer.hasOwnProperty(i)){ if(confige.roomPlayer[i] && confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curIndex = confige.getCurChair(i); if(curIndex != 0 && this.giveUpList[curIndex] == false && this.loseList[curIndex] == false) { console.log("showCompareLayer" + i); this.compareBtnList[curIndex].active = true; this.gamePlayerNode.lightBgList[curIndex].active = true; this.gamePlayerNode.lightBgList[curIndex].runAction(cc.repeatForever(cc.sequence(cc.fadeTo(0.5,100),cc.fadeTo(0.5,255)))); } } } } } }, hideCompareLayer:function(){ this.compareBtnBox.active = false; for(var i=1;i<6;i++) { this.compareBtnList[i].active = false; this.gamePlayerNode.lightBgList[i].stopAllActions(); this.gamePlayerNode.lightBgList[i].active = false; } }, changeBetNum:function(basicScore){ this.zhaBetList[2].getChildByName("Label").getComponent("cc.Label").string = (basicScore+1); this.zhaBetList[3].getChildByName("Label").getComponent("cc.Label").string = (basicScore+2); if(this.isWatchCard == true) { this.zhaBetList[1].getChildByName("double").active = true; this.zhaBetList[2].getChildByName("double").active = true; this.zhaBetList[3].getChildByName("double").active = true; }else{ this.zhaBetList[1].getChildByName("double").active = false; this.zhaBetList[2].getChildByName("double").active = false; this.zhaBetList[3].getChildByName("double").active = false; } if((basicScore+1) > this.jinHuaMaxBet) this.zhaBetList[2].active = false; else this.zhaBetList[2].active = true; if((basicScore+2) > this.jinHuaMaxBet) this.zhaBetList[3].active = false; else this.zhaBetList[3].active = true; // if(type == 0) // { // this.zhaBetList[1].getChildByName("Label").getComponent("cc.Label").string = 1; // this.zhaBetList[2].getChildByName("Label").getComponent("cc.Label").string = 2; // this.zhaBetList[3].getChildByName("Label").getComponent("cc.Label").string = 3; // this.zhaBetList[4].getChildByName("Label").getComponent("cc.Label").string = 4; // this.zhaBetList[5].getChildByName("Label").getComponent("cc.Label").string = 5; // }else if(type == 1){ // this.zhaBetList[1].getChildByName("Label").getComponent("cc.Label").string = 2; // this.zhaBetList[2].getChildByName("Label").getComponent("cc.Label").string = 4; // this.zhaBetList[3].getChildByName("Label").getComponent("cc.Label").string = 6; // this.zhaBetList[4].getChildByName("Label").getComponent("cc.Label").string = 8; // this.zhaBetList[5].getChildByName("Label").getComponent("cc.Label").string = 10; // } }, onBtnClickZhaLayer:function(event, customEventData){ console.log("clickIndex@@@@Zha" + customEventData); var self = this; var clickIndex = parseInt(customEventData); switch(clickIndex){ //下注按钮 case 1: pomelo.clientSend("useCmd",{"cmd" : "gen"},function(){ self.hideDoBtnLayer(); }); break; case 2: pomelo.clientSend("useCmd",{"cmd" : "addOne"},function(){ self.hideDoBtnLayer(); }); break; case 3: pomelo.clientSend("useCmd",{"cmd" : "addTwo"},function(){ self.hideDoBtnLayer(); }); break; case 4: pomelo.clientSend("useCmd",{"cmd" : "bet","bet" : 4},function(){ self.hideDoBtnLayer(); }); break; case 5: pomelo.clientSend("useCmd",{"cmd" : "bet","bet" : 5},function(){ self.hideDoBtnLayer(); }); break; //下注之外的操作 case 11: //弃牌 pomelo.clientSend("useCmd",{"cmd" : "giveUp"},function(){ self.hideDoBtnLayer(); }); break; case 12: //比牌 this.showCompareLayer(); break; case 13: //看牌 pomelo.clientSend("useCmd",{"cmd" : "look"}); break; //比牌选择座位按钮 case 21: console.log("compare with chair ===== " + confige.getOriChair(1)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(1)},function(){ self.hideDoBtnLayer(); self.hideCompareLayer(); }); break; case 22: console.log("compare with chair ===== " + confige.getOriChair(2)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(2)},function(){ self.hideDoBtnLayer(); self.hideCompareLayer(); }); break; case 23: console.log("compare with chair ===== " + confige.getOriChair(3)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(3)},function(){ self.hideDoBtnLayer(); self.hideCompareLayer(); }); break; case 24: console.log("compare with chair ===== " + confige.getOriChair(4)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(4)},function(){ self.hideDoBtnLayer(); self.hideCompareLayer(); }); break; case 25: console.log("compare with chair ===== " + confige.getOriChair(5)); pomelo.clientSend("useCmd",{"cmd" : "compare","target" : confige.getOriChair(5)},function(){ self.hideDoBtnLayer(); self.hideCompareLayer(); }); break; } }, onServerZhaCall:function(data){ switch(data.cmd){ case "curRound": console.log("当前进行到第" + data.curRound + "轮"); this.curRound = data.curRound; this.setRoundTime(this.curRound); //this.hideArrow(); this.hideDoBtnLayer(); switch(this.curRound){ case 0: if(this.joinLate == false) this.newDisCard(3); break; case 1: if(this.joinLate == false) this.newDisCard(1); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); if(this.giveUpList[curChair] == false && (this.joinLate == true || this.onReConnect == true)) this.gamePlayerNode.playerHandCardList[curChair].showCardBackWithIndex(3); } } console.log("this.lookCardList[this.meChair]===" + this.lookCardList[this.meChair]); if(this.meGiveUp == false) { console.log(this.gamePlayerNode.playerCardList[this.meChair]); if(data.card) { this.gamePlayerNode.playerCardList[this.meChair][3] = data.card; var callFunc2 = function(){ this.showOpenCard(1); }; this.scheduleOnce(callFunc2,0.3); } } if(this.lookCardList[this.meChair]) { if(data.card) { var callFunc = function(){ this.gamePlayerNode.playerHandCardList[confige.getCurChair(this.meChair)].setCardWithIndex(3, callFunc.data.card.num, callFunc.data.card.type); } callFunc.data = data; this.scheduleOnce(callFunc,0.5); } } break; case 2: if(this.joinLate == false) this.newDisCard(1); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); if(this.giveUpList[curChair] == false && (this.joinLate == true || this.onReConnect == true)) this.gamePlayerNode.playerHandCardList[curChair].showCardBackWithIndex(4); } } console.log("this.lookCardList[this.meChair]===" + this.lookCardList[this.meChair]); if(this.meGiveUp == false) { console.log(this.gamePlayerNode.playerCardList[this.meChair]); if(data.card) { this.gamePlayerNode.playerCardList[this.meChair][4] = data.card; var callFunc2 = function(){ if(this.joinLate == false) this.showOpenCard(2); }; this.scheduleOnce(callFunc2,0.3); } } if(this.lookCardList[this.meChair]) { if(data.card) { var callFunc = function(){ this.gamePlayerNode.playerHandCardList[confige.getCurChair(this.meChair)].setCardWithIndex(4, callFunc.data.card.num, callFunc.data.card.type); } callFunc.data = data; this.scheduleOnce(callFunc,0.5); } } break; case 3: break; } break; case "nextPlayer": this.timerItem.hideTimer(); if(confige.soundEnable == true) { confige.playSoundByName("soundNext"); } this.curRound = data.curRound; this.curBet = data.curBet; this.scoreRoundLabel.string = this.curBet; this.roundLabel.string = this.curRound; if(this.curRound > this.jinHuaStuffyRound) this.btnWatchCard.getComponent("cc.Button").interactable = true; console.log("当前进行操作的玩家座位是" + data.chair); var curChair = confige.getCurChair(data.chair); this.changeArrow(curChair); if(curChair == 0) { if(this.zhajinniuRoundTime > 10) { var self = this; self.timeCallFunc = function(){ console.log("nextPlayer.timeCallFunc!!!!!!!!!!!!!!"); self.timerItem.setTime(10); if(confige.soundEnable == true) { confige.playSoundByName("soundTimeOut"); } }; this.scheduleOnce(self.timeCallFunc, (this.zhajinniuRoundTime-10)); console.log("this.timerItem.scheduleOnce"); }else{ this.timerItem.setTime(this.zhajinniuRoundTime); } this.showGameStatus(2); this.changeBetNum(this.curBet); if(this.curRound == this.jinHuaMaxRound) this.showDoBtnLayer(0,true); else this.showDoBtnLayer(); if(this.curRound < 3) this.hideBtnCompare(); }else{ if(this.timeCallFunc != -1) { this.timerItem.hideTimer(); this.unschedule(this.timeCallFunc); } this.showGameStatus(4); this.hideDoBtnLayer(); } this.setRoundTime(data.curRound); break; case "lookCard": var curChair = confige.getCurChair(data.chair); this.gamePlayerNode.watchCardImgList[curChair].active = true; this.lookCardList[data.chair] = true; if(confige.soundEnable == true) { var curSex = 0; curSex = parseInt(confige.roomPlayer[data.chair].playerInfo.sex); var curMusicIndex = 1; curMusicIndex += parseInt(Math.random()*2); if(curSex == 2) confige.playSoundByName("f_watch"+curMusicIndex); else confige.playSoundByName("m_watch"+curMusicIndex); } if(data.handCard) { if(curChair == 0) { this.isWatchCard = true; this.changeBetNum(this.curBet); this.btnWatchCard.active = false; this.hideOpenCard(1); this.hideOpenCard(2); } for(var l in data.handCard) { var index = parseInt(l); this.gamePlayerNode.playerHandCardList[curChair].setCardWithIndex(index, data.handCard[index].num, data.handCard[index].type); } } break; case "compare": var fromChair = confige.getCurChair(data.chair); var targetChair = confige.getCurChair(data.target); var curWinChair = confige.getCurChair(data.winPlayer); var curLoseChair = (fromChair == curWinChair) ? targetChair : fromChair; if(confige.soundEnable == true) { var curSex = 0; curSex = parseInt(confige.roomPlayer[fromChair].playerInfo.sex); if(curSex == 2) confige.playSoundByName("f_bipai"); else confige.playSoundByName("m_bipai"); } this.showPK(data.chair,data.target,data.winPlayer); if(curLoseChair == 0) { this.meGiveUp = true; this.hideOpenCard(1); this.hideOpenCard(2); } this.loseList[curLoseChair] = true; this.loseNodeList[curLoseChair].active = true; this.gamePlayerNode.watchCardImgList[curLoseChair].active = false; this.gamePlayerNode.failureImgList[curLoseChair].active = true; this.gamePlayerNode.cardItemList.deActivePlayer(curLoseChair); if(data.handCard) { this.gamePlayerNode.playerCardList[this.meChair] = data.handCard; this.gamePlayerNode.showOneCard(this.meChair); this.btnWatchCard.active = false; } break; case "giveUp": var curChair = confige.getCurChair(data.chair); this.giveUpList[curChair] = true; this.loseNodeList[curChair].active = true; this.gamePlayerNode.watchCardImgList[curChair].active = false; this.gamePlayerNode.discardImgList[curChair].active = true; this.gamePlayerNode.cardItemList.deActivePlayer(curChair); if(confige.soundEnable == true) { var curSex = 0; curSex = parseInt(confige.roomPlayer[data.chair].playerInfo.sex); var curMusicIndex = 1 + parseInt(Math.random()*3); if(curSex == 2) confige.playSoundByName("f_giveup"+curMusicIndex); else confige.playSoundByName("m_giveup"+curMusicIndex); } if(curChair == 0) { this.btnWatchCard.active = false; this.timerItem.hideTimer(); this.meGiveUp = true; this.hideOpenCard(1); this.hideOpenCard(2); } for(var g in data.handCard) { this.gamePlayerNode.playerCardList[this.meChair] = data.handCard; this.gamePlayerNode.showOneCard(this.meChair); // var index = parseInt(g); // if(data.handCard[g]) // this.gamePlayerNode.playerHandCardList[0].setCardWithIndex(index, data.handCard[index].num, data.handCard[index].type); } break; } }, onNewGameStart:function(){ for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { if(confige.roomPlayer[i].isReady == true) { console.log("激活"+i+"号玩家发牌器"); this.gamePlayerNode.cardItemList.activePlayer(confige.getCurChair(i)); } this.gamePlayerNode.playerList[confige.getCurChair(i)].getChildByName("banker").active = false; } } this.gameBegin = true; this.gameStart = true; this.meGiveUp = false; this.newResetCard(); console.log("onNewGameStart"); this.gameInfoNode.roomCurTime ++; this.gameInfoNode.roomTime.string = "第" + this.gameInfoNode.roomCurTime + "/" + this.gameInfoNode.roomMaxTime + "局"; for(var i=0;i<6;i++) { this.gamePlayerNode.playerList[i].getChildByName("isReady").active = false; } this.gameInfoNode.btn_inviteFriend.active = false; // this.gameInfoNode.btn_close.interactable = false; this.gamePlayerNode.playerCount = this.gamePlayerNode.newPlayerCount; this.gamePlayerNode.noShowCardCount = this.gamePlayerNode.playerCount; this.showScorePool(0); this.allBetNum = 0; if(this.isJinHua) { // this.changeBetNum(0); this.isWatchCard = false; for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true && confige.roomPlayer[i].isReady == true) { var curChair = confige.getCurChair(i); console.log("onNewGameBegin" + curChair + "score===" + this.zhajinniuBasic); this.gamePlayerNode.playerList[curChair].getChildByName("isReady").active = false; this.gamePlayerNode.betNumNodeList[curChair].active = true; this.gamePlayerNode.curBetNumList[curChair] = this.zhajinniuBasic; this.gamePlayerNode.betNumLabelList[curChair].string = this.gamePlayerNode.curBetNumList[curChair].toString() + "分"; this.allBetNum += this.zhajinniuBasic; } } this.btnWatchCard.active = true; this.btnWatchCard.getComponent("cc.Button").interactable = false; this.showScorePool(this.allBetNum); this.newDisCard(3); } }, onNewGameBegin:function(data){ this.gameStart = true; this.gamePlayerNode.playerCount = this.gamePlayerNode.newPlayerCount; console.log("onNewGameBegin" + this.gamePlayerNode.playerCount); }, update: function (dt) { confige.CallGVoicePoll(); }, newDisCard:function(times){ if(confige.soundEnable == true) { confige.playSoundByName("fapai"); } if(times == 1) this.gamePlayerNode.cardItemList.disCardOneRound(); else this.gamePlayerNode.cardItemList.disCardWithRoundTime(times); }, newResetCard:function(){ this.gamePlayerNode.cardItemList.resetCardList(); for(var i in confige.roomPlayer) { if(confige.roomPlayer[i].isActive == true) { if(confige.roomPlayer[i].isReady == true) this.gamePlayerNode.cardItemList.activePlayer(confige.getCurChair(i)); } } }, showPK:function(player1,player2,win){ this.pkLayer.active = true; this.pk1.x = -700; this.pk2.x = 700; this.pk1.opacity = 255; this.pk2.opacity = 255; this.pkLayer.opacity = 255; this.pkImg.opacity = 255; this.pk1Win.opacity = 255; this.pk2Win.opacity = 255; this.pk1Win.active = false; this.pk2Win.active = false; this.pk1Lose.active = false; this.pk2Lose.active = false; this.pk1Name.string = confige.roomPlayer[player1].playerInfo.nickname; this.pk2Name.string = confige.roomPlayer[player2].playerInfo.nickname; this.pk1Head.spriteFrame = confige.WXHeadFrameList[confige.getCurChair(player1)+1]; this.pk2Head.spriteFrame = confige.WXHeadFrameList[confige.getCurChair(player2)+1]; var action1 = cc.moveTo(0.3,cc.p(0,0)); var action2 = cc.fadeOut(0.3); var hideCallBack = function(){ this.hidePK(); }; if(player1 == win) { // this.pk1Win.active = true; // this.pk2Lose.active = true; this.pk1.runAction(cc.sequence(cc.moveTo(0.3,cc.p(-250,0)),cc.delayTime(1),action1)); this.pk2.runAction(cc.sequence(cc.moveTo(0.3,cc.p(250,0)),cc.delayTime(1),action2)); }else{ // this.pk2Win.active = true; // this.pk1Lose.active = true; this.pk1.runAction(cc.sequence(cc.moveTo(0.3,cc.p(-250,0)),cc.delayTime(1),action2)); this.pk2.runAction(cc.sequence(cc.moveTo(0.3,cc.p(250,0)),cc.delayTime(1),action1)); } this.scheduleOnce(hideCallBack,2); var hidePkImg = function(){ this.pkImg.runAction(cc.fadeOut(0.5)); if(player1 == win) { this.pk1Win.active = true; }else{ this.pk2Win.active = true; } }; this.scheduleOnce(hidePkImg,1); }, hidePK:function(){ var hideCallBack = cc.callFunc(function () { this.pkLayer.active = false; }, this); this.pkLayer.runAction(cc.sequence(cc.fadeOut(0.5),hideCallBack)); }, showOpenCard:function(index){ this.openCardBox.active = true; var moveAction = cc.repeatForever(cc.sequence(cc.moveBy(0.5,cc.p(0,20)),cc.moveBy(0.5,cc.p(0,-20)))); if(index == 1) { this.openCardBtn1.active = true; this.openCardImg1.active = true; this.openCardImg1.y = -280; this.openCardImg1.runAction(moveAction); }else if(index == 2){ this.openCardBtn2.active = true; this.openCardImg2.active = true; this.openCardImg2.y = -280; this.openCardImg2.runAction(moveAction); } }, hideOpenCard:function(index){ this.openCardBox.active = true; if(index == 1) { this.openCardBtn1.active = false; this.openCardImg1.active = false; this.openCardImg1.stopAllActions(); }else if(index == 2){ this.openCardBtn2.active = false; this.openCardImg2.active = false; this.openCardImg2.stopAllActions(); } }, btnOpenCard:function(event,customEventData){ var index = parseInt(customEventData); if(index == 1) { this.hideOpenCard(1); this.gamePlayerNode.playerHandCardList[confige.getCurChair(this.meChair)].setCardWithIndex(3, this.gamePlayerNode.playerCardList[this.meChair][3].num, this.gamePlayerNode.playerCardList[this.meChair][3].type); }else if(index == 2){ this.hideOpenCard(2); this.gamePlayerNode.playerHandCardList[confige.getCurChair(this.meChair)].setCardWithIndex(4, this.gamePlayerNode.playerCardList[this.meChair][4].num, this.gamePlayerNode.playerCardList[this.meChair][4].type); } }, openShare:function(){ if(confige.curOverLayer != -1) confige.curOverLayer.openShare(); }, WXCancle:function(){ if(confige.curOverLayer != -1) confige.curOverLayer.openShare(); }, showReConnect:function(){ gameData.gameInfoNode.showReConnect(); console.log("showReConnect!!!!!!!!!"); }, hideReConnect:function(){ gameData.gameInfoNode.hideReConnect(); console.log("hideReConnect!!!!!!!!!"); }, sayWithID:function(voiceID){ pomelo.clientSend("say",{"msg": {"sayType":255, "id": voiceID, "time": this.gameInfoNode.sayTime}}); }, loadRes1:function(){ var self = this; var onLoadNext = false; var loadCard = false; var loadNiutype = false; //cardFrame cc.loader.loadRes("prefabs/game/cardNode", cc.Prefab, function (err, prefabs) { var newNode = cc.instantiate(prefabs); self.resNode.addChild(newNode); confige.cardFrameMap[0] = newNode.getChildByName("card_00").getComponent("cc.Sprite").spriteFrame; for(var j=0;j<4;j++) { for(var i=1;i<=13;i++) { var t = i; if(i == 10) t = 'a'; else if(i == 11) t = 'b'; else if(i == 12) t = 'c'; else if(i == 13) t = 'd'; var index = i + j*13; confige.cardFrameMap[index] = newNode.getChildByName("card_"+j+t).getComponent("cc.Sprite").spriteFrame; } } loadCard = true; if(loadCard == true && loadNiutype == true) { if(onLoadNext == false) { onLoadNext = true; self.loadLater(); self.startLater(); self.loadRes2(); } } }); //niutypeFrame cc.loader.loadRes("prefabs/game/jinHua/jinHuaTypeNode", cc.Prefab, function (err, prefabs) { var newNode = cc.instantiate(prefabs); self.resNode.addChild(newNode); for(var i=0;i<=5;i++) { var spriteFrame = newNode.getChildByName("niu_W"+i).getComponent("cc.Sprite").spriteFrame; var spriteFrame2 = newNode.getChildByName("niu_L"+i).getComponent("cc.Sprite").spriteFrame; confige.jinHuaTypeFrameMap[i] = spriteFrame; confige.jinHuaTypeFrameMap[i+10] = spriteFrame2; } loadNiutype = true; if(loadCard == true && loadNiutype == true) { if(onLoadNext == false) { onLoadNext = true; self.loadLater(); self.startLater(); self.loadRes2(); } } }); }, loadRes2:function(){ var self = this; //faceFrame cc.loader.loadRes("prefabs/game/faceNode", cc.Prefab, function (err, prefabs) { var newNode = cc.instantiate(prefabs); self.resNode.addChild(newNode); for(var i=1;i<=12;i++) { confige.faceFrameMap[i-1] = newNode.getChildByName(""+i).getComponent("cc.Sprite").spriteFrame; } confige.loadFaceFrame = true; }); //faceAni cc.loader.loadRes("prefabs/game/faceAniNode", cc.Prefab, function (err, prefabs) { var newNode = cc.instantiate(prefabs); self.resNode.addChild(newNode); for(var i=1;i<=6;i++) confige.faceAniMap[i] = newNode.getChildByName("faceAni"+i); confige.loadFaceAni = true; }); this.initAudio(); }, initAudio:function(){ for(var i=0;i<8;i++) { cc.loader.loadRes("sound/0/chat" + (i+1),function(index){ return function (err, audio) { var curIndex = "female_" + "chat_" + index; confige.audioList[curIndex] = audio; } }(i)); cc.loader.loadRes("sound/1/chat" + (i+1),function(index){ return function (err, audio) { var curIndex = "male_" + "chat_" + index; confige.audioList[curIndex] = audio; } }(i)); } for(var i=0;i<6;i++) { cc.loader.loadRes("sound/F_" + (i+1),function(index){ return function (err, audio) { var curIndex = "female_" + "face_" + index; confige.audioList[curIndex] = audio; } }(i+1)); cc.loader.loadRes("sound/M_" + (i+1),function(index){ return function (err, audio) { var curIndex = "male_" + "face_" + index; confige.audioList[curIndex] = audio; } }(i+1)); } for(var i=0;i<7;i++) { cc.loader.loadRes("sound/" + (i+1),function(index){ return function (err, audio) { var curIndex = "face_" + index; confige.audioList[curIndex] = audio; } }(i+1)); } for(var i=0;i<=18;i++) { cc.loader.loadRes("sound/0/type" + i,function(index){ return function (err, audio) { var curIndex = "female_" + "type_" + index; confige.audioList[curIndex] = audio; } }(i)); cc.loader.loadRes("sound/1/type" + i,function(index){ return function (err, audio) { var curIndex = "male_" + "type_" + index; confige.audioList[curIndex] = audio; } }(i)); } cc.loader.loadRes("sound/fapai", function (err, audio) { confige.audioList["fapai"] = audio; }); cc.loader.loadRes("sound/new/f_add",function(err, audio){ confige.audioList["f_add"] = audio; }); cc.loader.loadRes("sound/new/m_add",function(err, audio){ confige.audioList["m_add"] = audio; }); cc.loader.loadRes("sound/new/f_follow1",function(err, audio){ confige.audioList["f_follow1"] = audio; }); cc.loader.loadRes("sound/new/m_follow1",function(err, audio){ confige.audioList["m_follow1"] = audio; }); cc.loader.loadRes("sound/new/f_follow2",function(err, audio){ confige.audioList["f_follow2"] = audio; }); cc.loader.loadRes("sound/new/m_follow2",function(err, audio){ confige.audioList["m_follow2"] = audio; }); cc.loader.loadRes("sound/new/f_giveup1",function(err, audio){ confige.audioList["f_giveup1"] = audio; }); cc.loader.loadRes("sound/new/m_giveup1",function(err, audio){ confige.audioList["m_giveup1"] = audio; }); cc.loader.loadRes("sound/new/f_giveup2",function(err, audio){ confige.audioList["f_giveup2"] = audio; }); cc.loader.loadRes("sound/new/m_giveup2",function(err, audio){ confige.audioList["m_giveup2"] = audio; }); cc.loader.loadRes("sound/new/f_giveup3",function(err, audio){ confige.audioList["f_giveup3"] = audio; }); cc.loader.loadRes("sound/new/m_giveup3",function(err, audio){ confige.audioList["m_giveup3"] = audio; }); cc.loader.loadRes("sound/new/f_watch1",function(err, audio){ confige.audioList["f_watch1"] = audio; }); cc.loader.loadRes("sound/new/m_watch1",function(err, audio){ confige.audioList["m_watch1"] = audio; }); cc.loader.loadRes("sound/new/f_watch2",function(err, audio){ confige.audioList["f_watch2"] = audio; }); cc.loader.loadRes("sound/new/m_watch2",function(err, audio){ confige.audioList["m_watch2"] = audio; }); cc.loader.loadRes("sound/new/f_bipai",function(err, audio){ confige.audioList["f_bipai"] = audio; }); cc.loader.loadRes("sound/new/m_bipai",function(err, audio){ confige.audioList["m_bipai"] = audio; }); cc.loader.loadRes("sound/new/sendBet",function(err, audio){ confige.audioList["sendBet"] = audio; }); cc.loader.loadRes("sound/new/getBet",function(err, audio){ confige.audioList["getBet"] = audio; }); cc.loader.loadRes("sound/new/soundNext",function(err, audio){ confige.audioList["soundNext"] = audio; }); cc.loader.loadRes("sound/new/soundTimeOut",function(err, audio){ confige.audioList["soundTimeOut"] = audio; }); }, });
const http = require('http'); const net = require('net'); const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer(); let requestCount = 0; const server = http.createServer((req, res) => { const requestToProxy = req; requestToProxy.headers.pprcount = requestCount; requestCount += 1; proxy.web(requestToProxy, res, { changeOrigin: true, prependPath: false, target: req.url, }); }); const port = 5060; server.on('connect', (req, socket) => { const parts = req.url.split(':', 2); // open a TCP connection to the remote host const conn = net.connect(parts[1], parts[0], () => { // respond to the client that the connection was made socket.write('HTTP/1.1 200 OK\r\n\r\n'); // create a tunnel between the two hosts socket.pipe(conn); conn.pipe(socket); }); }); server.listen(port); console.log(`listening on port ${port}`); // eslint-disable-line no-console module.exports.server = server; module.exports.proxy = proxy;
import {combineReducers} from 'redux'; import { GET_CATPRODUCTOS_SUCCESS, SAVE_CATPRODUCTOS_SUCCESS, DELETE_CATPRODUCTOS_SUCCESS, EDIT_CATPRODUCTOS_SUCCESS} from "../../actions/catalogos/catProductosActions"; function list(state=[], action){ switch(action.type){ case GET_CATPRODUCTOS_SUCCESS: return action.catalogoPro; case SAVE_CATPRODUCTOS_SUCCESS: return [...state, action.catalogoPro]; case EDIT_CATPRODUCTOS_SUCCESS: let newL = state.filter(a=>{ return a.id!=action.catalogoPro.id }); return [...newL, action.catalogoPro]; case DELETE_CATPRODUCTOS_SUCCESS: let acualL = state.filter(a=>{ return a.id!=action.catalogoProId; }); return acualL; default: return state; } } const catProductosReducer = combineReducers({ list:list, }); export default catProductosReducer;
import React, { Component } from 'react'; class Home extends Component { adv = { advOption: [ { id: 1, name: 'http://demo.posthemes.com/pos_organica/layout6/img/cms/cms_6.1.jpg' }, { id: 2, name: 'http://demo.posthemes.com/pos_organica/layout6/img/cms/cms_6.2.jpg' }, { id: 3, name: 'http://demo.posthemes.com/pos_organica/layout6/img/cms/cms_6.3.jpg' } ] } render() { const advertising =this.adv.advOption.map((item, index) => <li> <a href="javascript:void(0)"> <img src={item.name} alt="" /> </a> </li>); return ( <div className="banner-slide"> <ul className="box-col"> {advertising} </ul> </div> ); } } export default Home;
/* eslint-env node */ 'use strict'; function randomAmount() { return Math.round(Math.random()*5000); } function randomInt() { return Math.floor(Math.random() * 10); } function randomSuffix() { return new Array(4).fill(true).map(_ => randomInt()).join(''); } function randomDate() { let date = new Date() - (Math.random() * 1000*60*60*24*32); date = new Date(date); date.setUTCHours(Math.random() * 12 - 8); return date; } function makePayment(i) { return { id: String(i), capturedAt: randomDate(), amount: randomAmount(), paymentCard: `•••• •••• •••• ${randomSuffix()}` }; } const DB = new Array(50).fill(true) .map((_, i) => makePayment(i)) .sort((a, b) => b.capturedAt - a.capturedAt); module.exports = function(app) { const express = require('express'); let paymentsRouter = express.Router(); paymentsRouter.get('/', function(req, res) { res.send({ 'payments': DB }); }); paymentsRouter.post('/', function(req, res) { res.status(201).end(); }); paymentsRouter.get('/:id', function(req, res) { res.send({ 'payments': { id: req.params.id } }); }); paymentsRouter.put('/:id', function(req, res) { res.send({ 'payments': { id: req.params.id } }); }); paymentsRouter.delete('/:id', function(req, res) { res.status(204).end(); }); // The POST and PUT call will not contain a request body // because the body-parser is not included by default. // To use req.body, run: // npm install --save-dev body-parser // After installing, you need to `use` the body-parser for // this mock uncommenting the following line: // //app.use('/api/payments', require('body-parser').json()); app.use('/api/payments', paymentsRouter); };
'use strict'; var express = require('express'); var router = express.Router(); var models = require('../models'); var Page = models.Page; var User = models.User; router.get('/', function(req, res, next) { Page.findAll({ attributes: ['title', 'urlTitle'] }) .then(function(foundPage){ res.render('index', { pages: foundPage }); }) .catch(next); /******************************* throw new Error('Can\'t set headers after they are sent.'); means too many res.renders . ************************************/ }); router.post('/', function(req, res, next) { // res.json(req.body); var userid; User.findOne({ attributes: ['id'], where:{ email: req.body.email } }) .then(function success(foundUser){ if(foundUser != null){ userid = foundUser.id; } else { var user = User.build({ name: req.body.name, email: req.body.email }); user.save().catch(next); userid = user.id; } }, function failure(err){console.error(err);}); var page = Page.build({ title: req.body.title, content: req.body.content, status: req.body.status, authorid: userid }); page.save() .then(function(savedPage){ res.redirect(savedPage.route); // route virtual FTW }) .catch(next); }); router.get('/add', function(req, res, next) { res.render('addpage'); }); router.get('/:article', function(req, res, next){ var urlTitle = req.params.article; Page.findOne({ where: { urlTitle: urlTitle } }) .then(function(foundPage){ res.render('wikipage', { title: foundPage.title, content: foundPage.content }); }) .catch(next); }); module.exports = router;
export class AccorionConstructor { constructor(options) {} }
import React from 'react' import { Card, CardContent, CardMedia, Typography } from '@material-ui/core' import { useGlobalContext } from '../../../context/menu-context' import useStyles from './styles' export default function Category({ image, title }) { const classes = useStyles() const { selectedCategory, categoryClickHandler } = useGlobalContext() return ( <Card className={selectedCategory === title ? [classes.root, classes.active].join(' ') : classes.root} onClick={() => categoryClickHandler(title)}> <CardMedia className={classes.image} image={image} title='imag' /> <CardContent> <Typography variant="body2" component="p" align='center' style={{ textTransform: 'capitalize' }}> {title} </Typography> </CardContent > </Card > ) }
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ mangoHttpInterceptorFactory.$inject = ['MA_BASE_URL', 'MA_TIMEOUTS', '$q', '$injector']; function mangoHttpInterceptorFactory(mangoBaseUrl, MA_TIMEOUTS, $q, $injector) { /** * @ngdoc service * @name ngMangoServices.maHttpInterceptor * * @description Automatically prepends the base url onto the HTTP request's url, also augments HTTP error * responses with a human readable error message extracted from the response body, headers or generic status. */ class MangoHttpInterceptor { request(config) { if (this.isApiCall(config)) { config.url = mangoBaseUrl + config.url; } if (config.timeout == null) { config.timeout = MA_TIMEOUTS.xhr; } return config; } responseError(error) { // TODO error.xhrStatus abort might be a cancel, but could also be a timeout if (error.config && this.isApiCall(error.config) && !error.config.ignoreError && // ignoreError is set true by maWatchdog service (error.status < 0 && ['timeout', 'error'].includes(error.xhrStatus) || error.status === 401)) { $injector.get('maWatchdog').checkStatus(); } if (error.data instanceof Blob && error.data.type === 'application/json') { return $injector.get('maUtil').blobToJson(error.data).then(parsedData => { error.data = parsedData; return this.augmentError(error); }).catch(e => { return this.augmentError(error); }); } return this.augmentError(error); } augmentError(error) { let message = error.data && typeof error.data === 'object' && (error.data.message || error.data.localizedMessage); // TODO error.data.cause is now the only place containing the exception message, display this if it is available // try the 'errors' header if (!message) { message = error.headers('errors'); } // try the status text if (!message) { message = error.statusText; } // error.statusText is empty if its an XHR error if (!message && error.xhrStatus !== 'complete') { message = error.xhrStatus === 'abort' && this.safeTranslate('ui.app.xhrAborted', 'Request aborted') || error.xhrStatus === 'timeout' && this.safeTranslate('ui.app.xhrTimeout', 'Request timed out') || error.xhrStatus === 'error' && this.safeTranslate('ui.app.xhrError', 'Connection error'); } // fallback to generic description of HTTP error code if (!message) { message = this.safeTranslate(`rest.httpStatus.${error.status}`, `HTTP error ${error.status}`); } error.mangoStatusText = message; error.mangoStatusTextShort = message; if (error.status === 422) { let messages = []; if (error.data.result && Array.isArray(error.data.result.messages)) { messages = error.data.result.messages; } else if (Array.isArray(error.data.validationMessages)) { messages = error.data.validationMessages; } if (messages.length) { const firstMsg = messages[0]; let trKeyArgs; if (firstMsg.property) { trKeyArgs = ['ui.app.errorFirstValidationMsgWithProp', message, firstMsg.property, firstMsg.message]; } else { trKeyArgs = ['ui.app.errorFirstValidationMsg', message, firstMsg.message]; } error.mangoStatusTextFirstValidationMsg = firstMsg.message; error.mangoStatusText = this.safeTranslate(trKeyArgs, message); } } return $q.reject(error); } safeTranslate(key, fallback) { try { return $injector.get('maTranslate').trSync(key); } catch (e) { return fallback; } } isApiCall(config) { return String(config.url).startsWith('/'); } } const interceptor = new MangoHttpInterceptor(); return { request: interceptor.request.bind(interceptor), responseError: interceptor.responseError.bind(interceptor) }; } export default mangoHttpInterceptorFactory;
import React from "react"; import { useLocation } from "react-router-dom"; import styles from "./NoMatch.module.css"; function NoMatch() { let location = useLocation(); return ( <div className={styles.nomatch}> <b>No match for:</b> <code>{location.pathname}</code> </div> ); } export default NoMatch;
var messages = require('../config/messages'); module.exports = function (err, callback) { let ErrorMessage = ""; if (typeof err === 'string') { ErrorMessage = err; } else if (err.errors) { ErrorMessage = err.errors[Object.keys(err.errors)[0]].message; } else if (err.code) { ErrorMessage = messages.mongoErrCodes[err.code]; } else if (err.message) { ErrorMessage = err.message; } else if (err.isJoi) { ErrorMessage = err.details; } else { ErrorMessage = `New Error Code ${err.code}`; console.log(err); } var status = !!err ? (!!err.statusCode ? err.statusCode : 400) : 400; return callback({statusCode: status, message: ErrorMessage}); };
var cfg = require("../../utils/cfg.js"); var app = getApp() var that; let query= { uuid: "", cuser: "", checkres: 999999, time: "", done: 999999, page: 1, pagesize: 10, totalPage:1, begin:0, end:0 }; Page({ data: { tasks:[] }, getTasks: function () { var that=this wx.request({ url:cfg.getAPIURL()+"/api/projects/"+ that.data.taskid + "/task/reviews", method: "POST", header: app.globalData.header, data:{ uuid: query.uuid, username:that.data.username, checkuser: query.cuser, checkres: query.checkres, done: query.done, page: query.page, pagesize: query.pagesize, totalpage:query.totalPage, begin: query.begin, end: query.end }, success: function(response){ if(response.statusCode===200){ that.setData({ tasks: that.data.tasks.concat(response.data.tasks) }); query.totalpage=response.data.pager.totalPage query.page=response.data.pager.page query.pagesize=response.data.pager.pageSize } }, fail: function(response) { wx.showToast({ title: app.language('validator.taskfailture'), icon: "none", duration: 1500 }); } }); }, setLang() { const set = wx.T._ this.setData({ my_submission: set('my_submission'), }) }, onLoad: function (options) { this.data.taskid=options.taskid; this.data.username=options.username; query.page=1 this.getTasks(); wx.setNavigationBarTitle({ title: app.language('validator.tasktitle') }); var that=this wx.getStorage({ key: 'langIndex', success: res => { that.setData({ langIndex: res.data }) } }); this.setLang(); }, onPullDownRefresh: function () { wx.stopPullDownRefresh() }, onReachBottom: function () { if (query.page < query.totalpage) { query.page=query.page+1 this.getTasks() } else { wx.showToast({ title: app.language('validator.loadingfinish'), icon: "none", duration: 1500 }); } }, onShareAppMessage: function(res) { return { title: app.globalData.ShareAppTitle, desc: app.globalData.ShareAppDesc, path: "/pages/index/index" }; } });
import express from 'express'; import bodyParser from 'body-parser'; import dotenv from 'dotenv'; //importing the Routes import ridesRoute from './routes/rides'; // Configure dotenv dotenv.config() const app = express(); // App to Use these app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api/v1/rides', ridesRoute); const port = 3000 || process.env.PORT ; app.get('/', (req, res) => { res.status(200).json({ message: 'You reached my homepage successfully.' }); }); app.listen(port, () => { console.log(`App started on port ${port}`); }) export default app; // For testing purposes
import React, { useEffect, useState } from "react"; import Modal from '@material-ui/core/Modal'; import Input from '@material-ui/core/Input'; import Grid from '@material-ui/core/Grid'; import Alert from '@material-ui/lab/Alert'; import Button from '@material-ui/core/Button'; import TextField from "@material-ui/core/TextField"; import { useFirebase, useFirestore } from "react-redux-firebase"; import { useDispatch, useSelector } from "react-redux"; import { AppstoreAddOutlined } from "@ant-design/icons"; import { addNewTutorialStep, clearCreateTutorials, } from "../../../store/actions"; const AddNewStepModal = ({ viewModal, viewCallback, tutorial_id, steps_length, owner, }) => { const firebase = useFirebase(); const firestore = useFirestore(); const dispatch = useDispatch(); const [visible, setVisible] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const [title,setTitle]=useState(""); const [time,setTime]=useState(0); useEffect(() => { clearCreateTutorials()(dispatch); return () => { clearCreateTutorials()(dispatch); }; }, [dispatch]); const loadingProp = useSelector( ({ tutorials: { create: { loading }, }, }) => loading ); const errorProp = useSelector( ({ tutorials: { create: { error }, }, }) => error ); useEffect(() => { setLoading(loadingProp); }, [loadingProp]); useEffect(() => { setError(errorProp); }, [errorProp]); useEffect(() => { setVisible(viewModal); }, [viewModal]); useEffect(() => { if (loading === false && error === false) { setVisible(false); clearCreateTutorials()(dispatch); } }, [loading, error, dispatch]); const onSubmit = () => { const formData={ title, time } const set_data = { ...formData, id: `${tutorial_id}_${new Date().getTime()}`, tutorial_id, owner, }; addNewTutorialStep(set_data)(firebase, firestore, dispatch); }; const handleCancel = () => { setVisible(false); }; return ( <Modal title={`Add New Step`} open={visible} onClose={() => viewCallback()} onOk={() => viewCallback()} footer={false} destroyOnClose={true} maskClosable={false} style={{ display: "flex", alignItems: "center", justifyContent: "center", }} > <Grid style={{background:"white",padding:"2rem"}}> {error && ( <Alert message={""} description={"Tutorial Creation Failed"} type="error" closable className="mb-24" /> )} <form onSubmit={onSubmit} > <Input prefix={ <AppstoreAddOutlined style={{ color: "rgba(0,0,0,.25)" }} /> } onChange={e=>setTitle(e.target.value)} placeholder="Title of the Step" autoComplete="title" style={{marginBottom:"2rem"}} /> <TextField type="number" onChange={e=>setTime(e.target.value)} placeholder="Time (minutes)" style={{ width: "100%" }} /> <Button style={{marginTop:"2rem"}} variant="contained" color="secondary" key="back" onClick={handleCancel}> Cancel </Button> <Button style={{marginTop:"2rem"}} key="submit" type="primary" htmlType="submit" variant="contained" color="primary" loading={loading} > {loading ? "Creating..." : "Create"} </Button> </form> </Grid> </Modal> ); }; export default AddNewStepModal;
class Wall { constructor(x, y) { this.x = x; this.y = y; } } class Pairs { constructor(a, b, dist) { this.origin = a; this.destination = b; this.distance = dist; } } var cur_stat; var arrWall = new Array(); var intervalVisited; var intervalPath; var type = ""; var x_start = -1; var y_start = -1; var x_end = -1; var y_end = -1; var cost = []; var queue = []; var visited = []; var final_path = []; var visual_started = false; var hor_length = 55; var ver_length = 20; var move_comp = ""; function view_dropdown() { dropdown = document.getElementsByClassName("dropdown-menu")[0]; if (dropdown.style.display == "block") { dropdown.style.display = "none"; } else { dropdown.style.display = "block"; } } function close_tutorial(){ document.getElementById("tutorial-container").style.display = "none"; } //estrablishing functions and generating grid function generate() { renew_arrays(); stop_cycle(); visual_started = false; document.getElementById("board").innerHTML = ""; if (window.screen.availWidth < 600) { hor_length = 10; ver_length = 15; x_start = 2; y_start = 2; x_end = 8; y_end = 12; document.getElementById("scatter-btn").innerHTML = "Scatter Obstacles"; } //tablet potrait else if (window.screen.availWidth > 600 && window.screen.availWidth < 770) { hor_length = 21; ver_length = 20; x_start = 1; y_start = 1; x_end = 10; y_end = 10; } //desktop else { hor_length = 55; ver_length = 20; x_start = 12; y_start = 9; x_end = 42; y_end = 9; document.getElementById("scatter-btn").innerHTML = "Scatter Random Obstacles"; } for (i = 0; i < ver_length; i++) { var tag = document.createElement("tr"); tag.setAttribute("id", "row " + i); document.getElementById("board").appendChild(tag); for (j = 0; j < hor_length; j++) { var tag = document.createElement("td"); tag.setAttribute("class", "grid"); tag.setAttribute("id", i + "-" + j); tag.addEventListener("click", function () { cur_stat = this.id; coords = this.id.split("-"); y = parseInt(coords[0]); x = parseInt(coords[1]); if ( (this.className == "grid" || this.className == "grid-transition") && !visual_started && !move_comp ) { this.className = "wall"; arrWall.push(new Wall(x, y)); } else if ( (this.className == "grid" || this.className == "grid-transition") && !visual_started && move_comp != null ) { this.className = move_comp; if (move_comp == "start-node") { x_start = x; y_start = y; } else if (move_comp == "end-node") { x_end = x; y_end = y; } move_comp = ""; } else if (this.className == "wall" && !visual_started) { this.className = "grid"; for (var k = 0; k < arrWall.length; k++) { if (arrWall[k].x == x && arrWall[k].y == y) { arrWall.splice(k, 1); } } } else if (this.className == "start-node" && !visual_started) { if (move_comp == "end-node") alert("Place the target first!"); else { move_comp = "start-node"; this.className = "grid"; } } else if (this.className == "end-node" && !visual_started) { if (move_comp == "start-node") alert("Place the starting point first!"); else { move_comp = "end-node"; this.className = "grid"; } } }); tag.addEventListener("mousedown", function () { cur_stat = this.id; elem = document.getElementById(cur_stat); type = elem.className; }); tag.addEventListener("mouseenter", function () { if (mouseDown == true && !visual_started) { coords = this.id.split("-"); y = parseInt(coords[0]); x = parseInt(coords[1]); if (this.id != cur_stat) { if ( (this.className == "grid" || this.className == "grid-transition") && type != "start-node" && type != "end-node" ) { this.className = "wall"; arrWall.push(new Wall(x, y)); } else if (this.className == "wall") { this.className = "grid"; for (var k = 0; k < arrWall.length; k++) { if (arrWall[k].x == x && arrWall[k].y == y) { arrWall.splice(k, 1); } } } else if (type == "start-node") { if (x != x_end || y != y_end) { start = document.getElementById(y_start + "-" + x_start); start.setAttribute("class", "grid"); this.className = "start-node"; x_start = x; y_start = y; } } else if (type == "end-node") { if (x != x_start || y != y_start) { end = document.getElementById(y_end + "-" + x_end); end.setAttribute("class", "grid"); this.className = "end-node"; x_end = x; y_end = y; } } } cur_stat = this.id; } }); document.getElementById("row " + i).appendChild(tag); } } //initialize start start = document.getElementById(y_start + "-" + x_start); start.setAttribute("class", "start-node"); end = document.getElementById(y_end + "-" + x_end); end.setAttribute("class", "end-node"); initiate_matrix(); var mouseDown = false; body = document.getElementById("board"); body.addEventListener("mouseup", function () { mouseDown = false; cur_stat = null; type = null; }); body.addEventListener("mousedown", function () { mouseDown = true; }); } //matrix initiation function initiate_matrix() { for (var from = 0; from < hor_length * ver_length; from++) { cost.push([0]); for (var to = 0; to < hor_length * ver_length; to++) { //constituting the coordinates from index and the adjacent squares coor_x = from % hor_length; coor_y = Math.floor(from / hor_length); index_top = (coor_y - 1) * hor_length + coor_x; index_left = coor_y * hor_length + coor_x - 1; index_right = coor_y * hor_length + coor_x + 1; index_bottom = (coor_y + 1) * hor_length + coor_x; if (from == to) cost[from][to] = 0; else if (to == index_top && coor_y > 0) cost[from][to] = 1; else if (to == index_left && coor_x > 0) cost[from][to] = 1; else if (to == index_right && coor_x < (hor_length-1)) cost[from][to] = 1; else if (to == index_bottom && coor_y < (ver_length-1)) cost[from][to] = 1; else cost[from][to] = 999; } } } //reset function function reset_grid() { //stopping animation stop_cycle(); //renewing arrays renew_arrays(); //resetting board state grid = document.getElementById("board").getElementsByTagName("td"); for (var i = 0; i < grid.length; i++) { grid[i].setAttribute("class", "grid"); } start = document.getElementById(y_start + "-" + x_start); start.setAttribute("class", "start-node"); start = document.getElementById(y_end + "-" + x_end); start.setAttribute("class", "end-node"); //reinitiate matrix initiate_matrix(); //resetting visual state visual_started = false; } function renew_arrays() { queue = new Array(); arrWall = new Array(); visited = new Array(); cost = new Array(); final_path = new Array(); } function toggle_cycle() { cycle_view = document.getElementById("cycle_view"); if (cycle_view.style.display == "none") cycle_view.style.display = "block"; else cycle_view.style.display = "none"; } function stop_cycle() { if (intervalVisited) clearInterval(intervalVisited); if (intervalPath) clearInterval(intervalPath); } function scatter_wall() { if (!visual_started) { if (window.screen.availWidth < 600) { amount = 30; buffer = 0; } //tablet potrait else if (window.screen.availWidth > 600 && window.screen.availWidth < 770) { amount = 60; buffer = 2; } //desktop else { amount = 100; buffer = 3; } for (var i = 0; i < amount; i++) { cand_x = Math.floor(Math.random() * (hor_length - buffer * 2)) + buffer; cand_y = Math.floor(Math.random() * (ver_length - buffer * 2)) + buffer; cand = document.getElementById(cand_y + "-" + cand_x); if (cand.className != "start-node" && cand.className != "end-node") { cand.setAttribute("class", "wall"); arrWall.push(new Wall(cand_x, cand_y)); } } } else { alert("Clear board first!"); } } //establising walls in the matrix function establish_walls(arrWall, cost) { arrWall.forEach(function (item) { point = item.y * hor_length + item.x; index_top = (item.y - 1) * hor_length + item.x; index_left = item.y * hor_length + item.x - 1; index_right = item.y * hor_length + item.x + 1; index_bottom = (item.y + 1) * hor_length + item.x; //handles top row if (item.y > 0) { cost[point][index_top] = 999; cost[index_top][point] = 999; } //handles left side if (item.x > 0) { cost[point][index_left] = 999; cost[index_left][point] = 999; } //handles right side if (item.x < hor_length - 1) { cost[point][index_right] = 999; cost[index_right][point] = 999; } //handles bottom row if (item.y < ver_length - 1) { cost[point][index_bottom] = 999; cost[index_bottom][point] = 999; } }); } function trace_back(end_node, final_path) { traversed_node = end_node; while (traversed_node != start_node) { min_dist = 999; next_node = traversed_node; for (var i = visited.length - 1; i >= 0; i--) { if (visited[i].destination == traversed_node) { if (visited[i].distance < min_dist) { min_dist = visited[i].distance; next_node = visited[i].origin; } } } final_path.push(next_node); traversed_node = next_node; } } //// AI METHODS //visualize visited function visualize_visited(visited, final_path) { count = 0; timer = 1; if (window.screen.availWidth < 600) timer = 15; else timer = 1; intervalVisited = setInterval(function () { y_temp = Math.floor(visited[count].destination / hor_length); x_temp = visited[count].destination % hor_length; color_visited = document.getElementById(y_temp + "-" + x_temp); if ( color_visited.className != "start-node" && color_visited.className != "end-node" ) color_visited.setAttribute("class", "visited-node"); count++; if (count == visited.length) { clearInterval(intervalVisited); visualize_path(final_path); } }, timer); } //visualize final_path function visualize_path(final_path) { counter = 0; intervalPath = setInterval(() => { coor_x = final_path[counter] % hor_length; coor_y = Math.floor(final_path[counter] / hor_length); path_step = document.getElementById(coor_y + "-" + coor_x); if ( path_step.className != "start-node" && path_step.className != "end-node" ) path_step.setAttribute("class", "final-path"); counter++; if (counter == final_path.length) clearInterval(intervalPath); }, 30); } function dijkstra() { if (!visual_started) { //defining walls establish_walls(arrWall, cost); //disabling mouse actions visual_started = true; //initializing finish state start_node = y_start * hor_length + x_start; end_node = y_end * hor_length + x_end; active_node = start_node; cur_cost = 0; queue.push(new Pairs(active_node, active_node, 0)); while (active_node != end_node) { //searching neighbors and establishing queues for (var i = 0; i < cost.length; i++) { if (cost[active_node][i] != 0 && cost[active_node][i] != 999) { // checking if already visited already_visited = false; for (var j = 0; j < visited.length; j++) { if (visited[j].origin == i) { already_visited = true; break; } } if (!already_visited) { //checking if already queued already_queued = false; perceived_distance = cost[active_node][i] + cur_cost; for (var j = 0; j < queue.length; j++) { if (queue[j].destination == i) { if (queue[j].distance > perceived_distance) { queue.splice(j, 1); } else { already_queued = true; } break; } } if (!already_queued) { queue.push(new Pairs(active_node, i, perceived_distance)); } } } } //sorting the queue sorted = true; do { sorted = true; for (var i = 0; i < queue.length - 1; i++) { if (queue[i].distance > queue[i + 1].distance) { temp = queue[i]; queue[i] = queue[i + 1]; queue[i + 1] = temp; sorted = false; } } } while (!sorted); visited.push(queue[0]); // y_temp = Math.floor(queue[0].destination / 55); // x_temp = queue[0].destination % 55; // color_visited = document.getElementById(y_temp + "-" + x_temp); // if (color_visited.className != "start-node") // color_visited.setAttribute("class", "visited-node"); queue.splice(0, 1); try { active_node = queue[0].destination; cur_cost = queue[0].distance; } catch (error) { alert("Path not found! Clear board to restart!"); break; } } //end node visited.push(queue[0]); final_path = []; final_path.push(end_node); //tracing the path trace_back(end_node, final_path); //visualization visualize_visited(visited, final_path); } }
var path = require("path"); module.exports = function(app) { app.get("/", function(req, res) { res.sendFile(path.join(__dirname, "../public/signup.html")); }); app.get("/login", function(req, res){ res.sendFile(path.join(__dirname, "../public/login.html")); }) app.get("/main", function(req, res){ res.sendFile(path.join(__dirname, "../public/main.html")); }) app.get("/whims", function(req, res){ res.sendFile(path.join(__dirname, "../public/whims.html")); }) // will contain posts for specific category app.get("/category/:id", function(req, res) { console.log('/category/:id'); res.sendFile(path.join(__dirname, "../public/main.html")); }); app.get("/post/:id", function(req, res) { console.log('/post/:id'); res.sendFile(path.join(__dirname, "")); }); app.get("/contact", function(req, res){ res.sendFile(path.join(__dirname, "../public/contact.html")); }) app.get("/about", function(req, res){ res.sendFile(path.join(__dirname, "../public/about.html")); }) app.get("/whim/:id",function(req, res) { res.sendFile(path.join(__dirname, "../public/whim.html")); }) };
// CLOSEST IS USED TO WORK WITH THE CLOSEST ELEMENT OF AN ELEMENT let btn = document.querySelector('.btn') btn.addEventListener('click',event=>{ //console.log(event.target) // IF YOU WILL DO THIS THEN IT WILL SHOW BUTTON OR MAIN2 let close = event.target.closest('.main2') console.log(close) // NOW IT WILL ONLY SHOW .main2 })
define([ "backbone", "modules/note/notes-nav" ], function (Backbone, NotesNav) { "use strict"; var Player = Backbone.View.extend({ _timeout: null, _currentNote: 0, repeat: true, initialize: function (options) { this._song = options.song; this.notesNav = new NotesNav({model: this._song}); $("#a-eduStart").on("click", this.play); $("#a-shuffleNotes").on("click", this.shuffle); this.render(); }, render: function () { $("#mainContent").prepend(this.notesNav.render().el); this.notesNav.showFirstNote(); }, shuffle: function () { this.pause(); var shuffleNotesSong = this._song.shuffle(); this._song.reset(); this._song.add(shuffleNotesSong); this._song.trigger("song:shuffle"); return false; }, getCurrentNote: function () { if (this.repeat) { } return this._currentNote; }, play: function () { if (this._lengthSong == this._currentNote) { this._currentNote = 0; } var self = this; this._timeout = setTimeout(function () { self.notesNav.showNoteByIndex(self._currentNote); self._currentNote += 1; self.play(); }, 3000); }, pause: function () { if (this._timeout !== null) { clearTimeout(this._timeout); } }, setSong: function (newSong) { this._song = newSong; } }); return Player; });
const MockApp = require('../../nodeMock/app'); class MockUtil{ async setMockResponse(method, endpoint, callback) { await MockApp.stopServer(); if (method === 'GET') { await MockApp.onGet(endpoint, callback); } if (method === 'POST') { await MockApp.onPost(endpoint, callback); } if (method === 'PUT') { await MockApp.onPut(endpoint, callback); } await MockApp.startServer(); } getMockApp(){ return MockApp; } async resetMock() { //const scenarioId = await MockApp.browserScenarioCookieCallback(); //MockApp.initScenarioSession(scenarioId); await MockApp.stopServer(); MockApp.init(); await MockApp.startServer(); } async start() { await MockApp.startServer(); } async stop() { await MockApp.stopServer(); } } module.exports = new MockUtil();