text
stringlengths
7
3.69M
var async = require('async'), AdmZip = require('adm-zip'), fstream = require('fstream'), mime = require('mime'), path = require('path'), fs = require('fs'), out = require('out'), config = require('./config.json'), spawn = require('child_process').spawn, handlebars = require('handlebars'), commandExt = process.platform == 'win32' ? '.bat' : '', devToolsPath = path.resolve(config.webworksPath, 'dependencies', 'tools', 'bin'), reIgnoreFiles = /^(\.git|node_modules|Jakefile|\.DS_Store|template|output|lib|package.json)/, ignoreExtensions = ['.DS_Store', '.bar', '.zip'], procOpts = { detached: true, stdio: 'inherit' }, reIsText = /^(text\/|application\/(json|xml|javascript))/i, projectFiles = []; // default the projectname if not set config.projectName = config.projectName || path.basename(__dirname); // add the projectname to the app if (config.app) { config.app.projectName = config.app.projectName || config.projectName; } // discover the nature of the project through task('discovery', { async: true }, function() { var reader = fstream.Reader({ path: __dirname, filter: function(entry) { var testPath = entry.path.slice(__dirname.length + 1), shouldIgnore = reIgnoreFiles.test(testPath); return ! (shouldIgnore || ignoreExtensions.indexOf(path.extname(entry.path)) >= 0); } }); reader.on('child', function(entry) { if (entry.type === 'File') { projectFiles.push(entry.path); } }); reader.on('end', complete); out('!{bold}analyzing project structure'); }); task('package', ['discovery'], { async: true }, function() { var targetFile = path.join('output', config.projectName + '.zip'), basePath = path.resolve(__dirname), args = [targetFile], relativeFiles, proc; relativeFiles = projectFiles.map(function(filename) { return filename.slice(basePath.length + 1); }); console.log(args.concat(relativeFiles)); proc = spawn('zip', args.concat(relativeFiles), { cwd: path.resolve(__dirname) }); proc.stdout.on('data', function(buffer) { console.log(buffer.toString()); }); proc.on('exit', function(code) { out('!{bold}zip completed with exit code: ' + code); complete(); }); out('!{bold}creating archive'); }); task('build', ['package'], { async: true }, function() { var args = [ path.resolve(__dirname, 'output', config.projectName + '.zip'), '-o', path.resolve('output') ]; if (config.signingPass) { args = args.concat(['-g', config.signingPass]); } else { args.push('-d'); } out('!{bold}building bar file'); spawn( path.resolve(config.webworksPath, 'bbwp' + commandExt), args, procOpts ).on('exit', complete); }); task('push', { async: true }, function() { var args = [ '-installApp', // '-launchApp', '-password', config.devicePass, '-device', config.deviceIP, path.resolve(__dirname, 'output', 'device', config.projectName + '.bar') ], proc = spawn(path.resolve(devToolsPath, 'blackberry-deploy' + commandExt), args, procOpts); out('!{bold}pushing to the device'); proc.on('exit', complete); }); task('default', ['build']);
angular .module('Board', []) .factory('Board', Board); function Board(Field, Pin) { class Board { constructor() { this.fields = []; this.pins = []; } init() { this.fields = this._generateFields(); return this; } initFromPlainFieldsObjects(objectsArray) { this.fields = this._generateFieldsFromObjects(objectsArray); return this; } /** * WHITES always starts from 1. * If you're WHITE!!!, your rendering engine will rotate board. * This way only 1 view of the board needs to be persisted, and GameMaster can make decisions, * based on field numbers and player color. */ _generateFields() { var fields = []; for (var fieldNumber = 1; fieldNumber <= 64; fieldNumber++) { var field = new Field(fieldNumber); this._addPinToFieldWhenNeeded(field); fields.push(field); } return fields; } _generateFieldsFromObjects(objectsArray) { var fields = []; for (var i = 0; i < objectsArray.length; i++) { var json = objectsArray[i]; var field = Field.fromPlainObject(json); fields.push(field); } return fields; } _addPinToFieldWhenNeeded(field) { if (field.color === 'black') { // PLAYER 1 fields if (field.number >= 41) { this._addPinToField(field, 'black'); } // PLAYER 2 fields if (field.number <= 24) { this._addPinToField(field, 'white'); } } } movePinToField(pin, targetField) { var baseField = this.getFieldByPin(pin); baseField.removePin(); targetField.setPin(pin); return targetField; } getFieldByPin(pin) { return this.fields.filter(function (field) { if (field.hasPin()) { return field.pin.id === pin.id; } else { return false; } })[0]; } _addPinToField(field, color) { var pin = new Pin(color, this.pins.length); field.setPin(pin); this.pins.push(pin); } toPlainObject() { var plainFieldObjects = []; for (var i = 0; i < this.fields.length; i++) { var nativeField = this.fields[i]; plainFieldObjects.push(nativeField.toPlainObject()); } return { fields: plainFieldObjects } } getFieldAtPosition(rowNumber, columnNumber) { return this.fields.filter(function(field) { return this._isFieldAtPosition(field, rowNumber, columnNumber); }, this)[0]; } _isFieldAtPosition(field, rowNumber, columnNumber) { return (field.rowNumber === rowNumber) && (field.columnNumber === columnNumber) } } return Board; }
// eslint-disable-next-line import/prefer-default-export export const Resume = '/carney-resume.pdf';
import React, { useContext, useEffect } from 'react'; import UserItem from './UserItem'; import Spinner from '../layout/Spinner'; import GithubContext from '../../context/github/githubContext'; const Users = () => { const githubContext = useContext(GithubContext) const { loading, users, getUsers} = githubContext; async function fetchData() { getUsers(); } useEffect(() => { if(users.length === 0){ fetchData() } }, []); if (loading) { return <Spinner />; } else { return ( <div style={cardContainerStyle}> <div className="grid-3"> {users.map(user => ( <UserItem key={user.id} user={user} /> ))} </div> </div> ); } }; // for setting mobile height of card container const containerHeight = window.innerWidth < 480 ? '40vh' : '70vh'; const cardContainerStyle = { paddingRight: '.1rem', marginTop: '.7rem', overflowY: 'auto', height: containerHeight }; export default Users;
/* eslint-disable no-param-reassign */ import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { calendar: null, socket: null, dailycasenumber: [], }, mutations: { // sync toggleDay(state, data) { // console.log("Something is wrong!") state.calendar.calendar[data.personkey].days[data.toggleevent.index].work = !data.toggleevent.item.work; state.socket.emit('updateCalendar', state.calendar); }, getDailyCaseNumber(state, number){ state.dailycasenumber = number; } }, actions: { // async toggleWork({ commit }, data) { commit('toggleDay', data); }, }, }); export default store;
/** * Title: Discussion Board 1.1 * Author: Nathaniel Liebhart * Date: August 6th, 2019 * Description: This is an example of a constructor prototype. */ // Create an empty constructor function function Employee() {} // Add property name, position, hire date to the prototype property of the Employee constructor function Employee.prototype.name = "John Doe"; Employee.prototype.position = "Software Engineer"; Employee.prototype.hireDate = "05/12/2005"; Employee.prototype.empSince = function() { let hYear = this.hireDate.substr(6, 9); let d = new Date(); let cYear = d.getFullYear(); let service = cYear - hYear; return service; }; // Create an object using the Employee constructor function const john = new Employee(); // Print a message to the console with the employees name, position and years of service console.log( `${john.name} has been a ${john["position"]} for ${john.empSince()} years.` );
const mongoose = require('mongoose'); const Blog = require('../model/blog'); const createBlog = async (req, res, next) => { const params = { title: req.body.title, content: req.body.content, } const result = await Blog.create(params); res.status(200).json(result); } const listBlog = async (req, res, next) => { const result = await Blog.find(); res.status(200).json(result); } module.exports = { createBlog, listBlog }
Ext.namespace('Ext.Syis.lib'); Ext.Syis.lib.SyisInputPanel = Ext.extend(Ext.Panel, { keyField : null, headFormTitle : null, headFormTbar : null, headItems : null, listFormTitle : null, listItems : null, listGridTitle : null, gridColumnModel : null, gridStore : null, formHeight : null, constructor : function(_config) { Ext.QuickTips.init(); if (_config == null) { _config = {}; }; Ext.apply(this, _config); var me = this; // 表头信息 this.head_form = new Ext.form.FormPanel({ labelAlign : 'right', labelWidth : 80, frame : true, labelSeparator : ':', border : false, title : me.headFormTitle ? me.headFormTitle : '表头信息', autoHeight : true, iconCls :'btn-form', style : 'border-bottom:1px solid #99BBE8;', bodyStyle : 'padding:5px 0px 0px 10px;background-color:#DFE8F6', defaults : { baseCls : 'x-plain' }, items : me.headItems }); // 表体信息 this.list_form = new Ext.form.FormPanel({ labelAlign : 'right', labelWidth : 80, frame : true, labelSeparator : ':', border : false, title : me.listFormTitle ? me.listFormTitle : '货物信息', autoHeight : true, iconCls : 'btn-form', style : 'border-bottom:1px solid #99BBE8;', bodyStyle : 'padding:5px 0px 0px 10px;background-color:#DFE8F6', defaults : { baseCls : 'x-plain' }, items : me.listItems }); this.head_panel = new Ext.Panel({ region : 'north', header : false, border : false, layout : 'fit', height : me.formHeight ? me.formHeight : (Ext.isIE ? 400 : 370), tbar: me.headFormTbar, items : [this.head_form, this.list_form] }); me.selectionModel = new Ext.grid.RowSelectionModel({ singleSelect : true, listeners : { rowselect : function(sm, rowIndex, record){ me.list_form.getForm().loadRecord(record); } } }); // 表体列表 this.list_grid = new Ext.grid.GridPanel({ sm : me.selectionModel, cm : me.gridColumnModel, iconCls : 'btn-form', stripeRows : true, region : 'center', border : false, autoScroll: true, viewConfig : { scrollOffset : -3, forceFit : true }, store : me.gridStore, loadMask : { msg : '正在加载...' } }); Ext.Syis.lib.SyisInputPanel.superclass.constructor.call(this, { layout : 'border', items : [ this.head_panel, this.list_grid ], height: Ext.getCmp('frmPanel').getInnerHeight() - (this.win != null ? 32 : 0) }); this.initHandler(); }, // 得到表头form getHeadForm : function(){ return this.head_form; }, // 得到表体form getListForm : function(){ return this.list_form; }, // 给列表添加删除数据功能 gridAddListener : function(){ var me = this; this.list_grid.addListener('rowcontextmenu', function(grid, index, e){ e.preventDefault(); if(index < 0) { return; } var rightMenu = new Ext.menu.Menu([{ text : '删除', pressed : true, handler : function(){ var record = grid.getStore().getAt(index); grid.getStore().remove(record); for(var j = 0; j < grid.getStore().getCount(); j++){ grid.getStore().getAt(j).set('index', j); } me.list_form.getForm().reset(); } }]); rightMenu.showAt(e.getPoint()); }, this); }, // 初始化处理 initHandler : function(){ var tf = this.head_form.findByType('textfield'); for(var i = 0; i < tf.length; i++){ if(tf[i].originReadOnly){ tf[i].setReadOnly(true); } } /*if(entType == 1){ this.head_panel.find('name', 'declareCode')[0].setValue(entCode); this.head_panel.find('name', 'declareName')[0].setValue(entCnName); }*/ this.gridAddListener(); }, // 加载出库单表头表体信息 syisLoadDetail : function(loadURL, params){ var me = this; if(params){ Ext.Ajax.request({ url : loadURL, params : params, success : function(response, opts){ var result = Ext.decode(response.responseText); if(result.success == false){ Ext.Msg.alert('错误', result.error); return; } var result_head = result.data; if(result_head){ me.head_form.getForm().loadRecord({data : result_head}); } me.list_grid.getStore().load({ params : params }); me.delcareHandler(result_head.billStatus); }, failure : function(response, opts){ Ext.Msg.alert('提示','发生错误,操作失败!'); } }); } }, // 新增操作:清空各个字段及表体列表 syisNewBill : function(){ var me = this; me.head_form.getForm().reset(); me.list_form.getForm().reset(); me.list_grid.getStore().removeAll(); me.list_grid.enable(); me.gridAddListener(); if(Ext.getCmp('headSave')){ Ext.getCmp('headSave').enable(); } if(Ext.getCmp('headDeclare')){ Ext.getCmp('headDeclare').enable(); } if(Ext.getCmp('headDelete')){ Ext.getCmp('headDelete').enable(); } var head_tf = this.head_form.findByType('textfield'); for(var i = 0; i < head_tf.length; i++){ if(!head_tf[i].originReadOnly){ head_tf[i].setReadOnly(false); } } var list_tf = this.list_form.findByType('textfield'); for(var i = 0; i < list_tf.length; i++){ if(!list_tf[i].originReadOnly){ list_tf[i].setReadOnly(false); } } }, // 暂存操作:保存表头、表体信息 syisHeadSave : function(saveURL, saveParams, successFunction){ var me = this; if(!saveURL || !saveParams || !successFunction){ return; } if(me.getHeadForm().getForm().isValid()){ Ext.Ajax.request({ url : saveURL, params : saveParams, success : function(response, opts){ var result = Ext.decode(response.responseText); if(result.success == false){ Ext.Msg.alert('错误', result.error); return; } Ext.Msg.alert('提示', '暂存成功!', successFunction(response)); }, failure : function(response, opts){ Ext.Msg.alert('提示','发生错误,操作失败!'); } }); } }, // 申报操作:向海关端申报当前表单 syisHeadDeclare : function(declareURL, params, successFunction){ var me = this; if(!declareURL || !params || !successFunction){ return; } if(me.getHeadForm().getForm().isValid()){ Ext.Ajax.request({ url : declareURL, params : params, success : function(response, opts){ var result = Ext.decode(response.responseText); if(result.success == false){ Ext.Msg.alert('错误', result.error); return; } Ext.Msg.alert('提示', '申报成功!', successFunction(response)); }, failure : function(response, opts){ Ext.Msg.alert('提示','发生错误,操作失败!'); } }); } }, // 删除操作:删除当前表单数据 syisHeadDelete : function(deleteURL, type){ var me = this; var uniqueId = me.head_form.find('name', me.keyField)[0].getValue(); if(!uniqueId){ Ext.Msg.alert('提示', '没有可供删除的数据!'); return; } if(!deleteURL){ return; } Ext.Msg.confirm('提示', "您确定要删除[" + (type == 'inbill' ? '入' : '出') + "库单号:" + uniqueId + "]这条记录吗?", function(btn){ if(btn == 'no') { return; } Ext.Ajax.request({ url : deleteURL, params : { 'billNo' : uniqueId }, success : function(response, opts){ var result = Ext.decode(response.responseText); if(result.success == false){ Ext.Msg.alert('错误', result.error); return; } Ext.Msg.alert('提示', '删除成功!', function(){ if(Ext.getCmp('syisbillWin') && Ext.getCmp('syisbillQuery')){ Ext.getCmp('syisbillWin').close(); Ext.getCmp('syisbillQuery').doQuery(); } else { me.syisNewBill(); } }); }, failure : function(response, opts){ Ext.Msg.alert('提示','发生错误,操作失败!'); } }); }); }, // 打印操作 : 打印表头、表体信息 syisPrint : function(printURL){ var uniqueId = this.head_form.find('name', this.keyField)[0].getValue(); if(!uniqueId){ Ext.Msg.alert('提示', '没有可供打印的数据!'); return; } window.open(printURL + '?billNo=' + uniqueId); }, // 生成表头表体json格式的string字符串 buildJsonString : function(headName, listName){ var me = this; var head_form = me.head_form.getForm(); var list_form = me.list_form.getForm(); var billHead = headName + ':' + Ext.encode(head_form.getValues()) + ''; var list = ''; for(var i = 0; i < me.list_grid.getStore().getCount(); i++){ list += Ext.encode(me.list_grid.getStore().getAt(i).data)+',' } var billList = listName + ':[' + list.substring(0,list.length-1) +']'; return '{' + billHead + ',' + billList + '}'; }, // 表体添加临时数据 handleEnter : function(){ if(this.list_form.getForm().isValid()){ var grid_Record = Ext.data.Record.create(['billNo','gname','gmodel','packNum']); var record = new grid_Record(this.list_form.getForm().getValues()); if(this.list_form.find('name', 'country')[0]){ record.set('countryText', this.list_form.find('name', 'country')[0].getRawValue()); } if(this.list_form.find('name', 'unit')[0]){ if(this.list_form.find('name', 'unit')[0].hidden == false){ record.set('unitText', this.list_form.find('name', 'unit')[0].getRawValue()); } } if(this.list_form.find('name', 'logisticsStatus')[0]){ record.set('logisticsStatusText', this.list_form.find('name', 'logisticsStatus')[0].getRawValue()); } if(this.list_form.find('name', 'currency')[0]){ record.set('currencyText', this.list_form.find('name', 'currency')[0].getRawValue()); } var selected = this.list_grid.getSelectionModel().getSelected(); var recIndex = this.list_grid.getStore().indexOf(selected); if(selected){ this.list_grid.getStore().remove(selected); } if(recIndex != 'undefined' && recIndex >= 0){ this.list_grid.getStore().insert(recIndex, record); //this.list_grid.getSelectionModel().selectRow(recIndex); } else { this.list_grid.getStore().add(record); } this.list_form.getForm().reset(); for(var j = 0; j < this.list_grid.getStore().getCount(); j++){ this.list_grid.getStore().getAt(j).set('index', j); } // 光标停留在第一个可输入框中 var textFields = this.list_form.findByType('textfield'); for(var i = 0; i < textFields.length; i++){ if(textFields[i].readOnly == false){ textFields[i].focus(); break; } } } }, // 选择海关代码反填海关名称 getCustomsName : function(){ if(this.head_panel.find('name', 'customsCode')[0].isValid()){ if(!this.head_panel.find('name', 'customsCode')[0].getValue()){ this.head_panel.find('name', 'customsName')[0].setRawValue(''); return; } var customsCode = this.head_panel.find('name', 'customsCode')[0].getValue(); var params = {'paraName' : 'customsCode'}; Ext.Ajax.request({ url : 'parameter/queryParametes', params : params, success : function(response){ responseJson = Ext.util.JSON.decode(response.responseText); if(responseJson.success){ var data = responseJson.data; if(data.length > 0){ var flag = true; for(var i = 0; i < data.length; i++){ if(data[i].code == customsCode){ flag = false; this.head_panel.find('name', 'customsName')[0].setValue(data[i].name); } } if(flag){ Ext.Msg.alert("提示", "查无此申报海关"); this.head_panel.find('name', 'customsName')[0].setRawValue(''); } }else{ Ext.Msg.alert("提示", "查无此申报海关"); this.head_panel.find('name', 'customsName')[0].setRawValue(''); } } }, failure : function(response) { Ext.Msg.alert("提示", "请求失败"); this.head_panel.find('name', 'customsName')[0].setRawValue(''); }, scope : this }); }else{ this.head_panel.find('name', 'customsName')[0].setRawValue(''); } }, fieldCombo : function(field1, field2, allowBlank){ if(allowBlank == false){ field1.allowBlank = allowBlank; field1.updateStyle(); field1.clearInvalid(); field2.allowBlank = allowBlank; field2.updateStyle(); field2.clearInvalid(); } if(allowBlank && field1.getValue() == '' && field2.getValue() == ''){ field1.allowBlank = allowBlank; field1.updateStyle(); field1.clearInvalid(); field2.allowBlank = allowBlank; field2.updateStyle(); field2.clearInvalid(); } } });
import React from 'react'; //import LikePart from './like-part' import PhotoService from '../../../photo-service/photo-service' import './image-item.css'; export default class ImageItem extends React.Component { photoServise = new PhotoService(); _arr = [false, false, false, false, false]; state = { numberPictures: 5, likes: null, data: null }; componentDidMount() { this.photoServise.getImages(1,this.state.numberPictures) .then((result) => { this.setState({ likes: this._arr, data: result }) }); }; componentDidUpdate(prevState) { if(this.state.numberPictures !== prevState.numberPictures){ this.photoServise.getImages(1,this.state.numberPictures).then((result) => { this.setState(() => { return { data: result } }); }); } } addImage = () => { this.setState(prevState => ({ numberPictures: prevState.numberPictures + 5, likes: [...prevState.likes, ...this._arr] })); }; likeAdd = (id) => { const { likes } = this.state; const result = likes.map((item, index) => { if (index === id){ return item = !item; } else { return item } }); this.setState(() => { return { likes: result } }); }; filterLike = () =>{ const { likes, data } = this.state; debugger let d = [...data]; let newData = []; for(let i = 0; i < likes.length; i++){ if(likes[i]){ newData = [...newData, d[i]]; }; }; this.setState({ data: newData }); }; render(){ const { data, likes } = this.state; if( !data ){ return null; } const items = data.map(({id, download_url, author, likeID}) => { return( <div className="card-image" key={id}> <a href={download_url}> <img className="img-content" src={download_url} alt={author}/> </a> <span className="card-title">{ author }</span> <div > <div className="likeContainer"> <button className="likeButton" onClick={ () => this.likeAdd(likeID) }>LIKE</button> <span>{ Number( likes[likeID] ) }</span> </div> </div> </div> ); }); return( <div> <div> <button onClick={ this.filterLike } className="image-btn">Liked Image</button> </div> <div className="img-container"> { items } </div> <div> <button onClick={ this.addImage } className="image-btn">add more images</button> </div> </div> ); }; };
import "bootstrap/dist/css/bootstrap.min.css"; import React from "react"; import Detector from "./components/Detector/Detector"; import FooterPage from "./components/Footer/FooterPage"; import IntroView from "./components/IntroView/IntroView"; import "./App.css"; import { Route } from "react-router-dom"; function App() { return ( <div className="App"> <div className="content-wrap"> <Route path="/" exact component={IntroView} /> <Route path="/detector" component={Detector} /> </div> <FooterPage /> </div> ); } export default App;
import $ from 'jquery'; import RevealOnScroll from './modules/RevealOnScroll'; import StickyHeader from './modules/StickyHeader'; import Menu from './modules/Menu'; import Sliders from './modules/Slider'; import Interactions from './modules/Interactions'; new RevealOnScroll($(".secondpage"), "85%"); new RevealOnScroll($(".thirdpage"), "85%"); const stickyHeader = new StickyHeader(); const menu = new Menu(); const sliders = new Sliders(); const interactions = new Interactions();
import React from 'react'; import Button from '../button/button.jsx'; import { withRouter } from 'react-router'; import appStore from '../../stores/appStore'; import { events } from '../../js/consts'; class Bar extends React.Component { constructor(props, context) { super(props, context); this.state = this.getState(); this.onRefreshClick = this.onRefreshClick.bind(this); this.onStoreChange = this.onStoreChange.bind(this); appStore.on(events.CHANGE, this.onStoreChange); } componentWillUnmount() { appStore.off(events.CHANGE, this.onStoreChange); } onRefreshClick(evt) { var pageInfo = appStore.getCurrentPageInfo(); this.props.router.replace(pageInfo.path); } onStoreChange() { this.setState(this.getState()); } getState() { var pageInfo = appStore.getCurrentPageInfo(); return { pageName: pageInfo.name }; } render() { var buttons = []; buttons.push( <Button className="button_round button_action" key="new" icon="pencil-white" title="New message"/> ); if (this.state.pageName == "message") { buttons.push( <Button className="button_round" key="reply" icon="docs" title="Reply"/> ); buttons.push( <Button className="button_round" key="replyAll" icon="docs2" title="Reply all"/> ); buttons.push( <Button className="button_round" key="trash" icon="trash" title="Move to trash"/> ); } buttons.push( <Button className="button_round" key="refresh" icon="refresh" title="Refresh" onClick={this.onRefreshClick}/> ); return ( <div className="bar"> {buttons} </div> ); } }; export default withRouter(Bar);
import styles from "./Header.module.scss"; import logo from "./../../assets/pngegg.png"; import Navbar from "../Navbar/Navbar"; function Header() { return ( <header className={styles.container}> <div className={styles.container__logo}> <img src={logo} className={styles.container__img} alt="Teemates logo" /> <h1>Teemates</h1> </div> <Navbar /> </header> ); } export default Header;
import React, { useEffect, useContext } from 'react'; import {Context} from '../Store'; import { Button } from 'antd'; function Login() { const [state, dispatch] = useContext(Context); console.log('state', state); useEffect(() => { dispatch({type: 'SET_POSTS', payload: [{id: 1, name: 'Aslam'}]}); }); return ( <div className="App"> <div>Login</div> <Button type="primary">Button</Button> </div> ); } export default Login;
// @ts-check import _ from 'lodash'; import { combineReducers } from 'redux'; const comments = (state = {}, action) => { // BEGIN (write your solution here) switch (action.type) { case 'TASK_COMMENT_ADD': return { [action.payload.comment.id]: action.payload.comment, ...state }; case 'TASK_COMMENT_REMOVE': return _.omit (state, action.payload.id); case 'TASK_REMOVE': return _.omitBy(state, x=>x.taskId === action.payload.id); default: // действие по умолчанию – возврат текущего состояния return state; } // END }; const tasks = (state = {}, action) => { // BEGIN (write your solution here) switch (action.type) { case 'TASK_ADD': return { [action.payload.task.id]: action.payload.task, ...state }; case 'TASK_REMOVE': return _.omit (state, action.payload.id); default: // действие по умолчанию – возврат текущего состояния return state; } // END }; export default combineReducers({ comments, tasks, });
import Title from './component'; export default Title;
/** * @author a */ /* title - slide */ var title_cnt = 1; var title_length = $(".move-title").find(".title").length; var move_flag = false; var current_value = 0;http://127.0.0.1:8020/hyunum/img/main-gal/g_02.png function get_title_cnt() {http://127.0.0.1:8020/hyunum/img/main-gal/g_02.png return title_cnt; }; function get_title_length() { return title_length; } function move_title(type,move_speed) { if (move_flag == false) { move_flag = true; if(type == "left") { if (title_cnt < title_length) { $(".move-title").animate({ left: "-="+move_speed+"", opacity: 0.5 }, 1000); $(".move-title").animate({ opacity: 1 }, 1000); remove_motion(title_cnt); title_cnt++;http://127.0.0.1:8020/hyunum/img/main-gal/g_01.png item_motion(title_cnt);http://127.0.0.1:8020/hyunum/img/icon/icon_left.png setTimeout(function() { move_flag = false; } , 2000); } else if( title_cnt == title_length ) { $(".move-title").animate({ left: "+="+ move_speed * (title_length - 1) +"", opacity: 0.5 }, 1000); $(".move-title").animate({ opacity: 1 }, 1000); remove_motion(title_cnt); title_cnt = 1; item_motion(title_cnt); setTimeout(function() { move_flag = false; } , 2000); } } else if(type == "right") { if (title_cnt > 1) { $(".move-title").animate({ left: "+="+move_speed+"", opacity: 0.5 }, 1000); $(".move-title").animate({ opacity: 1 }, 1000); remove_motion(title_cnt); title_cnt--; item_motion(title_cnt); setTimeout(function() { move_flag = false; } , 2000); } else if(title_cnt == 1 ) { $(".move-title").animate({ left: "-="+ move_speed * (title_length - 1) +"", opacity: 0.5 }, 1000); $(".move-title").animate({ opacity: 1 }, 1000); remove_motion(title_cnt); title_cnt = title_length; item_motion(title_cnt); setTimeout(function() { move_flag = false; } , 2000); } } } } function item_motion(title_cnt) { if (title_cnt == 1) { $(".item1").animate({ "top": "36%" , "left": "57%", opacity: 1 }, 4000); $(".item2").animate({ "top": "20%" , "left": "20%" }, 2000); $(".item3").animate({ "top": "35%", "left": "20%" }, 1500); } else if (title_cnt == 2) { $(".item4").animate({ "top": "20%", "left": "25%" }, 2000); $(".item5").animate({ "top": "30%", "left": "25%" }, 1500); $(".item6").animate({ "top": "40%", "left": "25%" }, 1000); $(".item7").show("scale" , 2000); $(".item8").animate({ "top": "52%" }, 3000); } else if (title_cnt == 3) { $(".item9").animate({ "left": "60%", "top": "37%" }, 2000); $(".item10").animate({ "left": "60%", "top": "55%" }, 2000); setTimeout(function(){ $(".item11").show("scale" , 1000); $(".item12").show("scale" , 1000); },1000); } } function remove_motion(title_cnt) { if (title_cnt == 1) { $(".item1").animate({ "top": "36%" , "left": "57%", opacity: 0 }, 4000); $(".item2").animate({ "top": "20%" , "left": "75%" }, 2000); $(".item3").animate({ "top": "35%", "left": "0%" }, 1500); } else if (title_cnt == 2) { $(".item4").animate({ "top": "20%", "left": "0%" }, 2000); $(".item5").animate({ "top": "30%", "left": "0%" }, 1500); $(".item6").animate({ "top": "40%", "left": "0%" }, 1000); $(".item7").hide("scale" , 2000); $(".item8").animate({ "top": "100%" }, 3000); } else if (title_cnt == 3) { $(".item9").animate({ "left": "0%", "top": "37%" }, 2000); $(".item10").animate({ "left": "79%", "top": "55%" }, 1500); $(".item11").hide("scale" , 2000); $(".item12").hide("scale" , 2000); } } $(".right-title").click(function() { move_title(type = "right", $(window).width()); }); $(".left-title").click(function() { move_title(type = "left", $(window).width()); }); item_motion(title_cnt = 1); /* setInterval(function() { move_title(type = "left", $(window).width()); } , 10000);*/
import React, { useState ,useEffect} from 'react'; import './App.css'; import { FormControl, MenuItem,Select,Card,CardContent } from '@material-ui/core'; import {Info} from './component/Info' import {Table} from './component/Table' import {Sortdata} from './component/utils' import Map from './component/Map' import LineGraph from './component/Linegraph' import "leaflet/dist/leaflet.css"; import {prettyPrintStat} from './component/utils' function App() { const [countries, setCountries] = useState(''); const [country, setCountry] = useState("worldwide") const [casestype, setCasestype] = useState("cases") const [total, setTotal] = useState(''); const [all, setAll] = useState('') const [allcountries, setAllcountries] = useState('') const [position, setPosition] = useState([34.80746, -40.4796]) const [zoom, setZoom] = useState(3) const fetchdata=async()=>{ const res=await fetch("https://disease.sh/v3/covid-19/countries"); const data=await res.json(); const countries=data.map((data)=>({ country:data.country, countryInfo:data.countryInfo.iso2, })) setAllcountries(data) setCountries(countries); setAll(Sortdata(data)) //console.log("data",data) } const handlechange=async(e)=>{ // console.log(e.target.value) setCountry(e.target.value) const cinfo=e.target.value; const url=cinfo==="worldwide"?"https://disease.sh/v3/covid-19/all":`https://disease.sh/v3/covid-19/countries/${cinfo}` //console.log("url",url) const res=await fetch(url); const data=await res.json(); setTotal(data); if(cinfo==="worldwide"){ setPosition([34.80746, -40.4796]); setZoom(4) }else{ setPosition([data.countryInfo.lat,data.countryInfo.long]) setZoom(4) } } const defaultdata=async ()=>{ const url="https://disease.sh/v3/covid-19/all" //console.log("url",url) const res=await fetch(url); const data=await res.json(); setTotal(data); //console.log("data is",data) } //console.log("new data is",total) useEffect(() => { fetchdata() defaultdata() }, []) return ( <div className="cont"> <div className="app left"> <div className="formcont"> <h1>Covid-19 Tracker</h1> <FormControl className="app_dropdown"> <Select variant="outlined" value={country} onChange={handlechange}> <MenuItem value="worldwide">worldwide</MenuItem> {countries && countries.map((data,index)=>{ return ( <MenuItem value={data.countryInfo} key={index}>{data.country}</MenuItem> ) })} </Select> </FormControl> </div> <div className="infocont"> <Info title={"corona cases"} isred active={casestype==="cases"} onClick={()=>setCasestype('cases')} total={prettyPrintStat(total.cases)} todaycases={prettyPrintStat(total.todayCases)} /> <Info title={"Death"} isred active={casestype==="deaths"} total={prettyPrintStat(total.deaths)} todaycases={prettyPrintStat(total.todayDeaths)} onClick={()=>setCasestype('deaths')}/> <Info title={"recovered"} active={casestype==="recovered"} total={prettyPrintStat(total.recovered)} todaycases={prettyPrintStat(total.todayRecovered)} onClick={()=>setCasestype('recovered')}/> </div> <Map countries={allcountries} casesType={casestype} center={position} zoom={zoom}/> </div> <div className="cardright"> <Card className="infocard "> <h2>List of countres</h2> <Table data={all}/> <h3 className="cases">worldwide new {casestype}</h3> <LineGraph isgreen={casestype==="recovered"} className="app__graph" casesType={casestype}/> </Card> </div> </div> ); } export default App;
import Validator from "./validator"; export function getSum(total, num) { return total + num; } /** * * * @export getRanking * @param {Object} rankData * @param {Number} rank the number between 1 and 5 * @returns object type with label, numberOfRank and total number of rank */ export function getRanking(rankData, rank) { const reviewData = Validator.propertyExist(rankData, "review") ? rankData.review : rankData; const totalRating = reviewData.filter(data => data.rating === rank).length; const grandTotal = reviewData.length; return { label: rank === 1 ? "1 star " : `${rank} stars`, numberOfRate: totalRating, totalRate: grandTotal, }; } /** * * * @export getAverageReview * @param {Object} rankData * @returns the total number of all rating divided by the number of people that review */ export function getAverageReview(rankData) { try { const reviewData = Validator.propertyExist(rankData, "review") ? rankData.review : rankData; const totalRating = reviewData.map(data => data.rating) .reduce(getSum); const grandTotal = reviewData.length; return (totalRating / grandTotal); } catch (e) { return 0; } } /** * * * @export checkUserItemRating * @param {Object} rankData * @param {String} customerId * @param {String} itemId * @returns true if customer has rated item before and false if customer has not */ export function checkUserItemRating(rankData, customerId, itemId) { try { if (customerId && itemId) { const reviewData = Validator.propertyExist(rankData, "review") ? rankData.review : rankData; return reviewData.filter(data => data.customer === customerId && data.subjectId === itemId) .length > 0; } return false; } catch (e) { return false; } } /** * * * @export * @param {String} user eg customer, vendor, admin * @returns return user Id */ export function getUserId(user) { try { const userLoginDetails = Validator.propertyExist(localStorage, `bezop-login:${user}`) ? JSON.parse(localStorage[`bezop-login:${user}`]) : null; if (userLoginDetails !== null) { return Validator.propertyExist(userLoginDetails, "profile", "id") ? userLoginDetails.profile.id : null; } return false; } catch (e) { return false; } } /** * * * @export IsJsonString * @param {String} str * @returns {String} object or string */ export function IsJsonString(str) { try { return typeof JSON.parse(str); } catch (e) { return typeof str; } } export function getJsonString(jsonString, firstElement) { try { return JSON.parse(jsonString)[firstElement]; } catch (e) { return false; } } export function inputErrorValidation(type, value, value2 = null) { let output = false; switch (type) { case "name": output = Validator.minStrLen(value, 3); break; case "kind": output = Validator.isEmpty(value); break; case "description": output = Validator.minStrLen(value, 15); break; default: output = false; break; } return output; } /** * Error Validation Structure * * @export * @param {string} [value=""] * @param {boolean} [valid=true] * @param {boolean} [success=false] * @param {boolean} [error=false] * @returns */ export function validatioObj( value = "", valid = true, success = false, error = false, ) { return { value, valid, success, error, }; }
import React from 'react'; import {Redirect} from 'react-router-dom'; import {userHasRole, isUserLogged} from './user-info'; export const WithAuth = (WrappedComponent, allowedRoles) => { return props => userHasRole(allowedRoles) ? <WrappedComponent {...props} /> : <Redirect to='/welcome'/>; }; export const WithoutAuth = (WrappedComponent) => { return props => isUserLogged() ? <Redirect to='/'/> : <WrappedComponent {...props} />; };
import React from 'react'; import { BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom'; import { useAuth0 } from '@auth0/auth0-react'; import PasswordPage from './components/PasswordPage' import UploadPage from './components/UploadPage' import HomePage from './components/HomePage' import './App.css'; const App = () => { const { isAuthenticated, logout } = useAuth0(); return ( <> {isAuthenticated ? <div className="container"> <Router> <nav className="nav"> <div className="nav-brand">Cloud Image Storage</div> <ul className="nav-items"> <li className="nav-item"> <Link to="/">Gallery</Link> </li> <li className="nav-item"> <Link to="/upload">Upload</Link> </li> <li className="nav-item"> <Link to="/" onClick={() => logout()}>Log Out</Link> </li> </ul> </nav> <Switch> <Route path="/upload"> <UploadPage /> </Route> <Route path="/"> <HomePage /> </Route> </Switch> </Router> </div> : <PasswordPage />} </> ); } export default App;
'use strict'; define(['main'], function(ngApp) { ngApp.provider.controller('ctrlPage', ['$scope', 'http2', function($scope, http2) { $scope.edit = function(event, prop) { event.preventDefault(); event.stopPropagation(); var name = $scope.wx[prop]; if (name && name.length) { location.href = '/rest/pl/fe/code?site=platform&name=' + name; } else { http2.get('/rest/pl/be/sns/wx/page/create?site=platform').then(function(rsp) { $scope.wx[prop] = rsp.data.name; location.href = '/rest/pl/fe/code?site=platform&name=' + rsp.data.name; }); } }; $scope.reset = function(event, prop) { event.preventDefault(); event.stopPropagation(); if (window.confirm('重置操作将覆盖已经做出的修改,确定重置?')) { var name = $scope.wx[prop]; if (name && name.length) { http2.get('/rest/pl/be/sns/wx/page/reset?site=platform&name=' + name).then(function(rsp) { location.href = '/rest/pl/fe/code?site=platform&name=' + name; }); } else { http2.get('/rest/pl/be/sns/wx/page/create?site=platform').then(function(rsp) { $scope.wx[prop] = rsp.data.name; location.href = '/rest/pl/fe/code?site=platform&name=' + rsp.data.name; }); } } }; }]); });
"use strict"; angular.module("GolfClub", [ "ngRoute", "GolfClub", "dx" ]) .config(["$routeProvider", function ($routeProvider) { $routeProvider .when("/home", { templateUrl: "partials/home.html", controller: "HomeCtrl" }) .when("/search", { templateUrl: "partials/search.html", controller: "SearchCtrl" }) .when("/info", { templateUrl: "partials/info.html", controller: "InfoCtrl" }) .otherwise({ redirectTo: "/home" }); }]) .run(["$route", function ($route) { $route.reload(); }]);
var express = require('express') var morgan = require( 'morgan' ) var bodyParser = require( 'body-parser' ) var mongoose = require( 'mongoose' ) var cors = require( 'cors' ) var path = require( 'path' ) var config = require( './config') var app = express() //configure bodyParser app.use( bodyParser.urlencoded({ extended: true }) ) app.use( bodyParser.json() ) //configure cors app.use( cors() ) //configure morgan app.use( morgan( 'dev' ) ) app.use(express.static('./public')) app.listen( config.port, function( req, res ) { console.log( 'app listening on port: ' + config.port) })
import React, { useState } from "react"; import Recipe from "./Recipe"; import Pagination from "./Pagination"; import styled from "styled-components"; const RecipeList = ({ recipes, handleActiveRecipe }) => { const [index, setIndex] = useState(0); const displayAmount = 3; var currRecipes = recipes.slice(index, index + displayAmount); var currPage = index / displayAmount; var numPages = Math.ceil(recipes.length / displayAmount); // If there is a next page, displays the next recipes const incIndex = () => { if (currPage < numPages - 1) { setIndex(index + displayAmount); } }; // If there is a previous page, displays the previous recipes const decIndex = () => { if (currPage >= 1) { setIndex(index - displayAmount); } }; return ( <ListStyle> {currRecipes.map(recipe => ( <Recipe key={recipe.recipe.label} title={recipe.recipe.label} calories={recipe.recipe.calories} image={recipe.recipe.image} ingredients={recipe.recipe.ingredients} handleActiveRecipe={handleActiveRecipe} /> ))} <br /> <Pagination incIndex={incIndex} decIndex={decIndex} currPage={currPage} numPages={numPages} /> </ListStyle> ); }; export default RecipeList; // Styled Components const ListStyle = styled.div` width: 100%; height: 70vh; display: inline-block; white-space: nowrap; overflow-x: none; &::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0); } `;
//Importation de React, des composants associés et du style (style récupéré dans le fichier global de style et rendu avec l'attribut "style" d'un composant) import { Image, Pressable, Text, TextInput, View } from 'react-native'; import { FontAwesome } from '@expo/vector-icons'; import React from 'react'; import style from '../Style'; const AjoutMembreInactif = (props) => { //Fonction return permettant le rendu de la page, il contient le squelette de la page return ( <View style={style.view}> {/* Composant "Image" permettant de rendre une image (l'attribut source contient l'emplacement de l'image) Photo de profil */} <Image style={style.mainphoto} source={require("../assets/photo.png")} /> <Text style={{fontSize:0, fontWeight:"normal", color:"transparent"}}></Text> {/* Composant "Text" permettant de rendre un texte Nom du champ de texte */} <Text style={style.txtChampTexte}>Nom</Text> {/* Composant "TextInput" permettant de rendre un champ de texte Champ de texte */} <TextInput placeholder="Entrer le nom du membre" style={style.champTexte} autoCapitalize="none" /> <Text style={style.txtChampTexte}>Prénom</Text> <TextInput placeholder="Entrer le prénom du membre" style={style.champTexte} autoCapitalize="none" /> <Text style={style.txtChampTexte}>Description</Text> <TextInput placeholder="Entrer la description du membre" style={style.champTexte} autoCapitalize="none" /> {/* Composant "Pressable" permettant de rendre cliquable les composants qu'il contient (méthode onPress exécutée lors d'un clic, dans ce cas on envoie un message dans la console et on redirige vers une autre page) Rend cliquable l'icone */} <Pressable style={style.btnValider} onPress={() => {console.log("Valider appuyé"), props.navigation.navigate("PersonnesGroupe")}}> {/* Composant "FontAwesome" (qui n'est pas un composant React Native) permettant d'utiliser le service FontAwesome permettant d'avoir des icones facilement Bouton confirmer pour valider la saisie */} <FontAwesome name="check" size={60} /> </Pressable> </View> ) } export default AjoutMembreInactif; {/* const style = { view: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#FEFCF3" }, mainphoto: { width: 150, height: 150, marginBottom: 20 }, txtChampTexte: { color: "#D74848", marginTop: 15, fontSize: 20 }, champTexte: { marginVertical: 10, padding: 10, width: "70%", borderWidth: 1, borderColor: "#D74848", borderRadius: 10 }, btnValider: { marginTop: 20 } }; */}
localStorage.setItem('background-color', document.getElementById('dark').value); console.log(document.getElementById('dark').value); function darkMode() { localStorage.setItem( 'background-color', document.getElementById('dark').value ); //localStorage.bgColor = localStorage.getItem('background-color'); if (localStorage.getItem('background-color') == 2) { document.getElementById('header').style.cssText = 'color:#fff;background:#333;'; document.body.classList.toggle('dark-mode'); localStorage.setItem('background-color', 1); } else { document.getElementById('header').style.cssText = 'color:#000000;background:#fff;'; document.getElementById('content').style.cssText = 'color:#000000;background:f0f1f6;blockColor:#f0f1f6;'; document.body.classList.toggle('dark-mode'); localStorage.setItem('background-color', 2); } } function logOut() { window.location = 'login.html'; } function preview_image(event) { var reader = new FileReader(); reader.onload = function() { var output = document.getElementById('output_image'); output.src = reader.result; } reader.readAsDataURL(event.target.files[0]); alert("Image has been uploaded"); }
import { getProductPrice } from './Cart'; test('getProductPrice', () => { const value = getProductPrice(2,3); expect(value).toBe(6); });
var initialHtml, relodeInterval; chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ if (typeof initialHtml === "undefined") initialHtml = message.pageCont; else if (initialHtml !== message.pageCont) { chrome.tabs.executeScript(null, { code: 'document.body.style.backgroundColor="red"' }); chrome.tabs.query({'active': true}, function(tab) { chrome.tabs.executeScript(tab[0].id, { code: 'alert("Rejestracja")' }); }); if (typeof relodeInterval !== "undefined") clearInterval(relodeInterval); } }); chrome.tabs.query({'url': 'http://2015.confitura.pl/'}, function(tab) { relodeInterval = setInterval(function() { chrome.tabs.executeScript(tab[0].id, { code: 'window.location.reload()' }); }, 10000); });
import React from 'react'; import { render } from 'react-dom'; import { Provider as StoreProvider } from 'react-redux'; import { appendIconDefinitions } from 'yarn-design-system-icons'; import { store } from './store/store'; import { login } from './store/actions'; import { api, Provider as ApiProvider } from './services/api'; import { Provider as TranslationProvider, translations } from './locales/i18n'; import { initI18n } from './services/i18n'; import { get } from './services/storage'; import { Layout } from './layout'; import { STORAGE_KEY } from './config'; import './vendor'; import './styles/styles.scss'; document.addEventListener('DOMContentLoaded', () => { const { en, dev } = translations; const { t } = initI18n({ language: { lng: 'en', messages: en }, fallbackLanguage: { lng: 'dev', messages: dev }, namespace: 'reactAsyncFlow' }); appendIconDefinitions(document.body); const user = get(STORAGE_KEY.user); user && store.dispatch(login(user)); render(( <ApiProvider value={ api }> <StoreProvider store={ store }> <TranslationProvider value={ t }> <Layout /> </TranslationProvider> </StoreProvider> </ApiProvider> ), document.getElementById('root')); });
export function addItem(data){ return { type: "ADDDATA", data } } export function handleChange(id){ return { type: "CHANGECHECK", id } } export function handleDelete(id){ return { type: "DELETE", id } } export function searchUnpacked(value){ return { type: "SEARCH_UNPACKED", value } } export function searchPacked(value){ return { type: "SEARCH_PACKED", value } }
angular.module("demo", ['ngMessages']);
var express = require('express'); var app = express.Router(); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema( { name: String, email: String, password: String }); var User = mongoose.model('users', UserSchema); //REGISTER - renders registration form app.get('/register', function (req,res) { res.render('users/register.jade'); }); //writes user info to db app.post('/usersave', function (req,res) { console.log('im here'); //console.log(req.body); //check to see if server got message from client var user = new User({ name: req.param('userName'), email: req.param('userEmail'), password: req.param('userPassword') }); console.log(user); //check b4 saving user.save(function(err, user) { if(err) { res.send(500, err); } res.redirect('/tasks/new') }); }); //LOGIN VERIFICATION - verifies login info and checks password app.post('/login', function (req,res) { if (req.param('userEmail') === '') {//checks if form empty res.render('users/login.jade', {errors : 'Incorrect Email'}); return; }; if (req.param('userPassword') === '') { res.render('users/login.jade', {errors : 'Incorrect Password'}); return; } User.findOne({'email': req.param('userEmail')}, function (wert, users) { if (users !== null) {//user is found in db //checks to see if password of email entered matches db pswd if (req.param('userPassword') === users.password) { console.log('match'); req.session.user = users;//store in session res.redirect('/tasks/'); } else { // res.redirect('/users/login'); res.render('users/login.jade', {errors : 'Either the email or password is incorrect, please try again.'}); } } else {//user is not found in db res.render('users/login.jade', {errors : 'Either the email or password is incorrect, please try again.'}); } }); }); module.exports = app;
import * as route from '@/router'; import '@/css/weui.scss' import '@/css/main.scss' // 状态管理工具 import Store from '@/redux'; window.Store = Store; // 实例化路由 var routerType; var Routes = Backbone.Router.extend({ routes: route.router_object, ...route.routes, initialize() {} }) window.appRouter = new Routes(); appRouter.on('route', function(route, params) { window.scrollTo(0,0); //每次切换页面容器置顶 // setTimeout(() => { //这个方法不好使用了 // document.body.scrollTop = 0; // 每次切换页面容器置顶 // }, 10); }); Backbone.history.start();
import React from 'react' import { Title } from 'bypass/ui/title' import { Container } from 'bypass/ui/page' import { AutoSizer, ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout' import { HowUpTimeout } from 'bypass/ui/notice' import { Condition } from 'bypass/ui/condition' import { Paginate } from 'bypass/ui/paginate' import { Button } from 'bypass/ui/button' import { Sort } from 'bypass/ui/sort' import { Aside } from './aside' import { List } from './list' import Info from './Info' const Desktop = ({ columns, sortColumns, list, total, limit, count, perpage, offset, search, showSearch, showResult, hasSelected, allSelected, cart, checkTimeout, onChangeSort, onLoadPage, onToggleDefault, onSaveSearch, onLoadSearch, onFastBuy, onAddToCart, onShowFilter, onSearch, onShowSearch, onHideSearch, onClearSearch, onLoad, onSelect, onSelectAll, }) => ( <AutoSizer> <ColumnLayout> <Layout> <Aside cart={cart} search={search} showSearch={showSearch} onShowFilter={onShowFilter} onSearch={onSearch} onShowSearch={onShowSearch} onHideSearch={onHideSearch} onClearSearch={onClearSearch} onSaveSearch={onSaveSearch} onLoadSearch={onLoadSearch} onToggleDefault={onToggleDefault} /> </Layout> <Layout grow={1} shrink={1}> <Condition match={showResult}> <Container indent> <AutoSizer> <RowLayout> <Layout> <ColumnLayout align='center'> <Layout grow={1}> <Title offset='right'> {__i18n('LANG.SERVICE.SEARCH_RESULT')} <Info count={count} limit={limit} /> </Title> </Layout> <Layout> <HowUpTimeout timeout={checkTimeout} /> </Layout> </ColumnLayout> </Layout> <Layout grow={1} shrink={1}> <List list={list} total={perpage} columns={columns} rowHeight={30} allSelected={allSelected} onLoad={onLoad} onSelect={onSelect} onSelectAll={onSelectAll} onAddToCart={onAddToCart} /> </Layout> <Layout basis='20px' /> <Layout> <ColumnLayout align='center'> <Layout grow={1} shrink={1}> <Paginate count={total} offset={offset} pageSize={perpage} onChange={onLoadPage} /> </Layout> <Layout> <Sort value={search.sort} columns={sortColumns} onChange={onChangeSort} /> </Layout> <Layout basis='20px' /> <Layout> <Button disabled={!hasSelected} onClick={onAddToCart}> {__i18n('COM.ADD_TO_CART')} </Button> </Layout> <Layout basis='15px' /> <Layout> <Button disabled={!hasSelected} onClick={onFastBuy}> {__i18n('SEARCH.FAST_BUY.FAST')} </Button> </Layout> </ColumnLayout> </Layout> <Layout basis='20px' /> </RowLayout> </AutoSizer> </Container> </Condition> </Layout> </ColumnLayout> </AutoSizer> ) export default Desktop
import React, { Component } from 'react'; import {Consumer} from '../../context'; import uuid from 'uuid'; import TextInputGroup from '../layout/TextInputGroup'; import axios from 'axios'; class EditContact extends Component { constructor(){ super(); this.state = { name:'', email:'', phone:'', error:{} } this.onChange= this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); // this.onEmailChange= this.onEmailChange.bind(this); // this.onAddressChange= this.onAddressChange.bind(this); // this.onPhoneChange= this.onNameChange.bind(this); } async componentDidMount(){ const {id} = this.props.match.params; const res = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`); const contact = res.data; this.setState({ name:contact.name, email:contact.email, phone:contact.phone }) } // onNameChange(e){ // this.setState({name:e.target.value}); // } // onEmailChange(e){ // this.setState({email:e.target.value}); // } // onAddressChange(e){ // this.setState({address:e.target.value}); // } // onPhoneChange(e){ // this.setState({phone:e.target.value}); // } onChange(e){ this.setState({[e.target.name]:e.target.value}); } async onSubmit(dispatch,e){ e.preventDefault(); // console.log(this.state); const {name,email,phone} = this.state; if(name===''){this.setState({error:{name:'Name is required'}});return;}; if(email===''){this.setState({error:{email:'Email is required'}});return;}; if(phone===''){this.setState({error:{phone:'Phone is required'}});return;}; // if(address===''){this.setState({error:{address:'Address is required'}});return;}; const updContact ={ name,email,phone } const {id} = this.props.match.params; const res = await axios.put(`https://jsonplaceholder.typicode.com/users/${id}`,updContact); dispatch({type:'UPDATE_CONTACT',payload:res.data}); this.setState ({ name:'', email:'', phone:'', error:{} }) this.props.history.push('/'); } render() { const {name,email,phone,error} = this.state; return( <Consumer> {value=>{ const { dispatch } = value; return( <div className="card mb-3"> <div className="card-header">Edit Contact for {name} </div> <form onSubmit={this.onSubmit.bind(this,dispatch)} > <TextInputGroup label="Name" name="name" placeholder="Enter the NAME" value={name} onChange={this.onChange} error={error.name}/> <TextInputGroup label="Email" name="email" placeholder="Enter the EMAIL" value={email} onChange={this.onChange} type="email" error={error.email}/> <TextInputGroup label="Phone Number" name="phone" placeholder="Enter the PHONE NUMBER" value={phone} onChange={this.onChange} error={error.phone}/> <input type="submit" value="Edit Contact" className="btn btn-light btn-block"/> </form> </div> ) }} </Consumer> ) } // onChange(e){ // this.setState({e.target.name:e.target.value}) // } } // let onChange = (e)=>{ // this.setState({[e.target.name]:e.target.value}); // } // let onSubmit =(e)=>{ // e.preventDefault(); // console.log(this.state); // } export default EditContact;
/* @flow */ import common from './common'; import logging from './logging'; import singleton from './singleton'; export { common, logging, singleton };
'use strict' // COLUMN CLASS function Column(id, name) { const self = this this.id = id this.name = name this.element = generateTemplate('column-template', {name: this.name, id: this.id}) this.element.querySelector('.column').addEventListener('click', function(event) { event.stopPropagation() event.preventDefault() if(event.target.classList.contains('btn-delete')) { self.removeColumn() } if(event.target.classList.contains('add-card')) { let cardName = prompt('Enter the name of the card') if(cardName !== null) { let data = new FormData() data.append('name', cardName) data.append('bootcamp_kanban_column_id', self.id) sendRequest('POST', baseUrl + '/card', function(resp) { self.addCard(new Card(resp.id, cardName)) }, data) } } else if(event.target.classList.contains('btn-edit')) { self.editColumn() } else if(params.pickedColor !== null) { self.element.querySelector('.column').style.backgroundColor = params.pickedColor } }) } Column.prototype = { addCard: function(card) { this.element.querySelector('ul').appendChild(card.element) }, removeColumn: function() { const self = this sendRequest('DELETE', baseUrl + '/column/' + self.id, function() { self.element.parentNode.removeChild(self.element) }) }, editColumn: function() { let self = this self.name = prompt('Enter the new name of the column') let data = new FormData() data.append('name', self.name) sendRequest('PUT', baseUrl + '/column/' + self.id, function(resp) { self.element.querySelector('.column-title').innerText = self.name }, data) }, }
var map; var baseLayer; function init(){ map = new ol.Map({ target: 'map', // layers: [ // new ol.layer.Tile({ // source: new ol.source.XYZ({ // url: 'http://localhost:8888/dark1/{z}/{x}/{y}.png' // }) // }) // ], view: new ol.View({ center: ol.proj.transform([104.40,31.13], 'EPSG:4326', 'EPSG:3857'), zoom: 8 }), controls: ol.control.defaults({ attributionOption: { collapsible: false } }) }); baseLayer = new ol.layer.Tile({ source: new ol.source.XYZ({ url: "http://localhost:8888/light/{z}/{x}/{y}.png" }) }); map.addLayer(baseLayer); }
var searchData= [ ['bridge',['BRIDGE',['../classplateau.html#a94b54e0a84c850657a83176f812db222a980eb058ada027f23b4dc56b52f7853f',1,'plateau']]] ];
process.on('message', (msg) => { const Jasmine = require('jasmine'); const reporter = { jasmineStarted: (data) => process.send({type: 'jasmineStarted', data: data}), suiteStarted: (data) => process.send({type: 'suiteStarted', data: data}), specStarted: (data) => process.send({type: 'specStarted', data: data}), jasmineDone: (data) => { process.send({type: 'jasmineDone', data: data}); }, specDone: (data) => process.send({type: 'specDone', data: data}), suiteDone: (data) => process.send({type: 'suiteDone', data: data}), isComplete: (data) => process.send({type: 'isComplete', data: data}), print: (data) => {} }; const jasmine = new Jasmine(); jasmine.exit = () => { setTimeout(() => {process.exit()},700); }; jasmine.addReporter(reporter); jasmine.configureDefaultReporter(reporter); jasmine.execute([msg]); });
import * as PropTypes from 'prop-types'; import * as React from 'react'; /* eslint-disable */ /** * @uxpincomponent */ const MarketingIcon = (props) => ( <div onClick={props.click} onMouseEnter={props.mouseOver} onMouseLeave={props.mouseLeave} onMouseDown={props.mouseDown} onMouseUp={props.mouseUp}> <chi-marketing-icon icon={props.icon} size={props.size}> <span className="-sr--only"> i </span> </chi-marketing-icon> </div> ); MarketingIcon.propTypes = { size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg']), icon: PropTypes.string, click: PropTypes.func, mouseDown: PropTypes.func, mouseLeave: PropTypes.func, mouseOver: PropTypes.func, mouseUp: PropTypes.func, }; /* eslint-enable */ MarketingIcon.defaultProps = { size: 'sm', icon: 'business-big-data', }; export { MarketingIcon as default };
/* eslint-disable */ import React from 'react' import Link from 'react-router/lib/Link' import { timeConverter } from 'bypass/app/utils/utils' import BaseUpdate from './BaseUpdate' import { DesktopContainer } from 'bypass/ui/page' /** * @media only screen and (max-width: 667px) * .NewsItemContainer * .newsItemBody * font-size: 13px */ class newsItem extends React.Component { onVote(vote) { const { news, onVote } = this.props if (onVote) { onVote(news.news_id, vote) } } render() { const { news, vote } = this.props return ( <DesktopContainer> <article className='appContainer-woInfinity NewsItemContainer'> <Link className='newsItemNav' to='/news'>{__i18n('NEWS.BACK_TO_LIST')}</Link> <header className='newsItemHeader'> <h3 className='newsItemHeader-title'>{news.subject}</h3> <span className='newsItemHeader-date icon'> <span className='clock' /> {timeConverter(news.add_time, true, true)} </span> </header> <div className='newsItem'> {news.type == 'base_update' ? <BaseUpdate loads={news.news}/> : <main className='newsItemBody' dangerouslySetInnerHTML={{__html: news.news}}/> } </div> <footer className='newsItemFooter'> <a className='button-green' onClick={this.onVote.bind(this, 'p')}> {__i18n('NEWS.LIKE')} <span className='icon like'>{vote.p ? vote.p : ''}</span> </a> <a className='button-red' onClick={this.onVote.bind(this, 'n')}> {__i18n('NEWS.DISLIKE')} <span className='icon dislike'>{vote.n ? vote.n : ''}</span> </a> </footer> </article> </DesktopContainer> ) } } export default newsItem
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PosterModel = new Schema({ userId: {type: String, required: true, default: ''}, content: {type: String, required: true, default: ''}, list_image: {type: Array, default: []}, timeStamp: Number }); module.exports = mongoose.model('PosterModel', PosterModel);
cc.Class({ extends: cc.Component, properties: { //主角跳跃高度 jumpHeight: 0, //主角持续跳跃时间 jumpDuration: 0, //形变持续时间 squashDuration: 0, //最大移动速度 maxMoveSpeed: 0, //加速度 accel: 0, //跳跃音效 jumpAudio: { default: null, url: cc.AudioClip }, }, setJumpAction:function() { //上升 var jumpUp = cc.moveBy(this.jumpDuration,cc.p(0,this.jumpHeight)).easing(cc.easeCubicActionInOut()); //下落 var jumpDown = cc.moveBy(this.jumpDuration,cc.p(0,-this.jumpHeight)).easing(cc.easeCubicActionIn()); //形变 var squash = cc.scaleTo(this.squashDuration,1,0.6); var stretch = cc.scaleTo(this.squashDuration,1,1.2); var scaleback = cc.scaleTo(this.squashDuration,1,1); //添加一个回调函数,用于动作结束后的音效 var callback = cc.callFunc(this.playJumpSound,this); //重复 return cc.repeatForever(cc.sequence(squash,stretch,jumpUp,scaleback,jumpDown,callback)); }, playJumpSound: function() { //调用声音引擎播放声音 cc.audioEngine.playEffect(this.jumpAudio,false); }, getCenterPos: function() { var centerPos = cc.p(this.node.x,this.node.y + this.node.height / 2); return centerPos; }, startMoveAt: function (pos) { this.enabled = true; this.xSpeed = 0; this.node.setPosition(pos); this.node.runAction(this.setJumpAction); }, stopAllMove: function() { this.node.stopAllActions(); }, setInputControl: function() { var self = this; //添加键盘事件监听 //有按键按下时,判断是否我们指定的方向控制键,并设置对应的方向加速键 cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,function(event){ switch(event.keyCode){ case cc.KEY.a: self.accLeft = true; break; case cc.KEY.d: self.accRight = true; break; } }); //松开按键,停止向该方向的加速 cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP,function(event){ switch(event.keyCode){ case cc.KEY.a: self.accLeft = false; break; case cc.KEY.d: self.accRight = false; break; } }); }, onLoad: function() { //初始化跳跃 this.jumpAction =this.setJumpAction(); this.node.runAction(this.jumpAction); //加速度开关 this.accLeft = false; this.accRight = false; //屏幕的大小 this.minPosX = -this.node.parent.width / 2; this.maxPosX = this.node.parent.width / 2; //主角当前水平方向速度 this.xSpeed = 0; //初始化键盘监听 this.setInputControl(); }, update: function(dt) { //根据当前加速方向每帧更新速度 if (this.accLeft) { this.xSpeed -= this.accel * dt; } else if (this.accRight) { this.xSpeed += this.accel * dt; } //限制主角的速度不超过最大值 if (Math.abs(this.xSpeed) > this.maxMoveSpeed ) { this.xSpeed = this.maxMoveSpeed * this.xSpeed / Math.abs(this.xSpeed); } //根据当前速度更新主角的位置 this.node.x += this.xSpeed * dt; //限制主角在屏幕内 if (this.node.x > this.node.parent.width / 2){ this.node.x = this.node.parent.width / 2; this.xSpeed = 0; } else if (this.node.x < -this.node.parent.width / 2) { this.node.x = -this.node.parent.width / 2; this.xSpeed = 0; } }, });
(function(){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var w = canvas.width = innerWidth; var h = canvas.height = innerHeight; var particles = []; var prop = { bgColor : 'rgba(17,17,19,1)', particColor : 'rgba(255,40,40,1)', particRadius : 3, particCount : 120, particSpeed : 2, lineLength : 150, particLife : 2, }; document.querySelector('body').appendChild(canvas); window.onresize = function(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight; } class Particle{ constructor(){ this.x = Math.random()*w; this.y = Math.random()*h; this.speedX = Math.random()*(prop.particSpeed*2) - prop.particSpeed; this.speedY = Math.random()*(prop.particSpeed*2) - prop.particSpeed; this.life = Math.random()*prop.particLife*60; } position(){ ((this.x + this.speedX > w) && (this.speedX > 0)) || ((this.x + this.speedX < 0) && this.speedX < 0) ? this.speedX *= -1 : this.speedX; ((this.y + this.speedY > h) && (this.speedY > 0)) || ((this.y + this.speedY < 0) && this.speedY < 0) ? this.speedY *= -1 : this.speedY; this.x += this.speedX; this.y += this.speedY; } reDraw(){ ctx.beginPath(); ctx.arc(this.x,this.y,prop.particRadius,0,Math.PI*2); ctx.closePath(); ctx.fillStyle = prop.particColor; ctx.fill(); } reCalcLife(){ if(this.life < 1){ this.x = Math.random()*w; this.y = Math.random()*h; this.speedX = Math.random()*(prop.particSpeed*2) - prop.particSpeed; this.speedY = Math.random()*(prop.particSpeed*2) - prop.particSpeed; this.life = Math.random()*prop.particLife*60; } this.life--; } } function reDrawBack(){ ctx.fillStyle = prop.bgColor; ctx.fillRect(0,0,w,h); } function drawLines(){ var x1,y1,x2,y2,length,opacity; for(var i in particles){ for(var j in particles){ x1 = particles[i].x; y1 = particles[i].y; x2 = particles[j].x; y2 = particles[j].y; length = Math.sqrt(Math.pow(x2 - x1,2) + Math.pow(y2 - y1,2)); if(length < prop.lineLength){ opacity = 1 - length/prop.lineLength; ctx.lineWidth = '0.5'; ctx.strokeStyle = 'rgba(255,40,40,'+opacity+')'; ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); ctx.closePath(); ctx.stroke(); } } } } function reDrawPartic(){ for(var i in particles){ particles[i].reCalcLife(); particles[i].position(); particles[i].reDraw(); } } function loop(){ reDrawBack(); reDrawPartic(); drawLines(); requestAnimationFrame(loop); } function init(){ for(var i = 0;i<prop.particCount;i++){ particles.push(new Particle); } loop(); } init(); }())
/** * @module FooMain */ /// <reference path="foo.bar" /> /// <reference types="node" /> /// <reference><reference/> /// <amd-module /> /// The main class class Main { constructor() {} }
const express = require('express'); const router = express.Router(); const Article = require('../models/article'); router.get('/api/articles', (req, res) => { Article.find() .then(articles => { res.status(200).json({ articles }); }) .catch(error => { res.status(500).json({ error }); }); }); router.post('/api/articles', (req, res) => { Article.create(req.body.article) .then((newArticle) => { res.status(201).json({article: newArticle}) }) .catch((error) => { res.send(500).json(error); }); }); router.get('/api/articles/:id', (req, res) => { Article.findById(req.params.id) .then(article => { if(article){ res.status(200).json({article}); } else { res.status(404).json({error: { name: 'Document not found', message: 'The provided ID doesn\'t match any documents', }}); } }) .catch(error => { res.status(500).json({error}) }); }); router.delete('/api/articles/:id', (req, res) => { Article.findById(req.params.id) .then(article => { if(article) { return article.remove(); } else { res.status(404).json({error: { name: 'Document not found', message: 'The provided ID doesn\'t match any documents', }}); } }) .then(() => { res.status(204).end(); }) .catch(error => { res.status(500).json(error); }) }); module.exports = router;
var Board = { id: 'fo-board', row: 13, col: 61, color0: '#ebedf0', color1: '#239a3b', color2: '#c6e48b', catLoc: [], tubeLocs: [], treeLocs: [], catPoints: [], barrierPoints: [], element: null } Board.cat = [ [0, 0, 1, 0, 0, 0, 1], [0, 0, 1, 1, 1, 1, 1], [0, 0, 1, 2, 1, 2, 1], [1, 0, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1], [0, 0, 1, 0, 1, 0, 1], ] Board.tube = [ [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], ] Board.tree = [ [0, 1, 1, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], ] Board.init = function() { Board.catLoc = [5, 3] Board.tubeLocs = [[20, 9], [58, 0]] Board.treeLocs = [[38, 10]] Board.catPoints = [] Board.barrierPoints = [] Board.timer = {} } Board.handleKeydown = function(e) { if (e.keyCode == 32 && e.target == document.body) { e.preventDefault(); Board.jump() } } Board.bindKeyPress = function() { window.addEventListener('keydown', Board.handleKeydown); } Board.unbindKeyPress = function() { window.removeEventListener('keydown', Board.handleKeydown); } Board.setUpInterval = function() { Board.setUpIntervalFall() Board.setUpIntervalMove() } Board.setUpIntervalFall = function() { if (!Game.running || Game.paused) { return false } Board.timer.fall = setTimeout(function() { Board.fall() Board.setUpIntervalFall() }, Game.intervalFall) } Board.setUpIntervalMove = function() { if (!Game.running || Game.paused) { return false } Board.timer.move = setTimeout(function() { Board.move() if (Game.score % 50 == 0) { Game.intervalMove = Math.ceil(Game.intervalMove * 0.8) } Board.setUpIntervalMove() }, Game.intervalMove) } Board.pointDebug = function(li) { li.addEventListener('click', function(e) { if(!Board.color(this) || Board.color(this) == Board.color0) { Board.fill(this, Board.color1); } else { Board.fill(this, Board.color0); } }) } Board.open = function() { var element = document.getElementById(Board.id) if (!element) { element = document.createElement('div') element.id = Board.id element.innerHTML = ('<ul>' + '<li></li>'.repeat(Board.row) + '</ul>').repeat(Board.col) var i = 0 element.querySelectorAll('ul').forEach(function(ul){ var j = 0 ul.querySelectorAll('li').forEach(function(li) { li.setAttribute('id', 'p-' + j + '-' + i) // Board.pointDebug(li) j += 1 }) i += 1 }) Board.element = element Game.container.appendChild(element) Board.refresh() } } Board.start = function() { Board.refresh() Board.bindKeyPress() Board.setUpInterval() } Board.color = function(e) { return e.getAttribute('fill') } Board.fill = function(e, color) { e.style.backgroundColor = color e.setAttribute('fill', color) } Board.clear = function() { Board.element.querySelectorAll('li').forEach(function(li){ Board.fill(li, Board.color0) }) Board.catPoints = [] Board.barrierPoints = [] } Board.draw = function(matrix, loc, type) { var p var color for (r in matrix) { for (c in matrix[r]) { y = parseInt(loc[1]) + parseInt(r) x = parseInt(loc[0]) + parseInt(c) if (x >= Board.col || x < 0) { continue } if (y >= Board.row || y < 0) { continue } id = 'p-' + y + '-' + x p = document.getElementById(id) if (matrix[r][c] != 0) { if (type == 'cat') { Board.catPoints.push(id) } else { Board.barrierPoints.push(id) } } Board.fill(p, Board['color' + matrix[r][c]]) } } } Board.refresh = function() { Board.clear() Board.draw(Board.cat, Board.catLoc, 'cat') Board.tubeLocs.forEach(function(tubeLoc){ Board.draw(Board.tube, tubeLoc, 'tube') }) Board.treeLocs.forEach(function(treeLoc){ Board.draw(Board.tree, treeLoc, 'tree') }) Board.check() } Board.jump = function() { if (Game.running && !Game.paused) { var step = 2 if (Board.catLoc[1] < 2) { step = Board.catLoc[1] } if (step > 0) { Board.catLoc = [Board.catLoc[0], Board.catLoc[1] - step] Board.refresh() } } } Board.fall = function() { if (Game.paused) return if (Board.catLoc[1] + Board.cat.length < Board.row) { Board.catLoc = [Board.catLoc[0], Board.catLoc[1] + 1] Board.refresh() } } Board.move = function() { if (Game.paused) return Game.addScore() var tubeLocs = Board.tubeLocs Board.tubeLocs = [] tubeLocs.forEach(function(loc) { if (loc[0] + Board.tube[0].length > 0) { Board.tubeLocs.push([loc[0] - 1, loc[1]]) } }) var treeLocs = Board.treeLocs Board.treeLocs = [] treeLocs.forEach(function(loc) { if (loc[0] + Board.tree[0].length > 0) { Board.treeLocs.push([loc[0] - 1, loc[1]]) } }) if ((Board.tubeLocs.length + Board.treeLocs.length) < 3 && Math.random() > 0.2) { Board.generateBarrier() } Board.refresh() } Board.generateBarrier = function() { var rand = Math.random() if (rand < 0.3) { Board.tubeLocs.push([Board.col - 1, 0]) } else if (rand < 0.7) { Board.tubeLocs.push([Board.col - 1, Board.row - Board.tube.length]) } else { Board.treeLocs.push([Board.col - 1, Board.row - Board.tree.length]) } } Board.check = function() { if (!Game.running) { return false } Board.catPoints.every(function(p) { if (Board.barrierPoints.indexOf(p) > -1) { Board.die() return false } return true }) } Board.die = function() { Game.die() Board.flash(6) } Board.flash = function(times) { if (times > 0) { Board.timer.flash = setTimeout(function(){ document.getElementById(Board.id).querySelectorAll('li').forEach(function(li){ if (Board.color(li) == Board.color0) { Board.fill(li, Board.color1) } else if (Board.color(li) == Board.color1) { Board.fill(li, Board.color0) } }) Board.flash(times - 1) }, 150) } } Board.close = function() { if (Board.element) { Board.element.parentNode.removeChild(Board.element) Board.element = null Board.unbindKeyPress() Object.keys(Board.timer).forEach(function(n) { clearTimeout(Board.timer[n]) }) } } Board.init();
$(document).ready(function() { var $toggleButton = $('.toggle-button'), $menuWrap = $('.menu-wrap'), $sidebarArrow = $('.sidebar-menu-arrow'); // Hamburger button $toggleButton.on('click', function() { $(this).toggleClass('button-open'); $menuWrap.toggleClass('menu-show'); }); // Sidebar navigation arrows $sidebarArrow.click(function() { $(this).next().slideToggle(300); }); }); $(window).scroll(function(){ // Change this to target a different percentage var targetPercentage = 50; //Change this to the ID of the content you are trying to show. var targetID = "#navigation"; //Window Math var scrollTo = $(window).scrollTop(), docHeight = $(document).height(), windowHeight = $(window).height(); scrollPercent = (scrollTo / (docHeight-windowHeight)) * 100; //네비바 보이기 if(scrollPercent > targetPercentage) { $(targetID).css({ top: '0' }); } else { $(targetID).css({ top: '-'+$(targetID).height+'px' }); } }).trigger('scroll');
var formulario = document.getElementById("formulario"); formulario.addEventListener("submit", function (e) { e.preventDefault(); var datos = new FormData(formulario); console.log(datos.get("email")) Email.send({ Host : "smtp.wiroos.com", Username : "info@leguinainformatica.com.ar", Password : "pass", To : 'info@leguinainformatica.com.ar', From : datos.get("email"), Subject : "This is the subject", Body : "And this is the body" }).then( message => alert(message) ); })
module.exports = { apiSidebar: [ { type: "link", href: "/api", label: "JSON RPC API", }, { type: "doc", id: "api/http", label: "HTTP Methods", }, { type: "doc", id: "api/websocket", label: "Websocket Methods", }, ], apiHttpMethodsSidebar: [ { type: "link", href: "/api", label: "JSON RPC API", }, { type: "doc", id: "api/websocket", label: "Websocket Methods", }, { type: "category", link: { type: "doc", id: "api/http" }, label: "HTTP Methods", collapsed: false, items: [ { type: "link", href: "#getaccountinfo", label: "getAccountInfo", }, { type: "link", href: "#getbalance", label: "getBalance", }, { type: "link", href: "#getblockheight", label: "getBlockHeight", }, { type: "link", href: "#getblock", label: "getBlock", }, { type: "link", href: "#getblockproduction", label: "getBlockProduction", }, { type: "link", href: "#getblockcommitment", label: "getBlockCommitment", }, { type: "link", href: "#getblocks", label: "getBlocks", }, { type: "link", href: "#getblockswithlimit", label: "getBlocksWithLimit", }, { type: "link", href: "#getblocktime", label: "getBlockTime", }, { type: "link", href: "#getclusternodes", label: "getClusterNodes", }, { type: "link", href: "#getepochinfo", label: "getEpochInfo", }, { type: "link", href: "#getepochschedule", label: "getEpochSchedule", }, { type: "link", href: "#getfeeformessage", label: "getFeeForMessage", }, { type: "link", href: "#getfirstavailableblock", label: "getFirstAvailableBlock", }, { type: "link", href: "#getgenesishash", label: "getGenesisHash", }, { type: "link", href: "#gethealth", label: "getHealth", }, { type: "link", href: "#gethighestsnapshotslot", label: "getHighestSnapshotSlot", }, { type: "link", href: "#getidentity", label: "getIdentity", }, { type: "link", href: "#getinflationgovernor", label: "getInflationGovernor", }, { type: "link", href: "#getinflationrate", label: "getInflationRate", }, { type: "link", href: "#getinflationreward", label: "getInflationReward", }, { type: "link", href: "#getlargestaccounts", label: "getLargestAccounts", }, { type: "link", href: "#getlatestblockhash", label: "getLatestBlockhash", }, { type: "link", href: "#getleaderschedule", label: "getLeaderSchedule", }, { type: "link", href: "#getmaxretransmitslot", label: "getMaxRetransmitSlot", }, { type: "link", href: "#getmaxshredinsertslot", label: "getMaxShredInsertSlot", }, { type: "link", href: "#getminimumbalanceforrentexemption", label: "getMinimumBalanceForRentExemption", }, { type: "link", href: "#getmultipleaccounts", label: "getMultipleAccounts", }, { type: "link", href: "#getprogramaccounts", label: "getProgramAccounts", }, { type: "link", href: "#getrecentperformancesamples", label: "getRecentPerformanceSamples", }, { type: "link", href: "#getrecentprioritizationfees", label: "getRecentPrioritizationFees", }, { type: "link", href: "#getsignaturesforaddress", label: "getSignaturesForAddress", }, { type: "link", href: "#getsignaturestatuses", label: "getSignatureStatuses", }, { type: "link", href: "#getslot", label: "getSlot", }, { type: "link", href: "#getslotleader", label: "getSlotLeader", }, { type: "link", href: "#getslotleaders", label: "getSlotLeaders", }, { type: "link", href: "#getstakeactivation", label: "getStakeActivation", }, { type: "link", href: "#getstakeminimumdelegation", label: "getStakeMinimumDelegation", }, { type: "link", href: "#getsupply", label: "getSupply", }, { type: "link", href: "#gettokenaccountbalance", label: "getTokenAccountBalance", }, { type: "link", href: "#gettokenaccountsbydelegate", label: "getTokenAccountsByDelegate", }, { type: "link", href: "#gettokenaccountsbyowner", label: "getTokenAccountsByOwner", }, { type: "link", href: "#gettokenlargestaccounts", label: "getTokenLargestAccounts", }, { type: "link", href: "#gettokensupply", label: "getTokenSupply", }, { type: "link", href: "#gettransaction", label: "getTransaction", }, { type: "link", href: "#gettransactioncount", label: "getTransactionCount", }, { type: "link", href: "#getversion", label: "getVersion", }, { type: "link", href: "#getvoteaccounts", label: "getVoteAccounts", }, { type: "link", href: "#isblockhashvalid", label: "isBlockhashValid", }, { type: "link", href: "#minimumledgerslot", label: "minimumLedgerSlot", }, { type: "link", href: "#requestairdrop", label: "requestAirdrop", }, { type: "link", href: "#sendtransaction", label: "sendTransaction", }, { type: "link", href: "#simulatetransaction", label: "simulateTransaction", }, ], }, // { // type: "category", // label: "Unstable Methods", // collapsed: true, // items: [ // { // type: "link", // href: "#blocksubscribe", // label: "blockSubscribe", // }, // ], // }, { type: "category", label: "Deprecated Methods", collapsed: true, items: [ { type: "link", href: "#getconfirmedblock", label: "getConfirmedBlock", }, { type: "link", href: "#getconfirmedblocks", label: "getConfirmedBlocks", }, { type: "link", href: "#getconfirmedblockswithlimit", label: "getConfirmedBlocksWithLimit", }, { type: "link", href: "#getconfirmedsignaturesforaddress2", label: "getConfirmedSignaturesForAddress2", }, { type: "link", href: "#getconfirmedtransaction", label: "getConfirmedTransaction", }, { type: "link", href: "#getfeecalculatorforblockhash", label: "getFeeCalculatorForBlockhash", }, { type: "link", href: "#getfeerategovernor", label: "getFeeRateGovernor", }, { type: "link", href: "#getfees", label: "getFees", }, { type: "link", href: "#getrecentblockhash", label: "getRecentBlockhash", }, { type: "link", href: "#getsnapshotslot", label: "getSnapshotSlot", }, ], }, ], apiWebsocketMethodsSidebar: [ { type: "link", href: "/api", label: "JSON RPC API", }, { type: "doc", id: "api/http", label: "HTTP Methods", }, { type: "category", link: { type: "doc", id: "api/websocket" }, label: "Websocket Methods", collapsed: false, items: [ { type: "link", href: "#accountsubscribe", label: "accountSubscribe", }, { type: "link", href: "#accountunsubscribe", label: "accountUnsubscribe", }, { type: "link", href: "#logssubscribe", label: "logsSubscribe", }, { type: "link", href: "#logsunsubscribe", label: "logsUnsubscribe", }, { type: "link", href: "#programsubscribe", label: "programSubscribe", }, { type: "link", href: "#programunsubscribe", label: "programUnsubscribe", }, { type: "link", href: "#signaturesubscribe", label: "signatureSubscribe", }, { type: "link", href: "#signatureunsubscribe", label: "signatureUnsubscribe", }, { type: "link", href: "#slotsubscribe", label: "slotSubscribe", }, { type: "link", href: "#slotunsubscribe", label: "slotUnsubscribe", }, ], }, { type: "category", label: "Unstable Methods", collapsed: false, items: [ { type: "link", href: "#blocksubscribe", label: "blockSubscribe", }, { type: "link", href: "#blockunsubscribe", label: "blockUnsubscribe", }, { type: "link", href: "#slotsupdatessubscribe", label: "slotsUpdatesSubscribe", }, { type: "link", href: "#slotsupdatesunsubscribe", label: "slotsUpdatesUnsubscribe", }, { type: "link", href: "#votesubscribe", label: "voteSubscribe", }, { type: "link", href: "#voteunsubscribe", label: "voteUnsubscribe", }, ], }, // { // type: "category", // label: "Deprecated Methods", // collapsed: true, // items: [ // { // type: "link", // href: "#getconfirmedblock", // label: "getConfirmedBlock", // }, // ], // }, ], };
import React from 'react'; import PropTypes from 'prop-types'; import NavList from './NavList'; const FoldersList = ({ folders, onSelect, selectedFolder }) => { let items = folders.map(folder => (<li key={folder} className={ folder === selectedFolder ? 'selected' : null } onClick={ () => onSelect(folder) }>{ folder || 'Default' }</li>)); return <NavList className='folders-list'>{ items }</NavList>; }; FoldersList.propTypes = { folders: PropTypes.arrayOf(PropTypes.string).isRequired, selectedFolder: PropTypes.string, onSelect: PropTypes.func.isRequired }; export default FoldersList;
const {sequelize, DataTypes} = require("./sequelize"); const Appointment = sequelize.define('Appointment', { name: DataTypes.STRING, phone: DataTypes.STRING, query: DataTypes.TEXT, email: DataTypes.STRING, date: DataTypes.DATE, branch: DataTypes.STRING, practice: DataTypes.STRING, purpose: DataTypes.STRING, approved: { type: DataTypes.BOOLEAN, defaultValue: false } }); module.exports = Appointment;
import React from 'react'; import PropTypes from 'prop-types'; import { TouchableOpacity } from 'react-native'; const propTypes = {}; const defaultProps = {}; /** * Touchable component * @param {any} props * @default activeOpacity={0.8} */ const Touchable = props => <TouchableOpacity activeOpacity={0.8} {...props} /> Touchable.propTypes = propTypes; Touchable.defaultProps = defaultProps; export default Touchable;
import startGame from '../src/js/application.js'; import Controller from '../src/js/controller.js'; describe('Checking startGame()', () => { it('should successfully create Controller object', () => { const testObject = startGame(); const result = testObject instanceof Controller; assert.equal(result, true); }); });
import { StyleSheet, Platform, StatusBar } from 'react-native'; import Colors from '../../constants/Colors'; import Layout from '../../constants/Layout'; const screenWidth = Layout.window.width; const screenHeight = Layout.window.height; export default StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, flexContainer: { flex: 1, backgroundColor: '#fff', }, header: { height: Platform.OS === 'android' ? 120 + StatusBar.currentHeight : 120, backgroundColor: 'white', justifyContent: 'center' }, searchContainer: { flexDirection: 'row', alignItems: 'center', padding: 12, backgroundColor: 'white', marginHorizontal: 24, shadowOffset: { width: 0, height: 0 }, shadowRadius: 7, shadowColor: Colors.gray04, shadowOpacity: 0.2, elevation: 3, marginTop: Platform.OS === 'android' ? 30 : null, height: 50, borderRadius: 6, borderWidth: 0.7, borderColor: Colors.gray05, zIndex: 2 }, searchIcon: { paddingLeft: 5 }, closeIcon: { marginTop: 1, opacity: 0.6 }, textInputBox: { flex: 1, fontSize: 14, fontWeight: '500', color: Colors.red, opacity: 0.85, backgroundColor: 'white', paddingLeft: 20, marginTop: 2.5 }, categoriesText: { color: Colors.gray04, fontSize: 22, fontWeight: '600', paddingHorizontal: 24 }, titleText: { color: Colors.black, opacity: 0.85, fontSize: 17, fontWeight: '600' }, subtitleText: { color: '#afb8bb', fontSize: 14, fontWeight: '500' }, ratingContainer: { flexDirection: 'row', marginTop: 5, alignItems: 'center' }, rankingText: { color: 'grey', fontSize: 10, marginLeft: 4 }, adContainer: { borderWidth: 1, borderColor: 'green', borderRadius: 3, marginRight: 10 }, adText: { color: 'green', fontSize: 10, marginHorizontal: 3, marginVertical: 2 }, indicatorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', marginBottom: 10 }, noResultsContainer: { flex: 1, marginTop: 100, justifyContent: 'center', alignItems: 'center' }, noResultsText: { fontSize: 14, fontWeight: '400', color: Colors.gray03, textAlign: 'center' }, recomendedHeadline: { color: Colors.gray04, fontSize: 24, fontWeight: '600', paddingHorizontal: 24 }, recommendedCardContainer: { width: (screenWidth/2) - 34, height: (screenHeight/4), paddingBottom: 25 }, })
"use strict"; const FujiwaraError = require('./fujiwara-error'); const isString = require('lodash.isstring'); module.exports = function(text, opts) { if (!isString(text)) { const errorMessage = 'そ゛ん゛な゛ひ゛き゛す゛う゛わ゛か゛ら゛ね゛え゛よ゛お゛お゛お゛お゛!゛!゛!゛'; throw new FujiwaraError(errorMessage); } opts = Object.assign({ separator: '゛', ignoreSpaces: true, ignoreChars: [], }, opts); if ( opts.ignoreSpaces ) { opts.ignoreChars = opts.ignoreChars.concat([' ', ' ']); } return text.split('').map((char) => { if ( char.charCodeAt() < 0x20 ) return char; if ( opts.ignoreChars.indexOf(char) !== -1 ) return char; return char + opts.separator; }).join(''); }
import * as api from 'api'; const SEARCH_FOCUS = 'SEARCH_FOCUS'; const SEARCH_BLUR = 'SEARCH_BLUR'; const SEARCH_REQUEST = 'SEARCH_REQUEST'; const SEARCH_COMPLETE = 'SEARCH_COMPLETE'; const SEARCH_ERROR = 'SEARCH_ERROR'; export const searchFocus = () => ({ type: SEARCH_FOCUS, }); export const searchBlur = () => ({ type: SEARCH_BLUR, }); export const searchRequest = (term) => ({ type: SEARCH_REQUEST, term }); export const searchComplete = (results) => ({ type: SEARCH_COMPLETE, results }); export const searchError = (message) => ({ type: SEARCH_ERROR, message }) export const fetchSearchResults = (term) => { return async function(dispatch, getState) { dispatch(searchRequest(term)); const results = await api.getSearchResults(term); const currentTerm = getState().search.term; if (currentTerm === term && !results.error) { dispatch(searchComplete(results)); } else { dispatch(searchError(results.message)); } }; }; const initialState = { hasFocus: false, isPending: false, term: '', results: [], }; export const searchReducer = (state = initialState, action) => { switch (action.type) { case SEARCH_FOCUS: return Object.assign({}, state, { hasFocus: true, }); case SEARCH_BLUR: return Object.assign({}, state, { hasFocus: false, }); case SEARCH_REQUEST: return Object.assign({}, state, { isPending: true, term: action.term, results: [], }); case SEARCH_COMPLETE: return Object.assign({}, state, { isPending: false, results: action.results, }); case SEARCH_ERROR: return Object.assign({}, state, { isPending: false, error: action.message, }) default: return state; } }
/** * Created by wen on 2016/8/16. */ import React, { PropTypes,Component } from 'react'; import s from './SearchInput.css'; import ClassName from 'classnames'; import history from './../../core/history'; import {Icon} from './../../components'; class SearchInput extends Component { constructor(props) { super(props); this.state = { label: true, searchVal: '', linkUrl: this.props.linkUrl || '', searchUrl: this.props.serachUrl || '', }; } static contextTypes = { insertCss: PropTypes.func.isRequired, }; componentWillMount() { const { insertCss } = this.context; this.removeCss = insertCss(s); } componentWillUnmount() { this.removeCss(); } handleLabelClick (){ if(this.state.linkUrl){ history.push(this.state.linkUrl); }else { //手动获取焦点 this.refs.search.focus(); this.setState({ label: false }); } } handleBlur(){ if(this.state.searchVal.length === 0){ this.setState({ label: true }); } } handleFocus(){ if(this.state.searchVal.length === 0){ this.setState({ label: true }); } } handleChange(e){ if(e.target.value.length === 0){ this.setState({ label: true, searchVal: e.target.value }); }else { this.setState({ label: false, searchVal: e.target.value }); } } getVal(){ return this.state.searchVal; } jumpToSearchUrl(){ this.props.jumpEvent && this.props.jumpEvent(); this.state.linkUrl && history.push(this.state.linkUrl); } render() { return ( <div className={ClassName([s.searchDir,s.flex1])} onClick={(e)=>this.jumpToSearchUrl(e)}> {this.state.label ? (<span onClick={(e)=>this.handleLabelClick(e)}><span>请输入精品酒店/城市/国家</span></span>) : null} <input type="text" id="search" ref="search" onFocus={(e)=>this.handleFocus(e)} onBlur={(e)=>this.handleBlur(e)} onChange={(e)=>this.handleChange(e)} value={this.state.searchVal} className={ClassName([s.flex1])} /> </div> ); } } export default SearchInput;
import { parseQuery, stringifyQuery } from './querystring' export function parseUrl(path, parse) { let hash = '' let query = '' const hashIndex = path.indexOf('#') if (hashIndex >= 0) { hash = path.slice(hashIndex) path = path.slice(0, hashIndex) } const queryIndex = path.indexOf('?') if (queryIndex >= 0) { query = path.slice(queryIndex + 1) path = path.slice(0, queryIndex) } if (parse && query) { query = parseQuery(query) } return { path, query, hash } } export function stringifyUrl({ path, query, hash }) { query = typeof query === 'object' ? stringifyQuery(query) : query query = query ? `?${query}` : '' hash = hash ? `#${hash}` : '' return `${path}${query}${hash}` }
import classes from './Categories.module.css'; import { CategoriesArray } from '../../utils/static-data'; import PageHeader from '../PageHeader/PageHeader'; import ImageOverlayText from '../UI/ImageOverlayText/ImageOverlayText'; const Categories = () => { return ( <> <PageHeader heading="Categories" /> <div className={classes.CategoriesContainer}> {CategoriesArray.map((category) => ( <ImageOverlayText title={category.category} image={category.image} /> ))} </div> </> ); }; export default Categories;
import React, { useContext, useState } from 'react'; import Link from 'next/link'; import { useRouter } from 'next/router'; import { useQuery, useMutation } from '@apollo/client'; import Layout from '../../components/Layout'; import Spinner from '../../components/Spinner'; import ProductCard from './ProductCard'; import TodoContext from '../../context/TodoContext'; import { OBTENER_PRODUCTOS_USUARIO, ELIMINAR_PRODUCTO } from '../../graphql/dslgql'; import Swal from 'sweetalert2'; const Propios = () => { const router = useRouter(); const { activeUser } = useContext(TodoContext); const [outProductId, setOutProductId] = useState(null); const { data: dataProductos, loading: obtenerProductosLoading, error: obtenerProductosError, } = useQuery(OBTENER_PRODUCTOS_USUARIO); const [ removeProduct, { loading: eliminarProductoLoading, error: eliminarProductoError }, ] = useMutation(ELIMINAR_PRODUCTO, { update(cache) { const { getProducts } = cache.readQuery({ query: OBTENER_PRODUCTOS_USUARIO, }); cache.writeQuery({ query: OBTENER_PRODUCTOS_USUARIO, data: { getProducts: getProducts.filter((userHere) => userHere.id !== outProductId), }, }); }, }); if (obtenerProductosLoading) return <Spinner />; if (obtenerProductosError) return ( <Layout> <h1>Problemas la llamada al origen de datos</h1> </Layout> ); const editProduct = (id, name) => { const styleParam = name.toString().toLowerCase().replace(/\s/g, '-'); router.push({ pathname: '/productos/editar/[name]', query: { name: styleParam, pid: id }, }); }; const removeProductId = (productId, productName) => { Swal.fire({ title: `Deseas eliminar - ${productName}.?`, text: 'Esta accion no podra revertirse..!', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si, eliminar', cancelButtonText: 'Cancelar', }).then(async (result) => { if (result.isConfirmed) { try { setOutProductId(productId); const { data } = await removeProduct({ variables: { removeProductId: productId, }, }); Swal.fire( `${data.removeProduct}`, `El producto ${productName} fue eliminado`, 'success' ); } catch (error) { // console.log(error); const { message } = error; Swal.fire('Error', `${message}`, 'error'); } } }); }; const { getProductsbyUser: listaDeProductos } = dataProductos; return ( <Layout> <title className="flex justify-between items-baseline"> <Link href="/productos/nuevo"> <a className="py-2 px-5 text-blue-800 rounded text-sm border hover:bg-gray-200 uppercase font-bold w-full lg:w-auto text-center"> <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 inline-block mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /> </svg> <span className="align-bottom">Nuevo Producto</span> </a> </Link> <h1 className="text-2xl text-gray-600 font-semibold uppercase mr-4"> Productos del Inventario </h1> </title> <div className="py-6 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-5"> {listaDeProductos.map((product, idx) => ( <ProductCard key={idx} productName={product.name} productDescription={product.description} nameUser={product.user.name} emailUser={product.user.email} hashtags={product.hashtags} userActive={activeUser} product={product} handleEdit={() => editProduct(product.id, product.name)} handleRemove={() => removeProductId(product.id, product.name)} /> ))} </div> </Layout> ); }; export default Propios;
// test/network.js; /* global apiKey, describe, it, should */ var TheEchoNest = require('../src'); var demoUrl = 'song/profile?format=json&id=SOCZMFK12AC468668F'; describe('Network', function() { var echonest = new TheEchoNest(apiKey); var network = echonest.network; it('should make a network request', function(done) { network.get(demoUrl, function(err, data) { should.not.exist(err); should.exist(data); done(); }); }); it('should handle rate limits', function(done) { echonest.setApiKey('FILDTEOIK2HBORODV'); this.timeout(10000); var finished = false; var fn = function(err, response) { if (finished) return; if (err) { echonest.setApiKey(apiKey); done(); finished = true; return; } response.headers.should.have.property('x-ratelimit-limit'); response.headers.should.have.property('x-ratelimit-used'); response.headers.should.have.property('x-ratelimit-remaining'); var limit = parseInt(response.headers['x-ratelimit-limit'], 10); var used = parseInt(response.headers['x-ratelimit-used'], 10); var remaining = parseInt(response.headers['x-ratelimit-remaining'], 10); used.should.be.below(limit); remaining.should.be.above(0); }; for (var i = 0; i < 10; i++) { network.get(demoUrl, fn); } }); });
Meteor.publish('snippets', function() { return Snippets.find({ owner: this.userId //this.userId is the logged in user }); }) Snippets.allow({ insert: function(userId, fields) { return userId; //make sure user is logged in } })
import { combineReducers } from "redux"; import { reduxForm as form } from "redux-form"; import addWordReducer from "./addWordReducer"; import getWordsReducer from "./getWordsReducer"; import dictionariesReducer from "./dictionariesReducer"; import preloadReducer from "./preloadReducer"; import errorReducer from "./errorReducer"; import recentLanguageReducer from "./recentLanguageReducer"; export default combineReducers({ form : form, word: addWordReducer, words: getWordsReducer, preload: preloadReducer, error: errorReducer, recentLanguage: recentLanguageReducer, dictionaries: dictionariesReducer })
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PassportLocalMongoose = require("passport-local-mongoose"); const userSchema = new Schema({ nombreUsuario:String, correo:String, nombre: String, apellido: String, googleID: String, fotoPerfil:String, codigoPostal: Number, cuentaConfirmada:{ type: Boolean, default:false }, terminosCondiciones:Boolean, correoEnviado:{ type: Boolean, default:false }, telefono:String, ranking: { type:Number, default:0 }, ganador:{ type: Boolean, default:false }, calificacion: { type:Number, default:0, min:0 }, total:{ type:Number, default:0, min:0 }, puesto:{ type: String, enum : ['SUPERADMIN', 'GERENTE', 'CHECKTICKET','SUPERVISOR','EMBAJADOR','USER'], default : 'USER' }, ventas: [{ type:Schema.Types.ObjectId, ref:"Ventas" }], ventasDinamica: [], marcas:[{ ref: { type:Schema.Types.ObjectId, ref:"Marca" }, puntosVentas:{ type: Number, default: 0, min:0, required: true }, puntosUsuario:{ type: Number, default: 0, min:0, required:true }, nombre:{ type: String, required:false } }], habilidades:[{ limpieza:{ type: Number, default: 0, min:0, max: 5, required: false }, puntualidad:{ type: Number, default: 0, min:0, max: 5, required: false }, disciplinado:{ type: Number, default: 0, min:0, max: 5, required: false }, colaborativo:{ type: Number, default: 0, min:0, max: 5, required: false } }], documentos:{ idOficial:{ type: String, required: false }, actaNac:{ type: String, required: false }, curp:{ type: String, required: false } }, centroConsumo:{ type: Schema.Types.ObjectId, ref: "CentroConsumo" }, brand:{ type:Schema.Types.ObjectId, ref:"Brand" }, dinamicasGanadas:[{ type:Schema.Types.ObjectId, ref:"Dinamica" }], evidencias:[{ type:Schema.Types.ObjectId, ref:"Evidencia" }], notificacion:[{ type:Schema.Types.ObjectId, ref:"Dinamica" }], notas:[{ type:Schema.Types.ObjectId, ref:"Nota" }] },{ timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); userSchema.plugin(PassportLocalMongoose, { usernameField:"correo" }); module.exports = mongoose.model('User', userSchema); // EL MODELO MAS GRANDE DE LA APP, ES EL CENTRO DE NUESTRA APP, TIENEN RELACION CON CASI TODOS LOS DEMAS MODELOS // UN USUARIO PERTENECE A UN CENTRO DE CONSUMO, CREA EVIDENCIAS, PARTICIPA EN DINAMICAS, GENERA VENTAS DE LAS EVIDENCIAS APROBADAS // LE HACEN NOTAS DE LAS EVIDENCIAS QUE LE RECHAZARON, VENDE MARCAS Y TIENE UN PUESTO, LOS QUE SON SOLO USER SOLO SON USUARIOS DEL APP // LOS QUE TIENEN OTRO PUESTO SON USUARIOS DEL DASHBOARD // QUIERO RESALTAR QUE LA CALIFICACION SE HA USADO PARA LO SPUNTOS GLOBALES DE LOS USUARIOS
//弹出层时间 var alertTime = 2; //弹出层标题 var alertTitle = "温馨提示"; /** * * 弹出框架 * url : 链接路径 * title : 窗口标题 * width : 宽 * height : 高 * */ var iframePop = function(url, title, width, height) { var index = parent.$.layer({ type: 2, //类型 title: title, //标题 area: [width, height], //宽高 iframe: {src: url} }); return index; }; /** * * 关闭弹出层 * */ var alertClose = function() { parent.layer.closeAll(); }; /** * 弹出HTML内容层 * @param {Object} title 标题 * @param {Object} width 宽度 * @param {Object} height 高度 * @param {Object} html 显示内容 */ var alertHtml = function(title, width, height, html) { var index = parent.$.layer({ type: 1, //类型 title: title, //标题 area: [width, height], //宽高 page: {html: html} }); return index; }; /** * 弹出指定选择器内容 * @param {Object} title 标题 * @param {Object} width 宽度 * @param {Object} height 高度 * @param {Object} id 选择器ID */ var alertDom = function(title, width, height, id) { var index = parent.$.layer({ type: 1, //类型 title: title, //标题 area: [width, height], //宽高 page: {html: $(id).html()} }); return index; }; /** * 弹出指定AJAX * @param {Object} url 路径异步路径 * @param {Object} width 宽度 * @param {Object} height 高度 * @param {Object} ok_callback 成功回调路径 */ var alertAjax = function(url, width, height, ok_callback) { parent.$.layer({ type: 1, //类型 title: title, //标题 loading: {type: 2}, area: [width, height], //宽高 page: { url: url, ok: function() { ok_callback(); } } }); }; window.alert = function(msg, icon, callback) { /** * 用例: * eq1:alert("我是一个测试弹出层"); * eq2:alert("我是一个测试弹出层",-1,function(){ * alertMsg("我要刷新页面"); * }); */ if (icon == undefined || icon == null) { icon = -1; } var index = 0; if (callback != undefined && callback != null) { index = parent.layer.alert(msg, icon, function() { callback(); }); } else { index = parent.layer.alert(msg, icon); } parent.layer.title(alertTitle, index); }; /** * * 简单的弹出层 * msg : 消息内容(必填) * icon : 图标(可选) -1没符号 1正确 2错误 * callback : 回调方法(可选) *; */ var alertMsg = function(msg, icon, callback, time) { /** * 用例: * eq1:alertMsg("我是一个测试弹出层"); * eq2:alertMsg("我是一个测试弹出层",-1,function(){ * alertMsg("我要刷新页面"); * }); */ if (icon == undefined || icon == null) { icon = -1; } if (time == undefined || time == null) { time = alertTime; } if (callback != undefined && callback != null) { parent.layer.msg(msg, time, icon, function() { callback(); }); } else { parent.layer.msg(msg, time, icon); } }; /** * * 弹出确认弹出层 * msg : 消息内容 * yes_callback : 正确的回调方法 (可选) * no_callback : 错误的回调方法(可选) * */ var alertConfirm = function(msg, yes_callback, no_callback) { /** * 用例: * eq1:alertConfirm("弹出确认提示层"); * eq2:alertConfirm("弹出确认提示层",function(){ * alertMsg("确认"); * }); * eq3:alertConfirm("弹出确认提示层",function(){ * alertMsg("确认"); * },function(){ * alertMsg("取消"); * }); */ if (yes_callback == undefined || yes_callback == null) { yes_callback = function() { }; } if (no_callback == undefined || no_callback == null) { no_callback = function() { }; } var index = parent.layer.confirm(msg, function() { yes_callback(); parent.layer.close(index); }, function(index) { no_callback(); }); parent.layer.title(alertTitle, index); }; /** * * 弹出加载弹出层 * msg : 消息内容 * callback : 回调方法 (可选) 返回true false */ var alertLoad = function(msg, callback) { /** * 用例: * eq1:alertLoad("加载中..."); * eq2:alertLoad("加载中...", function () { * return true; * }); */ if (callback == undefined || callback == null) { parent.layer.load(msg); } else { var index = parent.layer.load(msg); if (callback()) { setTimeout(function() { parent.layer.close(index); }, alertTime * 1000); } } }; //icon 对应数字 //parent.layer.alert(msg, -1); 没符号 //parent.layer.alert(msg, 0); 感叹号 //parent.layer.alert(msg, 1); 正确 //parent.layer.alert(msg, 2); 错误 //parent.layer.alert(msg, 3); 禁止 //parent.layer.alert(msg, 4); 问号 //parent.layer.alert(msg, 5); 减号 //parent.layer.alert(msg, 6); 赞 //parent.layer.alert(msg, 7); 锁 //parent.layer.alert(msg, 8); 哭脸 //parent.layer.alert(msg, 9); 笑脸 //parent.layer.alert(msg, 10); 正确 //parent.layer.alert(msg, 11); 闹钟 //parent.layer.alert(msg, 12); 消息 //parent.layer.alert(msg, 13); 米田共 //parent.layer.alert(msg, 14); 邮箱发送箭头 //parent.layer.alert(msg, 15); 鼠标下箭头 //parent.layer.alert(msg, 16); 加载
import jwtDecode from 'jwt-decode' /** * Check if token still active or not. */ export const isAuthenticated = () => { const token = window.localStorage.getItem('token') if (token){ const decodedToken = jwtDecode(token) return decodedToken.exp * 1000 - new Date().getTime() >= 0 } return false } /** * Remove token from local storage. */ export const clearToken = () => { window.localStorage.removeItem("token") } /** * Get token from local storage. */ export const getToken = () => { return window.localStorage.getItem("token") }
var utilityService =(function(){ var sr = this; sr.domList=[]; var timeout = 2000; var showStatus = function (msg){ sr.domList.forEach(function(domIn,index){ domIn.dom.innerHTML =msg; clearMsg(domIn.dom); }); }; var hide= function(dom){ dom.classList.remove('show'); dom.classList.add('hide'); }; var show= function(dom){ dom.classList.remove('hide'); dom.classList.add('show'); }; var toggle = function (dom,selector) { dom.addEventListener('click',function () { var ele=document.querySelector(selector); dom.classList.toggle("expand"); dom.classList.toggle("collapse"); if(ele){ ele.classList.toggle("hide"); ele.parentNode.classList.toggle("active"); } }); }; var clearMsg = function(dom){ setTimeout(function(){ dom.innerHTML = ''; },timeout); }; sr.registerDOM = function(dom,type){ sr.domList.push({dom:dom,type:type}); }; return { showStatus:function(msg){ showStatus(msg); }, registerDOM : function(dom,type){ sr.registerDOM(dom,type); }, toggle: function (dom,selector){ toggle(dom,selector); }, show: function(dom){ show(dom); }, hide:function(dom){ hide(dom); } }; });
import { configureStore } from "@reduxjs/toolkit"; import movieReducer from "./data/Movies/MovieSlice"; import tvshowReducer from "./data/Movies/TvShowsSlice"; import userReducer from "./data/auth/UserSlice"; // 3a6ea45912e022a5d4fdac499fa4adc2 export const store = configureStore({ reducer: { movie: movieReducer, tvshow: tvshowReducer, user: userReducer, }, });
import Ember from "ember"; export default Ember.Component.extend({ tagName: '', // don't create a tag for this component actions: { submit(newTitle) { if (newTitle) { this.sendAction('action', newTitle); } this.set('newTitle', ''); } } });
export PatientInputItem from './PatientInputItem'; export InputModal from './InputModal';
const test = require('tape'); const isSimilar = require('./isSimilar.js'); test('Testing isSimilar', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof isSimilar === 'function', 'isSimilar is a Function'); //t.deepEqual(isSimilar(args..), 'Expected'); //t.equal(isSimilar(args..), 'Expected'); //t.false(isSimilar(args..), 'Expected'); //t.throws(isSimilar(args..), 'Expected'); t.end(); });
"use strict"; PipedriveTest.Routers = PipedriveTest.Routers || {}; (function () { 'use strict'; PipedriveTest.Routers.User = Backbone.Router.extend({ routes: { "profile/:id": "profileContactInfo" }, initialize: function () { Backbone.history.start(); }, profileContactInfo: function(id) { $.ajax({ url: 'https://api.pipedrive.com/v1/persons?start=0&api_token=a77e4790e268f8a65e83efc2f9054a7de3d0ac75', success:function(result){ var profile = getObjectById(result.data, id); var dealsCollection = new PipedriveTest.Collections.Deals(); var profileInfoView = new PipedriveTest.Views.ProfileInfo({collection: profile, dealsCollection: dealsCollection}); if(profile.open_deals_count !== 0) { dealsCollection.getResults(); } } }) }, }); function getObjectById(collection, id) { return collection.filter(function (el) { return el.id == id; })[0] } })();
var isLoggedIn = false; jQuery.fn.simulateKeyPress = function(character) { jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) }); }; function ShowModal() { ShowSection('about'); // Get the modal var modal = document.getElementById('about'); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; modal.style.display = "block"; // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function (event) { if (event.target == modal) { modal.style.display = "none"; } } window.onkeyup = function (event) { if (event.keyCode == 27) { modal.style.display = "none"; } } } function ShowSection(id) { //hide all sections var section1 = document.getElementById('welcome'); section1.style.display = "none"; var section2 = document.getElementById('register'); section2.style.display = "none"; var section3 = document.getElementById('settings'); section3.style.display = "none"; var section4 = document.getElementById('about'); section4.style.display = "none"; var section5 = document.getElementById('login'); section5.style.display = "none"; var section6 = document.getElementById('pacman'); section6.style.display = "none"; //show only one section var selected = document.getElementById(id); selected.style.display = 'inline-block'; if (id !== 'pacman') { $('body').simulateKeyPress('p'); } } $('#mybutton').on('click', function (evt) { $('#mydiv').show(); return false;//Returning false prevents the event from continuing up the chain }); function Login() { // Log the user in and start pacman. // call login // var userName = document.forms["formLogIn"]["unInput"].value; //= ""; // var pass = document.forms["formLogIn"]["pswdInput"].value; // = ""; // if(checkPassword(userName,pass)){ document.forms["formLogIn"]["unInput"].value = ""; document.forms["formLogIn"]["pswdInput"].value = ""; if (isLoggedIn) { ShowSection('settings'); } // } } function changeInnerHtml(elementId, value) { document.getElementById(elementId).innerHTML = value; } // catch click on a and call pause
import React, { Component } from "react"; import { ComposedChart, Line, Area, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine } from "recharts"; class CustomTooltip extends Component { constructor(props) { super(props); } render() { const { active } = this.props; if (active) { const { payload } = this.props; return ( <div style={{ backgroundColor: "white", padding: 5 }}> <div style={{ textAlign: "center", fontSize: 10 }}> {payload[0].payload.name} Minute Games </div> <div style={{ textAlign: "center", fontSize: 10 }}> Win Rate: {(100 * payload[0].payload.rate).toFixed(2)}% </div> <div style={{ textAlign: "center", fontSize: 10 }}> Games Analyzed: {payload[0].payload.games} </div> </div> ); } return null; } } class WinsByMatchLength extends Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidUpdate(prevProps) { if (this.props != prevProps) { this.componentDidMount(); } } componentDidMount() { const { data } = this.props; if (!data) { this.setState({ data: null }); return; } let min = data.zeroToFifteen.count; let max = data.zeroToFifteen.count; for (var key in data) { let curCount = data[key].count; if (curCount < min) { min = curCount; } if (curCount > max) { max = curCount; } } function minMaxScale(val, max, min) { return ((val - min) / (max - min)) * (0.4 - 0.05) + 0.05; } let matchLengthData = [ { name: "0-15", rate: data.zeroToFifteen.winRate, games: data.zeroToFifteen.count, countMinMaxScaled: minMaxScale(data.zeroToFifteen.count, max, min) }, { name: "15-20", rate: data.fifteenToTwenty.winRate, games: data.fifteenToTwenty.count, countMinMaxScaled: minMaxScale(data.fifteenToTwenty.count, max, min) }, { name: "20-25", rate: data.twentyToTwentyFive.winRate, games: data.twentyToTwentyFive.count, countMinMaxScaled: minMaxScale(data.twentyToTwentyFive.count, max, min) }, { name: "25-30", rate: data.twentyFiveToThirty.winRate, games: data.twentyFiveToThirty.count, countMinMaxScaled: minMaxScale(data.twentyFiveToThirty.count, max, min) }, { name: "30-35", rate: data.thirtyToThirtyFive.winRate, games: data.thirtyToThirtyFive.count, countMinMaxScaled: minMaxScale(data.thirtyToThirtyFive.count, max, min) }, { name: "35-40", rate: data.thirtyFiveToForty.winRate, games: data.thirtyFiveToForty.count, countMinMaxScaled: minMaxScale(data.thirtyFiveToForty.count, max, min) }, { name: "40+", rate: data.fortyPlus.winRate, games: data.fortyPlus.count, countMinMaxScaled: minMaxScale(data.fortyPlus.count, max, min) } ]; this.setState({ data: matchLengthData }); } render() { const { palette } = this.props; const { data } = this.state; if (data) { return ( <div style={{ width: 500, height: 300 }}> <div style={{ fontWeight: "bold", position: "relative", textAlign: "center", color: "white" }}> Win Rates by Match Length </div> <ComposedChart width={500} height={300} data={data} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}> <XAxis dataKey="name" style={{ fontSize: 12 }} /> <YAxis domain={[0, 1]} style={{ fontSize: 12 }} /> <ReferenceLine y={0.5} stroke="white" /> <Tooltip content={<CustomTooltip />} /> <Legend wrapperStyle={{ color: "white" }} verticalAlign="top" /> <Area name="Win Rate" type="monotone" dataKey="rate" fill={palette.Vibrant} stroke={palette.Muted} /> <Bar name="Games Analyzed" dataKey="countMinMaxScaled" barSize={20} fill={palette.LightVibrant} /> </ComposedChart> </div> ); } else { return <div />; } } } export default WinsByMatchLength;
var CONSTANT = { postPerPage : 10 } module.exports = CONSTANT;
function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13, mapTypeId: 'roadmap' }); // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } // Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { if (!place.geometry) { console.log("Returned place contains no geometry"); return; } var icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; // Create a marker for each place. markers.push(new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location })); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); } //weatherly from here down var icon; var latitude; var longitude; var city; var temperature; function darksky_complete(result) { console.log(result.latitude); console.log(result.longitude); console.log(result.timezone); console.log(result.currently.icon); console.log(result.currently.time); console.log(result.currently.temperature); icon=result.currently.icon temperature =result.currently.temperature generateCard(); } function toggle_div(id){ var divElement = document.getElementById(id); if(divElement.style.display == 'none') divElement.style.display = 'block'; else divElement.style.display = 'none'; } function lookupLatLong_Complete(result) { city= result.results["0"].formatted_address; latitude = result.results["0"].geometry.location.lat; longitude = result.results["0"].geometry.location.lng; console.log("The lat and long is " + latitude + ", " + longitude); var request = { url: "https://api.darksky.net/forecast/3076dd7488b4447914c19faca690a9f0/" + latitude + "," + longitude, dataType: "jsonp", success: darksky_complete }; $.ajax(request); } function lookupLatLong(city, state, postalCode) { var address = ""; if (postalCode.length != 0) { address = postalCode.trim(); } else if (city.length != 0 && state != 0) { address = city.trim() + ", " + state; } else { return; } var googleUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyANgZVmo6IYYgJX4bG2m0mxyKsQhvM6aiE"; var request = { url: googleUrl, success: lookupLatLong_Complete }; $.ajax(request); } function lookupWeatherForPostalCode_Click() { var pcode = $("#postalCode").val(); lookupLatLong("", "", pcode); console.log(test); } function lookupWeatherForPostalCode_Click() { var pcode = $("#postalCode").val(); lookupLatLong("", "", pcode); } function hide() { $("#cards").empty(); } function weatherTemplate() { var template = $("#templateDiv").html(); switch(icon){ case "clear-day": case "clear-night": case "rain": case "fog": case "snow": case "sleet": case "cloudy": case "wind": case "partly-cloudy-day": case "partly-cloudy-night": template = template.replace("@@help@@", icon + ".png" ); break; default: template = template.replace("@@help@@", "http://wallpapercave.com/wp/4W2pw5V.jpg"); break; } template = template.replace("@@icon@@", icon); template = template.replace("@@latitude@@", latitude); template = template.replace("@@longitude@@", longitude); template = template.replace("@@city@@", city); template = template.replace("@@temperature@@", temperature); // Return the new HTML. return template; } // The divs will automatically wrap because of Bootstrap knowing it's a col-md-3. function generateCard(result){ var html = weatherTemplate; $("#cards").append(html); } $(function () { $("#postButton").on("click", lookupWeatherForPostalCode_Click) $("#cards").on("click", hide) });
import React, { useEffect, useRef } from "react"; import styled from "@emotion/styled"; import { md } from "../utils/markdown"; const Wrapper = styled.section` display: flex; align-items: center; `; const InnerDiv = styled.div` flex: 1; `; const Slide = ({ value }) => { const section = useRef(); useEffect(() => { section.current.scrollIntoView({ behavior: "smooth" }); }, [section, value]); return ( <Wrapper ref={section}> <InnerDiv dangerouslySetInnerHTML={{ __html: md.render(value) }} ></InnerDiv> </Wrapper> ); }; export default Slide;
import React from "react" import { View, Image, ImageBackground, TouchableOpacity, Text, Button, Switch, TextInput, StyleSheet, ScrollView } from "react-native" import Icon from "react-native-vector-icons/FontAwesome" import { CheckBox } from "react-native-elements" import { connect } from "react-redux" import { widthPercentageToDP as wp, heightPercentageToDP as hp } from "react-native-responsive-screen" import { getNavigationScreen } from "@screens" export class Blank extends React.Component { constructor(props) { super(props) this.state = {} } render = () => ( <ScrollView contentContainerStyle={{ flexGrow: 1 }} style={styles.ScrollView_1} > <View style={styles.View_2} /> <View style={styles.View_1127_5738}> <Text style={styles.Text_1127_5738}> Check your email, we send you the financial report. In certain cases, it might take a little longer, depending on the time period and the volume of activity. </Text> </View> <View style={styles.View_1271_5796}> <View style={styles.View_I1271_5796_1271_5613} /> <View style={styles.View_I1271_5796_1257_5008}> <View style={styles.View_I1271_5796_1257_5009} /> <View style={styles.View_I1271_5796_1257_5010}> <View style={styles.View_I1271_5796_1257_5011} /> </View> <View style={styles.View_I1271_5796_1257_5012}> <View style={styles.View_I1271_5796_1257_5013} /> <View style={styles.View_I1271_5796_1257_5014} /> <View style={styles.View_I1271_5796_1257_5015} /> </View> <View style={styles.View_I1271_5796_1257_5016} /> <View style={styles.View_I1271_5796_1257_5017} /> <View style={styles.View_I1271_5796_1257_5018} /> </View> </View> <View style={styles.View_1127_5737}> <View style={styles.View_I1127_5737_217_6977} /> </View> <View style={styles.View_1127_5740}> <View style={styles.View_I1127_5740_568_4137}> <Text style={styles.Text_I1127_5740_568_4137}>Back to Home</Text> </View> </View> <View style={styles.View_1127_5736}> <View style={styles.View_I1127_5736_816_137}> <View style={styles.View_I1127_5736_816_138}> <Text style={styles.Text_I1127_5736_816_138}>9:41</Text> </View> </View> <View style={styles.View_I1127_5736_816_139}> <View style={styles.View_I1127_5736_816_140}> <View style={styles.View_I1127_5736_816_141}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730" }} style={styles.ImageBackground_I1127_5736_816_142} /> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe" }} style={styles.ImageBackground_I1127_5736_816_145} /> </View> <View style={styles.View_I1127_5736_816_146} /> </View> <View style={styles.View_I1127_5736_816_147}> <View style={styles.View_I1127_5736_816_148} /> <View style={styles.View_I1127_5736_816_149} /> <View style={styles.View_I1127_5736_816_150} /> <View style={styles.View_I1127_5736_816_151} /> </View> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/6a2b/c9ca/21b52f3f9fca9a68ca91e9ed4afad110" }} style={styles.ImageBackground_I1127_5736_816_152} /> </View> </View> <View style={styles.View_1127_5741}> <View style={styles.View_I1127_5741_223_1218}> <View style={styles.View_I1127_5741_223_1219}> <Text style={styles.Text_I1127_5741_223_1219}>9:41</Text> </View> </View> <View style={styles.View_I1127_5741_223_1220}> <View style={styles.View_I1127_5741_223_1221}> <View style={styles.View_I1127_5741_223_1222}> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730" }} style={styles.ImageBackground_I1127_5741_223_1223} /> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe" }} style={styles.ImageBackground_I1127_5741_223_1226} /> </View> <View style={styles.View_I1127_5741_223_1227} /> </View> <View style={styles.View_I1127_5741_223_1228}> <View style={styles.View_I1127_5741_223_1229} /> <View style={styles.View_I1127_5741_223_1230} /> <View style={styles.View_I1127_5741_223_1231} /> <View style={styles.View_I1127_5741_223_1232} /> </View> <ImageBackground source={{ uri: "https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/6a2b/c9ca/21b52f3f9fca9a68ca91e9ed4afad110" }} style={styles.ImageBackground_I1127_5741_223_1233} /> </View> </View> </ScrollView> ) } const styles = StyleSheet.create({ ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" }, View_2: { height: hp("111%") }, View_1127_5738: { width: wp("91%"), minWidth: wp("91%"), minHeight: hp("10%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("57%"), justifyContent: "flex-start" }, Text_1127_5738: { color: "rgba(41, 43, 45, 1)", fontSize: 13, fontWeight: "500", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_1271_5796: { width: wp("83%"), minWidth: wp("83%"), height: hp("43%"), minHeight: hp("43%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("8%"), top: hp("10%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I1271_5796_1271_5613: { flexGrow: 1, width: wp("83%"), height: hp("43%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(196, 196, 196, 1)" }, View_I1271_5796_1257_5008: { flexGrow: 1, width: wp("83%"), height: hp("43%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_I1271_5796_1257_5009: { width: wp("69%"), height: hp("34%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), backgroundColor: "rgba(238, 229, 255, 1)", borderColor: "rgba(177, 138, 255, 1)", borderWidth: 1 }, View_I1271_5796_1257_5010: { width: wp("26%"), height: hp("28%"), top: hp("6%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, View_I1271_5796_1257_5011: { width: wp("26%"), height: hp("28%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), borderColor: "rgba(177, 138, 255, 1)", borderWidth: 3, borderTopLeftRadius: 24, borderTopRightRadius: 0, borderBottomLeftRadius: 0, borderBottomRightRadius: 24 }, View_I1271_5796_1257_5012: { width: wp("69%"), height: hp("34%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, View_I1271_5796_1257_5013: { width: wp("23%"), height: hp("22%"), top: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), backgroundColor: "rgba(211, 189, 255, 1)", borderTopLeftRadius: 0, borderTopRightRadius: 0, borderBottomLeftRadius: 0, borderBottomRightRadius: 24 }, View_I1271_5796_1257_5014: { width: wp("59%"), height: hp("14%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), backgroundColor: "rgba(211, 189, 255, 1)", borderTopLeftRadius: 24, borderTopRightRadius: 24, borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }, View_I1271_5796_1257_5015: { width: wp("37%"), height: hp("30%"), top: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("12%"), borderColor: "rgba(177, 138, 255, 1)", borderWidth: 3 }, View_I1271_5796_1257_5016: { width: wp("59%"), height: hp("14%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), borderColor: "rgba(177, 138, 255, 1)", borderWidth: 3, borderTopLeftRadius: 24, borderTopRightRadius: 24, borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }, View_I1271_5796_1257_5017: { width: wp("60%"), height: hp("16%"), top: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), borderColor: "rgba(177, 138, 255, 1)", borderWidth: 3 }, View_I1271_5796_1257_5018: { width: wp("69%"), height: hp("34%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), borderColor: "rgba(177, 138, 255, 1)", borderWidth: 3 }, View_1127_5737: { width: wp("100%"), minWidth: wp("100%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("106%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I1127_5737_217_6977: { flexGrow: 1, width: wp("36%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("32%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 1)" }, View_1127_5740: { width: wp("91%"), minWidth: wp("91%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("96%"), backgroundColor: "rgba(127, 61, 255, 1)" }, View_I1127_5740_568_4137: { flexGrow: 1, width: wp("32%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("30%"), top: hp("2%"), justifyContent: "center" }, Text_I1127_5740_568_4137: { color: "rgba(252, 252, 252, 1)", fontSize: 14, fontWeight: "400", textAlign: "center", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_1127_5736: { width: wp("100%"), minWidth: wp("100%"), height: hp("6%"), minHeight: hp("6%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5736_816_137: { flexGrow: 1, width: wp("14%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("2%") }, View_I1127_5736_816_138: { width: wp("14%"), minWidth: wp("14%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I1127_5736_816_138: { color: "rgba(22, 23, 25, 1)", fontSize: 12, fontWeight: "400", textAlign: "center", fontStyle: "normal", letterSpacing: -0.16500000655651093, textTransform: "none" }, View_I1127_5736_816_139: { flexGrow: 1, width: wp("18%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("2%") }, View_I1127_5736_816_140: { width: wp("7%"), minWidth: wp("7%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("11%"), top: hp("0%") }, View_I1127_5736_816_141: { width: wp("7%"), height: hp("2%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, ImageBackground_I1127_5736_816_142: { width: wp("6%"), minWidth: wp("6%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, ImageBackground_I1127_5736_816_145: { width: wp("0%"), minWidth: wp("0%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("1%") }, View_I1127_5736_816_146: { width: wp("5%"), minWidth: wp("5%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("0%"), backgroundColor: "rgba(22, 23, 25, 1)", borderColor: "rgba(76, 217, 100, 1)", borderWidth: 1 }, View_I1127_5736_816_147: { width: wp("5%"), height: hp("1%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, View_I1127_5736_816_148: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5736_816_149: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5736_816_150: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5736_816_151: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, ImageBackground_I1127_5736_816_152: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("0%") }, View_1127_5741: { width: wp("100%"), minWidth: wp("100%"), height: hp("6%"), minHeight: hp("6%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("-356%"), backgroundColor: "rgba(0, 0, 0, 0)" }, View_I1127_5741_223_1218: { flexGrow: 1, width: wp("14%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("2%") }, View_I1127_5741_223_1219: { width: wp("14%"), minWidth: wp("14%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_I1127_5741_223_1219: { color: "rgba(22, 23, 25, 1)", fontSize: 12, fontWeight: "400", textAlign: "center", fontStyle: "normal", letterSpacing: -0.16500000655651093, textTransform: "none" }, View_I1127_5741_223_1220: { flexGrow: 1, width: wp("18%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("2%") }, View_I1127_5741_223_1221: { width: wp("7%"), minWidth: wp("7%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("11%"), top: hp("0%") }, View_I1127_5741_223_1222: { width: wp("7%"), height: hp("2%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, ImageBackground_I1127_5741_223_1223: { width: wp("6%"), minWidth: wp("6%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, ImageBackground_I1127_5741_223_1226: { width: wp("0%"), minWidth: wp("0%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("1%") }, View_I1127_5741_223_1227: { width: wp("5%"), minWidth: wp("5%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("0%"), backgroundColor: "rgba(22, 23, 25, 1)", borderColor: "rgba(76, 217, 100, 1)", borderWidth: 1 }, View_I1127_5741_223_1228: { width: wp("5%"), height: hp("1%"), top: hp("0%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%") }, View_I1127_5741_223_1229: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5741_223_1230: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5741_223_1231: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_I1127_5741_223_1232: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, ImageBackground_I1127_5741_223_1233: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("0%") } }) const mapStateToProps = state => { return {} } const mapDispatchToProps = () => { return {} } export default connect(mapStateToProps, mapDispatchToProps)(Blank)
/* 266. Palindrome Permutation Given a string, determine if a permutation of the string could form a palindrome. Example 1: Input: "code" Output: false Example 2: Input: "aab" Output: true Example 3: Input: "carerac" Output: true */ str = "code"; function palindrome(str) { let hash = {}; let offSet = 0; for(let i = 0; i < str.length; i++) { if(!hash[str[i]]) { hash[str[i]] += 1; offSet++; } else { hash[str[i]] -= 1; offSet--; } } return console.log(offSet <= 1); } palindrome(str);
const propertiesTable = $('.properties'); const newRow = `<tr> <td> <input type=text class="property-name form-control" required> </td> <td> <select class="property-type form-control"> <option value="string">String</option> <option value="int">Int</option> <option value="double">Double</option> </select> </td> <td> <button type="button" class="btn btn-danger delete">Delete</button> </td> </tr> <tr>`; const textareaCode = ` <div class="form-group codeToShow mt-5"> <h4 class="text-center">Generated Code: </h4> <textarea id="code" rows="10" class="form-control"></textarea> </div>`; $('form').submit((e) => e.preventDefault()); $('.delete').click(deleteRow); function addRow() { propertiesTable.append(newRow); $('.delete').click(deleteRow); } function deleteRow() { $(this).parent().parent().remove(); } function copycode() { var copyText = document.getElementById("code"); copyText.select(); document.execCommand("copy"); } function generateCode() { if($(`input:required:invalid`).length > 0) { return; } $('.codeToShow').remove(); let className = $('#className').val(); let code = ` // Start s obiknovenni neshta #include <iostream> #include <string> #include <vector> #include <list> #include <exception> using namespace std; class ${className} { //Chlen Promenlivi, Chastni Promenlivi: private: `; let propertyNames = $('.property-name'); let propertyTypes = $('.property-type'); for(let i = 0; i < propertyNames.length; i++) { code += ` ${$(propertyTypes[i]).val()} ${$(propertyNames[i]).val()}; \n`; } code += `\n`; code += ` public:\n`; code += ` //GET/SET funkcii, Akcesori i Mutatori, Funkcii za chetene i zapis `; for(let i = 0; i < propertyNames.length; i++) { let name = $(propertyNames[i]).val(); let capitalized = name.charAt(0).toUpperCase() + name.slice(1); code += ` ${$(propertyTypes[i]).val()} get${capitalized}() \n`; code += ` {\n`; code += ` return ${$(propertyNames[i]).val()};\n`; code += ` }\n\n`; code += ` void set${capitalized}(${$(propertyTypes[i]).val()} ${name}_i) \n`; code += ` {\n`; code += ` ${$(propertyNames[i]).val()} = ${name}_i;\n`; code += ` }\n\n`; } code += ` //Konstuktor po podrazbirane:\n`; code += ` ${className}()\n`; code += ` {\n`; for(let i = 0; i < propertyNames.length; i++) { code += ` ${$(propertyNames[i]).val()} = `; if(`${$(propertyTypes[i]).val()}` === "string") { code += `""; `; } else { code += `0; `; } } code += ` } `; code += ` //Ekspliciten Konstruktor:\n`; code += ` ${className}(`; for(let i = 0; i < propertyNames.length; i++) { code += `${$(propertyTypes[i]).val()} ${$(propertyNames[i]).val()}_i`; if (i != propertyNames.length - 1) { code += `, `; } } code += `) { `; for(let i = 0; i < propertyNames.length; i++) { code += ` ${$(propertyNames[i]).val()} = ${$(propertyNames[i]).val()}_i; `; } code += ` } `; code += ` //Kopirasht Konstruktor `; code += ` ${className}(const ${className}& ${className.toLowerCase()}_i) { `; for(let i = 0; i < propertyNames.length; i++) { code += ` ${$(propertyNames[i]).val()} = ${className.toLowerCase()}_i.${$(propertyNames[i]).val()}; `; } code += ` } `; code += `//predefinirane na operatora < po otnoshenie na chlen promenlivata ${$(propertyNames[0]).val()} bool operator<(${className} ${className.toLowerCase()}_i) { return ${$(propertyNames[0]).val()} < ${className.toLowerCase()}_i.${$(propertyNames[0]).val()}; }`; code += ` };\n`; code += ` //Predefinirane na operator za izhod, izvezdane cherez fajlov potok `; code += `ostream& operator<<(ostream &stream, ${className} &${className.toLowerCase()}_i) { `; for(let i = 0; i < propertyNames.length; i++) { let name = $(propertyNames[i]).val(); let capitalized = name.charAt(0).toUpperCase() + name.slice(1); code += ` stream << "${$(propertyNames[i]).val()}: " << ${className.toLowerCase()}_i.get${capitalized}() << endl; `; } code += ` return stream; `; code += `}`; code += ` //Predefinirane na operator za vhod, vavezdane cherez fajlov potok `; code += `istream& operator>>(istream &stream, ${className} &${className.toLowerCase()}_i) { `; for(let i = 0; i < propertyNames.length; i++) { let name = $(propertyNames[i]).val(); let capitalized = name.charAt(0).toUpperCase() + name.slice(1); code += ` ${$(propertyTypes[i]).val()} ${$(propertyNames[i]).val()}_i; `; code += ` stream >> ${$(propertyNames[i]).val()}_i; `; code += ` ${className.toLowerCase()}_i.set${capitalized}(${$(propertyNames[i]).val()}_i); `; } code += ` return stream; `; code += `} `; code += ` //Chast 2 class Extend { //Chlen Promenlivi, Chastni Promenlivi private: string name; vector<${className}> collection; public: //GET funkcii, akcesori, funkcii za dostap, funkcii za chetene string getName() { return name; } vector<${className}> getCollection() { return collection; } //SET funkcii, mutatori, funkcii za zapis, funkcii za redaktirane void setName(string name_i) { name = name_i; } void setCollection(vector<${className}> collection_i) { collection = collection_i; } //predefinirane na operatora <= po otnoshenie na chlen promenlivata name bool operator<=(Extend extend_i) { return name <= extend_i.name; } //Kontruktor po podrazbirane Extend() { name = ""; } //EksplicitenKonstruktor Extend(string name_i) { name = name_i; } //Kopirasht Konstruktor Extend(const Extend& extend_i) { name = extend_i.name; collection = extend_i.collection; } }; //Predefinirane na operator za vhod, vavezdane cherez fajlov potok //Bi se nuzdaelo ot redakciq za da raboti ako e LIST, NO DA SE PISHE NA IZPIT istream& operator>>(istream &stream, Extend &extend_i) { vector<${className}> newCollection; string name_i; stream >> name_i; extend_i.setName(name_i); for(int i = 0; i < 3; i++) { ${className} ${className.toLowerCase()}_i; stream >> ${className.toLowerCase()}_i; newCollection.push_back(${className.toLowerCase()}_i); } extend_i.setCollection(newCollection); return stream; } //Predefinirane na operator za izhod, izvezdane cherez fajlov potok //Bi se nuzdaelo ot redakciq za da raboti ako e LIST, NO DA SE PISHE NA IZPIT ostream& operator<<(ostream &stream, Extend &extend_i) { stream << "name: " << extend_i.getName() << endl; for(int i = 0; i < 3; i++) { stream << extend_i.getCollection()[i] << endl; } return stream; }`; code += ` //Chast 3 //Demonstraciq na klasovete i funkciite im v glavnata funkciq kakto i obrabotka na greshki void main() { try { ${className} ${className.toLowerCase()}_1; ${className} ${className.toLowerCase()}_2; cin >> ${className.toLowerCase()}_1; cin >> ${className.toLowerCase()}_2; cout << "- - - - - - - - - - - - - -" << endl; cout << ${className.toLowerCase()}_1 << endl; cout << ${className.toLowerCase()}_2 << endl; Extend extend_test("testName"); Extend extend; cin >> extend; //NE RABOTI AKO E LIST NO DA SE PISHE NA IZPIT cout << "- - - - - - - - - - - - - -" << endl; cout << extend; //NE RABOTI AKO E LIST NO DA SE PISHE NA IZPIT } catch(exception error) { cout << error.what() << endl; } }`; if($('#copy-code') !== null) { $('#copy-code').remove(); } $('form').append(textareaCode); $('form').append('<button type="button" onclick="copycode()" id="copy-code" class="btn btn-info generate">Copy Code</button>'); $('textarea').val(code); }
/*jshint white: false, strict: false, plusplus: false, onevar: false, nomen: false */ /*global gladius: false, document: false, window: false, module: false, start, test: false, expect: false, ok: false, notEqual: false, stop, QUnit: false */ define(function() { return function (math) { // Name of our module module( 'Math/Transform' ); test( 'Translation (return)', function() { expect( 1 ); var position = math.Vector3( 1, 2, 3 ); var result = math.transform.translate( position ); ok( math.matrix4.equal( result, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1 ] ), 'Translation matrix is correct' ); }); test( 'Rotation', function() { expect( 1 ); var rotation = math.Vector3( math.TAU/2, math.TAU/3, math.TAU/4 ); var result = math.transform.rotate( rotation ); var expected = [ 0, -1/2, -Math.sqrt(3)/2, 0, 1, 0, 0, 0, 0, -Math.sqrt(3)/2, 1/2, 0, 0, 0, 0, 1 ]; ok( math.matrix4.equal( result, expected ), 'Expected: [ 0, -1/2, -0.866, 0, 1, 0, 0, 0, 0, -0.866, 1/2, 0, 0, 0, 0, 1 ] \n Returned: ' + result[0] + ', ' + result[1] + ', ' + result[2] + ', ' + result[3] + ', ' + result[4] + ', ' + result[5] + ', ' + result[6] + ', ' + result[7] + ', ' + result[8] + ', ' + result[9] + ', ' + result[10] + ', ' + result[11] + ', ' + result[12] + ', ' + result[13] + ', ' + result[14] + ', ' + result[15] ); }); test( 'Scale', function() { expect( 1 ); var scale = math.Vector3( 2, 2, 2 ); var result = math.transform.scale( scale ); ok( math.matrix4.equal( result, [ 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ] ), 'Scale matrix is correct' ); }); test( 'Fixed', function() { expect( 3 ); var result, expected; var position = math.Vector3( 1, 2, 3 ); result = math.transform.fixed( position, null, null ); ok( math.matrix4.equal( result, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1 ] ), 'Position is correct' ); var rotation = math.Vector3( math.TAU/2, math.TAU/3, math.TAU/4 ); result = math.transform.fixed( null, rotation, null ); var expected = [ 0, -1/2, -Math.sqrt(3)/2, 0, 1, 0, 0, 0, 0, -Math.sqrt(3)/2, 1/2, 0, 0, 0, 0, 1 ]; ok( math.matrix4.equal( result, expected ), 'Expected: [ 0, -1/2, -0.866, 0, 1, 0, 0, 0, 0, -0.866, 1/2, 0, 0, 0, 0, 1 ] \n Returned: ' + result[0] + ', ' + result[1] + ', ' + result[2] + ', ' + result[3] + ', ' + result[4] + ', ' + result[5] + ', ' + result[6] + ', ' + result[7] + ', ' + result[8] + ', ' + result[9] + ', ' + result[10] + ', ' + result[11] + ', ' + result[12] + ', ' + result[13] + ', ' + result[14] + ', ' + result[15] ); var scale = math.Vector3( 2, 2, 2 ); result = math.transform.fixed( null, null, scale ); ok( math.matrix4.equal( result, [ 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ] ), 'Scale matrix is correct' ); /* position = math.Vector3( [ 1, 2, 3 ] ); rotation = math.Vector3( [ 1, 2, 3 ] ); scale = math.Vector3( [ 1, 2, 3 ] ); expected = Float32Array([1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 1, 2, 3, 1]); result = math.transform.fixed( position, rotation, scale ); ok( math.matrix4.equal( result, expected ), "Fixed function is correct" ); */ }); }; });
/*! * SimpleTestJS JavaScript Library v1.0.0 * https://github.com/zoweb/SimpleTestJS * * Copyright zoweb and other contributors * Released under the MIT license * https://raw.githubusercontent.com/Zoweb/SimpleTestJS/master/LICENSE * * Compiled 2016-11-30T03:57:17.382Z */ (function(global, factory) { "use strict"; if (typeof module === "object" && typeof module.exports === "object") { module.exports = factory(global, true); } else { factory(global); } })(typeof window !== "undefined" ? window : this, function(window, noGlobal) { var version = "1.0.0", test = {}; var priv = { extend: function(obj1, obj2) { return Object.assign(obj1, obj2); }, val: function(obj2) { return Object.assign(priv, obj2); }, each: function(obj, fn, deep) { function loop(obj) { for (var inner in obj) { if (obj.hasOwnProperty(inner)) { var innerObj = obj[inner]; if (typeof innerObj === "object" && deep) { loop(innerObj); } else { fn.call(innerObj, Object.keys(obj).indexOf(inner), innerObj); } } } } } }; /** * If mainTest, tests that all otherTests match the wanted value * @param {boolean} mainTest The main test to complete * @param {object} [otherTests] Any other tests to complete */ test.result = function(mainTest, otherTests) { if (mainTest) { if (otherTests instanceof Array && otherTests.length > 0) { // We can't use `let` as we may not be parsed as ES6. var returnValue = {}; otherTests.forEach(function(curr) { returnValue[curr.name] = curr.check; }); return returnValue; } else { return true; } } else { return false; } }; if (noGlobal) { return test; } else { window.test = test; } });
import React from 'react'; import TopBarContainer from './TopBarContainer.jsx'; import ReviewsContainer from './ReviewsContainer.jsx'; import Stars from './Stars.jsx'; import FilterMessage from './FilterMessage.jsx'; import { AppContainer, Divider } from './Styles.js'; class App extends React.Component { constructor(props) { super(props); this.state = { hostInformation: {}, isFiltered: false, currentSearchTerm: '', visibleReviews: [], currentPageReviews: [], beginningIndexForCurrentPageReviews: 0, stars: {}, } this.getAllReviews = this.getAllReviews.bind(this); this.getHostInformation = this.getHostInformation.bind(this); this.getStars = this.getStars.bind(this); this.getFilteredReviews = this.getFilteredReviews.bind(this); this.toggleCurrentPageReviews = this.toggleCurrentPageReviews.bind(this); } componentDidMount() { this.getAllReviews(); this.getHostInformation(); this.getStars(); } getAllReviews() { const roomId = window.location.pathname.slice(7, -1); $.ajax({ method: 'GET', url: `/rooms/${roomId}/reviews`, success: (data) => { this.setState({ isFiltered: false, currentSearchTerm: '', visibleReviews: data, currentPageReviews: data.slice(0,7), beginningIndexForCurrentPageReviews: 0, }) } }) } getHostInformation() { const roomId = window.location.pathname.slice(7, -1); $.ajax({ method: 'GET', url: `/rooms/${roomId}/hostDetails`, success: (data) => { this.setState({ hostInformation: data[0], }) } }) } getStars() { const roomId = window.location.pathname.slice(7, -1); $.ajax({ method: 'GET', url: `/rooms/${roomId}/stars`, success: (data) => { this.setState({ stars: data[0], }) } }) } getFilteredReviews(searchTerm) { $.ajax({ method: 'GET', url: `/rooms/${this.state.hostInformation.room_id}/query/?queryTerm=${searchTerm}`, success: (data) => { this.setState({ isFiltered: true, currentSearchTerm: searchTerm, visibleReviews: data, beginningIndexForCurrentPageReviews: 0, currentPageReviews: data.slice(0, 7), }) } }) } toggleCurrentPageReviews(newBeginningIndex) { if(newBeginningIndex >= 0 && newBeginningIndex < this.state.visibleReviews.length) { const newEndIndex = newBeginningIndex + 7; const newBeginningIndexForCurrentPageReviews = newBeginningIndex; this.setState({ beginningIndexForCurrentPageReviews: newBeginningIndexForCurrentPageReviews, currentPageReviews: this.state.visibleReviews.slice(newBeginningIndex, newEndIndex), }) } } render() { const allReviewsView = ( <AppContainer> <div><Divider /></div> <TopBarContainer getStars={this.getStars} stars={this.state.stars} visibleReviews={this.state.visibleReviews} getFilteredReviews={this.getFilteredReviews} /> <div><Divider /></div> <Stars stars={this.state.stars} /> <ReviewsContainer hostInformation={this.state.hostInformation} currentPageReviews={this.state.currentPageReviews} stars={this.state.stars} beginningIndexForCurrentPageReviews={this.state.beginningIndexForCurrentPageReviews} toggleCurrentPageReviews={this.toggleCurrentPageReviews} visibleReviews={this.state.visibleReviews} /> </AppContainer> ) const filteredView = ( <AppContainer> <div><Divider /></div> <TopBarContainer stars={this.state.stars} visibleReviews={this.state.visibleReviews} getFilteredReviews={this.getFilteredReviews} /> <div><Divider /></div> <FilterMessage getAllReviews={this.getAllReviews} currentSearchTerm={this.state.currentSearchTerm} visibleReviews={this.state.visibleReviews} /> <div><Divider /></div> <ReviewsContainer hostInformation={this.state.hostInformation} currentPageReviews={this.state.currentPageReviews} stars={this.state.stars} beginningIndexForCurrentPageReviews={this.state.beginningIndexForCurrentPageReviews} toggleCurrentPageReviews={this.toggleCurrentPageReviews} visibleReviews={this.state.visibleReviews} /> </AppContainer> ) return ( <div> {this.state.isFiltered ? filteredView : allReviewsView} </div> ) } } export default App;
const app = new Vue({ el: '#app', delimiters: ['${', '}'], data: { isMenuActive: false, scrollPosition: 0 }, methods: { // Tracks scroll position to add shadow on navbar updateScroll() { this.scrollPosition = window.scrollY; }, registerServiceWorker() { if (! 'serviceWorker' in navigator) return; if ( window && window.location && window.location.hostname === 'localhost' ) return; // If loaded offline, shows notification when comes online and offers refresh if (!navigator.onLine) { window.addEventListener('online', () => { notify.snackbar('Atsirado internetas, ar tęsti?', {actionText: 'TAIP'}, () => { window.location.reload(); }); }, {passive: true}) } // Does all the beauty navigator.serviceWorker.register('/sw.js').then( reg => { window.addEventListener('load', () => { // Notifies on successful registration if (reg.installing) { reg.installing.onstatechange = e => { if (reg.active) { if (e.currentTarget.onstatechange) e.currentTarget.onstatechange = null; notify.primary('Svetainė veiks ir be interneto. 😎'); } }; } // Trim Caches if ('active' in reg && reg.active) reg.active.postMessage('trimCaches'); }, {passive: true, once: true}); }).catch( err => { // notify.danger('SW Klaida.'); console.log('Service Worker not installed. |', err); }); }, userExperience() { // Adds shadow to navbar window.addEventListener('scroll', this.updateScroll, {passive: true}); // Shows online/offline notification window.addEventListener('online', () => { notify.toast('Prisijungta.', 'link', 2000, 'top-right'); }, {passive: true}); window.addEventListener('offline', () => { notify.toast('Atsijungta.', 'link', 2000, 'top-right'); }, {passive: true}); // PNG Fallback for SVG brand image document.getElementById('brand').addEventListener('error', () => {this.src='/img/brand.png'}, {passive: true, once: true}); }, bannerImage() { try { const pageData = JSON.parse(document.getElementById('pageData').innerText); const images = pageData.image; const banner = document.getElementById('bannerImage'); Object.assign(banner.style, { background: `url('${images[0]}')`, }); } catch(e) { // console.log('Banner image not available.'); } } }, mounted() { this.userExperience(); this.registerServiceWorker(); this.bannerImage(); }, components: { VueDisqus: require('./components/VueDisqus.vue'), Database: require('./components/Database.vue') } });
"use strict"; class Vector { /** *A simple vector class. * * @param {number} x first coordinate of this vector * @param {number} y second coordinate of this vector */ constructor(x = 0, y = 0) { if (typeof x !== "number" || typeof y !== "number") { throw new Error("Invalid argument types"); } /** * The x coordinate of this vector * @type {number} */ this.x = x; /** * The y coordinate of this vector. * @type {number} */ this.y = y; } /** * Adds two vectors. * * @param other Vector The other vector * @returns {Vector} */ plus(other) { return new Vector(this.x + other.x, this.y + other.y); } minus(other) { return new Vector(this.x - other.x, this.y - other.y); } dot(other) { return this.x * other.x + this.y * other.y; } scaled(factor) { return new Vector(this.x * factor, this.y * factor); } distanceTo(other) { return this.minus(other).norm; } /** * Returns the angle between the two vectors in radians. */ angleTo(other) { return Math.atan2(other.y - this.y, other.x - this.x); } get norm() { return Math.sqrt(this.x * this.x + this.y * this.y); } get normSq() { return this.x * this.x + this.y * this.y; } get normalized() { return this.scaled(1 / this.norm); } /** * Alias for "x" * @returns {number} */ get width() { return this.x; } /** * Alias for "x" * @returns {number} */ get left() { return this.x; } /** * Alias for "y" * @returns {number} */ get height() { return this.y; } /** * Alias for "y" * @returns {number} */ get top() { return this.y; } get abs() { return new Vector(Math.abs(this.x), Math.abs(this.y)); } static origin() { return new Vector(); } static random() { return Vector.polar(Math.random() * 2 * Math.PI, 1); } static polar(angle, radius = 1) { const x = Math.cos(angle) * radius; const y = Math.sin(angle) * radius; return new Vector(x, y); } /** * Tries to convert the given arguments to a vector. * @returns {Vector} */ static of(obj, second) { if (obj instanceof Vector) return obj; const x = obj.x !== undefined ? obj.x : obj.left !== undefined ? obj.left : typeof obj === "number" ? obj : obj[0]; const y = obj.y !== undefined ? obj.y : obj.top !== undefined ? obj.top : second !== undefined ? second : obj[1]; if (x === undefined || y === undefined) throw new TypeError("Could not convert to vector", obj); return new Vector(x, y); } }
/** * Rct Card Content */ import React from 'react'; const RctCardContent = ({ children, customClasses, noPadding }) => ( <div className={`${noPadding ? 'rct-full-block' : 'rct-block-content'} ${customClasses ? customClasses : ''}`}> {children} </div> ); export { RctCardContent };
import React, { Component } from "react"; // import ReactGA from 'react-ga' //slide up slide down plugin import { SlideDown } from "react-slidedown"; import "react-slidedown/lib/slidedown.css"; import PropTypes from "prop-types"; //images import arrowIcon from "../../images/arrow-icon-services.svg"; class SlideUpDown extends Component { constructor(props) { super(props); this.state = { open: false, arrowTrace: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMCA3LjMzbDIuODI5LTIuODMgOS4xNzUgOS4zMzkgOS4xNjctOS4zMzkgMi44MjkgMi44My0xMS45OTYgMTIuMTd6Ii8+PC9zdmc+", expandedText: "" }; } // componentDidUpdate() {} toggleSlide() { this.setState({ open: !this.state.open }); } // componentDidMount() { // this.setText() // } // setText() { // if(this.expandedName === '' || null) // } handleClick() { this.toggleSlide(); // this.logEvent() } // logEvent() { // ReactGA.event({ // category: 'Service Click', // action: 'User clicked on Service Item', // }) // } handleName() { if (this.props.diffText) { return ( <> <h4 className={`faq__section__right__slide__title__name ${ !this.state.open ? "visible" : "hidden" }`} > {this.props.name} </h4> <h4 className={`faq__section__right__slide__title__name ${ this.state.open ? "visible" : "hidden" }`} > {this.props.expandedName} </h4> </> ); } else { return ( <h4 className="faq__section__right__slide__title__name visible"> {this.props.name} </h4> ); } } nameOfExpanded() { return this.name; } render() { return ( <div className="faq__section__right__slide"> <div className="faq__section__right__slide__title" onClick={this.handleClick.bind(this)} > {/* <h4> {!this.state.open ? this.props.name : this.props.expandedName} </h4> */} {this.handleName()} <svg className={this.state.open ? "expanded" : ""} viewBox="0 0 117 63" xmlns="http://www.w3.org/2000/svg" > <path d="M115.3,1.6 C113.7,0 111.1,0 109.5,1.6 L58.5,52.7 L7.4,1.6 C5.8,0 3.2,0 1.6,1.6 C-1.77635684e-15,3.2 -1.77635684e-15,5.8 1.6,7.4 L55.5,61.3 C56.3,62.1 57.3,62.5 58.4,62.5 C59.4,62.5 60.5,62.1 61.3,61.3 L115.2,7.4 C116.9,5.8 116.9,3.2 115.3,1.6 Z" /> </svg> </div> <SlideDown> {this.state.open ? ( <p dangerouslySetInnerHTML={{ __html: this.props.desc }} /> ) : null} </SlideDown> </div> ); } } export default SlideUpDown;
class DataUI { constructor(title, author, isbn) { this.title = title; this.author = author; this.isbn = isbn; } } class UI { //add book addBook(book) { const bookList = document.getElementById('book-list'); //create tr const tr = document.createElement('tr'); tr.innerHTML = ` <td>${book.title}</td> <td>${book.author}</td> <td>${book.isbn}</td> <td><a href='#' class='del'>x</a></td> `; bookList.appendChild(tr); } //show alert showAlert(msg, cla) { const container = document.querySelector('.container'); const form = document.getElementById('book-form'); //create div const div = document.createElement('div'); div.innerHTML = ` <a href = '#' class = 'alert ${cla}'>${msg}</a> `; div.style.marginBottom = '20px'; container.insertBefore(div, form); //hide alert msg after 3s setTimeout(() => { div.remove(); }, 3000) } //clear form clearForm(title, author, isbn) { title.value = ''; author.value = ''; isbn.value = ''; } //del tr deleteTr(target) { if (target.className === 'del') { target.parentElement.parentElement.remove(); this.showAlert('Book Removed', 'success'); } } } //Local Storage class LS { //add book static addBook(book) { let bookArr; if (localStorage.getItem('books') === null) { bookArr = []; } else { bookArr = JSON.parse(localStorage.getItem('books')); } bookArr.push(book); localStorage.setItem('books', JSON.stringify(bookArr)); } //display book static displayBook() { const bookVal = JSON.parse(localStorage.getItem('books')); if (localStorage.getItem('books') !== null) { const ui = new UI(); bookVal.forEach(cur => { ui.addBook(cur); }) } } //delete book static delBook(target) { if (target.className === 'del') { let isbn = target.parentElement.previousElementSibling.textContent; let isbnLS = JSON.parse(localStorage.getItem('books')); isbnLS.forEach((cur, index) => { if (cur.isbn === isbn) { isbnLS.splice(index, 1); } }) localStorage.setItem('books', JSON.stringify(isbnLS)); } } } //Event listeneres (function () { const form = document.getElementById('book-form'); const bookList = document.getElementById('book-list'); //form submit then pass data form.addEventListener('submit', passData); //click on delete button of tr bookList.addEventListener('click', removeTr); //when browser load document.addEventListener('DOMContentLoaded', LS.displayBook); })(); //add book function passData(e) { e.preventDefault(); //collect ui const inputTitle = document.getElementById('title'); const inputAuthor = document.getElementById('author'); const inputIsbn = document.getElementById('isbn'); const dataUI = new DataUI(inputTitle.value, inputAuthor.value, inputIsbn.value); const ui = new UI(); //ck is form fields empty if (inputTitle.value === '' || inputAuthor.value === '' || inputIsbn.value === '') { ui.showAlert('Pls fill the input field', 'error'); } else { //add book to table ui.addBook(dataUI); //book to LS LS.addBook(dataUI); //clear form after add book ui.clearForm(inputTitle, inputAuthor, inputIsbn); //show alet msg after book add successfully ui.showAlert('Book Addeded', 'success'); } } //remove book function removeTr(e) { e.preventDefault(); const ui = new UI(); //del tr ui.deleteTr(e.target); //del from LS LS.delBook(e.target); }
registrar = document.getElementById('reg'); contenedor = document.getElementById('usuarios'); contenedor2 = document.getElementById('commentInBD'); nombre = document.getElementById('nusuario'); nombreB = document.getElementById('busuario'); idUser = document.getElementById('idusuario'); function nuevoAjax() { var xmlhttp=false; try { xmlhttp = new ActivexObject('Msxml2.XMLHTTP'); } catch(e) { try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } //Envío de datos por GET function regUser() { var nameU = nombre.value; ajax=nuevoAjax(); ajax.open("GET","agregarusuario.php?nombre="+nameU,true); ajax.onreadystatechange = function() { if (ajax.readyState = 4) { contenedor.innerHTML = ajax.responseText } } ajax.send(null) contenedor.style.textAlign='center'; } function showUsers() { var nameU = nombreB.value; ajax=nuevoAjax(); ajax.open("GET","buscarusuarios.php?nombre="+nameU,true); ajax.onreadystatechange = function() { if (ajax.readyState = 4) { contenedor.innerHTML = ajax.responseText } } ajax.send(null) contenedor.style.textAlign='center'; } function showComments() { var id = idUser.value; ajax=nuevoAjax(); ajax.open("GET","mostrarcomentarios.php?idusuario="+id,true); ajax.onreadystatechange = function() { if (ajax.readyState = 4) { contenedor2.innerHTML = ajax.responseText } } ajax.send(null) contenedor2.style.textAlign='center'; } //Carga de Contenidos function cargarContenido() { ajax=nuevoAjax(); ajax.open("GET","mostrarusuarios.php",true); ajax.onreadystatechange = function() { if (ajax.readyState = 4) { contenedor.innerHTML = ajax.responseText } } ajax.send(null) contenedor.style.textAlign='center'; } registrar.onclick = function() { regUser(); } window.onload = function() { cargarContenido(); }
var log4js = require("log4js"); var cwd = process.cwd(); log4js.configure({ appenders:[ { type: "console" }, { type: "file", filename : cwd + "/logs/ejs.log", category: "ejs" }, { type: "file", filename : cwd + "/logs/staticize.log", category: "staticize" }, { type: "file", filename : cwd + "/logs/api.log", category: "api" } ] }); module.exports = log4js;
define(['require'], function(require) { 'use strict'; var ngApp = angular.module('app', ['ngRoute', 'ui.bootstrap', 'ui.tms', 'ui.xxt', 'http.ui.xxt', 'notice.ui.xxt', 'protect.ui.xxt']); ngApp.config(['$locationProvider', '$provide', '$controllerProvider', '$routeProvider', function($lp, $provide, $cp, $rp) { var RouteParam = function(name) { var baseURL = '/views/default/pl/be/sns/wx/'; this.templateUrl = baseURL + name + '.html?_=' + (new Date() * 1); this.controller = 'ctrl' + name[0].toUpperCase() + name.substr(1); this.resolve = { load: function($q) { var defer = $q.defer(); require([baseURL + name + '.js'], function() { defer.resolve(); }); return defer.promise; } }; }; $lp.html5Mode(true); ngApp.provider = { controller: $cp.register, service: $provide.service, }; $rp.when('/rest/pl/be/sns/wx/setting', new RouteParam('setting')) .when('/rest/pl/be/sns/wx/text', new RouteParam('text')) .when('/rest/pl/be/sns/wx/menu', new RouteParam('menu')) .when('/rest/pl/be/sns/wx/qrcode', new RouteParam('qrcode')) .when('/rest/pl/be/sns/wx/other', new RouteParam('other')) .when('/rest/pl/be/sns/wx/relay', new RouteParam('relay')) .when('/rest/pl/be/sns/wx/page', new RouteParam('page')) .otherwise(new RouteParam('setting')); }]); ngApp.controller('ctrlWx', ['$scope', 'http2', function($scope, http2) { $scope.subView = ''; $scope.$on('$locationChangeSuccess', function(event, currentRoute) { var subView = currentRoute.match(/([^\/]+?)$/); $scope.subView = subView[1] === 'wx' ? 'setting' : subView[1]; }); http2.get('/rest/pl/be/sns/wx/get').then(function(rsp) { $scope.wx = rsp.data; }); }]); /***/ require(['domReady!'], function(document) { angular.bootstrap(document, ["app"]); }); /***/ return ngApp; });
Ext.ns('App'); App.createViewProcessDefinition = function() { App.processDefinitions = new Ext.grid.GridPanel({ title: App.locale['viewDefinitions.title'], x: 20, y: 20, width: 500, height: 300, loadMask: true, shim: true, viewConfig: { forceFit: true }, store: new Ext.data.JsonStore({ url: 'jbpm.do?action=processDefinitions', root: 'result', fields: ['id', 'name', 'version', 'dbid'] }), columns: [{ header: App.locale['viewDefinitions.id'], dataIndex: 'id' },{ header: App.locale['viewDefinitions.name'], dataIndex: 'name' },{ header: App.locale['viewDefinitions.version'], dataIndex: 'version' }], bbar: new Ext.Toolbar(['->',{ text: App.locale['view'], handler: function() { var selections = App.processDefinitions.getSelectionModel().getSelections(); if (selections.length == 1) { var record = selections[0]; var id = record.get('id'); var name = record.get('name'); var pdDbid = record.get('dbid'); var tabs = Ext.getCmp('centerTabPanel'); var tabItem = tabs.getItem('ViewProcessInstance-' + id); if (tabItem == null) { var viewProcessInstance = App.createViewProcessInstance(id, pdDbid); tabItem = tabs.add(viewProcessInstance); tabItem.setTitle(name); } tabs.activate(tabItem); } } },{ text: App.locale['start'], handler: function() { var selections = App.processDefinitions.getSelectionModel().getSelections(); if (selections.length == 1) { var record = selections[0]; App.showTransitionForm('processStart', record.get('id'), function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); App.processDefinitions.getStore().reload(); var id = record.get('id'); var name = record.get('name'); var pdDbid = record.get('dbid'); var tabs = Ext.getCmp('centerTabPanel'); var tabItem = tabs.getItem(id); if (tabItem == null) { var viewProcessInstance = App.createViewProcessInstance(id,pdDbid); tabItem = tabs.add(viewProcessInstance); tabItem.setTitle(name); } tabs.activate(tabItem); }); } } }, { text: App.locale['suspend'], handler: function() { var selections = App.processDefinitions.getSelectionModel().getSelections(); if (selections.length == 1 ) { var record = selections[0]; Ext.Ajax.request({ url: 'jbpm.do?action=suspendProcessDefinition', params: { id: record.get('id') }, success: function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); App.processDefinitions.getStore().reload(); } }); } } }, { text: App.locale['delete'], handler: function() { var selections = App.processDefinitions.getSelectionModel().getSelections(); if (selections.length == 1 ) { var record = selections[0]; Ext.Ajax.request({ url: 'jbpm.do?action=removeProcessDefinition', params: { id: record.get('id') }, success: function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); App.processDefinitions.getStore().reload(); } }); } } }]) }); App.processes = new Ext.Panel ({ id: 'ViewProcessDefinition', title: App.locale['viewDefinitions.title'], iconCls: 'processManagement', layout: 'absolute', items: [App.processDefinitions, { title: App.locale['aboutProcessDefinition.title'], iconCls: 'aboutProcessDefinition', x: 550, y: 20, width: 250, height: 200, bodyStyle: 'padding:5px;font-size:12px;', html: App.locale['aboutProcessDefinition.content'] }, { title: App.locale['mostActiveProcess.title'], iconCls: 'metricsAndStats', x: 550, y: 250, width: 250, height: 200, html: '<embed type="application/x-shockwave-flash" src="scripts/FusionCharts/FCF_Pie3D.swf" width="200" height="150" id="mostActiveProcess" name="mostActiveProcess" quality="high" allowScriptAccess="always" wmode="transparent" flashvars="chartWidth=200&chartHeight=150&debugMode=0&DOMId=mostActiveProcess&registerWithJS=0&scaleMode=noScale&lang=EN&dataURL=jbpm.do?action=reportMostActiveProcess"/>', bbar: new Ext.Toolbar([ '->', App.locale['moreMetrics'] ]) }] }); return App.processes; };
// Mutations export const CAR_DETAILS = 'carDetails'; export const IS_EMPTY_CAR_DETAILS = 'isEmptyCarModelDetails'; // В базе нет информации о выбранной модели автомобиля export const IS_EMPTY_MOTORCYCLE_DETAILS = 'isEmptyMotorcycleModelDetails'; // В базе нет информации о выбранной модели мотоцикла export const IS_LOADING = 'isLoading'; export const MOTORCYCLE_DETAILS = 'motorcycleDetails'; export const SELECTED_BRAND = 'selectedBrand'; // При переходе по ссылке на конкретную модель открывает в боковом меню нужный список export const SET_LOADING_DATA = 'setLoadingData'; export const TOGGLE_SITE_SEARCH = 'toggleSearchOnSite'; export const VEHICLES_MODELS_LIST = 'vehiclesModelsList'; export const VEHICLES_SETTINGS = 'vehiclesSettings'; // Actions export const REQUEST_VEHICLES_SETTINGS = 'requestVehiclesSettings'; export const SET_CURRENT_VEHICLE_TYPE = 'setCurrentVehicleType';
import React, {Component} from 'react'; import { View, StyleSheet, StatusBar, ScrollView, Text, FlatList, TouchableOpacity, AsyncStorage, ActivityIndicator, Image, Dimensions, } from 'react-native'; import {Input, InputProps, Button} from 'react-native-ui-kitten'; import AntIcon from 'react-native-vector-icons/AntDesign'; import MessageMainLayout from './MessageMainLayout'; import CustomHeader from '../Header/CustomHeader'; import {withNavigation, DrawerActions} from 'react-navigation'; import * as CONSTANT from '../Constants/Constant'; const Entities = require('html-entities').XmlEntities; const entities = new Entities(); class MessagesMain extends Component { state = { data: [], default_color: '#fff', storedValue: '', storedType: '', profileImg: '', type: '', id: '', Pid: '', isLoading: true, fetchMessageList: [], }; componentDidMount() { this.fetchMessages(); } fetchMessages = async () => { const Pid = await AsyncStorage.getItem('projectUid'); const response = await fetch( CONSTANT.BaseUrl + 'chat/list_users/?user_id=' + Pid, ); const json = await response.json(); if ( Array.isArray(json) && json[0] && json[0].type && json[0].type === 'error' ) { this.setState({fetchMessageList: [], isLoading: false}); // empty data set } else { this.setState({fetchMessageList: json, isLoading: false}); } }; render() { const {isLoading} = this.state; return ( <View style={styles.container}> <StatusBar backgroundColor="#f7f7f7" barStyle="dark-content" /> <CustomHeader headerText={CONSTANT.MessagesHeaderText} /> {isLoading && ( <View style={styles.messagesMainActivityIndicatorArea}> <ActivityIndicator size="small" color={CONSTANT.primaryColor} style={styles.messagesMainActivityIndicatorStyle} /> </View> )} <ScrollView> {this.state.fetchMessageList.length >= 1 ? ( <FlatList data={this.state.fetchMessageList} keyExtractor={(a, b) => b.toString()} renderItem={({item}) => ( <TouchableOpacity style={styles.messagesMainTouchableStyle} activeOpacity={0.9} onPress={() => this.props.navigation.navigate('MessageDetailLayout', { receiver_id: item.receiver_id, }) }> <MessageMainLayout image={{ uri: `${ item.image != '' ? item.image_url : 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAeAAD/4QN/aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjYtYzEzOCA3OS4xNTk4MjQsIDIwMTYvMDkvMTQtMDE6MDk6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6MWFjM2JiZTYtZDJmMy0yZTRkLWFlYzAtYjU1NThiMDVlMDI2IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkFGQUMxQTAxRUVDQzExRTc5MTY4Q0JGNkVDOERCMkYxIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkFGQUMxQTAwRUVDQzExRTc5MTY4Q0JGNkVDOERCMkYxIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE3IChXaW5kb3dzKSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjI4NzM2MWE3LTExMTctNzg0YS05ZmVlLTVhYzRiMTU3OWU5ZiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDoxYWMzYmJlNi1kMmYzLTJlNGQtYWVjMC1iNTU1OGIwNWUwMjYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7/7gAOQWRvYmUAZMAAAAAB/9sAhAAQCwsLDAsQDAwQFw8NDxcbFBAQFBsfFxcXFxcfHhcaGhoaFx4eIyUnJSMeLy8zMy8vQEBAQEBAQEBAQEBAQEBAAREPDxETERUSEhUUERQRFBoUFhYUGiYaGhwaGiYwIx4eHh4jMCsuJycnLis1NTAwNTVAQD9AQEBAQEBAQEBAQED/wAARCAIAAgADASIAAhEBAxEB/8QAXwABAQEBAQAAAAAAAAAAAAAAAAMCAQYBAQAAAAAAAAAAAAAAAAAAAAAQAQACAAYCAwEBAQEAAAAAAAABAhExUWFxEzIDIUGhgRJCkREBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8A92AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMxGcgDM+ysZfLM+2fr4BRybVjOUptac5cBXspq1ExOSBFprOMAuFZi0YwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADk3rH2zPtj6gGzHDNKfZadmcZnMFZ9lY3Zn26QwA7N7T9uDsUtP0Dg3Hq1lqPXWPrEEsJnJqPXadlQEreuaxjjiyvMYxMIA36pzhRGk4WhYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcm9YzlztruDROP0x213O2u4Oz2TlhDM+u85y7213O2u4M9Vtjqts1213O2u4M9Vtjqts1213O2u4OR6p+5aj11jP5c7a7nbXcG4iIygY7a7nbXcGxjtrudtdwbGO2u5213BtO3rmZmYwd7a7nbXcHOq2sKMdtdztruDYx213d7a7g0ORes5S6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5Norm7af8xihMzM4yDc+3SGZvaftwBT1R/wBSey+HxGbVYwrCV5xtIOAp1RqCYp1RrJ1RrIJinVGsnVGsgmKdUaydUayCYp1RrJ1RrIJinVGsnVGsgmKdUaydUayCYp1RrJ1RrIJinVGsnVGsgmKdUaydUayCYp1RrJ1RrIJinVGsnVGoJqeu+PxOacxhODtZwtALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAx7coTV9kY14SBv10iYxlSIiMoT9U5woAhbynldC3lPIEZwuhGcLgA5a0VjGQdEp9lpy+HP8AdtQWE6+2f+v/AFSJifmAAAAAAAAAAAAAAAAAQt5TyVzjkt5TyVzjkFwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJjGJhBdG8YWkCk4WhZBeJxiJAQt5TyuhbynkCM4XQjOFwJ+PlG1ptOKns8ZSAAAa9dsJw+pZAXAAAAAAAAGeyP9YfWrQAAAAAAIW8p5K5xyW8p5K5xyC4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACftjKVGfZGNZ2BJX1zjXDRJv1T8zGoKIW8p5XQt5TyBGcLoRnC4OXjGsorpXp/mdgZAAIjGcBT10/6n+A2AAAAAAne/wBR/ZL3+o/ssAN0vh8TkwAuJ0vh8TkoAAAACFvKeSucclvKeSuccguAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZgCE/E4O1nC0S77IwtyyC6FvKeV6/MRwhbynkCM4XQjOFwAAYn1ROXw51TqoAzX11jeWgAAAAATvf6j+yXv8AUf2WAAAAAG6Xw+JyYAXE6Xw+JyUAABC3lPJXOOS3lPJXOOQXAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj2x8RKa14xrKILV8Y4Rt5TytXxjhG3lPIEZwuhGcLgAAA5a0VjGQLWisYy5S/+vifiUrWm04yAuM0v/r4nNoBO9/qP7Je/1H9lgAAAAAAAABul8PicmAFxn1+LQIW8p5K5xyW8p5K5xyC4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACExhMwul7IwtjqClfGOEbeU8rV8Y4Rt5TyBGcLoRnC4AFrRWMZBy1orGMo2tNpxktabTjIAAA1PsmYw/wDZZAAAAAAAAAAAAAV9Xj/WmfV4/wBaBC3lPJXOOS3lPJXOOQXAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY9sfGOjZaMazAOV8Y4Rt5TytXxjhG3lPIEZwuhGcLgWmKxjKNrTacZU9nikAAAAAAAAAAAAAAAAAACvq8f60z6vH+tAhbynkrnHJbynkrnHILgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIW8p5XQt5TyBGcLoRnC4M+zxSWtX/UYZMdW/4DA31b/h1b/gMDfVv+HVv+AwN9W/4dW/4DA31b/h1b/gMDfVv+HVv+AwN9W/4dW/4DA31b/h1b/gMDfVv+HVv+AwN9W/4dW/4DXq8f605Wv+YwzdBC3lPJXOOS3lPJXOOQXAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQt5Tyul7IwtO4MxnC6Dv+76gsI9l9TsvqCwj2X1Oy+oLCPZfU7L6gsI9l9TsvqCwj2X1Oy+oLCPZfU7L6gsI9l9TsvqCwj2X1Oy+oLCPZfU7L6gsI9l9TsvqCwj2X1Oy+oOW8p5K5xyO0jG0bfILAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOWrFodARmsxm4uAgL4GAIC+BgCAvgYAgL4GAIC+BgCAvgYAgL4GAIC+BgCAvgYAgL4GAIC+ACMVmcoVrWKxu6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//9k=' }`, }} name={`${entities.decode(item.user_name)}`} message={`${entities.decode(item.chat_message)}`} count={`${item.unread_count}`} /> </TouchableOpacity> )} keyExtractor={(item, index) => index} /> ) : ( <View style={styles.messagesMainScrollArea}> <Image resizeMode={'contain'} style={styles.messagesMainScrollImageStyle} source={require('../../Assets/Images/arrow.png')} /> <Text style={styles.messagesMainScrollOopsText}> {CONSTANT.OopsText} </Text> <Text style={styles.messagesMainScrollNoDataText}> {CONSTANT.NoDataText} </Text> </View> )} </ScrollView> </View> ); } } export default withNavigation(MessagesMain); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f7f7f7', }, messagesMainActivityIndicatorArea: { justifyContent: 'center', height: '100%', }, messagesMainActivityIndicatorStyle: { height: 30, width: 30, borderRadius: 60, alignContent: 'center', alignSelf: 'center', justifyContent: 'center', backgroundColor: '#fff', elevation: 5, }, messagesMainTouchableStyle: { backgroundColor: '#fff', flexDirection: 'column', borderRadius: 4, overflow: 'hidden', flex: 1, flexDirection: 'column', marginTop: 3, marginLeft: 5, marginRight: 7, marginBottom: 3, elevation: 5, shadowOffset: {width: 0, height: 2}, shadowOpacity: 0.2, shadowColor: '#000', }, messagesMainScrollArea: { flex: 1, marginTop: '40%', alignContent: 'center', height: '100%', width: '100%', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, messagesMainScrollImageStyle: { width: 250, height: 250, }, messagesMainScrollOopsText: { fontSize: 25, fontWeight: '700', marginVertical: 10, }, messagesMainScrollNoDataText: { fontSize: 17, fontWeight: '700', }, });
var $root=getRootPath(); function search(){ var bname=$("#bname").val(); var typeAge=$("#typeAge").val(); var typeTheme=$("#typeTheme").val(); var url="?bname="+bname; if(typeAge!=0){ url+="&typeAge="+typeAge; } url+="&typeTheme="+typeTheme; window.location.href=url; } function searchName(){ var bname=$("#bname").val(); var url="?bname="+bname+"&typeTheme=0"; window.location.href=url; } /** * 账号登陆 * @return */ function login(){ var mobile=$("#mobile").val(); var userPassword=$("#userPassword").val(); if(''==mobile||null==mobile){ Dialog.show("账号不能为空", 2, 2000); return; } if(''==userPassword ||null==userPassword){ Dialog.show("密码不能为空", 2, 2000); return; } var url="/user/login.html"; var data=$("#form1").serialize(); Dialog.show("正在登陆,请稍后。。。", 3, -1); $.ajax({ type:"post", url: url, data:data, dataType:'json', success:function(data){ if(data.success){ Dialog.show("登陆成功", 1, 2000); setTimeout(function() { var page=data.page; window.location.href=page; },2000); }else{ Dialog.show("账号或密码错误", 2, 2000); } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来"); } }); } function delCollection(id){ var $this=$("#"+id); var flag=$this.attr('bind_data'); var url=""; url="/delBook/"+id+".html"; Dialog.show("正在处理请求", 3, -1); $.ajax({ type:"post", url: url, async : false, success:function(data){ if(data.success){ var sum=parseInt($("#total").html()); $("#total").html(sum-1); $("#total2").html(sum-1); Dialog.show("移除书包成功", 1, 2000); $this.remove(); }else{ alert("您的人品也太不好了吧,收藏 失败了"); } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来收藏"); } }); } /*添加地址*/ function addAddress(){ var userName=$("#name").val(); var mobile=$("#mobile").val(); var address=$("#address").val(); if(userName==''){ Dialog.show("姓名不能为空", 2, 2000); return false; } if(mobile==''||null==mobile){ Dialog.show("手机号码不能为空", 2, 2000); return; }else{ var myreg = /^1[3458]\d{9}$/; if (!myreg.exec(mobile)){ errMsg='请输入正确的手机号'; Dialog.show(errMsg, 2, 2000); return; } } if(address==''||null==address){ Dialog.show("地址不能为空", 2, 2000); return ; } Dialog.show("正在添加地址...", 3, -1); var url="/addAddress.html"; var data=$("#form1").serialize(); $.ajax({ type:"post", url: url, data:data, async : false, success:function(data){ if(data.success=="nologin"){ Dialog.show("请先登录", 2, 2000); window.location.href="/book/login.html"; }else if(data.success){ Dialog.show("添加成功", 1, 2000); setTimeout(function() { window.location.href="/select/loveaddress.html"; },2000); }else{ Dialog.show("添加失败", 2, 2000); } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来收藏"); } }); } /*提交订单*/ function submitOrder(){ var total2=$("#total2").html(); if(total2==0){ Dialog.show("书包不能为空!", 0, 2000); return false; } var address=$("#addressId").val(); if(typeof(address) == "undefined"){ Dialog.show("请先添加地址", 2, 2000); return false; }else{ /*获取book...id*/ var bids=""; $(".bnames").each(function(){ bids+=$(this).attr('value')+","; }) bids=bids.substring(0, bids.length-1); var url="/order/create"; Dialog.show("正在提交订单...", 3, -1); $.ajax({ type:"post", url: url, data:{bids:bids,addressId:address}, async : false, success:function(data){ if(data.success){ Dialog.show("订单提交成功", 2, 2000); window.location.href="/book/order.html"; }else{ alert("您的人品也太不好了吧,收藏 失败了"); } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来收藏"); } }); } } function preOrder(){ var total2=$("#total2").html(); if(total2==0){ Dialog.show("书包不能为空!", 0, 2000); return false; } var ids=""; $(".app_news").each(function(){ var id=$(this).attr('id')+","; ids+=id; }) ids=ids.substring(0,ids.length-1); Dialog.show("正在提交订单...", 3, -1); var url="/order/precreate?cid="+ids; window.location.href=url; } function ajax(id,user){ //判断用户是否登陆 Dialog.show("正在处理请求", 3, -1); var login_url="/user/getUser.html"; $.ajax({ type:"post", url: login_url, async : false, success:function(data){ if(null==data.user){ Dialog.show("您还未登陆", 1, 2000); setTimeout(function() { window.location.href="/book/login.html"; },3000); return; }else{ ajaxSubmit(id); } },error:function(){ } }); } function ajaxSubmit(id){ var $this=$("#"+id); var flag=$this.attr('bind_data'); var url=""; if(flag=="no") { url="/addbook/"+id+".html"; }else{ url="/delBook/"+id+".html"; } Dialog.show("正在处理请求", 3, -1); $.ajax({ type:"post", url: url, async : false, success:function(data){ if(data.success=="max"){ Dialog.show("亲,一次最多只能借8本呦", 2, 3000); }else if(data.success=="min"){ Dialog.show("亲,此书借光啦,请选择其他绘本", 2, 3000); } else{ if(data.success){ if(flag=="yes"){ Dialog.show("移除书包成功", 1, 2000); $this.attr('src',"../../../res/images/book/frsb.jpg"); $this.attr("bind_data","no"); }else{ Dialog.show("加入书包成功", 1, 2000); $this.attr('src',"../../../res/images/book/yichu.jpg"); $this.attr("bind_data","yes"); } }else{ Dialog.show("您的人品也太不好了吧,加入失败了", 2, 2000); } } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来收藏"); } }); } var Dialog = new function () { this.show = function (b, l, f) { this.hide(); var g = l || 0; if (g > 3) { g = 0; } var m = f || 5000; var e = new Array(); e[0] = $root+"res/images/book/info.png"; e[1] = $root+"res/images/book/success.png"; e[2] = $root+"res/images/book/error.png"; e[3] = $root+"res/images/book/ajax-loader.gif"; var a = document.createElement("div"); a.id = "div_tip_1"; a.className = "dialog-div-box"; var d = '<div class="dialog-div"><div class="u-guodu-box"><div><table width="100%" cellpadding="0" cellspacing="0" border="0" ><tr><td align="center"><img src="' + e[g] + '"></td></tr><tr><td align="center" style="font-size:14px;font-weight: blod;line-height:30px">' + b + "</td></tr></table></div></div></div>"; a.innerHTML = d; document.body.appendChild(a); var c = document.documentElement.scrollTop; var k = $(window).width(); var i = $(window).height(); $(".dialog-div").css("display", "block"); $(".dialog-div").css("top", c + "px"); var h = $(".dialog-div").width(); var j = $(".dialog-div").height(); $(".dialog-div").css("left", (k / 2 - h / 2) + "px"); $(".dialog-div").css("top", (i / 2 - j / 2) + "px"); if (m > 0) { setTimeout(function () { a.parentNode.removeChild(a) }, m); } return a; }; this.hide = function () { var a = document.getElementById("div_tip_1"); if (a !== null || typeof (boj) !== "undefined") { a.parentNode.removeChild(a); } } }; function getRootPath(){ //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath=window.document.location.href; //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //获取主机地址,如: http://localhost:8083 var localhostPaht=curWwwPath.substring(0,pos); //获取带"/"的项目名,如:/uimcardprj var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return(localhostPaht+projectName+"/"); }
//credit https://codepen.io/anon/pen/vMmxwb $(document).ready(function() { $('a[href*=\\#]').bind('click', function(e) { e.preventDefault(); // prevent hard jump, the default behavior var target = $(this); // Set the target as variable // perform animated scrolling by getting top-position of target-element and set it as scroll target $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 1,function() { location.hash = target.attr("href"); //attach the hash (#jumptarget) to the pageurl }); return false; }); }); $(window).scroll(function() { var scrollDistance = $(window).scrollTop()+400 ; // Assign active class to nav links while scolling $('.page-section').each(function(i) { if ($(this).position().top <= scrollDistance) { //+ hauteur element $('.navigation a.active').removeClass('active'); $('.navigation a').eq(i).addClass('active'); } }); }).scroll();
import React from 'react'; import { shallow } from 'enzyme'; import Lightbox from 'react-image-lightbox'; import Image from 'components/image'; describe('Component - Image', () => { let wrapper, instance; beforeEach(() => { wrapper = shallow(<Image />); instance = wrapper.instance(); }); test('Displays title correctly', () => { wrapper.setProps({title: 'test'}); const title = wrapper.find('h5').text(); expect(title).toBe('test'); }); test('Display image correctly', () => { wrapper.setProps({thumbnailUrl: 'test'}); const image = wrapper.find('img'); expect(image.prop('src')).toBe('test'); }); test('Correct onClick method passed to image', () => { wrapper.setProps({thumbnail: 'test'}); const image = wrapper.find('img'); expect(image.prop('onClick')).toBe(instance.togglePreview); }); describe('previewMode', () => { test('Show lightbox when isPreviewMode true', () => { wrapper.setState({isPreviewMode: true}); const lightbox = wrapper.find(Lightbox); expect(lightbox.exists()).toBe(true); }); test('Correct url passed to lightbox when isPreviewMode true', () => { const url = 'test_url'; wrapper.setState({isPreviewMode: true}); wrapper.setProps({ url }); const lightbox = wrapper.find(Lightbox); expect(lightbox.prop('mainSrc')).toBe(url); }); test('Correct onCloseRequest method passed to lightbox when isPreviewMode true', () => { wrapper.setState({isPreviewMode: true}); const lightbox = wrapper.find(Lightbox); expect(lightbox.prop('onCloseRequest')).toBe(instance.togglePreview); }); test('Do not show lightbox when isPreviewMode false', () => { wrapper.setState({isPreviewMode: false}); const lightbox = wrapper.find(Lightbox); expect(lightbox.exists()).toBe(false); }); }); describe('togglePreview', () => { test('Sets isPreviewMode state to true when previously false', () => { wrapper.setState({isPreviewMode: false}); instance.togglePreview(); expect(wrapper.state('isPreviewMode')).toBe(true); }); test('Sets isPreviewMode state to false when previously true', () => { wrapper.setState({isPreviewMode: true}); instance.togglePreview(); expect(wrapper.state('isPreviewMode')).toBe(false); }); }); });