text
stringlengths
7
3.69M
import React from 'react' import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Switch, Route, } from 'react-router-dom'; import Home from './components/Home'; import Add from './components/Add'; import Edit from './components/Edit'; import EditC from './components/EditC'; import AddC from './components/AddC'; export default function App() { return ( <Router className="App__Container"> <Switch> <Route exact path="/"> <Home></Home> </Route> <Route exact path="/add"> <Add></Add> </Route> <Route exact path="/addc"> <AddC></AddC> </Route> <Route exact path="/edit/:id"> <Edit></Edit> </Route> <Route exact path="/editc/:id"> <EditC></EditC> </Route> </Switch> </Router> ) } ReactDOM.render(<App/>, document.getElementById('app'));
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "node-modules/fangchan-base/components/views/fangchan-cooperation-form" ], { 1482: function(n, e, o) { o.r(e); var t = o("e73f"), a = o("fc9d"); for (var i in a) [ "default" ].indexOf(i) < 0 && function(n) { o.d(e, n, function() { return a[n]; }); }(i); o("d0bd"); var c = o("f0c5"), s = Object(c.a)(a.default, t.b, t.c, !1, null, "08a36d2f", null, !1, t.a, void 0); e.default = s.exports; }, "22e9": function(n, e, o) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var t = function(n) { return n && n.__esModule ? n : { default: n }; }(o("b4fd")), a = { props: {}, data: function() { return { mobile: "", weixin_name: "", intention: "", maxlength: 300 }; }, methods: { submit: function(n) { var e = this, o = n.detail.value, a = o.mobile, i = o.weixin_name, c = o.intention, s = [ { tips: "请授权手机号", value: a }, { tips: "请输入您的微信号", value: i }, { tips: "请简要说明合作意向", value: c } ].every(function(n) { return "" !== n.value.trim() || (e.onShowToast(n.tips), !1); }); c.length > this.maxlength ? this.onShowToast("合作意向不能超过".concat(this.maxlength, "个字!")) : s && (wx.showLoading({ title: "提交中..." }), t.default.postBusinessCooperations({ mobile: a, weixin_name: i, intention: c.substr(0, this.maxlength) }).then(function() { wx.hideLoading(), wx.showModal({ title: "提示", content: "提交成功!", showCancel: !1, success: function(n) { n.confirm && wx.switchTab({ url: "/pages/index/main" }); } }); })); }, getPhoneNumber: function(n) { var e = this, o = n.target, a = o.iv, i = o.encryptedData, c = o.errMsg; t.default.postWeixinPhone(a, i, c).then(function(n) { 422 === Number(n.code) ? wx.showToast({ title: n.error_message, icon: "none" }) : e.mobile = n.phone; }); }, onShowToast: function(n) { wx.showToast({ title: n, icon: "none", duration: 2e3 }); } } }; e.default = a; }, c2ab: function(n, e, o) {}, d0bd: function(n, e, o) { var t = o("c2ab"); o.n(t).a; }, e73f: function(n, e, o) { o.d(e, "b", function() { return t; }), o.d(e, "c", function() { return a; }), o.d(e, "a", function() {}); var t = function() { var n = this; n.$createElement; n._self._c; }, a = []; }, fc9d: function(n, e, o) { o.r(e); var t = o("22e9"), a = o.n(t); for (var i in t) [ "default" ].indexOf(i) < 0 && function(n) { o.d(e, n, function() { return t[n]; }); }(i); e.default = a.a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "node-modules/fangchan-base/components/views/fangchan-cooperation-form-create-component", { "node-modules/fangchan-base/components/views/fangchan-cooperation-form-create-component": function(n, e, o) { o("543d").createComponent(o("1482")); } }, [ [ "node-modules/fangchan-base/components/views/fangchan-cooperation-form-create-component" ] ] ]);
/// <reference path="../scripts/rx.js" /> /// <reference path="../scripts/jquery-3.1.1.min.js" /> /* This sample shows how to send multiple request, but it does not know when last request has been received and therefore cannot handle final result... */ var webUrl; var endpoint; var items = []; var obs; function onDataReceived(data) { obs.onNext(data); } function getFieldValue(fieldname, skip, top) { var uri = endpoint + "?$select=" + fieldname + "&$skip=" + skip + "&$top=" + top; $.getJSON(uri, onDataReceived); } function getCount() { var url = '/sites/rxjs/_api/web/lists/getbytitle(\'Catalog\')/itemcount'; $.ajax({ url: url, type: "GET", contentType: "application/json;odata=verbose", headers: { "Accept": "application/json;odata=verbose" } }).done(function (result) { var value = result.d.ItemCount; console.log("ItemCount=" + value); var batch = 500; var count = Math.ceil(value / batch); for (var i = 0; i < count; i++) { var skip = batch * i; var top = batch * (i + 1) > value ? (value % batch) - 1 : batch; getFieldValue("Language", skip, top); } obs.onCompleted(); }); } $(function () { webUrl = _spPageContextInfo.webServerRelativeUrl; endpoint = webUrl + "/_vti_bin/ListData.svc/Catalog"; obs = new Rx.Subject(); //obs.error(function (err) { // console.err('something terrible just happened'); //}); //obs.onCompleted(function () { // console.log("ready to go"); // console.log(items.length); //}); obs.subscribe(function (value) { console.log(value); items = items.concat(value.d); }, function (err) { console.err('something terrible just happened'); }, function () { console.log("ready to go"); console.log(items.length); }); getCount(); });
import React from 'react'; import {render} from 'react-dom'; import { provider , hashHistory } from 'react-router-dom' import Routers from './routers'; render( <Routers/>, document.getElementById('root') );
// import React, { useState } from 'react'; // import PropTypes from 'prop-types'; // import Box from '@material-ui/core/Box'; // import Collapse from '@material-ui/core/Collapse'; // import IconButton from '@material-ui/core/IconButton'; // import Table from '@material-ui/core/Table'; // import TableBody from '@material-ui/core/TableBody'; // import TableCell from '@material-ui/core/TableCell'; // import TableContainer from '@material-ui/core/TableContainer'; // import TableHead from '@material-ui/core/TableHead'; // import TableRow from '@material-ui/core/TableRow'; // import Typography from '@material-ui/core/Typography'; // import Paper from '@material-ui/core/Paper'; // import Link from 'next/link'; // import JPMC from '../../../public/images/projects/jpmc.PNG'; // import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown'; // import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp'; // function Row(props) { // console.log('Inside row()'); // const { row, projectData } = props; // const [open, setOpen] = useState(false); // const year = Object.values(projectData)[0].year; // const description = Object.values(projectData)[0].description; // const madeAt = Object.values(projectData)[0].made_at; // const tech = Object.values(projectData)[0].tech; // const title = Object.values(projectData)[0].title; // const gitHublink = Object.values(projectData)[0].github_repo_link; // const projectHomePageLink = Object.values(projectData)[0].homepage_link; // const [id, setId] = useState(''); // console.log('What is open:: ' + open); // console.log(projectData); // // console.log({ index, id }); // function showArrowIcon(open) { // console.log('Inside showArrowIcon'); // console.log({ open }); // if (open) { // console.log('Show UP'); // // return <p>YES</p>; // // return <i className='fas fa-angle-up faIcon' />; // return <KeyboardArrowUpIcon />; // } // console.log('Show DOWN'); // // return <p>NO</p>; // return <KeyboardArrowDownIcon />; // // return <i className='fas fa-angle-down faIcon' />; // // open ? ( // // <i className='fas fa-angle-up faIcon' /> // // ) : ( // // <i className='fas fa-angle-down faIcon' /> // // ); // } // const result = showArrowIcon(open); // console.log(result); // return ( // <React.Fragment> // <TableRow> // <TableCell> // <IconButton // aria-label='expand row' // size='small' // onClick={() => { // console.log('In OnClikc'); // console.log({ open }); // // if (index === id) { // // console.log({ index, id }); // setOpen(!open); // // } // // setId(index); // console.log({ open }); // }} // > // {/* {showArrowIcon(open)} */} // {result} // {console.log('What is open right before:: ' + open)} // {/* {open ? ( // <i className='fas fa-angle-up faIcon' /> // ) : ( // <i className='fas fa-angle-down faIcon' /> // )} */} // </IconButton> // </TableCell> // <TableCell component='th' scope='row'> // {year} // </TableCell> // <TableCell className='projectTitle' align='left'> // {title} // </TableCell> // <TableCell align='left'>{madeAt}</TableCell> // <TableCell align='left'>{tech}</TableCell> // <TableCell align='left'> // <div className='linksContainer'> // <Link href={gitHublink}> // <a> // <i className='fab fa-github-square faIcon' /> // </a> // </Link> // <Link // href={{ // pathname: projectHomePageLink // }} // > // <a> // <i className='fas fa-external-link-alt faIcon' /> // </a> // </Link> // </div> // </TableCell> // </TableRow> // <TableRow> // <TableCell // style={{ paddingBottom: 0, paddingTop: 0 }} // colSpan={6} // > // <Collapse in={open} timeout='auto' unmountOnExit> // {/* <Box margin={1}> */} // <div className='container'> // <div className='row'> // <div className='col-md-12 col-sm-12 dataDropdownContainer'> // <div className='dataContainer'> // <p className='text10 sourceSansText whiteText boldText'> // About {title} // </p> // <p className='text10 sourceSansText whiteText'> // {description} // </p> // <p className='text10 sourceSansText whiteText'> // <b>Technologies Used:</b> {tech} // </p> // </div> // <div className='dataPictureContainer'> // <img // className='img-fluid' // src={JPMC} // alt='Picture about Project' // /> // </div> // </div> // </div> // </div> // </Collapse> // </TableCell> // </TableRow> // </React.Fragment> // ); // } // export default Row;
import { GET_LISTS, GET_LIST, UPDATE_LIST, REMOVE_LIST, TOGGLE_LIST_INGREDIENT, TO_SUBMIT_LIST, SUBMIT_LIST_SUCCESS, } from '../actions/types'; const initialState = { list: null, lists: null, submittingList: false, submitted: false, loading: true, }; export default function (state = initialState, action) { const { type, payload } = action; switch (type) { case GET_LISTS: return { ...state, lists: payload, submitted: false, }; case GET_LIST: return { ...state, list: payload, loading: false, }; case UPDATE_LIST: return { ...state, }; case REMOVE_LIST: return { ...state, list: null, loading: false, }; case TOGGLE_LIST_INGREDIENT: const ingredients = [...state.list.ingredients]; const newList = { ...state.list, ingredients: ingredients.map((el) => el.ingredient === payload.ingredient ? { ...payload, done: !payload.done } : el ), }; return { ...state, list: newList, }; case TO_SUBMIT_LIST: return { ...state, submittingList: payload, submitted: false, }; case SUBMIT_LIST_SUCCESS: const newLists = state.lists ? [...state.lists, payload] : [payload]; return { ...state, lists: newLists, submittingList: false, submitted: true, }; default: return state; } }
//ClientesFacturacionGrupoAQuery Entity: EntidadClienteGrupoA task.executeQuery.Q_CLIEGTEN_XH49 = function(executeQueryEventArgs){ executeQueryEventArgs.commons.execServer = true; //executeQueryEventArgs.commons.serverParameters.EntidadClienteGrupoA = true; executeQueryEventArgs.parameters.nombre = executeQueryEventArgs.commons.api.vc.model.EntidadClienteBusquedaGrupoA.nombre; };
import React, { Component } from 'react'; import { Card, CardImg, CardTitle, CardGroup, Button, Table, Jumbotron } from 'reactstrap'; import { Form, FormGroup, Label, Input } from 'reactstrap'; // using react router , route class TradeComponent extends Component { render() { return ( <div> <Table className='ml-4 mr-4' hover> <thead> <tr> <th>#</th> <th>Name</th> <th>Price</th> <th>Change</th> <th>Trade</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Bitcoin BTC</td> <td>840 Euros</td> <td>-2.73%</td> <td><Button color='success'>Buy</Button></td> </tr> <tr> <th scope="row">2</th> <td>Bartcoin BRC</td> <td>100 Euros</td> <td>-0.73%</td> <td><Button color='success'>Buy</Button></td> </tr> <tr> <th scope="row">3</th> <td>Ethereum ETH</td> <td>160 Euros</td> <td>-5.43%</td> <td><Button color='success'>Buy</Button></td> </tr> <tr> <th scope="row">4</th> <td>Bitcoin Cash BCH</td> <td>320 Euros</td> <td>-0.19%</td> <td><Button color='success'>Buy</Button></td> </tr> <tr> <th scope="row">5</th> <td>Litecoin LTC</td> <td>60 Euros</td> <td>-4.18%</td> <td><Button color='success'>Buy</Button></td> </tr> </tbody> </Table> <Jumbotron className="mb-0"> <h1 className="display-4">Learn How To Trade Like a Pro</h1> <h5>Develop your trading strategies and skills with our professional tools, education resources and daily reviews of market</h5> <br /> <CardGroup color='info'> <Card body outline color="info" > <CardImg top height='50%' src='images/news.jpg' alt='img1' /> <CardTitle><h1 className="display-3">News and Analysis</h1></CardTitle> <Button color='dark'>Learn More</Button> </Card> <Card body outline color="info"> <CardImg top height='50%' src='images/markets.jpg' alt='img2' /> <CardTitle><h1 className="display-3">Markets Review</h1></CardTitle> <Button color='dark'>Learn More</Button> </Card> <Card body outline color="info"> <CardImg top height='50%' src='/images/training.jpeg' alt='img3' /> <CardTitle><h1 className="display-3">Trading Guidelines</h1></CardTitle> <Button color='dark'>Learn More</Button> </Card> </CardGroup> <hr className="my-2" /> <h1 className="display-4">Contact us</h1> <Form> <FormGroup> <Label for="exampleEmail">Email</Label> <Input type="email" name="email" id="exampleEmail" placeholder="Type your email" style={{ width: '300px', height: '40px' }} /> </FormGroup> <FormGroup> <Label for="exampleText">Message</Label> <Input type="textarea" name="message" id="exampleText" placeholder="Type your message" style={{ width: '300px', height: '150px' }} /> </FormGroup> <Button color='primary'>Submit</Button> {/* <Button color='primary'>Submit</Button> */} </Form> <hr className="my-2" /> </Jumbotron> </div> ); } } export default TradeComponent;
export default { getServiceUrl: function() { return process.env.REACT_APP_API_SERVICE_URL; } }
var AccountWithdraw = function() { this.tips = $("#withdraw-errorMessage"); this.gowithdraw = $("#gowithdraw"); this.withdrawCash= $("#withdraw-cash"); this.balance = 0; this.fee = 0 this.enableClick = true; this.payOneLimit = 0; return this; } AccountWithdraw.prototype = { init: function() { GHutils.isLogin(); this.pageInit(); this.bindEvent(); }, pageInit: function() { var _this = this; _this.limitamount(); _this.getUserInfo(); _this.getMoneyInfo(); }, bindEvent: function() { var _this = this GHutils.checkInput($("#withdraw-Money"),3); GHutils.checkInput($("#payPwd"),5); GHutils.inputPwd("#payPwd") setTimeout(function(){ $("#withdraw-Money").val('') },50) GHutils.IEInputClear("#withdraw-Money",function(){ //ie input点击叉叉清空内容自定义事件 $('.rest').html('--') }) $('#allBank').off().on('click',function(){ _this.tips.html('&nbsp;') var columnDefine=[ {"name":"bankBigLogo","clazz":"col-xs-4","format":function(){return "<img width=130px src="+this.bankBigLogo+">"}}, {"name":"payOneLimit","format":function(){return GHutils.formatCurrency(this.payOneLimit)}}, {"name":"payDayLimit","format":function(){return GHutils.formatCurrency(this.payDayLimit)}}, {"name":"payMoonLimit","format":function(){return GHutils.formatCurrency(this.payMoonLimit)}} ] GHutils.load({ url:GHutils.API.ACCOUNT.bankList, type:'post', callback:function(result){ if(GHutils.checkErrorCode(result,_this.tips)){ GHutils.table("#modal_content",columnDefine,result.datas,"#modal_content-noRecord") $('#content_box').modal('show') } } }) }) }, getUserInfo:function(){ var _this = this; GHutils.load({ url: GHutils.API.ACCOUNT.userinfo, data: {}, type: "post", callback: function(result) { GHutils.log(result,"用户信息=======") if(GHutils.checkErrorCode(result,$(this.tips ))){ GHutils.userinfo = result //判断是否已经设置交易密码 // if(result.paypwd){ // $('#hasPayPwd').show().prev().hide() // }else{ // $('#hasPayPwd').hide().prev().show() // } //判断是否已经绑卡 var bankName = result.bankName // if(bankName){ $('#cardNo').html(bankName+'(**** **** '+result.bankCardNum.substring(4)+')') _this.getBankList(function(bankList){ GHutils.getBankStyle(bankName,bankList,_this.tips,function(res){ // $("#hasCard").show().next().hide(); GHutils.log(res,"银行卡信息=========") $("#bankPhone").html(result.bankPhone) // if(result.paypwd){ _this.gowithdraw.addClass("active"); _this.withdrawEvent(); // }else{ // _this.gowithdraw.removeClass("active").off(); // } }) }) // }else{ //// $('#hasCard').hide().next().show() // _this.gowithdraw.removeClass("active").off(); // } } } }) }, limitamount:function(){//获取用户账户信息 var _this = this; GHutils.load({ url:GHutils.API.ACCOUNT.limitamount, type:'post', async:false, callback:function(result){ GHutils.log(result,"限额=======") if(GHutils.checkErrorCode(result,_this.tips)){ _this.payOneLimit = result.withdrawalsSingleQuota+0 var withdrawalsSingleQuota = result.withdrawalsSingleQuota+0; if(withdrawalsSingleQuota > 10000){ withdrawalsSingleQuota = GHutils.formatCurrency(GHutils.toFixeds(withdrawalsSingleQuota/10000,2))+' 万' }else{ withdrawalsSingleQuota = GHutils.formatCurrency(withdrawalsSingleQuota); } var withdrawalsDailyLimit = result.withdrawalsDailyLimit+0; if(withdrawalsDailyLimit > 10000){ withdrawalsDailyLimit = GHutils.formatCurrency(GHutils.toFixeds(withdrawalsDailyLimit/10000,2))+' 万' }else{ withdrawalsDailyLimit = GHutils.formatCurrency(withdrawalsDailyLimit); } $('#singleQuota').append('本卡单次限额 '+withdrawalsSingleQuota+'元,'+'单日限额 '+withdrawalsDailyLimit+'元') } } }) }, getBankList:function(cb){//获取银行卡列表信息 var _this = this; GHutils.load({ url:GHutils.API.ACCOUNT.bankList, type:'post', callback:function(result){ GHutils.log(result,"银行卡限额======="); if(GHutils.checkErrorCode(result,_this.tips)){ if(cb && typeof(cb)=="function"){ cb.apply(null,[result.datas]); } } } }) }, getMoneyInfo:function(){ var _this = this; GHutils.load({ url: GHutils.API.ACCOUNT.usermoneyinfo, data: {}, type: "post", callback: function(result) { GHutils.log(result,"账户信息=========") if(GHutils.checkErrorCode(result,_this.tips)){ _this.balance = (result.withdrawAvailableBalance+0) var canWithDraw = _this.balance; if(_this.payOneLimit && _this.payOneLimit < canWithDraw) { canWithDraw = _this.payOneLimit } //页面显示账户余额 $('.withdraw_all_cash').html(GHutils.formatCurrency(canWithDraw)+"元") $('#withdraw-Money') .keyup(function() { var _val =$('#withdraw-Money').val(); if(_val && Number(_val) > Number(_this.balance)){ _val = _this.balance; $('#withdraw-Money').blur().next().hide(); } $('#withdraw-Money').val(_val) if(_val > _this.fee){ $('.rest').html(GHutils.formatCurrency(GHutils.Fsub(_val,_this.fee))) }else{ $('.rest').html('--') } }) .on("contextmenu",function(e){//禁止鼠标右键弹出操作选项列表 e.preventDefault(); }) var monthWithdrawCount = result.monthWithdrawCount+0//当月已经提现次数 GHutils.checkEnable('WithdrawNum','',function(times){//获取免费提现次数 if(monthWithdrawCount >= Number(times)){ GHutils.checkEnable('TradingDayWithdrawFee','',function(fee){//获取手续费 _this.fee = Number(fee) $("#fee").html(fee) }) }else{ $("#fee").html(0) } }) } } }) }, withdrawEvent:function(){//提现按钮点击事件 var _this = this; //点击确认提现 _this.gowithdraw.off().on('click',function(){ if(!_this.enableClick){ setTimeout(function(){ _this.enableClick = true; },2000); } _this.enableClick = false; if($(this).is('.btn_loading')){ return false; } _this.tips.html('&nbsp;') if(!GHutils.userinfo){ GHutils.userinfo = GHutils.getUserInfo(); } if(!GHutils.userinfo){ _this.tips.html('数据未加载成功,请等待或刷新页面') return false; }else if(!GHutils.userinfo.bankName){//没有绑卡 _this.tips.html('提示:请绑定银行卡再提现') return false; } if(!GHutils.userinfo.paypwd){//没有设置交易密码 _this.tips.html('提示:请设置交易密码再提现') return false; } if(GHutils.validate('withdraw-box')){ var money = parseFloat($('#withdraw-Money').val()) if(money<=0){ _this.tips.html('提示: 提现金额必须大于0元') return false; } if(_this.fee){//如果有手续费,提现金额必须大于手续费 if(money<=_this.fee){ _this.tips.html('提示: 提现金额必须大于手续费'+_this.fee+'元') return false; } } if(_this.payOneLimit && _this.payOneLimit < money) { _this.tips.html('提示: 提现金额不能超过'+_this.payOneLimit+'元') return false; } _this.gowithdraw.addClass('btn_loading') GHutils.isLogin(function(){ _this.checkPayPwd(money); }); } }) }, checkPayPwd:function(money){//校验支付密码 var _this = this; GHutils.load({ url: GHutils.API.USER.checkpaypwd, data:{ payPwd:GHutils.trim($('#payPwd').val()) }, type: "post", callback: function(result) { if(GHutils.checkErrorCode(result,_this.tips)){ if(_this.balance < money){ // _this.gowithdraw.removeClass('btn_loading') _this.tips.html('提示:账户余额不足') return false; } _this.withd(status,money) } } }); }, withd:function(statu,money){ var _this = this; GHutils.load({ url: GHutils.API.ACCOUNT.withdraw, data:{ orderAmount:money }, type: "post", callback: function(result) { _this.gowithdraw.removeClass('btn_loading') if(GHutils.checkErrorCode(result,_this.tips)){ window.location.href = 'product-result.html?action=withdraw&moneyVolume='+money+'&fee='+_this.fee } } }); }, callBackFun:function(){ var _this = this _this.pageInit(); _this.withdrawEvent(); } } $(function() { new AccountWithdraw().init(); window.pageFun = new AccountWithdraw(); })
export const primary = '#007a7c'; export const secondary = '#e18b7f'; export const mutedSecondary = '#f9e6e3'; export const accent = '#39cccc'; export const mutedAccent = '#dcf6f6'; export const darkBlue = '#001f3f'; export const mediumBlue = '#0f4880'; export const lightGray = '#eae5e5'; export const darkGray = '#979797'; export const primaryText = '#4a4a4a'; export const white = '#fff';
import _ from 'lodash' import React, { Component } from "react"; import { withApollo } from 'react-apollo'; import { Search, Label, Image } from 'semantic-ui-react'; import { QuerySearchUsers, MutationRemoveFriend, MutationAddFriend } from '../GraphQL'; const resultRenderer = ({ data, handlers }) => { return ( <div> <Image size="mini" style={{height:'100%', float:'left', marginRight:'1em' }} src={data.profilePic} /> <div> <div style={{marginBottom: '5px'}}>{data.username}</div> {data.followed === 1 ? <Label as='a' size='small' color='red' onClick={() => handlers.removeFriend(data.username, true)}>Unfollow</Label> : <Label as='a' size='small' color='blue' onClick={() => handlers.addFriend(data.username, true)}>Follow</Label>} </div> </div> ) } class SearchUsers extends Component { componentWillMount() { this.resetComponent() } runQuery = (search) => ( this.props.client.query({ query: QuerySearchUsers, variables: { search: search }, }) ) resetComponent = () => { this.props.client.resetStore() this.setState({ isLoading: false, results: [], value: '' }) } handleSearchChange = (event, { value }) => { this.setState({ isLoading: true, value }) if (value.length > 0) { this.runQuery(value) .then(({ data }) => { this.setState({ isLoading: false, results: data.searchUsers.items }) }) } else { setTimeout(() => { if (this.state.value.length < 1) return this.resetComponent() }, 300) } } handleRemoveFriend = (username, custom) => { if(custom === true) { this.setState({ isLoading: true }) const { value } = this.state; this.props.client.mutate({ mutation: MutationRemoveFriend, variables: { friendUsername: username }, }).then((data) => { this.props.client.resetStore() }).finally(() => { this.runQuery(value) .then(({ data }) => { this.setState({ isLoading: false, results: data.searchUsers.items }) }) }) } } handleAddFriend = (username, custom) => { if(custom === true) { this.setState({ isLoading: true }) const { value } = this.state; this.props.client.mutate({ mutation: MutationAddFriend, variables: { friendUsername: username }, }).then((data) => { this.props.client.resetStore() }).finally(() => { this.runQuery(value) .then(({ data }) => { this.setState({ isLoading: false, results: data.searchUsers.items }) }) }) } } getUrl = (file) => { try { if (file) { const { bucket, region, key } = file; const url = `https://s3-${region}.amazonaws.com/${bucket}/${key}`; return url; } return null; } catch (err) { console.error(err); } } render() { const { isLoading, value, results } = this.state let i; const res = []; for (i = 0; i < results.length; i++) { const profilePic = results[i].profilePic ? this.getUrl(results[i].profilePic) : null res.push({ data: { username: results[i].username, followed: results[i].followed ? 1 : 0, profilePic: profilePic, }, key: results[i].username, handlers: { removeFriend: this.handleRemoveFriend, addFriend: this.handleAddFriend } }) } return ( <Search loading={isLoading} onSearchChange={_.debounce(this.handleSearchChange, 500, { leading: true })} results={res} resultRenderer={resultRenderer} value={value} placeholder="Search people" /> ) } } export default withApollo(SearchUsers);
angular.module('gt-gamers-guild.nav-ctrl', []) .controller('NavCtrl', function($scope, $state) { $scope.go = function(route) { $state.go(route); } });
/** * 现金交易记录 */ import React, { Component, PureComponent } from 'react'; import { StyleSheet, Dimensions, View, Text, TouchableOpacity, } from 'react-native'; import moment from 'moment'; import { connect } from 'rn-dva'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import PickerOld from 'react-native-picker-xk'; import ScrollableTabBar from '../../components/CustomTabBar/ScrollableTabBar'; import FlatListView from '../../components/FlatListView'; import * as requestApi from '../../config/requestApi'; import Picker from '../../components/Picker'; import Header from '../../components/Header'; import CommonStyles from '../../common/Styles'; const { width, height } = Dimensions.get('window'); const date = new Date(); const fullYear = date.getFullYear(); const fullMonth = date.getMonth() + 1; const fullDay = date.getDate(); const DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; class FinanceTradeRecordScreen extends PureComponent { static navigationOptions = { header: null, }; constructor(props) { super(props); const params = props.navigation.state.params || {}; this.state = { currentTab: 0, // 当前tabs billType: params.billType || 'fi', // fi收入,fo支出 billStatus: params.billStatus || 'normal', // 账单类型 normal frozen currency: params.currency || '', // 记录 类型 xkq晓可券(现金),xkb晓可币,xfq消费券,swq实物券 startTime: '', endTime: '', tradeProduct: '', // 此字段暂时不传,可能更改 分类 b2c自营零售价,b2c 自营批发价,jb2c福利零售价,jb2b福利批发价,o2o 商圈价格,gift 礼物,redPackets红包 recordList: [], }; } componentDidMount() { Loading.show(); this.getList(true, false); } getList = (isFirst = false, isLoadingMore = false, loading = true, refreshing = true) => { const { currentTab, currentShop, currency, billType, } = this.state; let params = {}; params = this.getTitleAndParams().param; console.log('params',params) params.startTime ? params.startTime = parseInt(moment(params.startTime).valueOf() / 1000) : null; params.endTime ? params.endTime = parseInt(moment(params.endTime).valueOf() / 1000) : null; this.props.fetchList({ witchList: `accountRecord${currency}${billType}`, isFirst, isLoadingMore, paramsPrivate: params, api: currency == 'xkwl' ? requestApi.merchantWlsBillQPage : requestApi.shopAppUserAccQpage, loading, refreshing, }); }; componentWillUnmount() { PickerOld.hide(); } _createDateData = () => { const date = []; for (let i = fullYear - 10; i <= fullYear; i++) { const month = []; for (let j = 1; j < (i === fullYear ? fullMonth + 1 : 13); j++) { const day = []; const nowDays = 1; // 默认开始的天数为 1 号 const endDay = (i === fullYear) && (j === fullMonth) ? fullDay : 31; // 如果时间为当前 年 ,当前 月 ,则结束时间为当前 日 , 否则结束日为 31 天 if (j === 2) { for (let k = nowDays; k < 29; k++) { day.push(`${k }日`); } if (i % 4 === 0) { day.push(`${29 }日`); } } else if (j in { 1: 1, 3: 1, 5: 1, 7: 1, 8: 1, 10: 1, 12: 1, }) { for (let k = nowDays; k <= endDay; k++) { day.push(`${k}日`); } } else { for (let k = nowDays; k < endDay; k++) { day.push(`${k}日`); } } const _month = {}; _month[`${j}月`] = day; month.push(_month); } const _date = {}; _date[`${i}年`] = month; date.push(_date); } return date; } handleSelectData = (type) => { const { startTime, endTime } = this.state; const defaultDate = type === 'startTime' ? startTime : endTime; Picker._showDatePicker((date) => { let time = this.hanldeTimeRange(date, type); console.log('lll',date,time) if (type === 'startTime') { if (moment(endTime).isBefore(time)) { Toast.show('开始时间不能大于结束时间'); return; } } if (type === 'endTime') { if (moment(time).isBefore(startTime)) { Toast.show('结束时间不能小于开始时间'); return; } } this.changeState(type, time); }, this._createDateData, defaultDate ? moment(defaultDate)._d : moment()._d); } // 处理时间边界 hanldeTimeRange = (date, type) => { let dateArr = date.split('-') let selectYear = parseInt(dateArr[0]) let selectMon = parseInt(dateArr[1]) let selectDay = parseInt(dateArr[2]) let now_year = moment().year(); let now_mon = moment().month() + 1; let now_day = moment().get('date'); if(selectYear === now_year && selectMon === now_mon && selectDay === now_day){ return type === 'startTime'?`${selectYear}-${selectMon}-${selectDay} 00:00:00`: moment().format(DATETIME_FORMAT) } else { // 开始时间00:00:00 结束时间 23:59:59 return type === 'startTime' ? `${selectYear}-${selectMon}-${selectDay} 00:00:00` : `${selectYear}-${selectMon}-${selectDay} 23:59:59`; // 时间戳 } } getTitleAndParams = () => { const { billType, billStatus, startTime, endTime, currentTab, } = this.state; const currency = this.props.navigation.getParam('currency', ''); const param = { billStatus, billType, currency, }; startTime ? param.startTime = startTime : null; endTime ? param.endTime = endTime : null; switch (currency) { case 'xkq': return { title: '现金交易记录', param: { ...param, billStatus: currentTab == 0 ? 'normal' : '', }, }; case 'xkb': return { title: '晓可币消费记录', param, }; case 'xfq': return { title: '消费券使用记录', param, }; case 'swq': return { title: '实物券消费记录', param, }; case 'xkwl': return { title: billStatus == 'frozen' ? '晓可物流冻结记录' : '晓可物流交易金额记录', param, }; default: return { title: '未定义', param, }; } } renderItem = ({ item, index }) => { const currency = this.props.navigation.getParam('currency', ''); const borderTop = index === 0 ? styles.borderTop : {}; const borderBottom = index === this.state.recordList.length - 1 ? styles.borderBottom : {}; const borderTopRadius = index === 0 ? styles.borderTopRadius : {}; const borderBottomRadius = index === this.state.recordList.length - 1 ? styles.borderBottomRadius : {}; const isNotPrice = currency == 'xkb' || currency == 'xfq' || currency == 'swq'; return ( <TouchableOpacity style={[styles.ListItem, borderBottom, borderTop, styles.borderHor, borderTopRadius, borderBottomRadius]} key={index} disabled={currency == 'xkq' && this.state.currentTab == 0} onPress={() => { this.props.navigation.navigate('FinanceTradeRecordDetail', { data: item, id: item.id, currency }); }} > <View style={[CommonStyles.flex_end_noCenter]}> <Text style={{ fontSize: 14, color: '#222', flex: 1, lineHeight: 18, }} > {item.tradeName} </Text> { item.billType === 'fi' ? ( <Text style={{ fontSize: 20, color: '#EE6161', marginLeft: 20 }}> + {isNotPrice?'':'¥'} {item.amount } </Text> ) : ( <Text style={{ fontSize: 20, color: '#2491FF', marginLeft: 20 }}> - {isNotPrice?'':'¥'} {item.amount } </Text> ) } </View> <View style={[CommonStyles.flex_between]}> {/* <Text>{moment().format('YYYY-MM-DD HH:mm:ss')}</Text> */} <Text style={{ fontSize: 12, color: '#999' }}>{moment(item.createdAt * 1000).format('YYYY-MM-DD HH:mm:ss')}</Text> <Text style={{ fontSize: 12, color: '#999' }}> 流水号: {item.id} </Text> </View> </TouchableOpacity> ); } changeState(key, value) { this.setState({ [key]: value, }); } renderFlatlist=(tabLabel = '支出') => { const { currency, billType } = this.state; const longLists = this.props.longLists; const listName = `accountRecord${currency}${billType}`; const lists = longLists[listName] && longLists[listName].lists || []; return ( <FlatListView style={{ backgroundColor: CommonStyles.globalBgColor, marginTop: currency == 'xfq' || currency == 'swq' ? 60 : 0, marginBottom: 10, }} renderItem={this.renderItem} tabLabel={tabLabel} ItemSeparatorComponent={() => ( <View style={styles.flatListLine} /> )} store={{ ...(longLists[listName] || {}), page: longLists[listName] && longLists[listName].listsPage || 1, }} data={lists} numColumns={1} refreshData={() => this.getList(false, false) } loadMoreData={() => this.getList(false, true) } /> ); } render() { const { navigation } = this.props; const { currentTab, recordList, startTime, endTime, billStatus, } = this.state; const params = this.getTitleAndParams(); const currency = this.props.navigation.getParam('currency', ''); console.log(startTime) return ( <View style={styles.container}> <Header navigation={navigation} goBack title={params.title} /> { currency == 'xfq' || currency == 'swq' ? ( <View style={[styles.selectTimeWrap, CommonStyles.flex_between]}> <View style={[CommonStyles.flex_start]}> <TouchableOpacity style={styles.startTimeInput} onPress={() => { this.handleSelectData('startTime'); }} > <Text numberOfLines={1} style={{ textAlign: 'center', fontSize: 12 }}>{(startTime) ? startTime.split(' ')[0] : '开始时间'}</Text> </TouchableOpacity> <Text style={{ fontSize: 12, color: '#777', paddingHorizontal: 10 }}>至</Text> <TouchableOpacity style={styles.startTimeInput} onPress={() => { this.handleSelectData('endTime'); }} > <Text numberOfLines={1} style={{ fontSize: 12 }}>{(endTime) ? endTime.split(' ')[0] : '结束时间'}</Text> </TouchableOpacity> </View> <TouchableOpacity style={styles.searchBtn} onPress={() => { this.getList(false, false); }}><Text style={{ fontSize: 14, color: '#fff' }}>查询</Text></TouchableOpacity> </View> ) : null } { currency == 'xkwl' && billStatus == 'frozen' ? this.renderFlatlist() : ( <ScrollableTabView initialPage={0} onChangeTab={({ i }) => { const billType = (i === 0) ? 'fi' : 'fo'; Loading.show(); this.setState({ currentTab: i, billType }, () => { this.getList(false, false); }); }} renderTabBar={() => ( <ScrollableTabBar tabsContainerStyle={{ borderBottomColor: 'rgba(215,215,215,0.3)', borderBottomWidth: 1, width, }} underlineStyle={{ backgroundColor: '#4A90FA', height: 8, borderRadius: 10, marginBottom: -6, }} tabStyle={{ backgroundColor: '#fff', height: 43, }} activeTextColor="#4A90FA" inactiveTextColor="#555" tabBarTextStyle={{ fontSize: 14 }} style={{ backgroundColor: '#fff', height: 44, borderBottomWidth: 0, }} /> )} > {this.renderFlatlist('收入')} {this.renderFlatlist('支出')} </ScrollableTabView> ) } </View> ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, }, selectTimeWrap: { position: 'absolute', top: CommonStyles.headerPadding + 89, backgroundColor: '#fff', width, zIndex: 1, height: 60, padding: 15, borderBottomColor: 'rgba(215,215,215,0.3)', borderBottomWidth: 1, }, searchBtn: { paddingHorizontal: 17, paddingVertical: 5, backgroundColor: CommonStyles.globalHeaderColor, borderRadius: 50, }, startTimeInput: { borderRadius: 50, borderWidth: 1, borderColor: '#f1f1f1', // width: 120, maxWidth: 120, minWidth: 95, fontSize: 12, color: '#222', height: 30, justifyContent: 'center', alignItems: 'center', }, ListItem: { marginHorizontal: 10, padding: 15, backgroundColor: '#fff', }, flatListLine: { marginHorizontal: 10, height: 0.7, backgroundColor: '#f1f1f1', }, borderTop: { borderTopColor: 'rgba(215,215,215,0.5)', borderTopWidth: 1, }, borderBottom: { borderBottomColor: 'rgba(215,215,215,0.5)', borderBottomWidth: 1, }, borderHor: { borderLeftColor: 'rgba(215,215,215,0.5)', borderLeftWidth: 0.7, borderRightColor: 'rgba(215,215,215,0.5)', borderRightWidth: 0.7, }, borderTopRadius: { borderTopLeftRadius: 8, borderTopRightRadius: 8, }, borderBottomRadius: { borderBottomLeftRadius: 8, borderBottomRightRadius: 8, }, }); export default connect( state => ({ userShop: state.user.userShop || {}, longLists: state.shop.longLists || {}, serviceCatalogList: state.shop.serviceCatalogList || [], juniorShops: state.shop.juniorShops || [state.user.userShop || {}], }), dispatch => ({ fetchList: (params = {}) => dispatch({ type: 'shop/getList', payload: params }), shopSave: (params = {}) => dispatch({ type: 'shop/save', payload: params }), }), )(FinanceTradeRecordScreen);
import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; require('dotenv').config(); // const callbackURL = // process.env.NODE_ENV === 'development' // ? 'http://localhost:4000/auth/google/callback' // : `${process.env.AWS_PUBLIC_DNS}/auth/google/callback`; const callbackURL = 'http://ec2-54-180-95-94.ap-northeast-2.compute.amazonaws.com:4000/auth/google/callback'; module.exports = passport => { passport.serializeUser((user, done) => { console.log('serializeUser', Object.keys(user)); done(null, user.profile); }); passport.deserializeUser((user, done) => { console.log('deserializeUser', user.profile.displayName); done(null, user.profile); }); passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET_ID, callbackURL, proxy: true }, (accessToken, refreshToken, profile, done) => { console.log(profile); process.nextTick(() => { return done(null, { accessToken, refreshToken, profile }); }); } ) ); };
export function RandomStr(len = 8) { let charts = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split('') let s = '' for (let i = 0; i < len; i++) s += charts[(Math.random() * 0x3e) | 0]; return s; } export function FormatPrice(price, priceTick = 2) { if (typeof price === 'number') return price.toFixed(priceTick) else return price } export function FormatDatetime(datetime) { let dt = null if (typeof datetime === 'number') { if (datetime > 1000000000000 && datetime < 3000000000000) { // 说明dt是介于 2001 - 2065 年之间的毫秒数 dt = new Date(datetime) } else { dt = new Date(datetime / 1000000) } let YYYY = dt.getFullYear() + '' let MM = (dt.getMonth() + 1 + '').padStart(2, '0') let DD = (dt.getDate() + '').padStart(2, '0') let hh = (dt.getHours() + '').padStart(2, '0') let mm = (dt.getMinutes() + '').padStart(2, '0') let ss = (dt.getSeconds() + '').padStart(2, '0') let SSS = (dt.getMilliseconds() + '').padStart(3, '0') return YYYY + '/' + MM + '/' + DD + '-' + hh + ':' + mm + ':' + ss + '.' + SSS } else return dt } export function FormatDirection (value) { switch (value) { case 'BUY': return '买' case 'SELL': return '卖' default: return value } } export function FormatOffset (value) { switch (value) { case 'OPEN': return '开' case 'CLOSE': return '平昨' case 'CLOSETODAY': return '平今' default: return value } } export function FormatStatus (value) { switch (value) { case 'ALIVE': return '未完成' case 'FINISHED': return '已完成' default: return value } } export function ObjectToArray(obj, arr, key, fn) { // // // key [string | function] return string // fn [function] return bool if (typeof obj !== 'object' || !Array.isArray(arr)) return let recordedItems = [] for (let i=0; i < arr.length; i++) { let v = arr[i] let key_field_name = typeof key === 'string' ? key : key(v) let k = arr[i][key_field_name] if (obj.hasOwnProperty(k) && fn(v)) { arr[i] = obj[k] recordedItems.push(k) } else { arr.splice(i--, 1); } } for (let k in obj) { if (!recordedItems.includes(k)) { let v = obj[k] if (fn(v)) { arr.push(v) } } } }
/** * Created by cly on 16/12/27. */ import React,{Component, StyleSheet} from "react"; import {Text, View} from "react-native"; export default class Study extends Component{ render(){ return(<View> <Text>用户中心</Text> </View>) } }
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; const quotaRouter = router.namespace('/quotas'); quotaRouter.post('/list', controller.quota.list); quotaRouter.post('/:id', controller.quota.update); };
var model = "Submission";
$(document).ready(function(){ $('.hamburger-shell').click(function(){ $('#menu').slideToggle(300); $('.top').toggleClass('rotate'); $('.middle').toggleClass('rotate-back'); $('.menu-name').toggleClass('bump'); $('.bg-cover').toggleClass('reveal'); }); $('.bg-cover').click(function(){ $('#menu').slideToggle(300); $('.top').toggleClass('rotate'); $('.middle').toggleClass('rotate-back'); $('.menu-name').toggleClass('bump'); $('.bg-cover').toggleClass('reveal'); }); $("#project_pic1").on({ mouseenter: function() { $("#project_pic1").attr("src", "../images/gif/simon_game.gif"); //on hover replace pic.png to pic.gif(animation }, mouseleave: function() { $("#project_pic1").attr("src", "../images/screenshots/simon_game.png"); //change pic.gif to pic.png } }); $("#project_pic2").on({ mouseenter: function() { $("#project_pic2").attr("src", "../images/gif/travel_dairy.gif"); //on hover replace pic.png to pic.gif(animation }, mouseleave: function() { $("#project_pic2").attr("src", "../images/screenshots/travel_dairy.png"); //change pic.gif to pic.png } }); $("#project_pic3").on({ mouseenter: function() { $("#project_pic3").attr("src", "../images/gif/weatro.gif"); //on hover replace pic.png to pic.gif(animation }, mouseleave: function() { $("#project_pic3").attr("src", "../images/screenshots/weatro.png"); //change pic.gif to pic.png } }); $("#project_pic4").on({ mouseenter: function() { $("#project_pic4").attr("src", "../images/gif/tick_tac_toe.gif"); //on hover replace pic.png to pic.gif(animation }, mouseleave: function() { $("#project_pic4").attr("src", "../images/screenshots/tick_tac_toe.png"); //change pic.gif to pic.png } }); }); $(function() { var documentEl = $(document), fadeElem = $(".fade-scroll"); documentEl.on("scroll", function() { var currScrollPos = documentEl.scrollTop(); fadeElem.each(function() { var $this = $(this), elemOffsetTop = $this.offset().top; if (currScrollPos > elemOffsetTop) $this.css("opacity", 1 -(currScrollPos-elemOffsetTop)/100); }); }); }); $(document).ready(function() { //window and animation items var animation_elements = $.find('.animation_slide'); var web_window = $(window); //check to see if any animation containers are currently in view function check_if_in_view() { //get current window information var window_height = web_window.height(); var window_top_position = web_window.scrollTop(); var window_bottom_position = (window_top_position + window_height); //iterate through elements to see if its in view $.each(animation_elements, function() { //get the element sinformation var element = $(this); var element_height = $(element).outerHeight(); var element_top_position = $(element).offset().top; var element_bottom_position = (element_top_position + element_height); //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport) if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) { element.addClass('in-view'); } else { element.removeClass('in-view'); } }); } //on or scroll, detect elements in view $(window).on('scroll resize', function() { check_if_in_view() }) //trigger our scroll event on initial load $(window).trigger('scroll'); });
"use strict"; function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var SettingsScene = /*#__PURE__*/ function (_Scene) { _inherits(SettingsScene, _Scene); function SettingsScene(canvas, game) { var _this; _classCallCheck(this, SettingsScene); _this = _possibleConstructorReturn(this, _getPrototypeOf(SettingsScene).call(this, canvas, game)); _this.menuButtons = []; var buttonWidth = canvas.width / 4, buttonHeight = buttonWidth / 4; _this.inputRanges = []; _this.startLoop(); _this.playerImageLeft = this.initPicture("player_left.png"); _this.playerImageRight = this.initPicture("player_right.png"); var bestResult = Android.getBestResult().split(":"); _this.inputRanges.push(new InputRange(canvas, "colorRange", (canvas.width - buttonWidth) / 2 - buttonWidth, (canvas.height - buttonHeight) / 2 - buttonHeight * 1.5, buttonWidth, buttonHeight, this, (bestResult.length >= 3))); _this.inputRanges.push(new InputRange(canvas, "fpsRange", (canvas.width - buttonWidth) / 2 + buttonWidth, (canvas.height - buttonHeight) / 2 - buttonHeight * 1.5 + buttonHeight / 4, buttonWidth, buttonHeight / 2, this, true)); _this.menuButtons.push(new MenuButton(canvas, "playButton", (canvas.width - buttonWidth) / 2, (canvas.height - buttonHeight) / 2 + buttonHeight * 2, buttonWidth, buttonHeight, "PLAY", this, true)); _this.menuButtons.push(new MenuButton(canvas, "playExclusiveButton", (canvas.width - buttonWidth) / 2 - buttonWidth, (canvas.height - buttonHeight) / 2, buttonWidth, buttonHeight, "Exclusive color", this, (bestResult.length >= 3 && bestResult[0] >= 2))); _this.player = _this.player = new Player(_this.canvas, _this.playerImageLeft, _this.playerImageRight); _this.faster = false; inputState.THROTTLE = true; _this.bool = true; return _this; } _createClass(SettingsScene, [{ key: "onBackPressed", value: function onBackPressed() { this.endLoop(); game.setScene(MenuScene); } }, { key: "render", value: function render() { _get(_getPrototypeOf(SettingsScene.prototype), "render", this).call(this); if (inputState.THROTTLE === false) inputState.THROTTLE = true; this.player.render(); this.player.pushStream(); for (var i = 0; i < this.player.stream.length; i++) { if (!this.player.stream[i].isDone()) this.player.stream[i].update(); else this.player.stream.splice(i, 1); } this.player.renderStream(); for (var i = 0; i < this.menuButtons.length; i++) { this.menuButtons[i].render(); } for (var i = 0; i < this.inputRanges.length; i++) { this.inputRanges[i].render(); } } }]); return SettingsScene; }(Scene);
var inhaleAudio = new Audio('../audio/inhale.mp3'); var exhaleAudio = new Audio('../audio/exhale.mp3'); var holdAudio = new Audio('../audio/hold.mp3'); var audio = new Audio('../audio/ding.mp3'); var breathTime = []; //seconds of each breath stage var timeInSecs; //time left in stage var position; //position of breathTime array var breathText; //text display on overlay var ticker; function SetVolume(val){ audio.volume = val / 100; } function showBreath(){ document.getElementById("breath-display").style.backgroundColor = "rgba(121,134,203, 0.9)"; breathText = "Bridge"; document.getElementById("breath-text").innerHTML = breathText; document.getElementById("breath-display").style.width = "100%"; } function hideDisplay(){ document.getElementById("breath-display").style.width = "0%"; clearInterval(ticker); } function clickThis(){ breathTime[0] = parseInt(document.getElementById("inhale").value); breathTime[1] = parseInt(document.getElementById("inHold").value); breathTime[2] = parseInt(document.getElementById("exhale").value); breathTime[3] = parseInt(document.getElementById("outHold").value); position = 0; timeInSecs = breathTime[0]; startTimer(breathTime[0]); } function startTimer(secs){ audio.play(); timeInSecs = parseInt(secs); ticker = setInterval("tick()", 1000); } function tick(){ var secs; if (position == 0){ secs = timeInSecs; breathText = "inhale"; if (secs > 0){ timeInSecs--; } else{ clearInterval(ticker); position++; if (breathTime[1] == 0){ position++; startTimer(position[2]); timeInSecs = breathTime[2]; } else{ startTimer(position[1]); timeInSecs = breathTime[1]; } } } else if (position == 1){ secs = timeInSecs; breathText = "hold"; if (secs > 0){ timeInSecs--; } else{ clearInterval(ticker); startTimer(position[2]); timeInSecs = breathTime[2]; position++; } } else if (position == 2){ secs = timeInSecs; breathText = "exhale"; if (secs > 0){ timeInSecs--; } else{ clearInterval(ticker); position++; if (breathTime[3] == 0){ position = 0; startTimer(position[0]); timeInSecs = breathTime[0]; } else{ startTimer(position[3]); timeInSecs = breathTime[3]; } } } else if (position == 3){ secs = timeInSecs; breathText = "hold"; if (secs > 0){ timeInSecs--; } else{ clearInterval(ticker); startTimer(position[0]); timeInSecs = breathTime[0]; position = 0; } } document.getElementById("breath-text").innerHTML = breathText; }
/** * Init state */ import {state_init} from './init_state.js'; /** * Ball states */ import {state_slide_ball} from './state_slide_ball.js'; import {state_ball_flying} from './state_ball_flying.js'; /** * Gun shot states */ import {state_take_gun} from './state_take_gun.js'; import {state_gun_shot_init} from './state_gun_shot_init.js'; import {state_gun_shot_0} from './state_gun_shot_0.js'; import {state_gun_shot_1} from './state_gun_shot_1.js'; import {state_gun_shot_2} from './state_gun_shot_2.js'; import {state_gun_shot_last} from './state_gun_shot_last.js'; import {state_gun_shot_firework} from './state_gun_shot_firework.js'; /** * Firework */ import {state_firework} from './state_firework.js'; /** * Change environment */ import {state_change_env_0} from './state_change_env_0.js'; import {state_change_env_1} from './state_change_env_1.js'; import {state_change_env_2} from './state_change_env_2.js'; import {state_change_env_3} from './state_change_env_3.js'; import {state_change_env_4} from './state_change_env_4.js'; import {state_final} from './state_final.js'; export default [ state_init, state_slide_ball, state_ball_flying, state_take_gun, state_gun_shot_init, state_gun_shot_0, state_gun_shot_1, state_gun_shot_2, state_gun_shot_last, state_gun_shot_firework, state_firework, state_change_env_0, state_change_env_1, state_change_env_2, state_change_env_3, state_change_env_4, state_final, ];
#!/usr/bin/env node require('dotenv').config() var express = require('express'), axios = require('axios'), chalk = require('chalk'), pck = require('./package.json'), options = require('minimist')(process.argv.slice(2)), app = express(), api = 'https://api.github.com/graphql', port = process.env.PORT || options.port || options.p || 3000, number = process.env.MAXNUM || options.number || options.n || 50, token = process.env.TOKEN || options.token || options.t; if(options.v || options.version){ console.log( `${pck.version}`) process.exit(1); } else if (options.h || options.help) { // checking undifined args console.log(` Usage: ${pck.name} -p <Port Number> -t <Token> -l -t , --token for setting tokn -p , --port setting port number -v , --version for showing cli version -i , --issue for reporting web page (any issue or bugs) `); process.exit(0) } else if (options.i || options.issue) { // checking undifined args console.log(` Issues at ${pck.bugs.url} `); process.exit(0) } else{ app.listen(port, () => logger(`Server running at ${port}`)) } // setting axios header auth if (token) {// add express limit axios.defaults.headers.common['Authorization'] = `bearer ${token}`; logger(`Got Token ${token}`) } app.get('/github', (req,res) => { res.redirect(pck.homepage) }) app.get('/user/:name',(req, res) => { logger.req(`Name : ${req.params.name}`,req) axios.post(api, {query: ` query ($cursor: String) { user(login: "${req.params.name}") { repositories( last: ${number}, isFork: false, isLocked: false, ownerAffiliations: OWNER, privacy: PUBLIC, orderBy: { field: CREATED_AT, direction: ASC } before: $cursor ) { edges { node { name description url primaryLanguage { name color } forks { totalCount } } } } } } `,variables: { login: req.params.name },}) .then((response) => { res.json(response.data) }).catch((error) => { res.send(error) logger.err(error)})}) // logger function logger(message){ console.log(chalk.bgYellow.red(`(LOG):${Date()}:${message}`)) } logger.req = (message,req) => { console.log(chalk.bgYellow.blue(`(REQUEST):${Date()}:Ip : ${req.ip} : ${message}`)) } logger.err = (message) => { console.error(chalk.bgRed.green(`(ERROR):${Date()} : ${message}`)) }
import {mapValues} from 'lodash' import {handleActions} from 'redux-actions' // local libs import {assertPropTypes} from 'src/App/helpers/propTypes/check' // helps to validate store branch with prop types export default (model, mapping, initialState) => { if (process.env.NODE_ENV === 'production') { if (model !== null) console.warn( '`model` is not `null` in production mode, ' + 'try to avoid constructing prop types in production at all, ' + "add `process.env.NODE_ENV === 'production' ? null : {...}` condition " + '(keep this bare condition simple so bundler could easily detect ' + 'and remove this code from production bundle at all).', `Stack trace: ${new Error().stack}` ) return handleActions(mapping, initialState) } else { assertPropTypes(model, initialState) return handleActions(mapValues(mapping, f => (state, action) => { const nextState = f(state, action) assertPropTypes(model, nextState) return nextState }), initialState) } }
'use strict'; import React from 'react'; import classNames from 'classnames'; var If = React.createClass({ render: function() { if (this.props.condition) { return this.props.children; } else { return false; } } }); export default function (props, state) { var list = []; this.state.items.map((item, i) => { var styleCont = { backgroundImage: 'url(src/images/'+item.image+')' } list.push( <li key={i} onClick={this.handleClick.bind(this, item, 'web')}> <div className="cont" style={styleCont}> <if condition={item.caption}> <div className='caption right'> <p>{item.caption}</p> <span></span> </div> </if> <h3 className="title">{item.title}</h3> <p className="subtitle">{item.subtitle}</p> </div> </li> ) }); return ( <div className='home-list'> <ul> {list} </ul> </div> ); }
import fs from 'fs'; let env = {}; let envFile = `${__dirname}/../../src/config/env.json`; if (fs.existsSync(envFile)) { env = fs.readFileSync(envFile, 'utf-8'); env = JSON.parse(env); Object.keys(env).forEach(key => { process.env[key] = env[key]; }); } export default { client_email: process.env.client_email, private_key: process.env.private_key.replace(/_/g, ' '), docID: process.env.doc_id };
import Link from 'next/link' import {listDataFiles} from '../utils/fsUtils' function Home({links}) { return <div> <h1>Github Trending Daily. There are {links.length} files.</h1> <ul> {links.map((file) => ( <li key={file}> <Link href={`/trending/${encodeURIComponent(file)}`}> <a>{file}</a> </Link> (<Link href={`/${encodeURIComponent(file)}.json`}><a>raw</a></Link>) </li> ))} </ul> </div> } export async function getStaticProps() { // Call an external API endpoint to get posts. // You can use any data fetching library const links = (await listDataFiles()).map(f => f.split('.')[0]).sort((f1, f2) => f1.localeCompare(f2) * -1) // By returning { props: posts }, the Blog component // will receive `posts` as a prop at build time return { props: { links, }, } } export default Home
function buildButton(title) { return `<button>${title}</button>`; } $(document).ready(function(){ var currentColour = $("h1").css("color") ; var fontSize = $("h1").css("font-size") // $("h1").css("font-size","5rem") ; // $("h1").classes() ; // prepend/append/before/after $("h1").before(buildButton("before")) $("h1").prepend(buildButton("prepend")) $("h1").append(buildButton("append")) $("h1").after(buildButton("after")) console.log(currentColour) ; $("img").attr("src","images/dice" + (Math.floor(Math.random() * 6 + 1)) + ".png") ; $("a").attr("href","http://yahoo.co.uk") $("a").on("mouseenter",{data:"Hello World"},function(ev) { console.log(ev) }) ; $(document).on("mouseover",{data:"Hello World"},function(ev) { console.log(ev) $(ev.target).css("color","red"); }) ; /* $("h1").css("color","red") ; $("h1").css("color",currentColour) ; */ $("h1").hasClass("big-title") ; $("h1").addClass("big-title") ; $(".buttons button").text("CLICK ME") ; setTimeout(function () { $(".buttons button").remove() ; }, 4000); $(".single-button button").hide() ; $(".single-button button").html("<em>SINGLE BUTTON</em>") ; // Passing parameter to click Event handler. $("button").click( {myparam:"hello world!"}, function(ev){ console.log(ev,ev.data.myparam); //$("img").fadeToggle() ; // FadeUp FadeDown $("img").slideToggle(3000) ; // slideUp, SlideDown }) ; // var classLst = $("button").class() ; // console.log(classLst) ; $(document).keypress(function(evt){ console.log(evt); $("h1").html(evt.key); }) ; }) ;
{ const arr = [0,1,2,3,4]; const l = arr.push(4,5,6) console.log(arr) console.log(l) }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsCommit = { name: 'commit', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M22 11h-6.141a3.981 3.981 0 00-7.718 0H2v2h6.141a3.981 3.981 0 007.718 0H22z"/></svg>` };
module.exports = { USAGE: "USAGE: node bin/miojo <tempo de cozimento> <ampuleta> <ampuleta> - Todos valores devem ser número Inteiro", AMP_TIME_CANNOT_BE_LESS_THEN_COOKING_TIME: 'Oops! Tempo das ampuletas não pode ser menor que o tempo de cozimento.', CANNOT_COOK_WITH_THESE_TIMES: 'Oops! Não é possivel obter o tempo de cozimento exato com as ampulhetas informadas.', MAX_ATTEMPTS_REACHED: 'Game Over! Não foi possivel resolver com o número maximo de tentativas configurado.' }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var partsPerRepairSchema = mongoose.Schema({ quantity: Number, part: String }, {_id : true }); var RepairSchema = new Schema({ firstName: {type: String, minlength: 2}, lastName: {type: String, minlength: 2}, fullName: {type: String, minlength: 2}, date: {type: Date }, company: {type: String, minlength: 2}, address: {type: String, minlength: 2}, phoneCell: {type: String, minlength: 10}, email: {type: String, minlength: 2}, description: {type: String, minlength: 2}, comments: {type: String, minlength: 2}, avatarInitial: {type: String }, numWorkers: {type: Number }, numHours: {type: Number }, partsPerRepair: [partsPerRepairSchema] }, {timestamps: true}); mongoose.model('Repair', RepairSchema);
'use strict' const test = require('tape') const pw = require('../') test('compatibility with v1 (store format, not package)', t => { const pbkdf2 = '{"hashMethod":"pbkdf2","salt":"l2YExDSLfIEwKGNyl8nwFeqA1x5LlpCRmr4xQndlXpW4uwW6KTIrwVD6xyHELVDVAn2VErTiXC3JXaQSavEInw9f","hash":"Tfobv+rvC7daPs3eaPpfm2FqMu48VP6jkzIrE9TUJp8zY5nRhpBoDHlpOOgOt0SJXbN6pF5/I1K8LXKUIGJUrZXM","keyLength":66,"iterations":655217}' t.plan(1) pw.verify(pbkdf2, 'foo').then(isValid => t.ok(isValid)) }) test('compatibility with v2 (store format, not package)', t => { const pbkdf2 = '{"hashMethod":"pbkdf2-sha512","salt":"cdTGLYOz7lMtQfy7rFeazUfKRm7qWvfgnIzMeBWCKPm5QLEWr2MYWQ68NPbq/Y9TVFOBh0XMDSkmL1HGxyhNlQ==","hash":"cC3eniGMFhSZAJMxMINxPYwCDrnXusrEd4+qhpRd5DNPZexepAqHgiwsR1TvB7EHUq1BuE8fsOUyhVvCX9tyvA==","keyLength":64,"iterations":655226}' t.plan(1) pw.verify(pbkdf2, 'foo').then(isValid => t.ok(isValid)) })
var fs = require('fs'); var number = ['一', '二', '三', '四']; function writeNum(fd){ if(number.length){ var num = number.pop() + ' '; fs.write(fd, num , null , null , function(err, bytes){ if(err){ console.log('Failed'); }else{ console.log('Wrote: %s %d bytes', num, bytes); writeNum(fd); } }); }else{ fs.close(fd); } } fs.open('number.txt', 'w', function(err, fd){ writeNum(fd); });
import { Sequelize } from 'sequelize' import dotenv from 'dotenv' /* Config Vars */ dotenv.config() const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USERNAME, process.env.DB_PASSWORD, { host: process.env.DB_HOST, dialect: 'mysql' }) export default sequelize
import React, { Component } from "react"; import s from "./index.module.css"; import GameInterface from "../../components/GameInterface/GameInterface"; import LeaderBoard from "../../components/LeaderBoard"; import { connect } from "react-redux"; import { thunkCreaterGetModes, thunkCreaterPostWinner } from "../../reduxStore/actionCreater"; import uid from "uid"; import Spinner from "../../components/UI/Spinner"; class GamePage extends Component { state = { inputName: "", selectValue: "", winner: "", startGame: false, gameOver: false, randomArr: null, propertiesItemArr: [], resetGame: false, leader: [], }; i = 0; timer; timerStartSelected; createItemPropertiesArr = () => { const { selectValue } = this.state; const fieldSizeList = +selectValue; const arrProperties = fieldSizeList ? Array(Math.pow(fieldSizeList, 2)) .fill() .map(() => ({ id: uid(), isSelected: false, isCurrentUserSelected: false, isComputerSelected: false })) : []; this.setState({ propertiesItemArr: arrProperties }); }; componentDidMount = () => { const { thunkCreaterGetModes } = this.props; thunkCreaterGetModes(); this.createItemPropertiesArr(); }; componentDidUpdate = (_, prevState) => { if (prevState.selectValue !== this.state.selectValue) { this.createItemPropertiesArr(); } else if (prevState.gameOver !== this.state.gameOver) { this.setState({ resetGame: true }); } }; handleChangeInputName = e => this.setState({ inputName: e.target.value }); handleChangeSelect = e => this.setState({ selectValue: e.target.value }); onHandlePlay = () => { const { resetGame, gameOver, selectValue } = this.state; if (resetGame) { this.i = 0; this.setState( { inputName: "", selectValue: "", gameOver: false, randomArr: null, propertiesItemArr: [], resetGame: false, startGame: false, }) } if (!gameOver) { this.setState({startGame: true}) const delay = this.getDelay(selectValue); const len = Math.pow(+selectValue, 2); this.getRandomArr(len); setTimeout(this.selectedCell, delay); } }; isCurrentUserSelectedChecker = item => item.isCurrentUserSelected; isComputerSelectedChecker = item => item.isComputerSelected; isSelectedChecker = item => item.isSelected; createLeaderList = () => { const { winner } = this.state; const obj = { name: winner, date: JSON.stringify(new Date().toLocaleString()), } const leaderTemp = [obj]; this.setState((prevProps) => { return{ leader: [...leaderTemp, ...prevProps.leader], } }) } getDelay = (selectValue) => { const { gameMode } = this.props; const modeValue = +selectValue; return modeValue === 5 ? gameMode.easyMode.delay : modeValue === 10 ? gameMode.normalMode.delay : modeValue === 15 ? gameMode.hardMode.delay : null; } getRandomArr = arrLength => { const { randomArr } = this.state; const array = Array(arrLength) .fill() .map((_, i) => i); if (!randomArr) { this.setState({ randomArr: array.sort(() => Math.random() - 0.5), }); } }; stopGame = () => { const { propertiesItemArr, inputName } = this.state; const winUser = propertiesItemArr.filter(el => el.isCurrentUserSelected); const winComputer = propertiesItemArr.filter(el => el.isComputerSelected); let winner = null; let gameOver = false; if (winUser.length > Math.floor(propertiesItemArr.length / 2)) { winner = inputName; gameOver = true; } else if (winComputer.length > Math.floor(propertiesItemArr.length / 2)){ winner = "computer"; gameOver = true } gameOver && this.setState({ gameOver: gameOver, winner: winner, startGame: false, }); }; selectedCell = () => { const { propertiesItemArr, randomArr, selectValue, gameOver } = this.state; this.stopGame(); if (!gameOver) { const delay = this.getDelay(selectValue); const cloneArr = [...propertiesItemArr]; const ind = this.i++; cloneArr[randomArr[ind]].isSelected = true; this.setState({ propertiesItemArr: cloneArr }); this.timer = setTimeout(this.selectedComputer, delay); } }; selectedUser = e => { const { propertiesItemArr, selectValue, gameOver } = this.state; this.stopGame(); if (!gameOver) { const delay = this.getDelay(selectValue); const selectedItemID = e.currentTarget.dataset.id; const cloneArr = [...propertiesItemArr]; const selectedIndex = cloneArr.findIndex( e => e.isSelected && !e.isCurrentUserSelected && !e.isComputerSelected ); if(selectedIndex === +selectedItemID){ clearTimeout(this.timer); cloneArr[selectedItemID].isCurrentUserSelected = true; this.setState({ propertiesItemArr: cloneArr }); setTimeout(this.selectedCell, delay); } } }; selectedComputer = () => { const { propertiesItemArr, selectValue, gameOver, inputName, winner } = this.state; const { thunkCreaterPostWinner } = this.props; this.stopGame(); if (gameOver) { this.createLeaderList(); winner === inputName ? thunkCreaterPostWinner(JSON.stringify({winner: inputName, data: new Date()})) : thunkCreaterPostWinner(JSON.stringify({winner: "computer", data: new Date()})); } const delay = this.getDelay(selectValue); const cloneArr = [...propertiesItemArr]; const selectedIndex = cloneArr.findIndex( e => e.isSelected && !e.isCurrentUserSelected && !e.isComputerSelected ); cloneArr[selectedIndex].isComputerSelected = true; this.setState({ propertiesItemArr: cloneArr }); setTimeout(this.selectedCell, delay); }; render() { const { inputName, selectValue, startGame, propertiesItemArr, gameOver, leader, } = this.state; const { loading, gameMode } = this.props; if (loading) { return <div className={s.spinner}> <Spinner /> </div> } const winUser = propertiesItemArr.filter(el => el.isCurrentUserSelected); const winComputer = propertiesItemArr.filter(el => el.isComputerSelected); const winnerMassage = winUser.length > Math.floor(propertiesItemArr.length / 2) ? `${inputName} Win` : winComputer.length > Math.floor(propertiesItemArr.length / 2) ? `Computer Win` : (propertiesItemArr.length === 0 || inputName.length === 0) ? `Inputs should be full` : `Game` const buttonValue = gameOver ? "PLAY AGAIN" : "PLAY"; return ( <div className={s.gamePagePosition}> <div className={s.gamePage}> <div className={s.gameInterface}> <GameInterface inputName={inputName} propertiesList={propertiesItemArr} selectValue={selectValue} gameMode={gameMode} handleChangeSelect={this.handleChangeSelect} handleChangeInputName={this.handleChangeInputName} onHandlePlay={this.onHandlePlay} startGame={startGame} isUserSelected={this.isCurrentUserSelectedChecker} isSelected={this.isSelectedChecker} isComputerSelected={this.isComputerSelectedChecker} selectedUser={this.selectedUser} winnerMassage={winnerMassage} buttonValue={buttonValue} /> </div> <div className={s.leaderBoard}> <LeaderBoard list={leader} /> </div> </div> </div> ); } } const mapStateToProps = ({ loading, gameMode }) => { return { loading, gameMode }; }; const mapDispatchToProps = { thunkCreaterGetModes, thunkCreaterPostWinner }; export default connect( mapStateToProps, mapDispatchToProps )(GamePage);
import { DashboardsWrapper } from "../styleW/dashboardswrapper"; import { AiOutlineArrowDown, AiOutlineArrowUp, AiOutlineDollarCircle, } from "react-icons/ai"; import { RiContactsLine } from "react-icons/ri"; import { VscComment } from "react-icons/vsc"; import React from "react"; import { Table, TableBody, TableHead, TableRow, TableCell, } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import { Home } from './../styleW/homeW' import { Doughnut } from 'react-chartjs-2'; const useStyles = makeStyles({ table: { minWidth: 650, }, }); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } const rows = [ createData( "img", "Eren Jaegar ", "Spicy seasoned seafood noodles ", "$125", "Completed" ), createData( "img", "Eren Jaegar ", "Spicy seasoned seafood noodles ", "$125", "Completed" ), createData( "img", "Eren Jaegar ", "Spicy seasoned seafood noodles ", "$125", "Completed" ), createData( "img", "Eren Jaegar ", "Spicy seasoned seafood noodles ", "$125", "Completed" ), createData( "img", "Eren Jaegar ", "Spicy seasoned seafood noodles ", "$125", "Completed" ), ]; const data = [ { icon: <AiOutlineDollarCircle />, pratcent: "+32.40", iconToo: <AiOutlineArrowUp />, price: "$10,243.00", title: "Total Revenue", color: "#50D1AA", colorToo: "#9288E0", }, { icon: <VscComment />, pratcent: "+32.40", iconToo: <AiOutlineArrowUp />, price: "$10,243.00", title: "Total Revenue", color: "#FF7CA3", colorToo: "#FFB572", }, { icon: <VscComment />, pratcent: "+32.40", iconToo: <AiOutlineArrowUp />, price: "$10,243.00", title: "Total Revenue", color: "#50D1AA", colorToo: "#65B0F6", } ] const Dashboards = () => { const classes = useStyles(); return ( <Home> <div className="container"> <div className="row"> <div className="col-lg-8 mt-3"> <div className="row"> { data.map((v) => { return ( <> <div className="col-md-4"> <div className="summery-card"> <div className="card-header"> <div className="head1 d-flex align-items-center justify-content-around"> <div className="strelka" style={{ color: v.colorToo }}> {v.icon} </div> <h6 className="text-center" style={{ color: v.color }}>{v.pratcent}</h6> <div style={{ color: v.color }}> {v.iconToo} </div> </div> </div> <div className="card-body"> <h3>{v.price}</h3> <p className="titleColor">{v.title}</p> </div> </div> </div> </> ) }) } {/* <div className="card-header"> <div className="head1 d-flex align-item-center justify-content-around"> <AiOutlineDollarCircle /> <h6 className="text-center">+32.40</h6> <AiOutlineArrowUp /> </div> </div> <div className="card-body"> <h3>$10,243.00</h3> <p>Total Revinue</p> </div> */} </div> <div className="row mt-4"> <div className="col-12"> <div className="card TableBody"> <div className="card-header"> <div className="d-flex justify-content-between"> <h6>Order Report</h6> <button className="btn text-light">Order filter</button> </div> </div> <div className="l"> <Table className='TableBody'> <TableHead> <TableRow className=""> <TableCell className="text-white">Customer</TableCell> <TableCell className="text-white">Menu</TableCell> <TableCell className="text-white"> Total Payment </TableCell> <TableCell className="text-white">Status</TableCell> </TableRow> </TableHead> <TableBody className='TableBody'> {rows.map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row" className="text-white" > {/* {row.name} */} <img src="/child.jpg" alt="" className="client" /> {row.calories} </TableCell> <TableCell className="text-white"> {row.fat} </TableCell> <TableCell className="text-white"> {row.carbs} </TableCell> <TableCell className="butt text-white"> <button className="btn btnDark"> {row.protein} </button> </TableCell> </TableRow> ))} </TableBody> </Table> </div> </div> </div> </div> </div> <div className="col-lg-4 mt-3"> <div className="row"> <div className="TableBody"> <div className="card-header">right</div> <div className="card-body"> <ul> <li className="d-flex"> <img src="/lagmon.jpg" alt="" className="client" /> <div> <h6>Spicy seasoned seafood noodles</h6> <p>200 dishes ordered</p> </div> </li> <li className="d-flex"> <img src="/lagmon2.jpg" alt="" className="client" /> <div> <h6>Spicy seasoned seafood noodles</h6> <p>200 dishes ordered</p> </div> </li> <li className="d-flex"> <img src="/pilvin.jpg" alt="" className="client" /> <div> <h6>Spicy seasoned seafood noodles</h6> <p>200 dishes ordered</p> </div> </li> </ul> <button className="w-100 btn btnDark">View All</button> </div> </div> </div> <div className="row mt-3"> <div className="TableBody"> <div className="card-header d-flex justify-content-between"> <h5>Most Type Of Order</h5> <h6>Today</h6> </div> <div className="card-body"> <div className="row"> <div className="col-lg-12"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio nam ea vel id maiores corporis consectetur modi inventore odio, repudiandae quisquam placeat aliquam blanditiis alias, nisi natus laborum! Quia, labore.</p> </div> </div> <button className="w-100 btn btnDark">View All</button> </div> </div> </div> </div> </div> </div> </Home> ); }; export default Dashboards;
import App from "../components/App"; import Paper from "react-md/lib/Papers/Paper"; export default () => ( <App> <Paper className={"content"}> <p>About</p> </Paper> </App> );
import { useState } from 'react'; const useFormState = defaultValue => { const [value, setValue] = useState(defaultValue); const handleChange = e => setValue(e.target.value); return [value, handleChange]; }; export default useFormState;
'use strict'; const Service = require('egg').Service; const crypto = require('crypto'); class AuthService extends Service { async login({ username, password }) { const result = crypto.createHash('md5').update('12345').digest('hex'); if (!(username === 'admin' && result === password)) { return { success: false, msg: '用户名或密码不正确', }; } return { success: true, }; } } module.exports = AuthService;
import React from 'react'; const SellerActiveProduct = () => { return <div>Seller Active Product</div>; }; export default SellerActiveProduct;
const express = require('express') const bodyParser = require('body-parser') const { proxyCacheMiddleware, InMemoryCache } = require('apollo-proxy-cache') const backendServer = "http://m2.betelgeuse.yr"; const queryCache = new InMemoryCache() const proxyMiddlewareFactory = proxyCacheMiddleware(queryCache); const app = express(); app.use(bodyParser.json()); proxyMiddlewareFactory( app, '/graphql', { target: backendServer, changeOrigin: true } ) app.listen(4000, () => { console.log('Go to http://localhost:4000/graphql to run queries!'); });
import React from 'react'; import classes from './EmailErrors.css'; const emailErrors = ({errorsEmail}) => <div className='errors'> {Object.keys(errorsEmail).map((fieldName, i) => { let emailMessageClass; if (fieldName === 'email') { emailMessageClass = 'emailMessage' } else { emailMessageClass = 'passwordMessage' }; if(errorsEmail[fieldName].length > 0){ return ( <div className={classes.EmailErrors}> <div className={emailMessageClass}> <strong><p key={i}>{errorsEmail[fieldName]}</p></strong> </div> </div> ) } else { return ''; } })} </div> export default emailErrors;
function timeConvertToMinutes(time) { const [hr, min] = time.split(":"); const hrToMin = Number(hr) * 60; const totalMin = hrToMin + Number(min); return totalMin; } function calHourPass(inTime, outTime, lunchTime = 0.5) { let totalTime = outTime - inTime; let todayHour = totalTime / 60 - lunchTime; return Number(todayHour.toFixed(1)); } function calculateDailyHours(dailyClockIn, dailyClockOut) { const arriveTimeMins = timeConvertToMinutes(dailyClockIn); const leaveTimeMins = timeConvertToMinutes(dailyClockOut); return calHourPass(arriveTimeMins, leaveTimeMins); } export { calculateDailyHours };
import { ProxyState } from "../AppState.js" export default class Score { constructor() { this.score = ProxyState.score } get ScoreBoard() { return /*html*/ ` <div className="col-2 card"> <h2>Score: ${this.score}</h2> </div> ` } }
export default function Canvas() { const canvas = wx.createCanvas() canvas.type = 'canvas' canvas.addEventListener = function (type, callback) { const key = type const _callback = function (res) { callback && callback({ touches: res.touches, targetTouches: res.changedTouches, timeStamp: res.timeStamp }) } switch (key) { case 'touchstart': wx.onTouchStart(_callback) break case 'touchmove': wx.onTouchMove(_callback) break case 'touchend': wx.onTouchEnd(_callback) break case 'touchcancel': wx.onTouchEnd(_callback) break default: break } } return canvas }
import React, { Component, PropTypes } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, TextInput, Dimensions, Alert, AsyncStorage } from 'react-native'; export default class WriteComment extends Component { static propTypes = { postId: PropTypes.string.isRequired } constructor(props) { super(props); this.state = { postId: this.props.postId, commentText: '', height: 0 } } componentWillMount() { AsyncStorage.getItem('User', (err, user) => { user = JSON.parse(user); firebase.database().ref(`Users/${user.uid}`).on('value', function(snapshot) { let data = snapshot.val(); this.setState({ posts: data.posts, uid: user.uid, currentRankRep: data.currentRankRep, rep: data.reputation }); }.bind(this)); }); } handleComment = (commentText) => { this.setState({commentText}); } updateReputation = () => { firebase.database().ref(`Users/${this.state.uid}`).update({ currentRankRep: this.state.currentRankRep + 2, reputation: this.state.rep + 2 }); } sendComment = () => { let commentsRef = `Comments/${this.state.postId}`; let commentId = firebase.database().ref(commentsRef).push().key; if (!this.state.commentText) { Alert.alert('Error', 'You must type something to post a comment.'); } else { firebase.database().ref(`${commentsRef}/${commentId}`).update({ comment: this.state.commentText, postId: this.state.postId, id: commentId }); this.setState({commentText: '', height: 50}); this.updateReputation(); } } render() { return ( <View style={styles.content}> <TextInput value={this.state.commentText} onChangeText={this.handleComment} autoCapitalize="sentences" underlineColorAndroid="transparent" multiline={true} placeholder="Write something..." onChange={(event) => { this.setState({ commentText: event.nativeEvent.commentText, height: event.nativeEvent.contentSize.height, }); }} style={{height: Math.max(50, this.state.height > 200 ? 200 : this.state.height), fontSize: 18, flex: 1}} /> <View> <TouchableHighlight underlayColor="#16a085" onPress={this.sendComment} style={styles.sendBtn}> <Text style={styles.sendText}>Send</Text> </TouchableHighlight> </View> </View> ); } } const styles = StyleSheet.create({ content: { flex: 1, backgroundColor: 'white', position: 'absolute', bottom: 0, elevation: 3, // paddingTop: 5, // paddingBottom: 5, // paddingRight: 5, flexDirection: 'row', }, sendBtn: { height: 50, alignItems: 'center', width: 60, paddingTop: 10, // marginRight: 5, // borderRadius: 8, backgroundColor: '#02C39A' }, sendText: { marginTop: 4, marginRight: 6, marginLeft: 4, fontWeight: '900', fontSize: 18, // color: '#02C39A' color: 'white' } });
import React, { Component } from "react"; import GoogleMapReact from "google-map-react"; import Marker from "./marker"; const APIkey = require("./config/map_key").MapKey; class showMap extends Component { constructor(props) { super(props); } placeMarkers() { let business = this.props.business; return ( <Marker lat={business.lat} lng={business.long} name={business.business_name} color="#893c1f" /> ); } render() { return ( <div style={{ height: "135px", width: "275px" }}> <GoogleMapReact bootstrapURLKeys={{ key: APIkey }} defaultCenter={this.props.center} defaultZoom={this.props.zoom} > {this.placeMarkers()} </GoogleMapReact> </div> ); } } export default showMap;
// @TODO: YOUR CODE HERE! let width = 600; let height = 500; let margin = { top: 60, right: 60, bottom: 60, left: 60 }; // append the svg let svg = d3.select("#scatter") .append("svg") .attr("width", width ) .attr("height", height) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //reassign according to margin width = width - margin.left - margin.right; height = height - margin.top - margin.bottom; // import csv d3.csv("assets/data/data.csv").then(function(data) { // cast numbers data.forEach(d => { d.poverty = +d.poverty; d.healthcare = +d.healthcare; }); // x axis let povertyDomain = data.map(d => d.poverty); let x = d3.scaleLinear() .domain(d3.extent(povertyDomain)) .range([0, width]); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); svg.append("text") .attr("text-anchor", "middle") .attr("x", width / 2) .attr("y", height + 40) .text("Poverty%"); // y axis let healthcareDomain = data.map(d => d.healthcare); let y = d3.scaleLinear() .domain(d3.extent(healthcareDomain)) .range([height, 0]); svg.append("g") .call(d3.axisLeft(y)); // Add Y label svg.append("text") .attr("text-anchor", "middle") .attr("transform", "rotate(-90)") .attr("x", (height / 2) * -1) .attr("dy", -40) .text("Healthcare%"); // Add dots let dots = svg.selectAll("dots") .data(data) .enter() .append('g'); dots.append("circle") .attr("cx", d => x(d.poverty)) .attr("cy", d => y(d.healthcare)) .attr("r", 10) .style("fill", "#5DADE2"); // Add text dots.append("text") .text(d => d.abbr) .attr("x", d => x(d.poverty)) .attr("y", d => y(d.healthcare)) .attr("dx", -6) .attr("dy", 3) .style("font-size", "10px"); }).catch(e => { //I hope we don't get here! console.log(e); });
/** * Created by user on 2015/6/11. */ var Sort = { ORDER_BY: "orderBy", DESC: "desc", ASC: "asc" }; var ColumnType = { TEXT: "text", NUMBER: "number", RATE: "rate", DATE: "date", TIME: "time" }; var DataSourceManager = { createNew: function (usePage) { var dsr = {}; dsr.split = 0; dsr.dataSource = []; dsr.dataSize = dsr.dataSource.length; dsr.renderers = []; dsr.renderDataGroup = []; dsr.renderDataGroupSize = 0; dsr.usePage = usePage || false; dsr.pageInit = false; dsr.pageNo = 0; dsr.pageCount = 30; dsr.setDataSource = function (dataSource) { dsr.dataSource = dataSource; dsr.dataSize = dsr.dataSource.length; dsr.pageNo = 0; dsr.allocateData(); dsr.clearSort(); dsr.refresh(); if (dsr.usePage && !dsr.pageInit) { dsr.addPageController(); } if (dsr.usePage) { dsr.renderPageInfo(); } }; dsr.addRowData = function(rowData){ dsr.dataSource.push(rowData); dsr.dataSize = dsr.dataSource.length; dsr.allocateData(); dsr.clearSort(); dsr.refresh(); if (dsr.usePage) { dsr.renderPageInfo(); } }; dsr.removeRow = function (index) { dsr.dataSource.splice(index,1); dsr.dataSize = dsr.dataSource.length; dsr.allocateData(); dsr.clearSort(); dsr.refresh(); if (dsr.usePage) { dsr.renderPageInfo(); } }; dsr.updateRowData = function (index, rowData) { dsr.refreshRow(index); }; dsr.addRenderer = function (renderer) { renderer.setDataSourceRenderer(dsr); dsr.renderers.push(renderer); dsr.split++; }; dsr.getRenderRowCount = function () { return dsr.pageCount / dsr.split; }; dsr.getPageTotal = function () { return Math.ceil(dsr.dataSize / dsr.pageCount); }; dsr.getRowStartIndex = function () { return (dsr.usePage) ? dsr.getRenderRowCount() * dsr.pageNo : 0 }; dsr.sortData = function (sortIndex, field, orderBy, type) { if (type == "number" || type == "rate") { JsonTool.sort(dsr.dataSource, field, orderBy); } else { JsonTool.sortString(dsr.dataSource, field, orderBy); } dsr.allocateData(); dsr.updateSortColumn(sortIndex, orderBy); dsr.refresh(); }; dsr.allocateData = function () { //logTime("allocateData"); var renderRowCount = dsr.getRenderRowCount(); dsr.renderDataGroup = []; if(dsr.split==1){ dsr.renderDataGroup.push(dsr.dataSource); dsr.renderDataGroupSize = dsr.renderDataGroup.length; }else{ for (var s = 0; s < dsr.split; s++) { dsr.renderDataGroup.push([]); } dsr.renderDataGroupSize = dsr.renderDataGroup.length; var rowIndex = 1; var reportDataIndex = 0; var currentReportData = dsr.renderDataGroup[reportDataIndex]; for (var i = 0; i < dsr.dataSize; i++) { currentReportData.push(dsr.dataSource[i]); if (rowIndex >= renderRowCount) { if (reportDataIndex == dsr.renderDataGroupSize - 1) { reportDataIndex = 0; } else { reportDataIndex++; } currentReportData = dsr.renderDataGroup[reportDataIndex]; rowIndex = 1; } else { rowIndex++; } } } //logTimeEnd("allocateData"); }; dsr.updateSortColumn = function (sortIndex, orderBy) { for (var i = 0; i < dsr.renderers.length; i++) { dsr.renderers[i].updateSortColumn(sortIndex, orderBy); } }; dsr.clearSort = function () { for (var i = 0; i < dsr.renderers.length; i++) { dsr.renderers[i].clearSortColumn(); } }; dsr.refresh = function () { for (var i = 0; i < dsr.renderers.length; i++) { dsr.renderers[i].setDataSource(dsr.renderDataGroup[i]); } }; dsr.refreshRow = function (index) { for (var i = 0; i < dsr.renderers.length; i++) { dsr.renderers[i].renderRow(index); } }; dsr.addPageController = function () { var pageButton = "<div class='reportPageButton' style='float: right;'>" + "<button id='fpagebtn' class='btn btn-default'>第一頁</button>" + "<button id='pageupbtn' class='btn btn-default'>上一頁</button>" + "<button id='pagedownbtn' class='btn btn-default'>下一頁</button>" + "<button id='lpagebtn' class='btn btn-default'>最末頁</button>" + "</div>"; var pageInfo = "<div class='reportPageInfo' style='float: left;'>" + "當前第[<label id='pageIdxCount'>0/0</label>]頁" + "</div>"; var pageDiv = "<div class='reportPage'>" + pageInfo + pageButton + "</div>"; $(".reportTableContainer").after(pageDiv); dsr.initPageButtonEvent(); dsr.pageInit = true; }; dsr.initPageButtonEvent = function () { $("#pagedownbtn").click(function () { if (dsr.pageNo < dsr.getPageTotal() - 1) { dsr.pageNo++; dsr.renderAll(); } else { alert("抱歉!最後一頁囉"); } }); $("#pageupbtn").click(function () { if (dsr.pageNo > 0) { dsr.pageNo--; dsr.renderAll(); } else { alert("抱歉!第一頁囉"); } }); $("#fpagebtn").click(function () { dsr.pageNo = 0; dsr.renderAll(); }); $("#lpagebtn").click(function () { dsr.pageNo = dsr.getPageTotal() - 1; dsr.renderAll(); }); }; dsr.renderAll = function () { for (var i = 0; i < dsr.renderers.length; i++) { dsr.renderers[i].render(); } if (dsr.usePage) { dsr.renderPageInfo(); } }; dsr.renderPageInfo = function () { $("#pageIdxCount").text((dsr.pageNo + 1) + "/" + dsr.getPageTotal()); }; return dsr; } }; var DataSourceRenderer = { createNew: function () { var renderer = {}; renderer.dsr = null; renderer.data = []; renderer.dataSize = 0; renderer.setDataSource = function (newData) { renderer.data = newData; renderer.dataSize = renderer.data.length; renderer.render(); }; renderer.setDataSourceRenderer = function (dsr) { renderer.dsr = dsr; }; renderer.render = function () { }; renderer.renderRow = function (rowIndex) { }; renderer.updateSortColumn = function () { }; renderer.clearSortColumn = function () { }; return renderer; } };
import React, {useState} from "react"; import styled from "styled-components"; import axios from "axios"; import { FormControl, InputLabel, Button as MuiButton, Paper, Typography } from "@mui/material"; import {spacing} from "@mui/system"; const Button = styled(MuiButton)(spacing); const Wrapper = styled(Paper)` padding: ${props => props.theme.spacing(6)}; width: 100%; ${props => props.theme.breakpoints.up("md")} { padding: ${props => props.theme.spacing(10)}; } `; const yourConfig = { headers: { Authorization: "Bearer " + localStorage.getItem("token") } } function APIKey() { const [apikey, setApikey] = useState(false); axios.get(process.env.REACT_APP_SERVER_URL + "api-key", yourConfig) .then(function (response) { console.log(response); setApikey(response.data.apikey); }) .catch(function (error) { console.log(error); }); function apiFlask(event) { event.preventDefault(); axios .post(process.env.REACT_APP_SERVER_URL + "api-key", { resetapikey:true }, yourConfig) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error.data); }); return false; } return ( <Wrapper> <Typography component="h1" variant="h4" align="center" gutterBottom> API Key </Typography> <Typography component="h2" variant="body1" align="center"> </Typography> <form onSubmit={apiFlask}> <FormControl margin="normal" required fullWidth> <InputLabel htmlFor="email">API-key</InputLabel> {apikey} </FormControl> <Button type="Submit" to="" fullWidth variant="contained" color="primary" mt={2} > Reset API-Key </Button> </form> </Wrapper> ); } export default APIKey;
var permute = function(nums) { let ret = []; for (let i = 0; i < nums.length; i = i + 1) { let rest = permute(nums.slice(0, i).concat(nums.slice(i + 1))); if(!rest.length) { ret.push([nums[i]]) } else { for(let j = 0; j < rest.length; j = j + 1) { ret.push([nums[i]].concat(rest[j])) } } } return ret; }; console.log(permute([1,2,3]));
import * as DataGen from "./util/generator.js"; import {FRAME} from "./util/sleep.js"; import * as QuickSort from "./sorts/quick.js"; import * as MergeSort from "./sorts/merge.js"; import * as HeapSort from "./sorts/heap.js"; import * as SelectionSort from "./sorts/selection.js"; import * as BubbleSort from "./sorts/bubble.js"; import * as InsertionSort from "./sorts/insertion.js"; import * as CountingSort from "./sorts/counting.js"; import * as CycleSort from "./sorts/cycle.js"; import * as PermutationSort from "./sorts/permutation.js"; import * as StoogeSort from "./sorts/stooge.js"; import * as CircleSort from "./sorts/circle.js"; import * as IntroSort from "./sorts/intro.js"; import * as TimSort from "./sorts/tim.js"; import {Task} from "./util/task.js"; import {Counter} from "./util/counter.js"; const DEFAULT_FRAMES = FRAME; const DEFAULT_FPS = 1000/FRAME; const DEFAULT_LEN = 32; const DEFAULT_MODULUS = 4; const COLORS = [ //041 Happy Acid [ [72, 111], [198, 134], [239, 214] ], //039 Deep Blue [ [106, 37], [17, 117], [203, 252] ], //035 Itmeo Branding [ [42, 0], [245, 158], [152, 253] ], //034 Lemon Gate [ [150, 249], [251, 245], [196, 134] ], //059 Teen Notebook [ [151, 251], [149, 200], [240, 212] ], //064 Red Salvation [ [244, 69], [59, 58], [71, 148] ], //066 Night Party [ [2, 212], [80, 63], [197, 141] ], //069 Purple Division [ [112, 229], [40, 178], [228, 202] ], //073 Love Kiss [ [255, 255], [8, 177], [68, 153] ], //084 Phoenix Start [ [248, 249], [54, 212], [0, 35] ], //084 Frozen Berry [ [232, 199], [25, 234], [139, 253] ], //146 Juicy Cake [ [225, 249], [79, 212], [173, 35] ], ]; const ACCESS_COLOR = "#000"; const SWAP_COLOR = "#888"; const SORTS = [ QuickSort.LomutoNRQS, QuickSort.LomutoRQS, QuickSort.HoareRQS, QuickSort.HoareNRQS, MergeSort.RTD, MergeSort.BottomUp, HeapSort.SDHS, HeapSort.SUHS, SelectionSort.Basic, SelectionSort.Bingo, BubbleSort.BBS, BubbleSort.OBS, BubbleSort.Cocktail, BubbleSort.SPOE, BubbleSort.PPOE, BubbleSort.Comb, InsertionSort.Basic, InsertionSort.Gnome, InsertionSort.Shell, InsertionSort.RBIS, InsertionSort.IBIS, CountingSort.CS, CycleSort.CS, PermutationSort.PS, StoogeSort.RSS, StoogeSort.NRSS, CircleSort.RCS, CircleSort.NRCS, IntroSort.RBLPISSDHS, IntroSort.NRBLPISSDHS, IntroSort.RBHPISSDHS, IntroSort.NRBHPISSDHS, TimSort.BTISBUM, TimSort.BTRBISBUM, TimSort.BTIBISBUM ]; const ARRAY_TYPES = [ Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Float32Array, Float64Array ]; const ascending = (a, b) => a - b; const descending = (a, b) => b - a; function getCanvas(id){ return document.getElementById(id); } function getCanvasContext(cv){ return cv.getContext("2d"); } function lerp(a, b, t){ return a + (b - a)*t; } function gradient(t, grad){ let r = Math.floor(lerp(COLORS[grad][0][0], COLORS[grad][0][1], t)); let g = Math.floor(lerp(COLORS[grad][1][0], COLORS[grad][1][1], t)); let b = Math.floor(lerp(COLORS[grad][2][0], COLORS[grad][2][1], t)); return "rgb(" + r + ", " + g + ", " + b + ")"; } function DrawArrayToCanvas(cv, ctx, arr, len, s1, s2, drawType, grad){ let w = cv.width; let h = cv.height; //let normW = w/tw; //let normH = h/th; ctx.clearRect(0, 0, w, h); let normX = w/len; let normY = h/len; for(let i = 0; i < len; i++){ let x = i*normX; let y = arr[i]*normY; let factor = y/h; if(s1 == i){ ctx.fillStyle = ACCESS_COLOR; } else if(s2 == i){ ctx.fillStyle = SWAP_COLOR; } else{ ctx.fillStyle = gradient(factor, grad); } switch(drawType){ case 1: ctx.fillRect(x, h - y, normX, y); break; case 2: ctx.fillRect(x, 0, normX, h); break; default: ctx.fillRect(x, 0, normX, h); } } } class Timer{ constructor(){ this.now = performance.now(); } end(){ let now = performance.now() - this.now; now = now/1000; document.getElementById("time").innerHTML = "Time: " + now + " seconds"; } } let task = new Task(); function kill(t){ t.killTask(); } function restart(){ return new Task(); } function setFrames(v){ QuickSort.setFrames(v); MergeSort.setFrames(v); HeapSort.setFrames(v); SelectionSort.setFrames(v); BubbleSort.setFrames(v); InsertionSort.setFrames(v); CountingSort.setFrames(v); CycleSort.setFrames(v); PermutationSort.setFrames(v); StoogeSort.setFrames(v); CircleSort.setFrames(v); IntroSort.setFrames(v); TimSort.setFrames(v); } async function startSort(type, sorter, len, modulus, arrayType, asc, task){ let data = DataGen.createUnsorted(len, arrayType, type, asc, modulus); let cv = getCanvas("cv"); let ctx = getCanvasContext(cv); let c = asc ? ascending : descending; let timer = new Timer(); let comparison = new Counter(); let accesses = new Counter(); let swaps = new Counter(); let timeDisplay = document.getElementById("time"); let compDisplay = document.getElementById("compare"); let accessDisplay = document.getElementById("access"); let swapDisplay = document.getElementById("swap"); let grad = Math.floor(Math.random()*COLORS.length); let drawData = (a, b, arr=data) => { DrawArrayToCanvas(cv, ctx, arr, len, a, b, 1, grad); timeDisplay.innerHTML = "Time: " + ((performance.now() - timer.now)/1000) + " seconds"; compDisplay.innerHTML = "Accesses: " + accesses.count; accessDisplay.innerHTML = "Comparisons: " + comparison.count; swapDisplay.innerHTML = "Swaps: " + swaps.count; }; drawData(); await SORTS[sorter](data, 0, len - 1, c, drawData, task, comparison, accesses, swaps); drawData(); timer.end(); } async function startProgram( sorter = 1, len = DEFAULT_LEN, modulus = DEFAULT_MODULUS, arrayType = Array, asc = true, frames = DEFAULT_FRAMES, dataSet = "unique" ){ task = restart(); setFrames(frames); startSort(dataSet, sorter, len, modulus, arrayType, asc, task); } document.getElementById("start").addEventListener("click", () =>{ let s = document.getElementById("input-algo"); let sorter = s.options[s.selectedIndex].value; let data = document.getElementById("input-len").value; let modulus = document.getElementById("input-mod").value; let asc = document.getElementById("input-asc"); let a = document.getElementById("input-arr"); let arr = a.options[a.selectedIndex].value; let fps = document.getElementById("input-fps").value; let dt= document.getElementById("input-dataset"); let dataType = dt.options[dt.selectedIndex].value; fps = 1000/fps; kill(task); startProgram( sorter, data, modulus, ARRAY_TYPES[arr], asc.checked, fps, dataType ); }); document.getElementById("input-len").value = DEFAULT_LEN; document.getElementById("input-mod").value = DEFAULT_MODULUS; document.getElementById("input-fps").value = DEFAULT_FPS;
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); require('dotenv').config(); module.exports = { mode: 'development', optimization: { // removes minimization minimize: false, // separates files into main.js, vendor, runtime splitChunks: { chunks: 'all', name: false }, runtimeChunk: true }, entry: { // has to be main index.js in src folder main: path.resolve(__dirname, './src/index.js'), }, //devtool can be false or source-map or hidden-source-map (better for production) devtool: false, module: { rules: [ // JavaScript { test: /\.(js|jsx)$/i, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: ['@babel/plugin-transform-runtime', '@babel/transform-async-to-generator'], }, }, }, // CSS, PostCSS, and Sass { test: /\.(scss|css)$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: '', }, }, 'css-loader', 'postcss-loader', 'sass-loader', ], }, // Images { test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource', }, // Fonts and SVGs { test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: 'asset/inline', }, ], }, resolve: { // Enable importing JS / JSX files without specifying their extension extensions: ['.js', '.jsx'], }, };
function hasKey (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } function replace (obj, prop, replacement, track) { const orig = obj[prop] obj[prop] = replacement(orig) if (track) { track.push([obj, prop, orig]) } } function restore (track) { let builtin while (track.length) { builtin = track.shift() let obj = builtin[0] let name = builtin[1] let orig = builtin[2] obj[name] = orig // remove the wrapper attribute if (orig.__fm_wrapper__) { delete orig.__fm_wrapper__ } } } function wrap (func, before, after) { // if original function is already a wrapper function // don't want to wrap twice if (func.__fm_inner__) { return func } // if original function has already been wrapped before, return the wrapper if (func.__fm_wrapper__) { return func.__fm_wrapper__ } function wrapper () { before && before.apply(this, arguments) func.apply(this, arguments) after && after.apply(this, arguments) } // copy over properties of the original function for (let prop in func) { if (hasKey(func, prop)) { wrapper[prop] = func[prop] } } // wrapper.prototype = func.prototype wrapper.__fm_inner__ = func func.__fm_wrapper__ = wrapper return wrapper } function wrapFunc (obj, prop, before, after, track) { replace(obj, prop, function (orig) { return wrap(orig, before, after) }, track) }
var worker_1; function main() { var file1 = $('#file1')[0].files[0]; var file2 = $('#file2')[0].files[0]; var file3 = $('#file3')[0].files[0]; var file4 = $('#file4')[0].files[0]; var seq = $('#seq').val(); var cnt = $('#cnt').val(); var worker_1 = new Worker("/static/worker.js"); worker_1.onmessage = function (msg) { var e = msg.data; var s = '<tr><td>'+e[1].info[0]+'</td><td>'+String(e[1].info[1])+'</td></tr>'; for (var i = 0; i<e[1].seq_count.length; i++) { s+='<tr><td>'+e[1].seq_count[i][0]+'</td><td>'+String(e[1].seq_count[i][1])+'</td></tr>' } $('.input-output').html(String(s)); } worker_1.postMessage([file1, file2, file3, file4, seq, cnt]); };
export const state = () => ({ isFirstEnter: true, loadingConfig: { isShow: true, waiting: false, }, loadingStack: [new Promise((resolve) => { resolve() })], }) export const getters = { isLoading (state) { return !!state.loadingStack.length }, } export const mutations = { SET_FIRST_ENTER (state) { state.isFirstEnter = false }, CHANGE_LOADING_SHOW (state, payload) { state.loadingConfig.isShow = payload }, CHANGE_LOADING_WAITING (state, payload) { state.loadingConfig.waiting = payload }, SET_LOADING_STACK (state, payload) { state.loadingStack.push(payload) }, DEL_LOADING_STACK (state) { state.loadingStack.shift() }, } export const actions = { async nuxtServerInit ({ dispatch }) { await Promise.all([]) }, AJAX (context, options) { return new Promise((resolve, reject) => { this.$axios({ ...options, }).then(({ data, ...res }) => { resolve(data) }).catch((e) => { reject(e) }) }) }, ADD_LOADING_STACK ({ state, dispatch, commit }, payload) { if (payload instanceof Array) { const promise = Promise.allSettled(payload.filter(p => p instanceof Promise)).then((results) => { results.forEach(({ status, reason }) => { if (status === 'rejected') { console.warn(`Loading Rejected: ${reason}`) } }) return results }) commit('SET_LOADING_STACK', promise) return promise } if (payload instanceof Promise) { commit('SET_LOADING_STACK', payload) return payload } }, WAIT_LOADING ({ state, getters, dispatch, commit }) { if (!state.loadingConfig.waiting) { commit('CHANGE_LOADING_WAITING', true) return Promise.allSettled(state.loadingStack).then((results) => { results.forEach(({ status, reason }) => { commit('DEL_LOADING_STACK') if (status === 'rejected') { console.warn(`Loading Rejected: ${reason}`) } }) commit('CHANGE_LOADING_WAITING', false) if (getters.isLoading) { dispatch('WAIT_LOADING') } return results }) } }, }
export const setToken = (token) => { return { type: LOGIN_SUCCESS, isAuthenticated: true, token } } export const removeToken = () => { return { type: LOGOUT_SUCCESS, isAuthenticated: false } } export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS';
import React, {Component} from 'react'; class Footer extends Component { render() { return ( <footer id="footer" className="footer style-1 dark"> <a href="#"> <img src="/wunderkind/img/assets/footer-logo.png" alt="#" className="mr-auto img-responsive"/> </a> <ul> <li><a href="https://www.twitter.com/" target="_blank" className="color"><i className="ion-social-twitter"/></a></li> <li><a href="https://www.facebook.com/" target="_blank" className="color"><i className="ion-social-facebook"/></a></li> <li><a href="https://www.linkedin.com/" target="_blank" className="color"><i className="ion-social-linkedin"/></a></li> <li><a href="https://www.pinterest.com/" target="_blank" className="color"><i className="ion-social-pinterest"/></a></li> <li><a href="https://plus.google.com/" target="_blank" className="color"><i className="ion-social-googleplus"/></a></li> </ul> <a href="#" target="_blank"><strong>© HaveYouMet 2017</strong></a> <p>Made with <i className="ion-heart"/> for great people.</p> <span><a className="scroll-top"><i className="ion-chevron-up"/></a></span> </footer> ); } } export default Footer;
import GameScene from "./scenes/game.js"; import MainMenuScene from "./scenes/menu.js"; /** @type {Phaser.Core.Config} */ const config = { type: Phaser.AUTO, width: 800, height: 500, physics: { default: "arcade" }, scene: [MainMenuScene, GameScene], plugins: { scene: [ { key: "PhaserRaycaster", plugin: PhaserRaycaster, mapping: "raycasterPlugin" } ] } }; const game = new Phaser.Game(config);
//验收中心/委派设置 import React, { Component, PureComponent } from "react"; import { StyleSheet, Dimensions, View, Text, Button, Image, TouchableOpacity, Platform, ScrollView } from "react-native"; import { connect } from "rn-dva"; import FlatListView from "../../components/FlatListView"; import Header from "../../components/Header"; import CommonStyles from "../../common/Styles"; import * as requestApi from "../../config/requestApi"; import Line from "../../components/Line"; import Content from "../../components/ContentItem"; const { width, height } = Dimensions.get("window"); import DashLine from "../../components/DashLine"; import ImageView from '../../components/ImageView.js' import ScrollableTabView from "react-native-scrollable-tab-view" import DefaultTabBar from '../../components/CustomTabBar/DefaultTabBar.js'; import * as taskRequest from "../../config/taskCenterRequest" const tabtitle = [{ name: '委派给商户', key: 0 }, { name: '委派给员工', key: 1 }] export default class TaskSetting extends Component { static navigationOptions = { header: null }; constructor(props) { super(props) this.state = { editor: false, currentTab: 0, superMerchant: [], //上级联盟商列表 superMerchantSelectIndex: -1, // employeePage: null, //员工 employeePageSelectIndex: -1, hasBeeEmployees: [], //已经委派的员工 allEmployee: [], //所有的员工 多选 store:{ refreshing: false, loading: false, hasMore: true, } }; //已经委派设置的员工数据参数 this.querySethasBeanEmpls = { page:1, limit:10, } this.queryAllEmployee={ page:1, limit:10 } this.queryemployeeDelegate = { limit:10, page:1 } } //查询委派设置已经委派的数据 requesthMerchantJoinTaskBatchAppointedFind = (isFirest) => { const {taskPosition} = this.props.navigation.state.params let requestList = taskRequest.fetchMerchantJoinTaskBatchAppointedFind //任务 if(taskPosition === 'taskcore'){ requestList = taskRequest.fetchMerchantJoinTaskBatchAppointedFind }else if(taskPosition === 'auditcore'){ //审核 requestList = taskRequest.fetchPreAuditDelegatedPage }else{ //验收 requestList = taskRequest.fetchPreCheckDelegatedPage } const {store} = this.state store.refreshing = true this.setState({ store }) if(isFirest){ this.querySethasBeanEmpls.page = 1 }else{ if(!store.hasMore){ return } this.querySethasBeanEmpls.page+=1 } requestList(this.querySethasBeanEmpls).then((res) => { if (res) { let hasMore = true let data = res.data if (data.length < 10) { hasMore = false } store.hasMore = hasMore store.refreshing = false store.loading = false if(!isFirest){ data = this.state.hasBeeEmployees.concat(data) } this.setState({ hasBeeEmployees: data, store }) } else { store.hasMore = false store.refreshing = false store.loading = false if(isFirest){ this.setState({ hasBeeEmployees: [], store }) }else{ this.setState({ store }) } } }).catch((res) => { store.hasMore = false store.refreshing = false store.loading = false this.setState({ store }) }) } //请求所有员工 委派设置 requestEmployeePage = (isFirst) => { const {store,hasBeeEmployees} = this.state const {taskPosition} = this.props.navigation.state.params let requestList = null if(taskPosition === 'taskcore'){ requestList = taskRequest.fetchPreJobDelegatingPage }else if(taskPosition === 'auditcore'){ requestList = taskRequest.fetchPreAuditDelegatingPage }else{ requestList = taskRequest.fetchPreCheckDelegatingPage } store.refreshing = true this.setState({ store }) if(isFirst){ this.queryAllEmployee.page = 1 }else{ if(!store.hasMore){ return } this.queryAllEmployee.page +=1 } requestList(this.queryAllEmployee).then((res) => { if (res) { let allEmployee = res.pageable.data let userIds = res.userIds if (userIds && userIds.length) { allEmployee.forEach((item) => { if(userIds.includes(item.id)){ item.select = true } }) } let hasMore = true if (allEmployee.length < 10) { hasMore = false } store.hasMore = hasMore store.refreshing = false store.loading = false if(!isFirst){ allEmployee = this.state.allEmployee.concat(allEmployee) } this.setState({ allEmployee: allEmployee, store }) }else{ store.hasMore = false store.refreshing = false store.loading = false this.setState({ store }) } }).catch((res) => { store.hasMore = false store.refreshing = false store.loading = false this.setState({ store }) }) } componentDidMount() { //单个的委派需要已经委派的人员的接口 const { isSingle} = this.props.navigation.state.params if (isSingle) { // let param = { // merchantType: merchantType, // merchantId: merchantId, // taskPosition: taskPosition, // taskId: taskId, // } // taskRequest.fetchMerchantJoinTaskAppointedFind(param).then((res) => { // if (res) { // this.setState({ // hasBeeEmployees: [res] // }) // } else { // this.setState({ // hasBeeEmployees: [] // }) // } // }) } else { this.requesthMerchantJoinTaskBatchAppointedFind(true) } } selectUser = (index) => { let { currentTab, superMerchant, allEmployee, superMerchantSelectIndex, employeePageSelectIndex } = this.state let isSingle = this.props.navigation.state.params.isSingle if (isSingle) { let selecredOne = null if (superMerchantSelectIndex !== -1) { superMerchant[superMerchantSelectIndex].select = false } else { superMerchant.forEach((item) => { item.select = false }) } if (employeePageSelectIndex !== -1) { allEmployee[employeePageSelectIndex].select = false } else { allEmployee.forEach((item) => { item.select = false }) } if (currentTab == 0) { superMerchant[index].select = true selecredOne = superMerchant[index] this.setState({ superMerchant, superMerchantSelectIndex: index }) } else { allEmployee[index].select = true selecredOne = allEmployee[index] this.setState({ allEmployee, employeePageSelectIndex: index }) } this.setState({ hasBeeEmployees: [selecredOne] }) } else { allEmployee[index].select = !allEmployee[index].select this.setState({ allEmployee }) } } renderContent = (data, index) => { let item = data.item return ( <Content style={[styles.content, { position: 'relative'}]} key={index}> { this.state.editor ? <TouchableOpacity style={styles.selectImage} onPress={() => this.selectUser(index)}> <Image source={ item.select ? require("../../images/index/select.png") : require("../../images/index/unselect.png") } /> </TouchableOpacity> : null } <ImageView source={{ uri: item.avatar || '' }} soureWidth={52} sourceHeight={52} resizeMode='contain' /> <Text style={[styles.text, { marginTop: 6 }]}>{item.realName}</Text> <Text style={[styles.text, { color: '#BDC1C7' }]}>{item.phone}</Text> </Content> ) } changeRightBtn = () => { const { editor, allEmployee, hasBeeEmployees } = this.state const { isSingle, id } = this.props.navigation.state.params if (isSingle) { if (!editor) { // if(hasBeeEmployees && hasBeeEmployees.length>0){ // Toast.show('已经委派了人员,不可再委派') // return // } //上级联盟商 一个数据 taskRequest.fetchSuperMerchant({jobId:id}).then((res) => { if (res) { if (hasBeeEmployees && hasBeeEmployees.length > 0){ hasBeeEmployees.find((item)=>{ if(item.id === res.id){ res.select = true return true } }) } this.setState({ superMerchant: [res] }) } }).catch((err)=>{ console.log(err) }); this.setState({ editor: !editor, currentTab: 0 }) } else { const { id,taskPosition,getnewList } = this.props.navigation.state.params if (hasBeeEmployees && hasBeeEmployees.length == 0) { Toast.show('请选择员工') return } if(taskPosition === 'taskcore'){ requestList = taskRequest.fetchsetJobDelegate }else if(taskPosition === 'auditcore'){ //审核 requestList = taskRequest.fetchSetAuditDelegate }else{ //验收 requestList = taskRequest.fetchsetCheckDelegate } let param = { jobId: id, delegateId: hasBeeEmployees[0].id, } requestList(param).then((res) => { Toast.show('保存成功') if(getnewList){ getnewList(true) } this.setState({ editor: !editor, currentTab: 0 }) }).catch((err)=>{ console.log(err) }); } } else { //请求员工数据 if (!editor) { this.requestEmployeePage(true) this.setState({ editor: !editor }) } else { const {taskPosition} = this.props.navigation.state.params let requestList = null if(taskPosition === 'taskcore'){ requestList = taskRequest.fetchMerchantJoinBatchAppointedSave }else if(taskPosition === 'auditcore'){ requestList = taskRequest.fetchPreAuditDelegateSetting }else{ requestList = taskRequest.fetchPreCheckDelegateSetting } let param = { userIds:[], } let newdata = [] allEmployee.forEach((item) => { if (item.select) { newdata.push(item) param.userIds.push(item.id) } }) if (param.userIds.length == 0) { Toast.show('请选择员工') return } if(requestList){ requestList(param).then((res) => { Toast.show('保存成功') this.setState({ hasBeeEmployees: newdata }) this.setState({ editor: !editor }) }).catch((err)=>{ console.log(err) }); } } } } ListEmptyComponent = () => { const { store,editor } = this.state; const { refreshing, loading, isFirstLoad } = store; return ( <View style={styles.emptyView}> { refreshing && loading || isFirstLoad ?null: <React.Fragment> <Image source={require('../../images/user/empty.png')} /> <View style={[CommonStyles.flex_center,styles.textWrap]}> { editor ? ( <View style={{alignItems:'center'}}> <Text style={{marginTop: 1,fontSize: 14,color: '#777',}}>你的账号暂无分号可用,</Text> <Text style={{marginTop: 1,fontSize: 14,color: '#777',}}>请先添加分号</Text> </View> ) : ( <Text style={{marginTop: 1,fontSize: 14,color: '#777',}}>暂未委派分号</Text> ) } </View> </React.Fragment> } </View> ) } //委派设置 renderWeiPaiSheZhi = () => { const {editor,allEmployee,hasBeeEmployees,store} = this.state let alldata = [] if (editor) { alldata = allEmployee } else { alldata = hasBeeEmployees } return ( <FlatListView renderItem={item => this.renderContent(item,item.index)} style={{ height:'100%',backgroundColor:CommonStyles.globalBgColor}} data={alldata} store={store} ItemSeparatorComponent={()=>null} ListHeaderComponent={()=>null} numColumns={2} ListEmptyComponent={this.ListEmptyComponent} refreshData={ ()=>{ if(editor){ this.requestEmployeePage(true) }else{ this.requesthMerchantJoinTaskBatchAppointedFind(true) } } } loadMoreData={ ()=>{ if(editor){ this.requestEmployeePage(false) }else{ this.requesthMerchantJoinTaskBatchAppointedFind(false) } } } /> ) } requestemployeeDelegate = (isFirst) => { const {store} = this.state store.refreshing = true this.setState({ store }) if(isFirst){ this.queryemployeeDelegate.page=1 }else{ this.queryemployeeDelegate.page += 1 } taskRequest.fetchEmployeeDelegate(this.queryemployeeDelegate).then((res)=>{ if (res) { let hasMore = true let data = res.data if (data.length < 10) { hasMore = false } store.hasMore = hasMore store.refreshing = false store.loading = false if(!isFirst){ data = this.state.allEmployee.concat(data) } this.setState({ allEmployee: data, store }) } else { store.hasMore = false store.refreshing = false store.loading = false if(isFirst){ this.setState({ allEmployee: [], store }) }else{ this.setState({ store }) } } // allEmployee }).catch((err)=>{ console.log(err) }); } render() { const { navigation } = this.props; const { editor, superMerchant, allEmployee, hasBeeEmployees,store } = this.state let isSingle = this.props.navigation.state.params.isSingle return ( <View style={styles.container}> <Header navigation={navigation} goBack={true} title={(!isSingle && !editor) ? '委派设置' : '选择分号'} rightView={ <TouchableOpacity style={{ width: 50 }} onPress={this.changeRightBtn}> <Text style={{ color: '#fff', fontSize: 17 }}>{editor ? (!isSingle ? (allEmployee && allEmployee.length > 0) ? '保存' : '' : '保存' ) : '编辑'}</Text> </TouchableOpacity> } /> { isSingle ? ( editor ? <ScrollView style={{width:width,height:height-44-CommonStyles.headerPadding}}> <ScrollableTabView initialPage={0} onChangeTab={({ i }) => { if (i == 1) { if (!allEmployee || (allEmployee && !allEmployee.length)) { // this.requestEmployeePage(true) this.requestemployeeDelegate(true) } } this.setState({ currentTab: i }) }} style={{ width: width, height: height - 44 - CommonStyles.headerPadding }} renderTabBar={() => ( <DefaultTabBar underlineStyle={{ backgroundColor: "#fff", height: 8, borderRadius: 10, marginBottom: -5, width: "14%", marginLeft: "13%" }} tabStyle={{ backgroundColor: "#4A90FA", height: 44, paddingBottom: -4 }} activeTextColor="#fff" inactiveTextColor="rgba(255,255,255,.5)" tabBarTextStyle={{ fontSize: 14 }} style={{ backgroundColor: "#4A90FA", height: 44, borderBottomWidth: 0, overflow: "hidden" }} /> )} > { tabtitle.map((item, index) => { let lists = [] if (index == 0) { lists = superMerchant } else if (index == 1) { lists = allEmployee } if(index === 0){ return ( <View style={[styles.contentView, { marginTop: 5 }]} tabLabel={item.name} key={index}> { lists && lists.length >0 ? ( lists.map((item, index) => { let data = {item:item} return this.renderContent(data, index) }) ) : ( <View style={styles.emptyView}> <Image source={require('../../images/user/empty.png')} /> <View style={[CommonStyles.flex_center,styles.textWrap]}> <Text style={{marginTop: 1,fontSize: 14,color: '#777',}}>暂未委派联盟商</Text> </View> </View> ) } </View> ) }else{ return ( <FlatListView key={index} tabLabel={item.name} renderItem={item => this.renderContent(item,item.index)} style={{backgroundColor:'4A90FA'}} data={lists} store={store} numColumns={2} ListEmptyComponent={this.ListEmptyComponent} refreshData={ ()=>{ this.requestemployeeDelegate(true) } } loadMoreData={ ()=>{ this.requestemployeeDelegate(false) } } /> ) } }) } </ScrollableTabView> </ScrollView> : <ScrollView style={{width:width,height:height-44-CommonStyles.headerPadding}}> <View> <Text style={[styles.text, { textAlign: 'center', color: CommonStyles.globalHeaderColor, marginTop: 15 }]}>请为任务分配商户或员工</Text> <View style={[styles.contentView, { marginTop: 10 }]}> { hasBeeEmployees && hasBeeEmployees.length>0 ? hasBeeEmployees.map((item, index) => { let data = {item:item} return this.renderContent(data, index) }) : ( <View style={styles.emptyView}> <Image source={require('../../images/user/empty.png')} /> <View style={[CommonStyles.flex_center,styles.textWrap]}> <Text style={{marginTop: 1,fontSize: 14,color: '#777',}}>暂未委派联盟商</Text> </View> </View> ) } </View> </View> </ScrollView> ) : ( <View style={{width:'100%',height:height-44}}> <Text numberOfLines={3} ellipsizeMode='tail' style={[styles.text, { color: '#999',paddingVertical:0,height:44, marginTop: 15, paddingHorizontal: 15 }]}> 委派员工后,系统分发给联盟商的任务会直接分配给相关员工,员工完成后需要验证,验证通过后提交审核。 </Text> <View style={[styles.contentView, { flex:1,marginBottom:15}]}> { this.renderWeiPaiSheZhi() } </View> </View> ) } </View > ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding }, text: { color: '#222', fontSize: 14 }, content: { width: (width - 30) / 2, marginLeft: 10, height: 147, alignItems: 'center', justifyContent: 'center', }, smallText: { fontSize: 13, color: '#999', marginBottom: 2 }, textWrap: { marginTop: 25, }, emptyView: { // flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: width, marginTop: 50, }, image: { borderRadius: 62, width: 62, height: 62, overflow: 'hidden' }, contentView: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', }, selectImage: { position: 'absolute', top: 0, right: 0, padding: 10, width:60, height:60, alignItems:'flex-end', zIndex:999 } })
/** *滑动事件 */ let touchEvent = function () { if(!!self.touch) self.slider.addEventListener('touchstart',self.events,false); //定义touchstart的事件处理函数 start(event){   var touch = event.targetTouches[0]; //touches数组对象获得屏幕上所有的touch,取第一个touch   startPos = {x:touch.pageX,y:touch.pageY,time:+new Date}; //取第一个touch的坐标值   isScrolling = 0; //这个参数判断是垂直滚动还是水平滚动   this.slider.addEventListener('touchmove',this,false);   this.slider.addEventListener('touchend',this,false); } } export default touchEvent;
let app = angular.module('app', []); app.directive('customOnChange', function() { return { restrict: 'A', link: function (scope, element, attrs) { let onChangeHandler = scope.$eval(attrs.customOnChange); element.on('change', onChangeHandler); element.on('$destroy', function() { element.off(); }); } }; }); app.controller('RecipeController', ['$scope','$http', function ($scope,$http) { let recipeCtrl = this; recipeCtrl.recipe = { id: null, name: null, ingredients: [], steps: [], image: 'uploads/default.png' }; recipeCtrl.edit = false; recipeCtrl.get_recipe = function (id) { let url = new URL(location.protocol + '//' + location.host + "/api/recipe"), params = {id: id}; Object.keys(params).forEach(function (key) {url.searchParams.append(key, params[key])}); if (id == null){ recipeCtrl.edit = true; recipeCtrl.NameText = 'New Recipe'; return } $http.get(url.toString()).then(function (response) { recipeCtrl.recipe.id = response.data.id; recipeCtrl.recipe.name = response.data.name; recipeCtrl.recipe.ingredients = response.data.ingredients; recipeCtrl.recipe.steps = response.data.steps; recipeCtrl.recipe.image = response.data.image; recipeCtrl.NameText = recipeCtrl.recipe.name; }).catch(reason => console.log(reason)) }; recipeCtrl.addStep = function () { let nr = 1; if (recipeCtrl.recipe.steps.length > 0) { nr = Math.max.apply(Math,recipeCtrl.recipe.steps.map(s => {return s.nr;})) + 1; } recipeCtrl.recipe.steps.push({description: recipeCtrl.stepText, nr: nr}); recipeCtrl.stepText = ""; }; recipeCtrl.removeStep = function (index) { recipeCtrl.recipe.steps.splice(index,1); for (let i = index; i < recipeCtrl.recipe.steps.length; i ++){ recipeCtrl.recipe.steps[i].nr -= 1; } }; recipeCtrl.addIngredient = function () { let url = new URL(location.protocol + '//' + location.host + "/api/ingredient"), params = {name: recipeCtrl.ingrName}; Object.keys(params).forEach(function (key) {url.searchParams.append(key, params[key])}); $http.get(url.toString()).then(response => { if (!response.data.hasOwnProperty('id')){ let req = { method: 'POST', url: '/api/ingredient', headers: { 'Content-Type': 'application/json' }, data: { name: recipeCtrl.ingrName } }; return $http(req) } else { return response.data.id } }).then(result => { if (typeof (result) === "number"){ recipeCtrl.recipe.ingredients.push({ ingredient: result, name: recipeCtrl.ingrName, unit: recipeCtrl.ingrUnit, quantity: recipeCtrl.ingrAmount }); } else { recipeCtrl.recipe.ingredients.push({ ingredient: result.data.id, name: recipeCtrl.ingrName, unit: recipeCtrl.ingrUnit, quantity: recipeCtrl.ingrAmount }); } recipeCtrl.ingrAmount = ""; recipeCtrl.ingrName = ""; recipeCtrl.ingrUnit = ""; }).catch(reason => console.log(reason)) }; recipeCtrl.saveRecipe = function () { recipeCtrl.recipe.name = recipeCtrl.NameText; let method = 'POST'; if (recipeCtrl.recipe.id != null){ method = 'PUT'; } let req = { method: method, url: '/api/recipe', headers: { 'Content-Type': 'application/json' }, data: recipeCtrl.recipe }; $http(req).then(response => { recipeCtrl.recipe.id = response.data.id; recipeCtrl.recipe.name = response.data.name; recipeCtrl.recipe.ingredients = response.data.ingredients; recipeCtrl.recipe.steps = response.data.steps; recipeCtrl.edit = false; }).catch(reason => console.log(reason)) }; recipeCtrl.abortEdit = function () { if (confirm('Are you sure? All unsaved changes will be lost!')){ if (recipeCtrl.recipe.id != null){ recipeCtrl.edit = false; recipeCtrl.get_recipe(recipeCtrl.recipe.id); } else { location.reload() } } }; recipeCtrl.deleteRecipe = function () { if (confirm('Do you really want to delete this recipe? This cannot be undone!')){ if (recipeCtrl.recipe.id != null){ req = { method: 'DELETE', url: '/api/recipe', headers: { 'Content-Type': 'application/json' }, data: { id: recipeCtrl.recipe.id} }; $http(req).then(response => { location.href = '/'; }).catch(reason => {console.log(reason)}) } } }; $scope.previewImage = function (event) { let fileLst = event.target.files; if (fileLst.length > 0){ let fileReader = new FileReader(); let file = fileLst[0]; if (file.type === 'image/jpeg' || file.type === 'image/png'){ fileReader.addEventListener('load', () => { let img = document.getElementById('recipePicture'); let r = fileReader.result; img.src = r; recipeCtrl.image = r; }, false); fileReader.readAsDataURL(file) } else { console.log('Wrong mime-type') } } } }]);
import SubMenu from "../nav-submenu"; import Link from "next/link"; const Menu = ({ nav, menu_id, HandleSelectMenu }) => { return nav.map((item, key) => ( <> <Link href={item.rute ? item.rute : "#"}> <span key={key*9} onClick={() => HandleSelectMenu(menu_id, item.id)} className={`${item.selected ? 'select' : ''} denote`} data-bs-toggle="collapse" data-bs-target={`#nav${item.name}`} aria-controls={`nav${item.name}`} aria-expanded="false" > <i class={item.icon}></i> <span>{item.name}</span> </span> </Link> {SubMenu({ sub_menu: item.sub_menu, id: `nav${item.name}` })} </> )); }; export default Menu;
export const TYPES = { PAGE: { UPDATE_PAGE: 'UPDATE_PAGE', CHANGE_THEME: 'PAGE_CHANGE_THEME', CHANGE_BG: 'PAGE_CHANGE_BG', CHANGE_STYLE: 'PAGE_CHANGE_STYLE', RESET_HEADER: 'PAGE_RESET_HEADER', RESET_FOOTER: 'PAGE_RESET_FOOTER', RESET_SECTIONS: 'PAGE_RESET_SECTIONS' } }; export default function pageReducer(draft, { type, payload }) { const { UPDATE_PAGE, CHANGE_THEME, CHANGE_BG, CHANGE_STYLE, RESET_HEADER, RESET_FOOTER, RESET_SECTIONS } = TYPES.PAGE; switch (type) { case CHANGE_BG: draft.background = payload; return; case CHANGE_STYLE: draft.styles = payload; return; case UPDATE_PAGE: return { ...payload }; default: throw new Error(); } }
// Called by SwiperNoSwiping and Generates Cards with the results passed down to it through // props named results import React, { Component } from 'react'; import { Card, CardText, CardBody, CardTitle, CardSubtitle } from 'reactstrap'; import Draggable from 'react-draggable'; // The default import './css/Cards.css' import firebase from 'firebase' import apiConfig from './apiKeys' import hoch from './images/hoch.jpg' import {Carousel, CarouselItem, CarouselControl, CarouselIndicators, CarouselCaption} from 'reactstrap'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import Drawer from '@material-ui/core/Drawer'; import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import {MailFolderListItems, OtherMailFolderListItems } from './tileData'; import squaduplogo from './images/squadlogowhite.png'; import grubhub from "./images/grubhub.png"; import googlemaps from "./images/googlemaps.png"; import call from "./images/call.png"; import { Row, Col } from 'reactstrap'; import { UncontrolledCollapse, Button} from 'reactstrap'; import yelp from "./images/yelp.png" var items = [] const styles = { root: { flexGrow: 1, }, flex: { flexGrow: 1, }, menuButton: { marginLeft: -12, marginRight: 20, }, }; export class Cards extends Component { constructor(props){ super(props); this.state=({ activeIndex: 0, results: null , key: apiConfig.key, countRight: 0, countLeft: 0 , deltaPosition: { x: 0, y: 0 }, visibility: "hidden", resultsCount: 0, currentResult:0, cardPosition: null, inital: true, Header: null, Rating: null, resultNames:[], IMG: hoch, pictures:["","",""], Type: null, AllData: null, otherCards: false, }); this.next = this.next.bind(this); this.previous = this.previous.bind(this); this.goToIndex = this.goToIndex.bind(this); this.onExiting = this.onExiting.bind(this); this.onExited = this.onExited.bind(this); } toggleDrawer = (side, open) => () => { this.setState({ [side]: open, }); }; onExiting() { this.animating = true; } onExited() { this.animating = false; } next() { if (this.animating) return; const nextIndex = this.state.activeIndex === items.length - 1 ? 0 : this.state.activeIndex + 1; this.setState({ activeIndex: nextIndex }); } previous() { if (this.animating) return; const nextIndex = this.state.activeIndex === 0 ? items.length - 1 : this.state.activeIndex - 1; this.setState({ activeIndex: nextIndex }); } goToIndex(newIndex) { if (this.animating) return; this.setState({ activeIndex: newIndex }); } handleD(e, ui) { // Handles the drag and collects the deltas of the cards being dragged around const {x, y} = this.state.deltaPosition; this.setState({ deltaPosition: { x: x + ui.deltaX, y: y + ui.deltaY, } }); } handleSTOP(){ // Handles the release of the card after being dragged. this.completeSwipe(false) this.setState({ deltaPosition: { x: 0, y: 0 }, })} componentDidMount() { if(this.state.otherCards==false){ let currentComponent = this console.log(currentComponent.props.results) currentComponent.setState({ results: currentComponent.props.results }) //setting the result's name in a list var resultName=[] for(var k in this.state.results) resultName.push(this.state.results[k].name) console.log("listing restaurant name",resultName) currentComponent.setState({ resultNames:resultName })} } completeSwipe(veto){ // registers the direction in which the swipe took place. // Updates the values in firebase (assuming firebase has a list of results with list of results) console.log("completing swipe") var x = this.state.deltaPosition.x //var left = this.state.countLeft if(Math.abs(this.state.deltaPosition.x)>100 || veto){ // Checks if swipe delta > 100 var restaurantName= this.state.Header var restaurantRating = this.state.Rating var restaurantImage = this.state.IMG var restaurantType = this.state.Type var AllD= this.state.AllData const ResultsRef = firebase.database().ref(this.props.groupCode).child('Results') //check if restaurant exists ResultsRef.once("value",function(snapshot){ if(!snapshot.hasChild(restaurantName)&&x>0 && !veto){ console.log({ rating: restaurantRating, left:0, right:1, photoRef: restaurantImage, categories: restaurantType, AllData: AllD }) ResultsRef.child(restaurantName).set({ rating: restaurantRating, left:0, right:1, photoRef: restaurantImage, categories: restaurantType, allData: AllD }) }else if(!snapshot.hasChild(restaurantName)&& x<0 || veto) { console.log("vetoed") var left =1 if(veto){ left=3 } ResultsRef.child(restaurantName).set({ rating: restaurantRating, left:left, right:0, photoRef: restaurantImage, categories: restaurantType, allData: AllD }) }else if(snapshot.hasChild(restaurantName)&& x>0 && !veto) { ResultsRef.child(restaurantName).once("value", function(snapshot){ var count=snapshot.val().right const updates = {} updates['right']=count+1 ResultsRef.child(restaurantName).update(updates) } )}else if(snapshot.hasChild(restaurantName)&& x<0 || veto) { console.log("vetoed") var left =1 if(veto){ left=3 } ResultsRef.child(restaurantName).once("value",function(snapshot){ var count=snapshot.val().left const updates = {} updates['left']= count + left ResultsRef.child(restaurantName).update(updates)}) } }) // Hide the card this.setState({ visibility: "hidden", }) // Reposition the cards and reset the deltas if(this.state.currentResult<this.state.results.length-1){ console.log("processing") this.setState({ resultsCount: this.state.resultsCount+1 , deltaPosition: { x: 0, y: 0 }, cardPosition: {x: 0, y: 0} }) this.setData() // Updating card info this.setState({ cardPosition: null, visibility: "visible", currentResult: this.state.resultsCount, }) } else { // LOAD RESULTS- all swipes are completed and the results page is ready to be loaded. this.continueCards() } } else { // If the swipe position deltas is not greater than 100px than the position is reset this.setState({ cardPosition: {x: 0, y: 0} }) this.setState({ cardPosition: null }) } } replaceAll (search, replacement, s) { var target = s; return target.split(search).join(replacement); } typeToString(types){ var toString= "" if(types){ types.map((category)=> toString= toString+ " "+category.title )} return toString } continueCards(){ const currentComponent= this if(this.state.otherCards===false){ if(!window.confirm("See other member's cards?")){ this.props.DisplayResults() }else{ this.setState({otherCards:true}) let currentComponent = this console.log(currentComponent.props.results) var generatedResult=[] var otherResults = firebase.database().ref(this.props.groupCode).child('Results') otherResults.once("value",function(snapshot){ var results = Object.assign(snapshot.val(),results) Object.keys(results).forEach(i=>{ console.log("result restaurant name is ",i,"; right is ",results[i].right,"; left is ",results[i].left,) if(results[i].right-results[i].left>0){ console.log(i,!(currentComponent.state.resultNames.includes(i))) if(!(currentComponent.state.resultNames.includes(i))){ console.log(i) generatedResult.push(results[i].allData)} } }) }) console.log("generated results",generatedResult) currentComponent.setState({ results:generatedResult, resultsCount: -1, currentResult:-1, }) if(generatedResult.length==0){ currentComponent.completeSwipe() alert("No restaurant from other member!!") this.props.DisplayResults() } if(!currentComponent.state.results){ this.setData() this.setState({ inital: false, cardPosition: {x: 0, y: 0} }) } } }else{ this.props.DisplayResults() } } setData(){ console.log("setting data") const currentComponent= this console.log(currentComponent.state.results[currentComponent.state.resultsCount]) var toString= this.typeToString(this.state.results[this.state.resultsCount].categories) if(!this.state.results[this.state.resultsCount].photos && this.state.otherCards==false){ firebase.database().ref(this.props.groupCode+"/users/"+this.props.userInGroup+"/results").on("value",function(snapshot){ console.log(snapshot.val()) currentComponent.setState({ results:snapshot.val() }) }) } console.log("results are,", this.state.results) // Updating the information on the card with the results on the next list of results this.setState({ Header: this.state.results[this.state.resultsCount].name, Rating: this.state.results[this.state.resultsCount].rating, IMG: this.state.results[this.state.resultsCount].image_url, Type: toString, pictures: this.state.results[this.state.resultsCount].photos, currentResult: this.state.resultsCount, AllData: this.state.results[this.state.resultsCount] }) } componentWillMount(){ if(!this.state.results){ console.log("results updating", this.props.results) this.setState({ results: this.props.results }) console.log("results updated", this.state.results) } } handleVeto(bool){ this.completeSwipe(bool) if(!bool){ this.handleVeto(!bool) } } render() { const currentComponent= this const classes = this.props; // side panel from tileData.js const sideList = ( <div className={classes.list}> <List> <MailFolderListItems groupCode={this.props.groupCode} userInGroup={this.props.userInGroup} allUsers = {this.props.allUsers}/> </List> <Divider /> <List> <OtherMailFolderListItems logout={this.props.logout}/> </List> </div> ); const fullList = ( <div className={classes.fullList}> <List> <MailFolderListItems groupCode={this.props.groupCode} userInGroup={this.props.userInGroup} allUsers = {this.props.allUsers}/> </List> <Divider /> <List> <OtherMailFolderListItems logout={this.props.logout}/> </List> </div> ); const Loading = require('react-loading-animation'); if(this.state.pictures){ items = [ { src: this.state.pictures[0], altText: '', caption: '' }, { src: this.state.pictures[1], altText: '', caption: '' }, { src: this.state.pictures[2], altText: '', caption: '' } ]; } else{ items = [ { src: this.state.IMG, altText: '', caption: '' }] } const { activeIndex } = this.state; const slides = items.map((item) => { return ( <CarouselItem onExiting={this.onExiting} onExited={this.onExited} key={item.src} > <img src={item.src} alt={item.altText} /> <CarouselCaption captionText={item.caption} captionHeader={item.caption} /> </CarouselItem> ); }); if(this.state.results!=null){ if(this.state.results.length!==0 && this.state.visibility==="hidden") { // If the results are finally generated by API, start displaying the cards this.setState({ visibility: "visible" }) if(this.state.inital){ // If this is the first call for the cards, load the data into them. this.setData() this.setState({ inital: false }) } } } var coord= [] var yelpUrl= "" var phoneNO= 0 if(this.state.results[this.state.resultsCount]){ if(this.state.results[this.state.resultsCount]["coordinates"]){ coord= this.state.results[this.state.resultsCount]["coordinates"] } else{ coord= { latitide: '0' , longitude: '0' }} yelpUrl= this.state.results[this.state.resultsCount]["url"] phoneNO= this.state.results[this.state.resultsCount]["phone"] } //const deltaPosition = this.state.deltaPosition; return ( // displaying page with app bar, preference selection, and side panel <div> <AppBar position="static" className="tab" style={{maxHeight:"80px"}}> <Toolbar className="tab"> <IconButton aria-haspopup="true" onClick={this.toggleDrawer('left', true)} className={classes.menuButton} color="inherit" aria-label="Menu"> <MenuIcon /> </IconButton> <img src={squaduplogo} style={{width:"80%", maxWidth:"150px", margin:"5%", float:"center"}} /> </Toolbar> </AppBar> <Drawer open={this.state.left} onClose={this.toggleDrawer('left', false)}> <div tabIndex={0} role="button" onClick={this.toggleDrawer('left', false)} onKeyDown={this.toggleDrawer('left', false)} > {sideList} </div> </Drawer> <div className= "BOX" id="scroll-container"> <Loading isLoading = {this.state.visibility === "hidden"}/> <Draggable axis="x" handle=".handle" defaultPosition={{x: 0, y: 0}} position={this.state.cardPosition} grid={[25, 25]} onStart={this.handleStart} onDrag={this.handleD.bind(this)} onStop={this.handleSTOP.bind(this)}> <div className="BOX2"> <div className="handle"> <Card className={"Card-"+this.state.visibility}> <Carousel activeIndex={activeIndex} next={this.next} previous={this.previous} > <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} /> {slides} <CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} /> <CarouselControl direction="next" directionText="Next" onClickHandler={this.next} /> </Carousel> {/* <CardImg top width="100%" crossOrigin="Anonymous" src= {this.state.IMG} alt={hoch} /> */} <CardBody> <CardTitle>{this.state.Header}</CardTitle> <CardSubtitle>Rating: {this.state.Rating}</CardSubtitle> <CardText>Type: {this.state.Type}</CardText> {this.state.results[this.state.resultsCount]? <div> {/*adding icons for more information to each resturant on the card*/} <Button style={{width: "50%", backgroundColor:"white", borderColor:"white", margin:"5%", color:"#0077B5", marginTop: "2%"}} id="toggler"> More Info v </Button> <UncontrolledCollapse toggler="#toggler"> <Row> <Col> { <a href={'https://www.google.com/maps/search/?api=1&query='+coord["latitude"]+"%2C+"+coord["longitude"] } target="_blank"> <img alt="" src={googlemaps} style={{width:"98%",maxWidth:"49px"}}/> </a> } </Col> <Col> { <a href= {yelpUrl} target="_blank"> <img alt="" src={yelp} style={{width:"98%",maxWidth:"49px"}}/> </a> } </Col> <Col> {<a href= {"tel:"+phoneNO} > <img alt="" src={call} style={{width:"100%",maxWidth:"50px"}}/> </a>} </Col> <Col>{ <a href={'https://www.grubhub.com/search?latitude='+coord["latitude"]+"&longitude="+coord["longitude"]} target="_blank"> <img alt="" src={grubhub} style={{width:"98%",maxWidth:"45px"}}/> </a>} </Col> </Row> </UncontrolledCollapse></div> : <div/> } </CardBody> </Card> </div> </div> </Draggable> <button style={{width: "50%", maxWidth:"100px", backgroundColor:"#0077B5", borderColor:"#0077B5", marginTop:"5%"}} className="btn btn-primary"onClick={()=>currentComponent.handleVeto(false)}>Veto</button> </div> </div> ) } } Cards.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Cards)
// helper object/hash map to correlate to question_type in .json export default { SingleAnswer: "mutiplechoice-single", MultiAnswer: "mutiplechoice-multiple", TrueFalse: "truefalse", };
import React from 'react'; const MapView = () => { return ( <div> MAP GOES HERE </div> ) } export default MapView;
import { nuxtGenerate, nuxtModuleCallback } from "./jest/helpers/nuxtGenerate"; describe('Nuxt.js Module', () => { it('should build module with components specified', nuxtGenerate('nuxt.config.module.components.js', nuxtModuleCallback)); });
module.exports = function getZerosCount(number) { // your implementation var z = 0; while(number){ number = (number/5)|0; z+=number; } return z; }
const express = require('express'); const mongoose = require('mongoose'); const Donation = require('../models/donation'); const User = require('../models/user'); exports.postDonation = (req, res, next) => { new Donation({ _id: mongoose.Types.ObjectId(), userId: req.body.userId, coords: req.body.coords, item: req.body.item, address: req.body.address, }) .save() .then(result => { User.findOne({_id: req.body.userId}) .exec() .then(user => { user.postedDonations.push(result); user.save(); console.log(result); res.status(201).json({ message: 'Created Donation Successfully', createdDonation: result._id }) }); }) .catch(err => { console.log(err + ' here') ; res.status(500).json({ error: err }); }); } exports.deleteDonation = async (req, res) => { const { id } = req.params; try { const deleted = await Donation.findByIdAndDelete(id); if (deleted) { return res.send("success") } } catch (err) { return res.send(err) } } exports.getUnclaimedDonations = async (req, res) => { try { const donations = await Donation.find({ pickedUp: false }) if (donations) { return res.status(200).json({ message: "success", donations }) } throw "Error fetching donations" } catch (err) { console.log(err) return res.status(500).json({ error: err }) } }
const express = require("express"); const fs = require("fs"); const parse = require("csv-parse"); const Max = require("max-api"); const app = express(); app.get("/sound/:id", (req, res) => { // res.header("Access-Control-Allow-Origin", "*"); // res.header( // "Access-Control-Allow-Headers", // "Origin, X-Requested-With, Content-Type, Accept" // ); const parser = parse({}, (_err, data) => { if (Max) Max.outlet({ [req.query.track]: data[req.params.id] }); res.sendStatus(200); }); fs.createReadStream(__dirname + "/data/sounds.csv").pipe(parser); }); app.listen(5000);
module.exports = { purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'], darkMode: false, // or 'media' or 'class' theme: { extend: { filter: { // defaults to {} 'none': 'none', 'grayscale': 'grayscale(1)', 'invert': 'invert(1)', 'sepia': 'sepia(1)', }, backdropFilter:['hover','focus'], // defaults to {} backgroundImage: theme => ({ 'first-half': "url('/src/components/images/firsthalf.jpg')", 'second-half': "url('/src/components/images/secondhalf.jpg')", }) }, }, variants: { filter: ['responsive'], // defaults to ['responsive'] backdropFilter: ['responsive'], // defaults to ['responsive'] extend: { borderWidth: ['hover', 'focus'], borderCollapse: ['hover', 'focus'], borderRadius: ['hover', 'focus'], backdropBlur: ['hover', 'focus'], filter: ['hover', 'focus'], borderColor: ['active'], }, }, plugins: [ require('tailwindcss-filters'),], }
import React, { Component } from 'react'; import Items from '../Items'; import Comments from '../Comments'; import IdGenerator from '../../libs/idGenerator'; import './Main.scss'; const idGenerator = new IdGenerator(); class Main extends Component { state = { items: [ { id: idGenerator.generate(), name: 'Test', comments: [ { id: '0-0', body: 'Test', color: 'black' } ] } ], activeItem: null }; componentWillMount() { const { items, activeItem } = this.state; const itemsFromStore = JSON.parse(window.localStorage.getItem('items')); const activeItemFromStore = JSON.parse(window.localStorage.getItem('activeItem')); if (itemsFromStore && itemsFromStore.length) { this.setState({ items: [...itemsFromStore], activeItem: { ...activeItemFromStore } }); } else { if (!activeItem && items && items[0]) { this.setActiveItem(items[0]); } } } componentDidUpdate() { const { items, activeItem } = this.state; window.onunload = () => { window.localStorage.setItem('items', JSON.stringify(items)); window.localStorage.setItem('activeItem', JSON.stringify(activeItem)); }; } setActiveItem = (item) => { this.setState({ activeItem: { ...item, comments: [ ...item.comments ] } }); } addNewItem = (name) => { const { items } = this.state; const item = { name, id: idGenerator.generate(), comments: [] }; if (!items.length) { this.setActiveItem(item); } this.setState({ items: [ ...items, item ] }); }; deleteItem = (item) => { const { items } = this.state; const newItems = items.filter(i => i.id !== item.id); this.setState({ items: [ ...newItems, ] }); if (newItems.length) { this.setActiveItem(newItems[newItems.length - 1]); } else { this.setState({ activeItem: null }); } }; addNewComment = (color, body) => { const { activeItem, items } = this.state; activeItem.comments.push({ id: `${activeItem.id}-${activeItem.comments.length}`, body, color }); for (let i = 0; i < items.length; i++) { if (items[i].id === activeItem.id) { items[i] = { ...activeItem }; break; } } this.setState({ items: [ ...items ], activeItem: { ...activeItem } }); }; render() { const { state: { items, activeItem }, addNewItem, setActiveItem, addNewComment, deleteItem } = this; return ( <main className="react-main container"> <div className="row justify-content-around"> <div className="col-xs-6"> <Items data={items} activeItem={activeItem} addNewItem={addNewItem} setActiveItem={setActiveItem} deleteItem={deleteItem} /> </div> <div className="col-xs-6"> <Comments data={activeItem} addNewComment={addNewComment} /> </div> </div> </main> ); } } export default Main;
import React, {Component} from 'react' import FormDetails from './FormDetails'; export class EmpForm extends Component{ state ={ step: 1, role: '', firstName: '', lastName: '', email: '', mobile: '', address: '' } //proceed to next step nextStep = () => { const {step} = this.state; this.setState({ step: step + 1 }); } //go back to prev step prevStep = () => { const {step} = this.state; this.setState({ step: step - 1 }); } //handle fields change handleChange = input => e => { this.setState({[input]: e.target.value}); } render(){ const {step} = this.state; const {role, firstName, lastName, email, mobile, address} = this.state; const values = {role, firstName, lastName, email, mobile, address} switch(step){ case 1: return( <FormDetails nextStep={this.nextStep} handleChange={this.handleChange} values={values} /> ) default: return <h1>form details</h1> } } } export default EmpForm;
import React, { useState } from "react"; function App() { const [expression, setExpression] = useState(""); const [answer, setAnswer] = useState(expression); function display(symbol) { // setExpression(prevValue => { // if(/[-]/.test(symbol) && /[+*/]/.test(prevValue[prevValue.length - 1])){ // setExpression(prevValue + symbol); // } else if(/[+*/]/.test(symbol) && /[+*/]/.test(prevValue[prevValue.length - 1])){ // let newValue = prevValue.slice(0, prevValue.length - 1) + symbol; // setExpression(newValue); // } else { // setExpression(prevValue + symbol); // } // }); setExpression((prevValue) => { if ( /[+*-/]/.test(symbol) && /[+*-/]/.test(prevValue[prevValue.length - 1]) ) { let newValue; if (/[-]/.test(symbol)) { newValue = prevValue.slice(0, prevValue.length) + symbol; } else { let count = 0; for (let i = 0; i < prevValue.length; i++) { if (isNaN(+prevValue[i])) { count++; } else { count = 0; } } newValue = prevValue.slice(0, prevValue.length - count) + symbol; } setExpression(newValue); } else { if (prevValue) { prevValue = prevValue + ""; let valArr = prevValue.split(/[+/*-]/g); console.log("valArr " + JSON.stringify(valArr)); let lastNumber = valArr[valArr.length - 1]; if (!isNaN(lastNumber) && /[.]/.test(lastNumber) && symbol === ".") { console.log("symbol = empty "); symbol = ""; } } setExpression( (prevValue + symbol).replace(/^0/g, "").replace(/\.+/g, ".") ); } }); setAnswer((prevValue) => (prevValue + symbol).replace(/^0/g, "").replace(/\.+/g, ".") ); } function calculate() { setAnswer(eval(expression)); setExpression(eval(expression)); } function allClear() { setExpression(""); setAnswer(0); } function clear() { setExpression((prev) => { setAnswer(0); console.log(prev); prev = prev + ""; return prev .split("") .slice(0, prev.length - 1) .join(""); }); } return ( <div className="container"> <div className="grid"> <div className="display"> <input class="expression" disabled placeholder="0" value={expression} ></input> <input id="display" className="answer" disabled value={answer} ></input> </div> <div onClick={allClear} className="padButton clear red" id="clear"> AC </div> <div onClick={clear} className="padButton c red" id="c"> C </div> <div onClick={() => display("/")} className="padButton divide" id="divide" > / </div> <div onClick={() => display("*")} className="padButton multiply" id="multiply" > * </div> <div onClick={() => display("7")} className="padButton seven dark-grey" id="seven" > 7 </div> <div onClick={() => display("8")} className="padButton eight dark-grey" id="eight" > 8 </div> <div onClick={() => display("9")} className="padButton nine dark-grey" id="nine" > 9 </div> <div onClick={() => display("-")} className="padButton subtract" id="subtract" > - </div> <div onClick={() => display("4")} className="padButton four dark-grey" id="four" > 4 </div> <div onClick={() => display("5")} className="padButton five dark-grey" id="five" > 5 </div> <div onClick={() => display("6")} className="padButton six dark-grey" id="six" > 6 </div> <div onClick={() => display("+")} className="padButton add" id="add"> + </div> <div onClick={() => display("1")} className="padButton one dark-grey" id="one" > 1 </div> <div onClick={() => display("2")} className="padButton two dark-grey" id="two" > 2 </div> <div onClick={() => display("3")} className="padButton three dark-grey" id="three" > 3 </div> <div onClick={calculate} className="padButton equals" id="equals"> = </div> <div onClick={() => display("0")} className="padButton zero dark-grey" id="zero" > 0 </div> <div onClick={() => display(".")} className="padButton decimal dark-grey" id="decimal" > . </div> </div> </div> ); } export default App;
import Component from '@ember/component'; export default class VeeakkerHomeMapComponent extends Component { classNames = ['veeakker-home-map__leaflet-map'] // Configuration of butchery location // (popup marker content is in the template) butcheryLat = 50.874007 butcheryLng = 4.689850 defaultZoom = 12 init() { super.init(...arguments); this.set('veeakkerButcheryLocation', [this.butcheryLat, this.butcheryLng]); } }
var Modeler = require("../Modeler.js"); var className = 'Typepicklist'; var Typepicklist = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { searchid: { type: "string", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "searchid", nillable: true, "s:annotation": { "s:documentation": "The unique GUID assigned to the CallML search" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 38 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, searchdate: { type: "string", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "searchdate", nillable: true, "s:annotation": { "s:documentation": "The date the search was carried out" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 20 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, applicant: { type: "Typepicklistapplicant", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "applicant", nillable: true, type: "tns:picklistapplicant", "s:annotation": { "s:documentation": "Input and matched name and address details for an applicant" } }, mask: Modeler.GET | Modeler.SET, required: false }, maxaddressitems: { type: "number", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "maxaddressitems", type: "s:int", "s:annotation": { "s:documentation": "Maximum number of address items" } }, mask: Modeler.GET | Modeler.SET, required: true }, maxnameitems: { type: "number", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "maxnameitems", type: "s:int", "s:annotation": { "s:documentation": "Maximum number of name items" } }, mask: Modeler.GET | Modeler.SET, required: true }, picklist: { type: "number", wsdlDefinition: { minOccurs: 1, maxOccurs: 1, name: "picklist", type: "s:int", "s:annotation": { "s:documentation": "Picklist" } }, mask: Modeler.GET | Modeler.SET, required: true } }, parentObj, json); }; module.exports = Typepicklist; Modeler.register(Typepicklist, "Typepicklist");
"use strict"; const range = document.querySelector("#font-size-slider"); const text = document.querySelector("#text"); range.addEventListener("input", elem => { const countFontSize = elem.currentTarget.value; text.style.fontSize = range.value + "px" });
// 1. Open the testcase, open Firebug, enable & select the Console panel. // 2. Click the Execute Test button. // 3. Scroll to top. // 4. Switch to the HTML panel. // 5. Click the Execute Test button. // 6. Switch back to Console tab // 7. The Console panel scroll position must be at the top. var theWindow; function runTest() { FBTest.openNewTab(basePath + "console/2122/issue2122.html", function() { FBTest.openFirebug(function() { FBTest.enableConsolePanel(function(win) { FBTest.selectPanel("console"); theWindow = win; var tests = []; tests.push(test0); tests.push(test1); tests.push(test2); tests.push(test3); FBTest.runTestSuite(tests, function() { FBTest.testDone(); }); }); }); }); } // ************************************************************************************************ // Test logic implementation. The entire test takes > 10 sec to execute so, there must be // some log/trace messages during the execution to break test-timeout. function test0(callback) { FBTest.progress("issue2122; Console panel selected, start logging."); executeTest(theWindow, function() { scrollToTop(); callback(); }); }; function test1(callback) { FBTest.progress("issue2122; Select HTML panel"); FBTest.selectPanel("html"); callback(); }; function test2(callback) { FBTest.progress("issue2122; HTML panel selected, start logging."); executeTest(theWindow, function() { FBTest.selectPanel("console"); callback(); }); } function test3(callback) { FBTest.progress("issue2122; Console panel selected, check scroll position."); FBTest.ok(isScrolledToTop(), "The Console panel must be scrolled to the top."); callback(); } // ************************************************************************************************ function executeTest(win, callback) { function listener(event) { testButton.removeEventListener("TestDone", listener, true); callback(); }; var testButton = win.document.getElementById("testButton"); testButton.addEventListener("TestDone", listener, true); FBTest.click(testButton); } // ************************************************************************************************ function isScrolledToTop() { var panel = FBTest.getPanel("console"); FBTest.progress("scrollTop: " + panel.panelNode.scrollTop); return (panel.panelNode.scrollTop == 0); } function scrollToBottom() { var panel = FBTest.getPanel("console"); return FW.FBL.scrollToBottom(panel.panelNode); } function scrollToTop() { var panel = FBTest.getPanel("console"); return panel.panelNode.scrollTop = 0; }
angular.module('starter.controllers', []) .controller('AppCtrl', function($scope, $cordovaPush, $cordovaDialogs, $cordovaMedia, $cordovaToast, ionPlatform, $http) { $scope.notifications = []; // call to register automatically upon device ready ionPlatform.ready.then(function (device) { $scope.register(); }); // Register $scope.register = function () { var config = null; if (ionic.Platform.isAndroid()) { config = { "senderID": "YOUR_GCM_PROJECT_ID" // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073 }; } else if (ionic.Platform.isIOS()) { config = { "badge": "true", "sound": "true", "alert": "true" } } $cordovaPush.register(config).then(function (result) { console.log("Register success " + result); $cordovaToast.showShortCenter('Registered for push notifications'); $scope.registerDisabled=true; // ** NOTE: Android regid result comes back in the pushNotificationReceived, only iOS returned here if (ionic.Platform.isIOS()) { $scope.regId = result; storeDeviceToken("ios"); } }, function (err) { console.log("Register error " + err) }); } // Notification Received $scope.$on('$cordovaPush:notificationReceived', function (event, notification) { console.log(JSON.stringify([notification])); if (ionic.Platform.isAndroid()) { handleAndroid(notification); } else if (ionic.Platform.isIOS()) { handleIOS(notification); $scope.$apply(function () { $scope.notifications.push(JSON.stringify(notification.alert)); }) } }); // Android Notification Received Handler function handleAndroid(notification) { // ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too // via the console fields as shown. console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if (notification.event == "registered") { $scope.regId = notification.regid; storeDeviceToken("android"); } else if (notification.event == "message") { $cordovaDialogs.alert(notification.message, "Push Notification Received"); $scope.$apply(function () { $scope.notifications.push(JSON.stringify(notification.message)); }) } else if (notification.event == "error") $cordovaDialogs.alert(notification.msg, "Push notification error event"); else $cordovaDialogs.alert(notification.event, "Push notification handler - Unprocessed Event"); } // IOS Notification Received Handler function handleIOS(notification) { // The app was already open but we'll still show the alert and sound the tone received this way. If you didn't check // for foreground here it would make a sound twice, once when received in background and upon opening it from clicking // the notification when this code runs (weird). if (notification.foreground == "1") { // Play custom audio if a sound specified. if (notification.sound) { var mediaSrc = $cordovaMedia.newMedia(notification.sound); mediaSrc.promise.then($cordovaMedia.play(mediaSrc.media)); } if (notification.body && notification.messageFrom) { $cordovaDialogs.alert(notification.body, notification.messageFrom); } else $cordovaDialogs.alert(notification.alert, "Push Notification Received"); if (notification.badge) { $cordovaPush.setBadgeNumber(notification.badge).then(function (result) { console.log("Set badge success " + result) }, function (err) { console.log("Set badge error " + err) }); } } // Otherwise it was received in the background and reopened from the push notification. Badge is automatically cleared // in this case. You probably wouldn't be displaying anything at this point, this is here to show that you can process // the data in this situation. else { if (notification.body && notification.messageFrom) { $cordovaDialogs.alert(notification.body, "(RECEIVED WHEN APP IN BACKGROUND) " + notification.messageFrom); } else $cordovaDialogs.alert(notification.alert, "(RECEIVED WHEN APP IN BACKGROUND) Push Notification Received"); } } // Stores the device token in a db using node-pushserver (running locally in this case) // // type: Platform type (ios, android etc) function storeDeviceToken(type) { // Create a random userid to store with it var user = { user: 'user' + Math.floor((Math.random() * 10000000) + 1), type: type, token: $scope.regId }; console.log("Post token for registered device with data " + JSON.stringify(user)); $http.post('http://192.168.1.16:8000/subscribe', JSON.stringify(user)) .success(function (data, status) { console.log("Token stored, device is successfully subscribed to receive push notifications."); }) .error(function (data, status) { console.log("Error storing device token." + data + " " + status) } ); } // Removes the device token from the db via node-pushserver API unsubscribe (running locally in this case). // If you registered the same device with different userids, *ALL* will be removed. (It's recommended to register each // time the app opens which this currently does. However in many cases you will always receive the same device token as // previously so multiple userids will be created with the same token unless you add code to check). function removeDeviceToken() { var tkn = {"token": $scope.regId}; $http.post('http://192.168.1.16:8000/unsubscribe', JSON.stringify(tkn)) .success(function (data, status) { console.log("Token removed, device is successfully unsubscribed and will not receive push notifications."); }) .error(function (data, status) { console.log("Error removing device token." + data + " " + status) } ); } // Unregister - Unregister your device token from APNS or GCM // Not recommended: See http://developer.android.com/google/gcm/adv.html#unreg-why // and https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/unregisterForRemoteNotifications // // ** Instead, just remove the device token from your db and stop sending notifications ** $scope.unregister = function () { console.log("Unregister called"); removeDeviceToken(); $scope.registerDisabled=false; //need to define options here, not sure what that needs to be but this is not recommended anyway // $cordovaPush.unregister(options).then(function(result) { // console.log("Unregister success " + result);// // }, function(err) { // console.log("Unregister error " + err) // }); } }) .controller('MediaCtrl', function($scope, $ionicModal) { $scope.ambienteImages = [{ 'src' : 'img/logo.png' }, { 'src' : 'img/paco.png' }, { 'src' : 'img/rsz_1ambiente.png' }, { 'src' : 'img/rsz_2ambiente.png' }]; $scope.pratosImages = [{ 'src' : 'img/rsz_entrada.png' }, { 'src' : 'img/salmao.png' }, { 'src' : 'img/sobremesa.png' }]; $scope.showImages1 = function(index) { $scope.activeSlide = index; $scope.showModal('templates/image-popover1.html'); } $scope.showImages2 = function(index) { $scope.activeSlide = index; $scope.showModal('templates/image-popover2.html'); } $scope.showModal = function(templateUrl) { $ionicModal.fromTemplateUrl(templateUrl, { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; $scope.modal.show(); }); } // Close the modal $scope.closeModal = function() { $scope.modal.hide(); $scope.modal.remove() }; $scope.clipSrc = 'img/coffee.MOV'; $scope.playVideo = function() { $scope.showModal('templates/video-popover.html'); } }) .controller('DashCtrl', function($scope) { $scope.message = "Hi"; //console.log($scope.sampleData); }) .controller('LaDouaneCtrl', function($scope) {}) .controller('ChatsCtrl', function($scope, $ionicPopup, Chats) { $scope.chats = Chats.all(); $scope.remove = function(chat) { Chats.remove(chat); } $scope.showAlert = function () { alert("popup-template.html"); } $scope.showDetailPage = function () { // An elaborate, custom popup var myPopup = $ionicPopup.show({ templateUrl : 'templates/detailPage.html', scope: $scope, buttons: [ { text: '<b>Ok</b>', type: 'button-positive', onTap: function(e) { //alert($scope.contactMessage); return 'ok button' } } ] }); } }) .controller('ChatDetailCtrl', function($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); }) .controller('AccountCtrl', function($scope,$cordovaOauth,$cordovaSocialSharing) { $scope.settings = { enableFriends: true }; // $scope.facebook= function() { // $cordovaOauth.facebook("1667249886831540", ["mgmm@ecomp.poli.br"]).then(function(result) { // // results // console.log("success"); // }, function(error) { // console.log(error); // // error // }); // } // $scope.facebook1=function(){ // $cordovaSocialSharing // .share("hello", null, null, null) // Share via native share sheet // .then(function(result) { // // Success! // }, function(err) { // // An error occured. Show a message to the user // }); // } }) .controller('MenuCtrl', function($scope) { $scope.showAlert() = function () { alert("hello"); }; }) .controller('MapCtrl', function($scope, $ionicLoading, $compile) { function initialize() { var myLatlng = new google.maps.LatLng(-8.065752, -34.873039); var mapOptions = { center: myLatlng, zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), mapOptions); //Marker + infowindow + angularjs compiled ng-click var contentString = "<div><a ng-click='clickTest()'>La Douane</a></div>"; var compiled = $compile(contentString)($scope); var infowindow = new google.maps.InfoWindow({ content: compiled[0] }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Uluru (Ayers Rock)' }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); $scope.map = map; } // function route(pos.coords.latitude, pos.coords.longitude) { // var site = new google.maps.LatLng(-8.065752, -34.873039); // var hospital = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); // var mapOptions = { // streetViewControl:true, // center: site, // zoom: 18, // mapTypeId: google.maps.MapTypeId.TERRAIN // }; // var map = new google.maps.Map(document.getElementById("map"), // mapOptions); // //Marker + infowindow + angularjs compiled ng-click // var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>"; // var compiled = $compile(contentString)($scope); // var infowindow = new google.maps.InfoWindow({ // content: compiled[0] // }); // var marker = new google.maps.Marker({ // position: site, // map: map, // title: 'Strathblane (Job Location)' // }); // var hospitalRoute = new google.maps.Marker({ // position: hospital, // map: map, // title: 'Hospital (Stobhill)' // }); // var infowindow = new google.maps.InfoWindow({ // content:"Project Location" // }); // infowindow.open(map,marker); // var hospitalwindow = new google.maps.InfoWindow({ // content:"Nearest Hospital" // }); // hospitalwindow.open(map,hospitalRoute); // google.maps.event.addListener(marker, 'click', function() { // infowindow.open(map,marker); // }); // $scope.map = map; // var directionsService = new google.maps.DirectionsService(); // var directionsDisplay = new google.maps.DirectionsRenderer(); // var request = { // origin : site, // destination : hospital, // travelMode : google.maps.TravelMode.DRIVING // }; // directionsService.route(request, function(response, status) { // if (status == google.maps.DirectionsStatus.OK) { // directionsDisplay.setDirections(response); // } // }); // directionsDisplay.setMap(map); // } google.maps.event.addDomListener(window, 'load', initialize); $scope.centerOnMe = function() { if(!$scope.map) { return; } $scope.loading = $ionicLoading.show({ content: 'Getting current location...', showBackdrop: false }); navigator.geolocation.getCurrentPosition(function(pos) { $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); $scope.loading.hide(); // $scope.route = route; // var contentString = "<div><a ng-click='clickTest()'>Me</a></div>"; // var compiled = $compile(contentString)($scope); }, function(error) { alert('Unable to get location: ' + error.message); }); }; $scope.clickTest = function() { alert('Example of infowindow with ng-click'); }; }); // .controller('MapCtrl', function($scope, $ionicLoading, $compile) { // function initialize() { // var myLatlng = new google.maps.LatLng(-8.0578381,-34.88289689999999); // var mapOptions = { // center: myLatlng, // zoom: 16, // mapTypeId: google.maps.MapTypeId.ROADMAP // }; // var map = new google.maps.Map(document.getElementById("map"), // mapOptions); // //Marker + infowindow + angularjs compiled ng-click // var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>"; // var compiled = $compile(contentString)($scope); // var infowindow = new google.maps.InfoWindow({ // content: compiled[0] // }); // var marker = new google.maps.Marker({ // position: myLatlng, // map: map, // title: 'Uluru (Ayers Rock)' // }); // google.maps.event.addListener(marker, 'click', function() { // infowindow.open(map,marker); // }); // $scope.map = map; // } // google.maps.event.addDomListener(window, 'load', initialize); // $scope.centerOnMe = function() { // if(!$scope.map) { // return; // } // $scope.loading = $ionicLoading.show({ // content: 'Getting current location...', // showBackdrop: false // }); // navigator.geolocation.getCurrentPosition(function(pos) { // $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); // $scope.loading.hide(); // }, function(error) { // alert('Unable to get location: ' + error.message); // }); // }; // $scope.clickTest = function() { // alert('Example of infowindow with ng-click') // }; // }); // .controller('MarkerRemoveCtrl', function($scope, $ionicLoading) { // $scope.positions = [{ // lat: -8.0578381, // lng: -34.88289689999999 // }]; // $scope.$on('mapInitialized', function(event, map) { // $scope.map = map; // }); // $scope.centerOnMe= function(){ // $scope.positions = []; // $ionicLoading.show({ // template: 'Loading...' // }); // navigator.geolocation.getCurrentPosition(function(position) { // var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // $scope.positions.push({lat: pos.k,lng: pos.B}); // console.log(pos); // $scope.map.setCenter(pos); // $ionicLoading.hide(); // }); // }); // .controller('PopupCtrl',function($scope, $ionicPopup, $timeout) { // // Triggered on a button click, or some other target // $scope.showPopup = function() { // $scope.data = {} // // An elaborate, custom popup // var myPopup = $ionicPopup.show({ // title: 'Details', // subTitle: 'each detail', // scope: $scope, // buttons: [ // { // text: '<b>OK</b>', // type: 'button-positive', // onTap: function(e) { // } // } // ] // }); // myPopup.then(function(res) { // console.log('Tapped!', res); // }); // $timeout(function() { // myPopup.close(); //close the popup after 3 seconds for some reason // }, 3000); // };
export default { en: { result_for: "result for", about_the: "about the", completion_time: 'completion time', participant: 'participant', seconds: 'seconds', filter: { title: 'filter', help: 'the filter is applied to all sections below', hint_click_answers: 'you can also click on any answer which then filters by all participants which have answered equal', actions: { select_all: 'select all', invert_filter: 'invert filter' } }, summary: { title: 'summary', event: 'event', questionnaire_open: 'questionnaire open', questions_asked: 'questions asked', participants: 'participants', completion_rate: 'completion rate', average_completion_time: 'average completion time', }, slider: { average: 'average over {response_count} responses' } } }
import { mount } from "@vue/test-utils"; import tableGrid from '../../../src/components/index/table/TableGrid'; describe('TableGrid.vue', () => { const wrapper = mount(tableGrid); test('if tableGrid default grid max size is 10x10', () => { expect(wrapper.vm.$data.gridSize.max.x).toBe(10); expect(wrapper.vm.$data.gridSize.max.y).toBe(10); }); test('if bind proper class after mouseover', async () => { wrapper.setData({ gridSize: { max: { x: 10, y: 10 }, hovered: { x: 1, y: 1 }, selected: { x: 0, y: 0 } } }); expect( wrapper .find('.table-grid__grid-col--hover') .classes('table-grid__grid-col--hover') ).toBe(true); }); test('if it hide after choosing grid', () => { wrapper.setData({ show: false }); expect(wrapper.find('.table-grid').classes()).toContain('table-grid__collapsed') }); test('if event emitter work', () => { wrapper.vm.$emit('generate::table', {x: 1, y: 1}) expect(wrapper.emitted()).toBeTruthy() }); });
import React, { useState, useEffect } from 'react'; import moment from 'moment'; import getMoon from './helpers/moon.js' import './Moon.css'; function Moon(props) { const [moon, setMoon] = useState(); const [loading, setLoading] = useState(true); useEffect(() => { getMoon(props.size, (moon, success) => { if(success) { setMoon(moon) setLoading(false) if (props.popup && props.moonLoaded) { props.moonLoaded(); } } }) }) if (loading) { return <div className="moon-load" /> } const today = new Date(); const day = today.getDate(); const thumbSvg = moon.phase[day].svg.replace(`<a xlink:href="http://www.icalendar37.net/lunar/app/" target="_blank">`, '').replace('</a>', ''); return ( <> { props.desktop && <div className="moon"> <div>{moment(today).format('dddd')}</div> <div>{moment(today).format('DD MMMM YYYY')}</div> <div className="moon-image" dangerouslySetInnerHTML={{ __html: moon.phase[day].svg }}></div> <div>{moon.phase[day].phaseName + " "+ Math.round(moon.phase[day].lighting) + "%"}</div> </div> } { props.thumbnail && <div className="moon-mobile-menu" onClick={() => props.toggleMoonPopup(true)} dangerouslySetInnerHTML={{ __html: thumbSvg }}></div> } { props.popup && <div> <h1 className="moon-popup-text">{moment(today).format('dddd')}</h1> <h1 className="moon-popup-text">{moment(today).format('DD MMMM YYYY')}</h1> <div className="moon-image" dangerouslySetInnerHTML={{ __html: moon.phase[day].svg }}></div> <h1 className="moon-popup-text">{moon.phase[day].phaseName + " "+ Math.round(moon.phase[day].lighting) + "%"}</h1> </div> } </> ) } export default Moon;
import React from 'react'; import {StyleSheet, TouchableOpacity, View} from 'react-native'; import NrmIcon from '../NrmIcon'; export const HeaderIcon = ({onPress, ...props}) => ( <TouchableOpacity onPress={onPress}> <View style={styles.container}> <NrmIcon {...props} /> </View> </TouchableOpacity> ); const styles = StyleSheet.create({ container: { marginHorizontal: 16, }, });
export default function Pelicula(props) { return ( <div className="movie-item-style-2"> <img src="images/uploads/mv1.jpg" alt="" /> <div class="mv-item-infor"> <h6> <a href="moviesingle.html">{props.titulo}</a> </h6> <p class="rate"> <i class="ion-android-star"></i> <span>{props.calificacion}</span> /10 </p> <p class="describe"> { props.children } </p> <p class="run-time"> Duracion: {props.duracion}’.<span>MMPA: PG-13 </span>. <span>Fecha: { props.fecha }</span> </p> <p> Director: <a href="#">Joss Whedon</a> </p> <p> Actores: { props.actores } </p> </div> </div> ); }
/** * Load user controller functions */ const userController = require('./controllers/user.controller'); module.exports = function(app, passport){ /** * Get route for index page */ app.get('/', function(req, res){ res.render('pages/index',{ isAuthenticated: req.isAuthenticated(), user: req.user }); }); /** * Get route for profile page */ app.get('/profile', isLoggedIn, function(req, res){ res.render('pages/user/profile',{ errors: req.flash('errors'), messages: req.flash('messages'), user: req.user }); }); /** * Get route for user logout */ app.get('/logout', userController.userLogout); /** * Get route for user login page */ app.get('/login', userController.showLogin); /** * Post route for user login page */ app.post('/login', passport.authenticate('local-login', { successRedirect: '/', failureRedirect: '/login', failureFlash: true })); /** * Get route for user registration page */ app.get('/signup', userController.showRegister); /** * Post route for user registration page */ app.post('/signup', passport.authenticate('local-signup', { successRedirect : '/', failureRedirect : '/signup', failureFlash : true })); /** * Get route for forgot password page */ app.get('/forgot', userController.showForgot); /** * Post route for forgot password page - user enters his email address */ app.post('/forgot', userController.processForgot); /** * Get route for user reset password page */ app.get('/reset/:token', userController.getReset); /** * Post route for user reset password page - user enters his new password */ app.post('/reset/:token', userController.processReset); /** * Post route for user profile page - user changes his information */ app.post('/profile/info', isLoggedIn, userController.updateInfo); /** * Post route for profile page - user deletes his account */ app.post('/profile/delete', isLoggedIn, userController.deleteUser); /** * Post route for profile page - user changes his password */ app.post('/profile/pass', isLoggedIn, userController.updatePass); }; /** * Function to verify if an user is authenticated */ function isLoggedIn(req, res, next){ if(req.isAuthenticated()){ return next(); } res.redirect('/'); }
import React, {Component} from 'react'; import { StyleSheet, Text, View, TouchableOpacity, TextInput, Image,ImageBackground } from 'react-native'; import firebase from 'firebase'; const firebaseConfig = { apiKey: "AIzaSyDb-MHYH3z8wtKf-oMqevKUAZRFQ2cg6xg", authDomain: "polybus-gps.firebaseapp.com", databaseURL: "https://polybus-gps.firebaseio.com", projectId: "polybus-gps", storageBucket: "", messagingSenderId: "942603006584", appId: "1:942603006584:web:0dbbdafa56c59063" } if (!firebase.apps.length) { firebase.initializeApp({firebaseConfig}); } export default class LoginScreen extends Component { static navigationOptions = { title: 'Student LogIn' } constructor(props) { super(props); this.state = {email:'',Password:'',loading:false}; } OnLoginPress() { this.setState({error:'',loading:true}); const{email, Password} = this.state; firebase.auth().signInWithEmailAndPassword(email,Password) .then(() => { this.setState({error:'',}); this.props.navigation.navigate('Student'); }) .catch(() =>{ this.setState({error:'Authentication Failed',loading:false}); }) } renderButtonOrLoading() { return ( <View style ={styles.btnContainer}> <TouchableOpacity style={styles.userBtn} onPress={this.OnLoginPress.bind(this)} > <Text style={styles.btnTxt}>Login</Text> </TouchableOpacity> <TouchableOpacity style={styles.userBtn} onPress={() => this.props.navigation.navigate('SignUp')} > <Text style={styles.btnTxt}>Sign Up</Text> </TouchableOpacity> </View> ) } render() { return ( <ImageBackground source={require('../assets/images/abs.jpg')} style={styles.backgroundcontainer}> <Image source = {require('../assets/images/student.png')} style={{width: 100, height:100}} > </Image> <View style={{position: 'absolute', left: 20, right: 0, top: 12, bottom: 0}}> </View> <Text style={{ fontSize: 30,textAlign: 'center',margin: 10,}}>Student Login</Text> <TextInput style={styles.input} value={this.state.email} placeholder="Email" onChangeText={email => this.setState({email})} /> <TextInput style={styles.input} value={this.state.Password} placeholder="Password" secureTextEntry onChangeText={Password => this.setState({Password})} /> <Text>{this.state.error}</Text> {this.renderButtonOrLoading()} </ImageBackground> ); } } const styles = StyleSheet.create({ backgroundcontainer: { flex: 1, height:null, width: null, alignItems: 'center', justifyContent: 'center', }, btnContainer: { flexDirection: "row", justifyContent: "space-between", width: "90%", }, userBtn: { backgroundColor: "#FFD700", padding: 15, width: "45%", borderRadius: 25, }, btnTxt: { fontSize: 18, textAlign: "center" }, input: { width: "90%", backgroundColor: "#fff", padding: 15, marginBottom: 10, borderRadius: 25, } });
import React from "react"; import { Link } from "@reach/router"; const LogInButton = props => { if (props.uri === "/log-in" || props.user) return null; return ( <Link path="/*" to="/log-in"> <button className="logInButton">Log in</button> </Link> ); }; export default LogInButton;
const mongoose = require('mongoose'); const connectDB = require('../connectdb'); const config = require('config'); const dateFormat = require('dateformat'); const Farm = require('../models/FarmSchema'); const farm = Farm.farmModel; const _AI = require('../controllers/ai-controller'); const AIurl = config.get('AIurl'); var today = new Date(); var current_date = dateFormat(today, 'isoDate').toString() + 'T' + dateFormat(today, 'isoTime').toString() + '.000Z'; var oneWeek = dateFormat(today.setDate(today.getDate() + 7), 'isoDate'); updateTimelineOrder(); async function updateTimelineOrder() { console.log('request update timeline order'); await connectDB.connect_db(); const farmID = await farm.find({}).select(['_id']); for (let i in farmID) { const farmData = await farm.find({ _id: farmID[i] }); console.log( '\nFarm ID : ', farmData[0]._id, ' Farm name : ', farmData[0].name, 'is updating timeline order' ); var nextday = ''; var timeline = [{}]; var newTimeline; let count = 0; if ( typeof farmData[0].timeline !== null && farmData[0].timeline.length > 1 && farmData[0].location.province !== null && farmData[0].activate !== 'end' ) { for (let j in farmData[0].timeline) { if (farmData[0].timeline[j].order !== 1) { var status = farmData[0].timeline[j].status; if (status == '3') { nextday = farmData[0].timeline[j].order; break; } } } for (let j in farmData[0].timeline) { if (farmData[0].timeline[j].order !== 1) { var status = farmData[0].timeline[j].status; if (status == '3' || status == '4') { (timeline[count] = farmData[0].timeline[j]), count++; } } } const old_timeline = { evalproduct: farmData[0].evalproduct, timeline, }; var province_id = farmData[0].location.province; var rice_id = farmData[0].varieties; var start_date = dateFormat(farmData[0].startDate, 'isoDate').toString() + 'T' + dateFormat(farmData[0].startDate, 'isoTime').toString() + '.000Z'; var next_day = nextday; var test_mode = 1; var test_data = 0; newTimeline = await _AI.update_tl( province_id, rice_id, start_date, current_date, next_day, JSON.stringify(old_timeline), test_mode, test_data ); var count1 = 0; var new_Timeline = [{}]; for (let j in farmData[0].timeline) { var status = farmData[0].timeline[j].status; if ( status == '1' || status == '2' || farmData[0].timeline[j].order == 1 ) { new_Timeline[count1] = farmData[0].timeline[j]; count1++; } } for (let j in newTimeline.timeline) { new_Timeline[count1] = newTimeline.timeline[j]; count1++; } var newEvalproduct = newTimeline.evalproduct; await farm.updateOne( { _id: farmData[0]._id }, { $pullAll: { timeline } } ); await farm .findOneAndUpdate( { _id: farmData[0]._id }, { $set: { evalproduct: newEvalproduct, timeline: new_Timeline, }, } ) .then( console.log( 'farm ID ', farmData[0]._id, 'have already updated timeline order\n' ) ); } else { console.log( 'farm ID ', farmData[0]._id, 'not found timeline order or farm location\n' ); } } mongoose.connection.close(); }
import React from "react"; import { navigate } from "@reach/router"; class EventoConvocatorias extends React.Component { constructor(props) { super(props); this.state = { pdfs: this.props.eventDetails.pdfs }; } goToEventDetails = eventKey => { navigate(`/convocatorias/${this.props.eventDetails.name}`, { state: { clave: this.props.indice } }); }; render() { return ( <ul> <button className="event-reduced" onClick={this.goToEventDetails}> <img className="event-image" src={this.props.eventDetails.image} alt="imagen" /> <p className="event-date"> {this.props.eventDetails.date_fin_convocatoria.substring(0, 10)} </p> <p className="event-name">{this.props.eventDetails.name}</p> </button> </ul> ); } } export default EventoConvocatorias;
import React from 'react' import BlogCard from './BlogCard' import Title from '../Title.styled' import styles from '../../css/blog.module.css' import { graphql, useStaticQuery } from 'gatsby' const getPost = graphql` { posts: allContentfulPost(sort: {fields: createdAt, order: DESC}) { edges { node { slug title published(formatString: "Do MMMM, YYYY", locale: "ro") createdAt(formatString: "LLLL", locale: "ro") id: contentful_id image { fluid { ...GatsbyContentfulFluid_tracedSVG } } } } totalCount } } ` const BlogList = () => { const { posts } = useStaticQuery(getPost) return ( <section className={styles.blog}> <Title title="our" subtitle="blogs" /> <div className={styles.center}> {posts.edges.map(({node}) => ( <BlogCard key={node.id} blog={node} /> ))} </div> </section> ) } export default BlogList
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require moment //= require bootstrap-datetimepicker //= require_tree . (function() { 'use strict'; $('.datetimepicker').datetimepicker(); var datestring = function() { $('.datestring').each(function() { this.textContent = moment(this.textContent).format('dddd DD/MM/YYYY'); }); }; var datetimestring = function() { $('.datetimestring').each(function() { this.textContent = moment(this.textContent).format('dddd DD/MM/YYYY - HH:mm'); }); }; var datepicker1 = function() { $('#datetimepicker1').datetimepicker({ locale: 'es', format: 'DD/MM/YYYY' }); } var datepicker2 = function() { $('#datetimepicker2').datetimepicker({ locale: 'es', format: 'DD/MM/YYYY' }); } var datepicker3 = function() { $('#datetimepicker3').datetimepicker({ locale: 'es', format: 'DD/MM/YYYY HH:mm' }); } $(document).ready(datestring); $(document).on('page:load', datestring); $(document).ready(datetimestring); $(document).on('page:load', datetimestring); $(document).ready(datepicker1); $(document).on('page:load', datepicker1); $(document).ready(datepicker2); $(document).on('page:load', datepicker2); $(document).ready(datepicker3); $(document).on('page:load', datepicker3); })();
import React, { Fragment } from 'react'; import { Segment, Grid, Button, Image, Header } from 'semantic-ui-react'; import { FlexContainer } from '@gstarrltd/fragmented'; import ContentCarousel from '../../components/ContentCarousel'; import styles from './Home.scss'; import ArtistCard from "../../components/Cards/artist"; const HomePageContent = props => (<Fragment> <ContentCarousel> <Grid columns={2} divided className={styles.carouselContent}> <Grid.Row stretched> <Grid.Column > <Segment style={{ overflow: 'hidden' }}> <Image rounded fluid src="assets/images/wireframe/placeholder-dj.jpg" /> </Segment> </Grid.Column> <Grid.Column> <Segment style={{ overflow: 'hidden' }}> <Image rounded fluid src="assets/images/wireframe/placeholder-dj.jpg" /> </Segment> <Segment style={{ overflow: 'hidden' }}> <Image rounded fluid src="assets/images/wireframe/placeholder-dj.jpg" /> </Segment> </Grid.Column> </Grid.Row> </Grid> <div className={styles.carouselContent}> Hello </div> </ContentCarousel> </Fragment>); export default HomePageContent;
const get_new_car = () => { return { city: 'Toronto', passengers: 0, gas: 100 } } const add_car = (cars, new_car) => { cars.push(new_car) return `Adding new car to fleet. Fleet size is now ${cars.length}.` } const pick_up_passenger = car => { car['passengers'] += 1 car['gas'] -= 10 return `Picked up passenger. Car now has ${car['passengers']} passengers.` } const get_destination = car => { if (car['city'] === 'Toronto') { return 'Mississauga' } if (car['city'] === 'Mississauga') { return 'London' } if (car['city'] === 'London') { return 'Toronto' } } const fill_up_gas = car => { const old_gas = car['gas'] car['gas'] = 100 return `Filled up to ${get_gas_display( car['gas'] )} on gas from ${get_gas_display(old_gas)}.` } const get_gas_display = gas_amount => { return `${gas_amount}%` } const drive = (car, city_distance) => { if (car['gas'] < city_distance) { return fill_up_gas(car) } car['city'] = get_destination(car) car['gas'] -= city_distance return `Drove to ${car['city']}. Remaining gas: ${get_gas_display( car['gas'] )}.` } const drop_off_passengers = car => { const previous_passengers = car['passengers'] car['passengers'] = 0 return `Dropped off ${previous_passengers} passengers.` } const act = car => { const distance_between_cities = 50 if (car['gas'] < 20) { return fill_up_gas(car) } if (car['passengers'] < 3) { return pick_up_passenger(car) } if (car['gas'] < distance_between_cities) { return fill_up_gas(car) } const drove_to = drive(car, distance_between_cities) const passengers_dropped = drop_off_passengers(car) return `${drove_to} ${passengers_dropped}` } const command_fleet = cars => { let i = 1 cars.forEach(car => { let action = act(car) console.log(`Car ${i}: ${action}`) i += 1 }) console.log('---') } const add_one_car_per_day = (cars, num_days) => { for (let day = 0; day < num_days; day++) { let new_car = get_new_car() console.log(add_car(cars, new_car)) command_fleet(cars) } } const cars = [] add_one_car_per_day(cars, 10)
/** * Created by xiaojiu on 2017/8/10. */ 'use strict'; define(['../../../app','../../../services/logistics/deliverPutStorageDispatchManage/orderDeliverService'], function (app) { var app = angular.module('app'); app.controller('orderDeliverCtrl',['$rootScope','$scope','$state','$sce','$stateParams','orderDeliver', '$window', function ($rootScope,$scope,$state,$sce,$stateParams,orderDeliver,$window) { $scope.querySeting = { items: [ { type: 'text', model: 'taskId', title: '条码' ,autofocus:true}, ], btns: [ { text: $sce.trustAsHtml('查询'), click: 'searchClick' }] }; //table头 $scope.thHeader = orderDeliver.getThead(); //分页下拉框 $scope.pagingSelect = [ {value: 5, text: 5}, {value: 10, text: 10, selected: true}, {value: 20, text: 20}, {value: 30, text: 30}, {value: 50, text: 50} ]; //分页对象 $scope.paging = { totalPage: 1, currentPage: 1, showRows: 30, }; var pmsSearch = orderDeliver.getSearch(); pmsSearch.then(function (data) { $scope.searchModel = data.query; //设置当前作用域的查询对象 //获取table数据 get(); }, function (error) { console.log(error) }); //查询 $scope.searchClick = function () { $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows }; get(); } function get() { //获取选中 设置对象参数 var opts = angular.extend({}, $scope.searchModel, {}); //克隆出新的对象,防止影响scope中的对象 opts.pageNo = $scope.paging.currentPage; opts.pageSize = $scope.paging.showRows; var promise = orderDeliver.getDataTable( { param: { query: opts } } ); promise.then(function (data) { $scope.result = data.grid; $scope.newIndentModel.wlDeptNameSelect=data.query.wlDeptName; $scope.newIndentModel.deliveryWaySelect=data.query.deliveryWay; $scope.carrierNameList=data.query.carrierName; $scope.newIndentModel.wlDeptName=data.query.state; $scope.paging = { totalPage: data.total, currentPage: $scope.paging.currentPage, showRows: $scope.paging.showRows, };; }, function (error) { console.log(error); }); } //get(); //分页跳转回调 $scope.goToPage = function () { get(); } //发货model $scope.newIndentModel={ carrierName:'', wlDeptName:'', wlDeptNameSelect:'', deliveryWay:1, deliveryWaySelect:'', mobilePhone:'', carrierMan:'', thirdWlId:'', pay:'' } $scope.operationTitle="发货信息"; var ids=''; $scope.sendGoods=function(){ //获取选中 ids=''; angular.forEach($scope.result, function (item) { if (item.pl4GridCheckbox.checked) { ids+=item.id+','; } }); if(ids!='') { ids = ids.slice(0, ids.length - 1); $("#sendGoods").modal("show"); }else { alert('请选择需要发货的业务单!'); } } //输入框显示隐藏 $scope.isisWlDeptShow=function(){ $scope.newIndentModel.deliveryWay===1?$scope.isWlDeptShow=false:$scope.isWlDeptShow=true; } //模拟下拉自动补全 $scope.isShow =false; $scope.showListFun =function(){ $scope.isShow =!$scope.isShow; } $scope.listSelect = function(item){ $scope.isShow =!$scope.isShow; $scope.newIndentModel.carrierName=item.name; orderDeliver.confirmInCk({ param: { query:{ carrierName:item.name } } },'/vehicleParts/getCompInformation') .then(function(data){ if (data.status.code == "0000") { $scope.newIndentModel.carrierMan = data.query.carrierMan; $scope.newIndentModel.mobilePhone = data.query.mobilePhone; } }) } //确认发货 $scope.operationEnterAdd=function(){ var opts = angular.extend({}, $scope.newIndentModel, {}); delete opts.wlDeptNameSelect; delete opts.deliveryWaySelect; opts.ids = ids; orderDeliver.confirmInCk({ param: { query: opts } },$scope.newIndentModel.deliveryWay===1 ? '/vehicleParts/confirmDelivery' : '/vehicleParts/confirmTransit') .then(function (data) { if (data.status.code == "0000") { alert(data.status.msg); $('#sendGoods').modal('hide'); $scope.searchModel.taskId=''; } else{ alert(data.status.msg); $('#sendGoods').modal('hide'); } get(); ids=''; $scope.deleteData(); }) } //取消 $scope.deleteData=function(){ $scope.newIndentModel.carrierName=''; $scope.newIndentModel.mobilePhone=''; $scope.newIndentModel.carrierMan=''; $scope.newIndentModel.thirdWlId=''; } // 返回 $scope.goBack = function(){ $window.history.back(); } }]); });
var should = require("should"); var appRoot = "../../app/"; var Feature = require("../../app/core/feature"); var Device = require(appRoot + "/core/device"); var Layer = require(appRoot + "/core/layer"); //var Features = require(appRoot + '/core/features'); var Channel = Feature.getFeatureGenerator("Channel", "Basic"); var CircleValve = Feature.getFeatureGenerator("CircleValve", "Basic"); describe("Integration", function() { describe("#core", function() { it("Create a device, add layers and features, toJSON, fromJSON", function() { let dev = new Device( { width: 60, height: 30 }, "My Device" ); let flow = new Layer( { z_offset: 0, flip: false }, "flow" ); let control = new Layer( { z_offset: 1.2, flip: true }, "control" ); dev.addLayer(flow); dev.addLayer(control); let chan1 = new Channel({ start: [0, 0], end: [10, 10] }); console.log(chan1); flow.addFeature(chan1); let valve1 = new CircleValve({ position: [5, 5] }); control.addFeature(valve1); let devJSON = dev.toJSON(); let newDev = Device.fromJSON(devJSON); }); }); });
exports.run=(bot,msg,params=[])=>{ var random=Math.floor(Math.random()*6); //random number generator(0 to 5) if (random==0){ msg.channel.send('To die alone.'); } else if (random==1) { msg.channel.send('あなたはちんちんを食べたい'); } else if (random==2){ msg.channel.send('To be granted immortality and be permanently constipated.'); } else if (random==3){ msg.channel.send("Well, let's just say 'good luck'"); } else if (random==4){ msg.channel.send("You'll probablly be ok today; I guess."); } else if (random==5){ msg.channel.send('To take a endless standardized test for eternity.'); } }//end of run exports.conf={ enabled:true, aliases:[], permLevel:0 } exports.help={ name:"MY FATE", description: "Discover your future through an arbitrary random number generator.", usage: "MY FATE" }
/* Given a circular linked list, implement an algorithm which returns node at the begin- ning of the loop DEFINITION Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list EXAMPLE input: A -> B -> C -> D -> E -> C [the same C as earlier] output: C */ module.exports = function(list) { var current = list.head , index = 0 while (current) { var tmp = list.head , tmpIndex = 0 while (tmp && (tmpIndex < index)) { if (current === tmp) { return tmp } tmpIndex++ tmp = tmp.next } index++ current = current.next } return null }