text
stringlengths
7
3.69M
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {setFilterSettingsOpen, setActiveFilter, setActiveSort} from '../redux/actions'; import style from './filters.scss'; class Filters extends Component { render() { const {open, onSetFilterSettingsOpen, activeFilter, activeSort} = this.props; return ( <div className={`${style.view} ${open ? style['is-open'] : ''}`} > <div className={style.backdrop} onClick={() => onSetFilterSettingsOpen(false)} /> <ul className={style.menu}> <li onClick={this.handleSetActiveFilter.bind(this, 0)} className={`${activeFilter === 0 ? style.active : ''}`}>Show All</li> <li onClick={this.handleSetActiveFilter.bind(this, 1)} className={`${activeFilter === 1 ? style.active : ''}`}>Show Listen</li> <li onClick={this.handleSetActiveFilter.bind(this, 2)} className={`${activeFilter === 2 ? style.active : ''}`}>Show Buy</li> <li className={style.sep} /> <li className={`${style.sort} ${activeSort === 0 ? style.active : ''}`} onClick={this.handleSetActiveSort.bind(this, 0)}>Sort by Added At</li> <li className={`${style.sort} ${activeSort === 1 ? style.active : ''}`} onClick={this.handleSetActiveSort.bind(this, 1)}>Sort by Artist</li> <li className={`${style.sort} ${activeSort === 2 ? style.active : ''}`} onClick={this.handleSetActiveSort.bind(this, 2)}>Sort by Album Title</li> </ul> </div> ) } handleSetActiveFilter(filter) { const {onSetActiveFilter, onSetFilterSettingsOpen} = this.props; onSetActiveFilter(filter) setTimeout(() => { onSetFilterSettingsOpen(false); }, 100) } handleSetActiveSort(sort) { const { onSetActiveSort } = this.props; onSetActiveSort(sort) } } const mapState = state => ({ open: state.filters.open, activeFilter: state.filters.activeFilter, activeSort: state.filters.activeSort, }) const mapDispatch= dispatch => ({ onSetFilterSettingsOpen(open) { dispatch(setFilterSettingsOpen(open)) }, onSetActiveFilter(filter) { dispatch(setActiveFilter(filter)) }, onSetActiveSort(sort) { dispatch(setActiveSort(sort)) } }) export default connect(mapState, mapDispatch)(Filters);
import React, { Component } from "react"; import PropTypes from "prop-types"; import {connect} from "react-redux"; import CourseAddButton from "./CourseAddButton" import { getCourses, getUserCourses } from "../../actions/eduActions"; class Landing extends Component { static propTypes = { authenticated: PropTypes.bool, getUserCourses: PropTypes.func.isRequired, getCourses: PropTypes.func.isRequired, courses: PropTypes.array, }; componentDidMount = () => { this.props.getUserCourses(); this.props.getCourses(); }; renderCourses = () => { const courses = this.props.courses; return ( courses ? <div className="container"> {courses.map(item => ( <div className="card-transparent m-4" key={item.id}> <div className="card-body"> <h5 className="card-title"><strong>{item.title}</strong> ({item.price} $)</h5> <p>{item.description}</p> <CourseAddButton item={item}/> </div> </div> ))} </div> : null ); }; renderLanding = () => { if (this.props.authenticated) { if (this.props.courses) { return ( <div> <h1>Welcome to the main page!</h1> {this.renderCourses()} </div> ); } else { return ( <div> <h1>Welcome to the main page!</h1> <p>please, logout and sign in again</p> </div> ); } } else { return ( <h1>You need to Log In or Sign Up</h1> ); } }; render = () => { return ( <div className="text-center"> {this.renderLanding()} </div> ) } } const mapStateToProps = (state) => { return { authenticated: state.auth.authenticated, courses: state.edu.courses, } }; export default connect(mapStateToProps, { getUserCourses, getCourses } )(Landing);
console.log("Webpack Wizardd")
var app = getApp(); import util from '../../utils/util.js'; Page({ data: { windowHeight: 0, hidden: true, hasMore: false, tabs: [{ name: "全部", id: '' }, { name: "待接单", id: 'taking' }, { name: "待发货", id: 'preparing' }, { name: "待收货", id: 'receiving' }, { name: "退换/售后", id: 'reject' }], activeIndex: '', sliderOffset: 0, sliderLeft: 0, tabWidth: 0, sizePage: 1, orderData: [], rejectData:[], clientX: 0, clientY: 0, startTime: 0, startOffsetTop: 0, top: 0, }, onLoad: function (options) { console.log(options); wx.setNavigationBarTitle({ title: '我是买家' }); var that = this; this.data.orderType = options.type; if (options.status == null) { this.setData({ activeIndex: this.data.activeIndex, }) } else { this.setData({ activeIndex: options.status, }) } var i = 0; this.data.tabs.filter(function (item, index) { if (that.data.activeIndex == item.id) { return i = index } }) wx.getSystemInfo({ success: function (res) { that.setData({ windowHeight: res.windowHeight, sliderLeft: (res.windowWidth / that.data.tabs.length - res.windowWidth / that.data.tabs.length) / 2, sliderOffset: res.windowWidth / that.data.tabs.length * i, tabWidth: res.windowWidth / that.data.tabs.length }); } }); }, tabClick: function (e) {//切换 this.setData({ sliderOffset: e.currentTarget.offsetLeft, activeIndex: e.currentTarget.dataset.id, hasMore: true, top: 0 }); this.data.sizePage = 1; if (this.data.activeIndex == 'reject') { this.orderReturn(); } else { this.orderList(); } }, onReady: function () { // }, onShow: function () { // 页面显示 this.data.sizePage = 1; if (this.data.activeIndex == 'reject') { this.orderReturn(); } else { this.orderList(); } }, onHide: function () { // 页面隐藏 }, onUnload: function () { // 页面关闭 wx.switchTab({ url: '../homePage/homePage', }) }, orderReturn: function () { wx.showLoading({ title: '加载中', }) var that = this; var data = { page: this.data.sizePage, page_size: 10, Module: this.data.orderType } app.netWork.postJson(app.urlConfig.orderReturnUrl, data).then(res => { if (res.errorNo == '0') { that.setData({ rejectData: res.data }); wx.hideLoading(); if (res.total <= 10 || res.total == 0) { that.setData({ hasMore: false, }); } else { that.setData({ hasMore: true, }); } } }).catch(res => { console.log("订单列表失败") }) }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { this.data.sizePage = 1; wx.showLoading({ title: '加载中', }) var that = this; if (this.data.activeIndex == 'reject') { var data = { page: this.data.sizePage, page_size: 10, Module: this.data.orderType } app.netWork.postJson(app.urlConfig.orderReturnUrl, data).then(res => { if (res.errorNo == '0') { that.setData({ rejectData: res.data }); if (res.total <= 10 || res.total == 0) { that.setData({ hasMore: false, }); } else { that.setData({ hasMore: true, }); } } wx.hideLoading(); wx.stopPullDownRefresh(); }).catch(res => { // console.log("订单列表失败") }) } else { var data = { page: this.data.sizePage, page_size: 10, composite_status: this.data.activeIndex, Module: this.data.orderType } app.netWork.postJson(app.urlConfig.orderinfoListUrl, data).then(res => { if (res.errorNo == '0') { that.setData({ orderData: res.data }); if (res.total <= 10 || res.total == 0) { that.setData({ hasMore: false, }); } else { that.setData({ hasMore: true, }); } } wx.hideLoading(); wx.stopPullDownRefresh(); }).catch(res => { // console.log("订单列表失败") }) } }, loadMore: function (e) { //加载更多 if (!this.data.hasMore) return this.data.sizePage++; wx.showLoading({ title: '加载中', }) // var that = this; if (this.data.activeIndex == 'reject') { var data = { page: parseInt(this.data.sizePage), page_size: 10, Module: this.data.orderType } var allArr = []; app.netWork.postJson(app.urlConfig.orderReturnUrl, data).then(res => { if (res.errorNo == '0') { wx.hideLoading(); allArr = that.data.rejectData.concat(res.data); that.setData({ rejectData: allArr }); if (that.data.rejectData.length ==res.total) { that.setData({ hasMore: false, }); } } }).catch(res => { wx.hideLoading(); console.log("订单列表失败") }) }else{ var data = { page: parseInt(this.data.sizePage), page_size: 10, composite_status: this.data.activeIndex, Module: this.data.orderType } var allArr = []; app.netWork.postJson(app.urlConfig.orderinfoListUrl, data).then(res => { if (res.errorNo == '0') { wx.hideLoading(); allArr = that.data.orderData.concat(res.data); that.setData({ orderData: allArr }); if (that.data.orderData.length ==res.total) { that.setData({ hasMore: false, }); } } }).catch(res => { wx.hideLoading(); console.log("订单列表失败") }) } }, orderList: function () {//订单列表 wx.showLoading({ title: '加载中', }) var that = this; var data = { page: this.data.sizePage, page_size: 10, composite_status: this.data.activeIndex, Module: this.data.orderType } app.netWork.postJson(app.urlConfig.orderinfoListUrl, data).then(res => { if (res.errorNo == '0') { that.setData({ orderData: res.data }); wx.hideLoading(); if (res.total <= 10 || res.total == 0) { that.setData({ hasMore: false, }); } else { that.setData({ hasMore: true, }); } } }).catch(res => { console.log("订单列表失败") }) }, orderTaking: function (e) {//订单下按钮的状态 var action = e.currentTarget.dataset.value.act; var _this = this; var data = { order_sn: e.currentTarget.dataset.orderid, act: action, Module: this.data.orderType, } if (action == 'confirm') {//买家 待审核 app.netWork.postJson(app.urlConfig.orderApproveUrl, data).then(res => { if (res.errorNo == '0') { wx.showToast({ title: res.errorMsg, icon: 'success', duration: 2000, mask: true, success: function () { _this.orderList() } }) } else { wx.showToast({ title: res.errorMsg, icon: 'none', duration: 2000, mask: true }) } }) } else if (action == 'cancel') {//买家 取消订单 wx.showModal({ title: '取消订单确认', content: '您确认要取消订单吗?', confirmText: '确认取消', success: function (res) { if (res.confirm) { app.netWork.postJson(app.urlConfig.orderCancelUrl, data).then(res => { if (res.errorNo == '0') { wx.showToast({ title: res.errorMsg, icon: 'success', duration: 2000, mask: true, success: function () { _this.orderList() } }) } else { wx.showToast({ title: res.errorMsg, icon: 'none', duration: 2000, mask: true }) } }) } else if (res.cancel) { console.log('用户点击取消') } } }) } else if (action == 'receiveAll') {//买家--确认收货操作 wx.showModal({ title: '整单确认', content: '整单确认表示您确认收到的货品与卖家发出的数量完全一致,请谨慎操作,如部分产品不一致,请执行单个产品认。', confirmText: '整单确认', success: function (res) { if (res.confirm) { data.son_ordersn = e.currentTarget.dataset.orderid; app.netWork.postJson(app.urlConfig.orderReceiveAllUrl, data).then(res => { // console.log(res) if (res.errorNo == '0') { wx.showToast({ title: res.errorMsg, icon: 'success', duration: 2000, mask: true, success: function () { _this.orderList() } }) } else { wx.showToast({ title: res.errorMsg, icon: 'none', duration: 2000, mask: true }) } }) } else if (res.cancel) { console.log('用户点击取消') } } }) } else if (action == 'receiveSec') {//买家---逐个确认收货 util.navTo({ url: '../partGetGoods/partGetGoods?orderId=' + e.currentTarget.dataset.orderid + '&Module=' + this.data.orderType + '&action=' + action, }) } else if (action == 'reject') {//买家--退货 util.navTo({ url: '../orderSingleDetail/orderSingleDetail?orderId=' + e.currentTarget.dataset.orderid + '&Module=' + this.data.orderType + '&action=' + action }) } else if (action == 'openagain') {//买家--再次下单 分为 卖家拒绝的 再次下单 和 已完成的再次下单 data.son_ordersn = e.currentTarget.dataset.orderid; app.netWork.postJson(app.urlConfig.orderAgainUrl, data).then(res => { if (res.errorNo == '0') { wx.showToast({ title: res.errorMsg, icon: 'success', duration: 2000, mask: true, success: function () { util.navTo({ url: '../shoppingCart/shoppingCart' }) } }) } else { wx.showToast({ title: res.errorMsg, icon: 'none', duration: 2000, mask: true }) } }) } }, goInfo: function (e) { util.navTo({ url: '../orderSingleDetail/orderSingleDetail?orderId=' + e.currentTarget.dataset.orderid + '&Module=' + this.data.orderType + '&action=', }) }, callPhone: function (e) {//拨打电话 wx.makePhoneCall({ phoneNumber: e.currentTarget.dataset.phone //仅为示例,并非真实的电话号码 }) }, goReturn: function (e) {//退货详情 // util.navTo({ // url: '../returnGoods/returnGoods?Module=' + this.data.Module + '&item=' + JSON.stringify(e.currentTarget.dataset.item) // }) util.navTo({ url: '../returnGoods/returnGoods?Module=' + this.data.orderType + '&item=' + JSON.stringify(e.currentTarget.dataset.item) }) } })
import { parse } from 'react-docgen' import getPermutations from './get-permutations' export default function (src, opts) { opts = opts || {} try { const info = parse(src) const result = getPermutations(info.props, opts) return result } catch (e) { console.log('Could not read component') return false } }
/* Copyright Roman Riesen 2016-2017 License: Do wathever you want. Just keep this comment in this file. */ function Deck(deckCanvasCtx){ this.directions = ["N","NO","O","SO","S","SW","W","NW"] this.cards = [] this.usedCards = [] this.deckCanvasCtx = deckCanvasCtx //add all permutations to deck: for (var i = 0; i < this.directions.length; i++){ for (var j = 1; j <= 3; j++){ this.cards.push(new Card(this.directions[i],j)) } } this.shuffle = function(player1,player2){ //add usedCards to cards this.cards.push.apply(this.cards, this.usedCards) //clean the used cards this.usedCards = [] //shuffle Deck var temp,j for(var i = 0; i < this.cards.length-1; i++){ //j ← random integer such that i ≤ j < n j = Math.floor(Math.random()*(this.cards.length-i)+i) temp = this.cards[i] this.cards[i] = this.cards[j] this.cards[j] = temp } } this.getTopCard = function(){ var returnCard = this.cards.pop() if(this.cards.length == 0){ this.shuffle() //console.log("Deck got shuffled!"); } return returnCard } this.displayCardStack = function(player, width, height){ this.deckCanvasCtx.beginPath() this.deckCanvasCtx.fillStyle = player.color //'rgb(250,220,190)' var cardWidth = width var cardHeight = height this.deckCanvasCtx.fillRect(this.deckCanvasCtx.width/2-cardWidth/2,this.deckCanvasCtx.height/2-cardHeight/2,cardWidth,cardHeight) this.deckCanvasCtx.beginPath() this.deckCanvasCtx.fillStyle = player.color2//'rgb(0,0,0)' var textHeight = cardWidth this.deckCanvasCtx.font = textHeight+"px Arial" var textWidth = this.deckCanvasCtx.measureText(this.cards.length).width this.deckCanvasCtx.fillText( this.cards.length, this.deckCanvasCtx.width/2-(textWidth/1.9),//No clue why -5, but it is centered now. this.deckCanvasCtx.height/2+(textHeight/3))//same with -10 } this.copy = function(context){ //returns new deck var deckCopy = new Deck(context) for (var i = 0; i < this.cards.length; i++) { deckCopy.cards[i] = this.cards[i].copy() } for (var i = 0; i < this.usedCards.length; i++) { if(deckCopy.usedCards[i] === undefined){continue} deckCopy.usedCards[i] = this.usedCards[i].copy()//copy not necessary, since cards are only read from anyways } //deckCopy.cards = JSON.parse(JSON.stringify(this.cards)) //deckCopy.usedCards = JSON.parse(JSON.stringify(this.usedCards)) return deckCopy } this.extend = function (jsonString){ var obj = JSON.parse(jsonString) for (var key in obj) { this[key] = obj[key] console.log("Set ", key ," to ", obj[key]) } } }
//listar plugins navegador var qtdPlug = navigator.plugins.length; alert( qtdPlug.toString() + " Plugin(s)<br>" + "Name | Filename | description<br>" ); for(var i = 0; i < qtdPlug; i++) { alert( navigator.plugins[i].name + " | " + navigator.plugins[i].filename + " | " + navigator.plugins[i].description + " | " + navigator.plugins[i].version + "<br>" ); }
import React from 'react'; import PropTypes from 'prop-types'; import themeGet from '@styled-system/theme-get'; import { Global, css } from '@emotion/core'; import { ThemeProvider } from 'emotion-theming'; import normalize from 'emotion-normalize'; import theme from 'util/theme'; const ProviderProps = { children: PropTypes.node.isRequired, }; export const Theme = ({ children }) => ( <ThemeProvider theme={theme}>{children}</ThemeProvider> ); Theme.propTypes = ProviderProps; export const GlobalStyles = ({ children }) => ( <> <Global styles={normalize} /> <Global styles={theme => css` html, body { font-size: 16px; font-family: ${themeGet('fonts.sans')({ theme })}; scroll-behavior: smooth; box-sizing: border-box; } `} /> {children} </> ); GlobalStyles.propTypes = ProviderProps; export const SiteStyles = ({ children }) => ( <> <Global styles={theme => css` html, body { background: ${themeGet('colors.pink300')({ theme })}; } a { text-decoration: none; color: currentColor; } a.anchor { text-decoration: underline; } .js-loading *, .js-loading *:before, .js-loading *:after { animation-play-state: paused !important; } /* body > div > div > section { position: relative; z-index: 1; } body > div > div > section:last-of-type { box-shadow: 0px 14px 16px 0px hsla(0, 0%, 0%, 0.13), -1px 4px 4px 0px hsla(0, 0%, 0%, 0.09); } body > div > div > section + footer { position: sticky; bottom: 0; z-index: 0; } */ `} /> {children} </> ); SiteStyles.propTypes = ProviderProps; export const Stylings = ({ children }) => ( <Theme> <GlobalStyles> <SiteStyles>{children}</SiteStyles> </GlobalStyles> </Theme> ); Stylings.propTypes = { children: PropTypes.node.isRequired, };
var deals = [{ id: 1000000, name: 'Early bird', location: 'L Atmosphere Restaurant', category: 'Food', startdate: '10/10/2017', expirydate: '27/10/2017', information: '2 PEOPLE x 3 courses', price: 20 }, { id: 1000001, name: 'Premium movie for 2', location: 'Odeon cinema', category: 'Student', startdate: '2/10/2017', expirydate: '22/10/2017', information: '2 STUDENTS x 3 tickets', price: 14 }]; module.exports = deals;
// JavaScript Document function initDesc(){ hideList(); /* show the first element, make it selected */ document.getElementById('desc1').className="selected"; document.getElementById('regions').getElementsByTagName('li')[0].className="selected"; document.region_list.selectedRegion[0].checked=true; document.getElementById('desc1').style.display="block"; document.getElementById('regions').className="scripted"; document.getElementById('region-descriptions').className="scripted"; } function hideList(){ /*hide everything */ lis = document.getElementById('regions').getElementsByTagName('li'); for (var i=1; i<(lis.length + 1); i++){ document.getElementById('desc'+i).style.display="none"; lis[i-1].className="not-selected"; } } function showHide (obj, ele){ hideList(); obj.className="selected"; document.getElementById('desc'+ele).className="selected"; document.getElementById('desc'+ele).style.display="block"; document.region_list.selectedRegion[ele-1].checked=true; } addLoadEvent(initDesc);
import Root from './src' export default Root
//Código para enviar correos (function () { emailjs.init("user_nsfB75HsHb3gAeJ6RzBYc"); })(); function sendMail() { let fullName = document.getElementById("name").value; let userEmail = document.getElementById("email").value; let userMessage = document.getElementById("message").value; var contactParams = { from_name: fullName, from_email: userEmail, message: userMessage, }; emailjs .send("service_l8t7c6q", "template_74px0yb", contactParams) .then(function (res) {}); return true; } function envi() { window.location.reload(); } //formulario
(function (global, $) { "use strict"; var LCC = global.LCC || {} LCC.Modules = LCC.Modules || {} LCC.Modules.PreventDefault = function () { this.start = function (element) { var children = element.data('prevent-default-children') ? element.data('prevent-default-children') : ""; if(children !== "") { element.find(children).on('click', function (e) { e.preventDefault(); return true; }); } else { element.on('click', function (e) { e.preventDefault(); return true; }); } } }; global.LCC = LCC })(window, jQuery);
const zerotwo = require('../dist/app.js'); console.log(zerotwo());
import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { reducers } from './reducers'; const enhancer = applyMiddleware(thunk); export default function configureStore(initialState){ let store = createStore(combineReducers(reducers), initialState, enhancer); return store; }
window.onload = function () { const prodLeftShow = document.querySelector("#prodLeftShow"); let prodLeftBtn = document.querySelector("#prodLeftBtn"); prodLeftBtn.addEventListener("click", function () { let prodHeight = getComputedStyle(prodLeftShow); if (prodHeight.height !== "auto") { prodLeftShow.style.height = "auto"; document.querySelector("#prodLeftBox").style.display = "none"; } }); };
export { register } from './manager';
import React from 'react' class BlogForm extends React.Component{ constructor(props){ super(props); this.state = { title: '', checked: 'false' } this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({[event.target.name]: event.target.value}) } render(){ return( <form className="col-12 col-md-6 mb-5" onSubmit={(event) => this.props.handleSubmit(event, this.state)}> <div className="form-group"> <label htmlFor="title">Title</label> <input type="text" className="form-control" id="title" name="title" value={this.state.title} onChange={this.handleChange}/> </div> <button type="submit" className="btn btn-primary">Save</button> </form> ) } } export default BlogForm;
import React from 'react' import styled from 'styled-components' import SearchIcon from '@material-ui/icons/Search'; import ShoppingBasketIcon from '@material-ui/icons/ShoppingBasket'; import LocationOnIcon from '@material-ui/icons/LocationOn'; import {Link} from 'react-router-dom' function Header({cartItems,user,signOut}) { const getCount = () =>{ let count = 0; console.log(cartItems) cartItems.forEach((item)=>{ count += item.product.quantity; }) return count; } return ( <Container> <HeaderLogo> <Link to='/'> <img src={'https://i.imgur.com/7I9Was5.png'}/> </Link> </HeaderLogo> <HeaderOptionAddress> <LocationOnIcon/> <HeaderOption onClick={signOut}> <OptionLineOne>Hello,{user.name}</OptionLineOne> <OptionLineTwo>Select Your Address</OptionLineTwo> </HeaderOption> </HeaderOptionAddress> <HeaderSearch> <HeaderSearchInput type='text'/> <HeaderSearchIconContainer> <SearchIcon/> </HeaderSearchIconContainer> </HeaderSearch> <HeaderNavItem> <HeaderOption> <OptionLineOne>Hello,Pratiksha</OptionLineOne> <OptionLineTwo>Account & Lists</OptionLineTwo> </HeaderOption> <HeaderOption> <OptionLineOne>Return</OptionLineOne> <OptionLineTwo>& Order</OptionLineTwo> </HeaderOption> <HeaderOptionCart> <Link to='/cart'> <ShoppingBasketIcon/> <CartCount>{getCount()}</CartCount> </Link> </HeaderOptionCart> </HeaderNavItem> </Container> ) } export default Header const Container = styled.div` height:60px; background-color:black; display:flex; align-items:center; justify-content:space-between; color:white; ` const HeaderLogo = styled.div` img{ width:100px; margin-left:11px } ` const HeaderOptionAddress = styled.div` padding-left:9px; display:flex; align-items:center; ` const OptionLineOne = styled.div` ` const OptionLineTwo = styled.div` font-weight:700; ` const HeaderSearch = styled.div` display:flex; flex-grow:1; height:40px; border-radius:4px; overflow:hidden; margin-left:4px; background-color:white; :focus-within{ box-shadow:0 0 0 3px #F90; } ` const HeaderSearchInput = styled.input` flex-grow:1; border:0; :focus{ outline:none; } ` const HeaderNavItem = styled.div` display:flex ` const HeaderOption = styled.div` padding:10px 9px 10px 9px; cursor:pointer; ` const HeaderOptionCart = styled.div` display:flex; a{ display:flex; align-items:center; padding-right:9px; color:white; text-decoration:none; } ` const CartCount = styled.div` padding-left:4px; font-weight:700; color:#f08804; ` const HeaderSearchIconContainer = styled.div` background-color:#febd69; width:45px; color:black; display:flex; justify-content:center; align-items:center; `
import React from 'react'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; class QuoteBookingDetail extends React.Component{ formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [ day,month,year].join('-'); } render(){ var {hotel_details} = this.props.hotelDetail; let check_in_date = this.formatDate(this.props.date[0]); let check_out_date = this.formatDate(this.props.date[1]); return ( <div className="panel panel-default"> <div className="panel-body"> <div className="checkin-checkout-details-panel"> <div> <div className="dates-container"> <h4>{check_in_date} - {check_out_date}</h4> </div> <div className="nights-container"> <h4>{hotel_details.TotalDays} nights</h4> </div> </div> <div className="room-detail"> <div>{this.props.roomQuantity} x {this.props.bedDetail.BedName}</div> <div><Link to="#">Change</Link></div> </div> </div> <div className="person-detail-container"> <p><i className="fa fa-male"></i> {this.props.roomQuantity} room, 2 adults</p> <p><i className="fa fa-users"></i> Max 2 adults, 2 children (0-5 years)</p> </div> <Link to="#">Extra low price! (non-refundable)</Link> </div> </div> ) } } const mapStateToProps = (state)=>{ let {date} = state; let selectedHotel = state.bookHotel.hotelId; console.log(state.hotelList); let hotelList = Object.values(state.hotelList.hotel_details); let hotelDetail = hotelList.find(({hotel_details})=> parseInt(hotel_details.HotelID) === parseInt(selectedHotel) ); let roomQuantity = state.bookHotel.totalRooms; let selectedRoomId = state.bookHotel.roomId; let bedDetails = Object.values(hotelDetail.hotel_details.BedDetails); let bedDetail = bedDetails.find((detail)=> parseInt(detail.BedID) === parseInt(selectedRoomId)); return {hotelDetail,roomQuantity,bedDetail,date}; } export default connect(mapStateToProps)(QuoteBookingDetail);
import {combineReducers} from 'redux' import productReducer from './productReducer' import auth from './authReducer' import cart from './cartReducer' export default combineReducers({ product : productReducer, auth : auth, cart : cart })
'use strict'; module.exports = (sequelize, DataTypes) => { const TransactionItem = sequelize.define('TransactionItem', { TransactionId: DataTypes.INTEGER, ItemId: DataTypes.INTEGER, quantity: DataTypes.INTEGER }, {}); TransactionItem.associate = function(models) { }; return TransactionItem; };
(function(){ $('#openButton').click(function(){ if($('#whatsappView').hasClass('open-display')) { $('#whatsappView').addClass('close-display') $('#whatsappView').removeClass('open-display') } else { $('#whatsappView').addClass('open-display') $('#whatsappView').removeClass('close-display') } }) $('.jMFFum').click(function(){ $('#whatsappView').addClass('close-display') $('#whatsappView').removeClass('open-display') }) })()
let money = 30000, income = 'фриланс', addExpenses = 'Коммуналка, Интернет, Мобильная связь, Питание, Здоровье', deposit = true, mission = 100000, period = 12; alert('Должно работать!'); console.log(typeof money); console.log(typeof income); console.log(typeof deposit); console.log(typeof addExpenses); console.log(addExpenses.length); console.log('Период равет: ' + period + ' ' + 'месяцев'); console.log('Цель заработать ' + mission + ' ' + 'рублей/долларов/гривен/юани'); addExpenses = addExpenses.toLowerCase(); addExpenses = addExpenses.split(','); console.log(typeof addExpenses); console.log(addExpenses); let budgetDay = money / 30; console.log(budgetDay);
'use strict'; var assert = require('assert'), sinon = require('sinon'), fnUtils = require('../fn-utils'); describe('fnUtils', function() { describe('.times()', function() { it('invoke function n times', function() { var n = 10, fn = sinon.spy(); fnUtils.times(n, fn); assert.strictEqual(fn.callCount, n); }); }); });
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify:{ options: { manage: false, preserveComments: 'all' //preserve all comments on JS files }, target:{ files: { 'js/script.min.js' : ['app/js/*.js'] } } }, jshint: { // define the files to lint files: ['Gruntfile.js','app/js/*.js'], // configure JSHint (documented at http://www.jshint.com/docs/) options: { // more options here if you want to override JSHint defaults globals: { console: true, module: true, browser: true, node: true, strict: false }, reporterOutput: "" } }, cssmin:{ target:{ files: [{ expand: true, cwd: 'app/css/', src: ['*.css', '!*.min.css'], dest: 'css/', ext: '.min.css' }] } }, imagemin: { dynamic: { files: [{ expand: true, cwd: 'app/images', src: ['**/*.{png,jpg,gif}'], dest: 'images/' }] } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); //Validate JS grunt.loadNpmTasks('grunt-contrib-jshint'); // Load the plugin that provides the "cssmin" task. grunt.loadNpmTasks('grunt-contrib-cssmin'); // Load the plugin that provides the "cssmin" task. grunt.loadNpmTasks('grunt-contrib-imagemin'); // Default task(s). grunt.registerTask('default', ['uglify','cssmin', 'jshint', 'imagemin']); };
import React from "react"; import styles from "./IconPlus.module.scss"; const iconPlus = props => ( <svg aria-hidden="true" className={styles.IconPlus} {...props} version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32"> <title>Plus Icon</title> <path d="M15.5 29.5c-7.18 0-13-5.82-13-13s5.82-13 13-13 13 5.82 13 13-5.82 13-13 13zM21.938 15.938c0-0.552-0.448-1-1-1h-4v-4c0-0.552-0.447-1-1-1h-1c-0.553 0-1 0.448-1 1v4h-4c-0.553 0-1 0.448-1 1v1c0 0.553 0.447 1 1 1h4v4c0 0.553 0.447 1 1 1h1c0.553 0 1-0.447 1-1v-4h4c0.552 0 1-0.447 1-1v-1z"></path> </svg> ); export default iconPlus;
import React from 'react'; import './item.css'; import { Card, Image } from 'semantic-ui-react'; const Item = ({ data }) => ( <Card className="card"> <Image src={data.image} wrapped ui={false} /> <Card.Content> <Card.Header>{'$' + data.precio}</Card.Header> <Card.Meta> <span className="date">{data.nombre}</span> </Card.Meta> <Card.Description>{data.descripcion}</Card.Description> </Card.Content> </Card> ); export default Item;
// load q promise library var q = require("q"); // pass db and mongoose reference to model module.exports = function(db, mongoose) { // load user schema var UserSchema = require("./user.schema.server.js")(mongoose); // create user model from schema var UserModel = mongoose.model('UserModel', UserSchema); var api = { findUserByCredentials: findUserByCredentials, findAllUsers: findAllUsers, createUser: createUser, deleteUserById: deleteUserById, updateUserById: updateUserById, findUserByUsername: findUserByUsername, findUserById: findUserById }; return api; function findUserByCredentials(credentials) { var deferred = q.defer(); // find one user with mongoose user model's findOne() UserModel.findOne( // first argument is predicate { username: credentials.username, password: credentials.password }, // doc is unique instance matches predicate function(err, doc) { if (err) { console.log(err); // reject promise if error deferred.reject(err); } else { // resolve promise deferred.resolve(doc); } }); return deferred.promise; } function findAllUsers() { //console.log("in model findallusers"); var deferred = q.defer(); // find users with mongoose user model's find() UserModel.find( function(err, doc) { if (err) { console.log(err); // reject promise if error deferred.reject(err); } else { // resolve promise deferred.resolve(doc); } }); return deferred.promise; } function createUser(user) { //console.log(user); var newUser = { "username": user.username, "password": user.password, "firstName": user.firstName, "lastName": user.lastName, "emails" : [user.emails], "phones" : [user.phones], "roles" : user.roles, "type" : user.type }; //console.log(newUser); var deferred = q.defer(); UserModel.create(newUser, function (err, doc) { if (err) { // reject promise if error console.log(err); deferred.reject(err); } else { // resolve promise deferred.resolve(doc); } }); // return a promise return deferred.promise; } function deleteUserById(userId) { var deferred = q.defer(); // remove user with mongoose user model's remove() UserModel.remove( {_id: userId}, function(err, stats) { if (err) { // reject promise if error console.log(err); deferred.reject(err); } else { // resolve promise deferred.resolve(findAllUsers()); } }); return deferred.promise; } function findUserById(userId) { var deferred = q.defer(); UserModel.findById(userId, function(err, doc) { if (err) { console.log(err); // reject promise if error deferred.reject(err); } else { // resolve promise deferred.resolve(doc); } }); return deferred.promise; } function findUserByUsername(userName) { var deferred = q.defer(); // find one user with mongoose user model's findOne() UserModel.findOne ( {username: userName}, function (err, user) { if(err) { console.log(err); deferred.reject(err); } else { deferred.resolve(user); } }); return deferred.promise; } function updateUserById(userId, newUser) { var deferred = q.defer(); if(newUser.emails) { if(newUser.emails && newUser.emails.indexOf(",")>-1) { newUser.emails = newUser.emails.split(","); } } if(newUser.phones) { if(newUser.phones && newUser.phones.indexOf(",")>-1) { newUser.phones = newUser.phones.split(","); } } // update user with mongoose user model's update() UserModel.update ( {_id: userId}, {$set: newUser}, function (err, stats) { if(err) { console.log(err); deferred.reject(err); } else { UserModel.findById(userId, function (err, user) { if(err) { console.log(err); deferred.reject(err); } else { deferred.resolve(user); } }); } }); return deferred.promise; } };
import { render, cleanup } from '@testing-library/react'; import PreviewCardList from './index'; import SnippetFactory from 'test/fixtures/factories/snippet'; const snippetList = SnippetFactory.createMany('PreviewSnippet', 3); describe('<PreviewCardList />', () => { let wrapper; beforeEach(() => { wrapper = render(<PreviewCardList contentItems={snippetList} />).container; }); afterEach(cleanup); it('should render the appropriate number of PreviewCard components', () => { expect(wrapper.querySelectorAll('.list-card')).toHaveLength( snippetList.length ); }); });
class Negative { constructor (value) { this.value = value; } } module.exports = { Negative }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. require('dotenv').config(); const { BotStateSet, BotFrameworkAdapter, MemoryStorage, ConversationState, UserState, CardFactory } = require('botbuilder'); const { DialogSet, ChoicePrompt, ListStyle } = require('botbuilder-dialogs'); //add BOT sss //----------------------------------------------------------------------------- //ChatBot var //----------------------------------------------------------------------------- // Create adapter const adapter = new BotFrameworkAdapter({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); // Add state middleware const storage = new MemoryStorage(); const convoState = new ConversationState(storage); const userState = new UserState(storage); adapter.use(new BotStateSet(convoState, userState)); const dialogs = new DialogSet(); // Create a choice prompt and change the list style const cardPrompt = new ChoicePrompt().style(ListStyle.list); // Register the card prompt dialogs.add('cardPrompt', cardPrompt); // Create a dialog for prompting the user dialogs.add('cardSelector', [ async (dialogContext) => { await dialogContext.context.sendActivity({ attachments: [createHeroCard()] }); await dialogContext.end(); } ]); var phonenum = "Nothing"; var shownumber = "Nothing"; var protocols = "Nothing"; var AccessURL = process.env.CALLING_URL; var ErrorMsg = "Sorry, I couldn\'t find anyone. \n\n Please try a differentname, mail address, or phone number you want to call. \n\n For example:\n\n (1)Call to John Doe\n\n (2)Call to John@tms.myadd.co.jp\n\n (3)Call to 090-1234-5678\n\n If you need more information, please enter \"help\"."; //add BOT eee //add AD-2 sss https://docs.microsoft.com/ja-jp/azure/active-directory/develop/active-directory-devquickstarts-openidconnect-nodejs //----------------------------------------------------------------------------- //Server var //----------------------------------------------------------------------------- const express = require('express'); const cookieParser = require('cookie-parser'); const expressSession = require('express-session'); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); const passport = require('passport'); const util = require('util'); const bunyan = require('bunyan'); const config = require('./config'); const OIDCStrategy = require('passport-azure-ad').OIDCStrategy; var log = bunyan.createLogger({ name: 'Microsoft OIDC Example Web Application' }); const graphHelper = require('./utils/graphHelper.js'); //----------------------------------------------------------------------------- //set passport //----------------------------------------------------------------------------- passport.serializeUser(function(user, done) { done(null, user.oid); }); passport.deserializeUser(function(oid, done) { findByOid(oid, function (err, user) { done(err, user); }); }); // array to hold logged in users var users = []; var findByOid = function(oid, fn) { for (var i = 0, len = users.length; i < len; i++) { var user = users[i]; log.info('we are using user: ', user); if (user.oid === oid) { return fn(null, user); } } return fn(null, null); }; // Use the OIDCStrategy within Passport. passport.use(new OIDCStrategy({ identityMetadata: config.creds.identityMetadata, clientID: config.creds.clientID, responseType: config.creds.responseType, responseMode: config.creds.responseMode, redirectUrl: config.creds.redirectUrl, allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl, clientSecret: config.creds.clientSecret, validateIssuer: config.creds.validateIssuer, isB2C: config.creds.isB2C, issuer: config.creds.issuer, passReqToCallback: config.creds.passReqToCallback, scope: config.creds.scope, loggingLevel: config.creds.loggingLevel, nonceLifetime: config.creds.nonceLifetime, nonceMaxAmount: config.creds.nonceMaxAmount, useCookieInsteadOfSession: config.creds.useCookieInsteadOfSession, cookieEncryptionKeys: config.creds.cookieEncryptionKeys, clockSkew: config.creds.clockSkew, realm: config.creds.realm, skipUserProfile: true, }, function(iss, sub, profile, accessToken, refreshToken, done) { if (!profile.oid) { return done(new Error("No oid found"), null); } // asynchronous verification, for effect... process.nextTick(function () { findByOid(profile.oid, function(err, user) { if (err) { return done(err); } if (!user) { // "Auto-registration" users.push(profile); return done(null, profile); } return done(null, user); }); }); })); //----------------------------------------------------------------------------- // Create server //----------------------------------------------------------------------------- var app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.logger()); app.use(methodOverride()); app.use(cookieParser()); app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false })); app.use('/Web',bodyParser.urlencoded({ extended : true })); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); //----------------------------------------------------------------------------- // Set up the route controller //----------------------------------------------------------------------------- function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/Web/auth/login'); }; app.get('/', function(req, res) { res.redirect('/Web/auth/top'); }); // '/account' is only available to logged in user app.get('/Web/auth/account', ensureAuthenticated, function(req, res) { const accessToken2 = req.user.accessToken; request .get('https://graph.microsoft.com/beta/me/photo/$value') .set('Authorization', 'Bearer ' + accessToken2) .end((err, res) => { res.redirect('/Web/auth/top'); }); res.redirect('/Web/auth/top'); }); /* app.get('/Web/auth/account', ensureAuthenticated, function(req, res) { res.render('account', { user: req.user }); }); */ app.get('/Web/auth/top',function(req, res) { res.render('index', { user: req.user }); }); app.get('/Web/auth/login', function(req, res, next) { passport.authenticate('azuread-openidconnect', { response: res, // required //resourceURL: config.resourceURL, // optional. Provide a value if you want to specify the resource. //customState: 'my_state', // optional. Provide a value if you want to provide custom state value. failureRedirect: '/Web/auth/top' })(req, res, next); }, function(req, res) { log.info('Login was called in the Sample'); res.redirect('/Web/auth/top'); } ); // 'GET returnURL' app.get('/Web/auth/openid/return', function(req, res, next) { passport.authenticate('azuread-openidconnect', { response: res, // required failureRedirect: '/Web/auth/top' })(req, res, next); }, function(req, res) { log.info('We received a return from AzureAD.'); res.redirect('/Web/auth/top'); } ); app.post('/Web/auth/openid/return', function(req, res, next) { passport.authenticate('azuread-openidconnect', { response: res, // required failureRedirect: '/Web/auth/top' })(req, res, next); }, function(req, res) { log.info('We received a return from AzureAD.'); res.redirect('/Web/auth/top'); } ); app.get('/Web/auth/logout', function(req, res){ req.session.destroy(function(err) { req.logOut(); res.redirect(config.destroySessionUrl); }); }); // '/test' app.get('/Web/test', function(req, res) { res.send('testdayo'); }); // add AD-2 eee // add BOT sss //----------------------------------------------------------------------------- // ChatBot POST //----------------------------------------------------------------------------- app.post('/api/messages', (req, res) => { // Route received request to adapter for processing adapter.processActivity(req, res, async (context) => { if (context.activity.type === 'message') { const state = convoState.get(context); const count = state.count === undefined ? state.count = 0 : ++state.count; const dc = dialogs.createContext(context, state); await dc.continue(); protocols = setProtocols(context.activity.text); if (protocols != "Nothing") { var originText = context.activity.text; originText = originText.replace("ST500",""); originText = originText.replace("st500",""); originText = originText.replace("St500",""); phonenum = originText.replace(/[^0-9]/g,""); shownumber = originText.replace(/[^0-9\+\-\(\)]/g,""); protocols = setProtocols(context.activity.text); AccessURL = process.env.CALLING_URL + "?" + "protocols=" + protocols + "&phonenum=" + phonenum; if (!context.responded) { await dc.begin('cardSelector'); } } else { await context.sendActivity(`${ErrorMsg}`); } } else { await context.sendActivity(`[${context.activity.type} event detected]`); } }); }); // Methods to generate cards function createHeroCard() { var titleString = protocols + shownumber; titleString = titleString.replace("\/\/",""); return CardFactory.heroCard( 'Robin Richards', CardFactory.images(['https://h-mari-testbot.herokuapp.com/RobinRichards.png']), CardFactory.actions([ { type: 'openUrl', title: titleString, value: AccessURL }, { type: 'openUrl', title: titleString, value: AccessURL } ]) ); } // Methods to set calling protocols function setProtocols(userInputString) { userInputString = userInputString.toUpperCase(); var protocols = "Nothing"; if (userInputString.indexOf('CALL') > -1) { protocols = "callto:"; } if (userInputString.indexOf('TEL') > -1) { protocols = "tel:"; } if (userInputString.indexOf('ST') > -1) { protocols = "st500://"; } return protocols; } // add BOT eee app.listen(process.env.port || process.env.PORT || 3978, function () { console.log('test'); });
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const commentSchema = new Schema( { commentContent: { type: String, required: true, }, commentCreator: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, }, { timestamps: true, } ); const postSchema = new Schema( { postContent: { type: String, required: true, }, postType: { type: String, required: true, }, postCreator: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, comments: [commentSchema], }, { timestamps: true, } ); const Post = mongoose.model("Post", postSchema); module.exports = Post;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Segment, Table } from 'semantic-ui-react'; import '../css/scrollable.css'; import { selectModel } from '../actions/edm'; class TableContainer extends Component { headerRow = [ { key: 'header-type', content: 'Type', className: 'truncated'}, { key: 'header-title', content: 'Title', className: 'truncated'}, { key: 'header-description', content: 'Description', className: 'truncated'}, ]; renderBodyRow = ( model ) => { const { id, type, title, description } = model.entityType || model; const { currentModel } = this.props; const { selectModel } = this.props.actions; return { key: id, cells: [ type ? { key: 'type', content: type.namespace + '.' + type.name, className: 'truncated' } : 'No Type', title ? { key: 'title', content: title, className: 'truncated' } : 'No Title', description ? { key: 'description', content: description} : '-' ], active: id === currentModel, onClick: () => selectModel(id) //anonymous function causes all rows to re-render. consider avoiding semantic-ui shorthand to optimize } } render() { const { renderBodyRow, headerRow } = this; const { associationTypes, entityTypes, isFetching, modelType } = this.props; const data = modelType === 'entityTypes' ? entityTypes.entityTypes : associationTypes.associationTypes; return ( <Segment.Group > <Segment className='truncated tableHeader' size='large' color='violet'>{modelType}</Segment> <Segment loading={isFetching}> <Table className='scrollable' headerRow={headerRow} renderBodyRow={renderBodyRow} tableData={data} selectable unstackable sortable /> </Segment> </Segment.Group> ) } } const mapStateToProps = ({ associationTypes, entityTypes, currentModel, isFetching }) => ({ associationTypes, entityTypes, currentModel, isFetching }); const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ selectModel }, dispatch) }) export default connect(mapStateToProps, mapDispatchToProps)(TableContainer);
import { Component } from 'react'; import { NavLink} from 'react-router-dom'; import '../CSS/Style.css'; /** * Pagination class implementation allow a particular people page * to be display when a page number is selected. */ class Pagination extends Component { render() { let active = 0; let items = []; //Loop to display pagination page number with NavLink element for (let number = 1; number <= 9; number++) { active = number items.push( <NavLink to={{ pathname: '/', hash: `/Home/page=${active}`}} onClick={() => localStorage.setItem('currentPage', number)} key={number} activeClassName={items[number]?"active":null} >{number} </NavLink> ); } return( <div className="pagination"> <h4 style={{}}>Page: {localStorage.getItem('currentPage')} of 9</h4> <NavLink activeStyle={{fontWeight: "bold",color: "red", backgroundColor: "#F4F6F7"}} activeClassName={null} to="#">{"<"} </NavLink> {items} <NavLink activeStyle={{fontWeight: "bold",color: "red", backgroundColor: "#F4F6F7"}} activeClassName={null}to="#">{">"} </NavLink> </div> ); } } export default Pagination;
'use strict'; const axios = require('axios'); var debug = require('debug')('zapsdb:tenant') module.exports = class Tenant { constructor(){ } createTenant(tenantid, tenantname, tenantregion) { return new Promise((resolve, reject) => { var jsontenant = { 'tenant_id': tenantid, 'tenant_name': tenantname, 'tenant_region': tenantregion } debug('Tenent ', `https://platform.api${this.stage}.zapscloud.com/tenants`, jsontenant, this.header_param) axios.post(`https://platform.api${this.stage}.zapscloud.com/tenants`, jsontenant, this.header_param) .then(function (response) { return resolve(response.data); }) .catch(function (error) { return reject(error.response?(error.response.data?error.response.data:error.response):error); }); }); } removeTenant(tenantid) { return new Promise((resolve, reject) => { axios.delete(`https://platform.api${this.stage}.zapscloud.com/tenants/${tenantid}`, this.header_param) .then(function (response) { return resolve(response.data); }) .catch(function (error) { return reject(error.response?(error.response.data?error.response.data:error.response):error); }); }); } getTenant(tenantid) { return new Promise((resolve, reject) => { axios.get(`https://platform.api${this.stage}.zapscloud.com/tenants/${tenantid}`, this.header_param) .then(function (response) { return resolve(response.data); }) .catch(function (error) { return reject(error.response?(error.response.data?error.response.data:error.response):error); }); }); } getTenantList(filterquery) { return new Promise((resolve, reject) => { var queryparam = (filterquery ? `?filter=${filterquery}` : ''); queryparam = (sortquery ? (queryparam!=''?`${queryparam}&`:'?')+`sort=${sortquery}` : queryparam); queryparam = (skip ? (queryparam!=''?`${queryparam}&`:'?')+`skip=${skip}` : queryparam); queryparam = (limit ? (queryparam!=''?`${queryparam}&`:'?')+`limit=${limit}` : queryparam); debug('Filter Query ',encodeURI(queryparam), `https://platform.api${this.stage}.zapscloud.com/tenants${encodeURI(queryparam)}`) axios.get(`https://platform.api${this.stage}.zapscloud.com/tenants?${encodeURI(queryparam)}`, this.header_param) .then(function (response) { return resolve(response.data); }) .catch(function (error) { return reject(error.response?(error.response.data?error.response.data:error.response):error); }); }); } }
'use strict'; const defaultInputs = ['fio', 'email', 'phone']; const res = { success: { status: 'success' }, error: { status: 'error', reason: 'Не удалось отправить данные. Попробуйте еще раз' }, progress: { status: 'progress', timeout: 1000 } } const elems = { $resultContainer : document.getElementById('resultContainer'), $resultTextContainer : document.getElementById('resultsText'), $button : document.getElementById('submitButton') } const fetchImitation = (url) => { return new Promise(resolve => { setTimeout(() => { resolve(res[url]); }, 500); }) } EventTarget.prototype.addEventListener = (() => { const addEventListener = EventTarget.prototype.addEventListener; return function () { addEventListener.apply(this, arguments); return this; }; })(); class PhoneFormatter { static get formats() { return [ { range: [0,1], char: '+' }, { range: [1,4], char: '(' }, { range: [4,7], char: ')' }, { range: [7,9], char: '-' }, { range: [9,11], char: '-' } ] } static outputView(phone) { phone = PhoneFormatter.clearFromChars(phone); return PhoneFormatter.formats .map(format => phone.slice(format.range[0], format.range[1])) .map((group, i) => group.length ? `${PhoneFormatter.formats[i].char}${group}` : group) .join(''); } static clearFromChars(phone) { return phone.replace(/\D/g, '').slice(0,11); } static validate(phone) { return /^(\+7\(\d{3}\)\d{3}-\d{2}-\d{2})/.test(phone) && PhoneFormatter.clearFromChars(phone).split('').reduce((prev, curr) => parseInt(prev) + parseInt(curr)) <= 30; } } class Form { constructor() { this.$el = document.getElementById('myForm'); this._data = defaultInputs.reduce((acc, cur) => { acc[cur] = ''; return acc; }, {}); } validate() { let inputs = []; Object.keys(this._data).map(name => { let result = { case: name }; switch (name) { case 'fio': { result.isValid = this._data.fio.trim().replace(/\s/g, ' ').split(' ').length === 3 && !/\d/g.test(this._data.fio); break; } case 'phone': { result.isValid = PhoneFormatter.validate(this._data.phone); break; } case 'email': { result.isValid = /.+@(ya.ru|yandex.ru|yandex.ua|yandex.by|yandex.kz|yandex.com)/g.test(this._data.email); break; } default: { result.isValid = true; break; } } inputs.push(result); }); return { isValid: inputs.every(input => input.isValid), errorFields: inputs .filter(input => !input.isValid) .map(input => input.case) } } getData() { return this._data; } setData(newData) { this._data = defaultInputs.reduce((acc, cur) => { acc[cur] = newData[cur] ? newData[cur] : this._data[cur]; return acc; }, {}); if (newData.phone) { this._data.phone = PhoneFormatter.outputView(newData.phone); } Object.keys(this._data).map((name) => { let value = this._data[name]; if (name === 'phone') { value = PhoneFormatter.outputView(this._data.phone); } document.getElementsByName(name)[0].value = value; }); } submit() { let result = this.validate(); defaultInputs.map((field) => { let input = document.getElementsByName(field)[0]; if (result.errorFields.includes(field)) { input.classList.add('error'); } else { input.classList.remove('error'); } }); if (result.isValid) { elems.$button.setAttribute('disabled', true); const sendRequest = () => { fetchImitation(myForm.$el.getAttribute('action')).then(res => { switch(res.status) { case 'success': case 'error': { elems.$button.removeAttribute('disabled'); elems.$resultContainer.className = res.status; elems.$resultTextContainer.innerHTML = res.status === 'success' ? 'Success!' : res.reason; break; } case 'progress': { elems.$resultTextContainer.innerHTML += `<hr>Не получилось...`; elems.$resultContainer.className = res.status; elems.$resultTextContainer.innerHTML += `<br>Повторная отправка произойдет через ${res.timeout}мс...` setTimeout(() => { elems.$resultTextContainer.innerHTML += `<br>Отправляю еще раз...`; sendRequest(); }, res.timeout); break; } } }) } sendRequest(); } } } window.myForm = new Form(); myForm.$el .addEventListener('keydown', (e) => { let input = e.target; myForm.setData({ [input.getAttribute('name')] : input.value }) }) .addEventListener('submit', (e) => { e.preventDefault(); myForm.submit(); });
import viewChanger from "../app.js"; import domService from "../services/domService.js"; import postingService from "../services/postingService.js"; let topicContainer = document.querySelector("#topic-container"); let postForm = document.querySelector("#post-form"); postForm.addEventListener("submit", createPostHandler); let cancelButton = postForm.querySelector(".cancel"); cancelButton.addEventListener("click", postForm.reset()); async function getPostsHandler() { [...topicContainer.children].forEach(post => post.remove()); let posts = await postingService.getAllPosts(); Object.values(posts).forEach(post => { topicContainer.appendChild(createTopicWrapperDiv(post)); }); } async function createPostHandler(e) { e.preventDefault(); let formData = new FormData(postForm); let title = formData.get("topicName"); let username = formData.get("username"); let postText = formData.get("postText"); let newPost = { username: username, title: title, postText: postText, date: domService.timeFormats.getHomepagePostTimeFormat() } if (Object.values(newPost).some(field => field == "")) { return alert("All fields are required!"); } let createResult = await postingService.createPost(newPost); topicContainer.appendChild(createTopicWrapperDiv(createResult)); postForm.reset(); } function createTopicWrapperDiv(post) { let id = post._id; let nameWrapperDiv = domService.createNestedElement("div", { "id": id, class: "topic-name-wrapper" }); nameWrapperDiv.addEventListener("click", viewChanger.navigatoToTopicPage); let nameDiv = domService.createNestedElement("div", { class: "topic-name" }); let titleA = domService.createNestedElement("a", { class: "normal", href: "#" }); let titleHeading = domService.createNestedElement("h2", undefined, post.title); titleA.appendChild(titleHeading); let columnsDiv = domService.createNestedElement("div", { class: "columns" }); let insideColumnDiv = domService.createNestedElement("div"); let dateP = domService.createNestedElement("p", undefined, "Date: "); let date = domService.createNestedElement("date"); dateP.appendChild(date); let time = domService.createNestedElement("time", undefined, post.date); date.appendChild(time); let nicknameDiv = domService.createNestedElement("div", { class: "nick-name" }); let usernameP = domService.createNestedElement("p", undefined, "Username: "); let nameSpan = domService.createNestedElement("span", undefined, post.username); usernameP.appendChild(nameSpan); nicknameDiv.appendChild(usernameP); insideColumnDiv.appendChild(dateP); insideColumnDiv.appendChild(nicknameDiv); columnsDiv.appendChild(insideColumnDiv); nameDiv.appendChild(titleA); nameDiv.appendChild(columnsDiv); nameWrapperDiv.appendChild(nameDiv); return nameWrapperDiv; } let homeModule = { getPostsHandler } export default homeModule;
/* @flow weak */ import React, { Component, PropTypes } from 'react' import { Provider, connect } from 'react-redux' import store from '../../store' import IDE from '../IDE.jsx' import WorkspaceList from '../../components/Workspace' import ThemeProvider from '../../components/ThemeProvider' import { initState } from './actions' class Root extends Component { static proptypes = { dispatch: PropTypes.func } componentWillMount () { this.props.dispatch(initState()) } render () { const { selectingWorkspace } = this.props if (window.isSpaceKeySet) return <IDE /> if (selectingWorkspace) return <WorkspaceList /> return <IDE /> } } Root = connect( state => state.WorkspaceState )(Root) const defaultLanguage = 'zh_CN' export default () => { return ( <Provider store={store}> <ThemeProvider language={defaultLanguage}> <Root id='root-container' /> </ThemeProvider> </Provider> ) }
import { h } from 'rdfw' import style from '../styles' export default (state, actions) => h('div', { className: style.container }, [ h('nav', { className: style.navigation }, [ h('h1', { className: style.headTitle }, ['Welcome to Athēna']), h('p', { className: style.promotion }, ['Pick up somthing that you interested in:']), h('ul', { className: style.tagList }, [ state.tags.map(tag => h('li', { className: style.tagItem }, [ h('a', { className: style.tagLink, href: state.history.createHref({ pathname: '/posts', query: { tag } }) }, [ tag ]) ]) ) ]) ]) ])
var searchData= [ ['sor_2eh_62',['sor.h',['../sor_8h.html',1,'']]], ['stencils_2eh_63',['stencils.h',['../stencils_8h.html',1,'']]] ];
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const notaSchema = new Schema({ cuerpo: String, destinatario:{ type:Schema.Types.ObjectId, ref:"User" }, remitenteOtro:{ type:Schema.Types.ObjectId, ref:"Brand" }, remitente:{ type:Schema.Types.ObjectId, ref:"User" }, evidenciaPertenece:{ type:Schema.Types.ObjectId, ref:"Evidencia" }, dinamica:{ type: Schema.Types.ObjectId, ref:"Dinamica" }, todos:{ type:Boolean, required:true, default:false } },{ timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); module.exports = mongoose.model('Nota', notaSchema); // EL MODELO DE LAS NOTAS QUE SE CREAN CUANDO SE RECHAZA UNA EVIDENCIA O SE CREA UN MENSAJE GLOBAL // SI ES UN MENSAJE GLOBAL EL ATRIBUTO TODOS ES TRUE
import React from "react" import { Link } from "gatsby" import { StaticImage } from "gatsby-plugin-image" import Layout from "../components/Layout" import { header, btn } from "../styles/home.module.css" export default function Home({ data }) { return ( <Layout> <section className={header}> <div> <h2>Design!!!!!</h2> <h3>Develop & Deploy</h3> <p>UX designer & web developer based in manchester</p> <Link className={btn} to="/projects"> My Portfolio Projects </Link> </div> <StaticImage src="../images/banner.png" alt="banner" /> </section> </Layout> ) }
import React, { Component } from 'react'; import { View } from 'react-native'; import { createBottomTabNavigator } from 'react-navigation'; import Profile from './screens/Profile'; import Consultations from './screens/Consultations'; import Doctors from './screens/Doctors'; import Hospitals from './screens/Hospitals'; import { bootstrap } from './config/bootstrap'; import { KittenTheme } from './config/theme'; import Ionicons from 'react-native-vector-icons/Ionicons'; import SplashScreen from 'react-native-splash-screen'; import RNLanguages from 'react-native-languages'; import i18n from './i18n'; bootstrap(); const PatientApp = createBottomTabNavigator({ consultations: { screen: Consultations, path: 'cons', navigationOptions: { tabBarLabel: i18n.t('consultation.menuTitle'), tabBarIcon: ({ tintColor, focused, horizontal }) => ( <Ionicons name='ios-list' size={horizontal ? 20 : 26} style={{ color: tintColor }} /> ) } }, doctors: { screen: Doctors, path: 'docs', navigationOptions: { tabBarLabel: i18n.t('doctor.menuTitle'), tabBarIcon: ({ tintColor, focused, horizontal }) => ( <Ionicons name='ios-pulse' size={horizontal ? 20 : 26} style={{ color: tintColor }} /> ) } }, hospitals: { screen: Hospitals, path: 'hos', navigationOptions: { tabBarLabel: i18n.t('hospital.menuTitle'), tabBarIcon: ({ tintColor, focused, horizontal }) => ( <Ionicons name='ios-pin' size={horizontal ? 20 : 26} style={{ color: tintColor }} /> ) } }, profile: { screen: Profile, path: '', navigationOptions: { tabBarLabel: i18n.t('profile.menuTitle'), tabBarIcon: ({ tintColor, focused, horizontal }) => ( <Ionicons name='ios-person' size={horizontal ? 20 : 26} style={{ color: tintColor }} /> ) } } }, { tabBarOptions: { activeTintColor: KittenTheme.colors.primary } }); export default class App extends Component { componentWillMount() { RNLanguages.addEventListener('change', this._onLanguagesChange); } componentDidMount() { SplashScreen.hide(); } componentWillUnmount() { RNLanguages.removeEventListener('change', this._onLanguagesChange); } _onLanguagesChange = ({ language }) => { i18n.locale = language; }; render() { return <PatientApp />; } }
import React, {useEffect} from 'react' import {AccessTimeFilledRound, PlaceRound, HeadphonesRound} from '@ricons/material' import Aos from 'aos' import 'aos/dist/aos.css' import './style.scss' const HomeTimeWork = () => { useEffect(() => { Aos.init({ duration:1500, once: true }) }, []) return ( <div className = "home-time"> <div className="container"> <div className="home-time__container"> <div className="home-time__item" data-aos = "flip-up"> <div className="home-time__icon"> <AccessTimeFilledRound /> </div> <div className="home-time__text"> <h4>Time 10:00 am - 7:00 pm</h4> <span>Working hour</span> </div> </div> <div className="home-time__item" data-aos = "zoom-in" data-aos-delay= "500"> <div className="home-time__icon"> <PlaceRound /> </div> <div className="home-time__text"> <h4>Bien Hoa- Dong Nai</h4> <span>Get Directions</span> </div> </div> <div className="home-time__item" data-aos = "flip-down" data-aos-delay= "1000"> <div className="home-time__icon"> <HeadphonesRound /> </div> <div className="home-time__text"> <h4>+84 (012)345 6789</h4> <span>Call Online</span> </div> </div> </div> </div> </div> ) } export default HomeTimeWork
//var accountBalance = 300; //var nikeShoes = 799.23; //var coupon = 500; // //// === equal to and same type //// !== not equal to plus type check // //var myAge = 49; //var notAge = "67"; // //if (myAge === notAge) { // console.log("Don't Match"); //} else { // console.log ("One of These things is not like the other"); //} //if (nikeShoes <= accountBalance) { // accountBalance -= nikeShoes; // console.log("Shoes is bought."); // console.log("Account Balance: " + accountBalance); //} else if (nikeShoes - coupon <= accountBalance) { // console.log("Got yer shoes with a coupon, yo.") // accountBalance -= nikeShoes - coupon; // console.log("Account Balance: " + accountBalance); //} else { // console.log("No shoes for you!"); //} var cat1 = 5; var cat2 = 10; var cat3 = 1; var discat3 = true; if ((cat1 > cat2 && cat1 > cat3) && !discat3) { console.log("Cat 1 is the cutest!"); }
//sets that sum up to 16 function sum(arr, target) { return recursive(arr, target, arr.length-1) } function recursive(arr, target, i) { if (target === 0) {return 1} if (target < 0 || i < 0) {return 0} return recursive(arr.slice(0, i), target-arr[i], i-1) + recursive(arr.slice(0, i), target, i-1) } console.log(sum([2,4,6,10], 16)) function sumDP(arr, target) { mem = {}; return dp(arr, target, arr.length-1, mem) } function dp(arr, target, i, mem) { key = `${i}:${target}` if (target === 0) { return 1 } else if (target < 0 || i < 0) { return 0 } else if (target < arr[i]){ mem[key] = recursive(arr.slice(0, i), target, i-1, mem) } else if (!mem[key]) { mem[key] = recursive(arr.slice(0, i), target-arr[i], i-1, mem) + recursive(arr.slice(0, i), target, i-1, mem) } return mem[key]; } console.log(sumDP([2,4,6,10], 16))
const lassoClientTransport = require("lasso-modules-client/transport"); module.exports = function(el, ctx) { const { builder } = ctx; if (el.params.length) { // Receive context tag. const fromAttr = el.getAttribute("from"); let from = fromAttr && fromAttr.literalValue; if (from) { if (from === ".") { from = lassoClientTransport.getClientPath(ctx.filename); } else { const fromTag = ctx.taglibLookup.getTag(from); if (fromTag) { from = lassoClientTransport.getClientPath(fromTag.template); } else { return ctx.addError( `context receiver could not find context provider matching 'from="${from}"'.` ); } } } else { return ctx.addError( "context 'from' attribute is required and should point to another component." ); } const getNode = ctx.createNodeForEl("get-context"); getNode.params = el.params; getNode.setAttributeValue("__from", builder.literal(from)); getNode.body = el.body; el.replaceWith(getNode); } else { // Set context tag. const from = lassoClientTransport.getClientPath(ctx.filename); setNode = ctx.createNodeForEl("set-context", el.getAttributes()); setNode.setAttributeValue("__from", builder.literal(from)); setNode.body = el.body; el.replaceWith(setNode); } };
define(function() { var Class; Class = Backbone.View.extend({ options : { number : 200, tip : null, tipText : '您还可以输入<span class="number">{num}</span>字', errorText : '已经超出<span class="number">{num}</span>字', success : function() {}, error : function() {} }, _emit : function() { var self, element, number, tipText, tip, errorText, success, error; self = this; element = this.$el; tip = this.options.tip; number = this.options.number; tipText = this.options.tipText; errorText = this.options.errorText; success = this.options.success; error = this.options.error; this.Timer = setInterval(function() { self.num = checkNumber($.trim(element.val())); if (self.num > number) { tip.html(errorText.replace('{num}', self.num - number)).css('color', '#c00'); error(); } else { tip.html(tipText.replace('{num}', number - self.num)).css('color', '#999'); success(); } }, 400); }, start : function() { this._emit(); }, stop : function() { clearInterval(this.Timer); } }); function checkNumber(str) { var s = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i).match(/[\u0391-\uFFE5]/)) { s += 2; } else { s++; } } return parseInt(s / 2); } function checkTextNumber(element, options) { options = options || {}; options.el = element; return new Class(options); } return checkTextNumber; });
import { getContext } from 'svelte'; export { default as Provider } from './Provider.svelte'; export const useStore = () => getContext('@redux').store(); export const useDispatch = () => getContext('@redux').dispatch(); export const useSelector = (s) => getContext('@redux').selector(s);
$(document).ready(function(){ $('.slider').bxSlider({ mode: 'vertical', speed: 500, responsive: true, auto: true, pause: 5000, minSlides: 1, maxSlides: 1, controls: false, pager: true }); $('.slider2').bxSlider({ speed: 500, responsive: true, auto: true, pause: 5000, slideWidth: 1180, minSlides: 1, maxSlides: 3, pager: true, prevText: '<span></span>', nextText: '<span></span>', slideMargin: 30 }); /////////////////////////////////////// lightbox.option({ 'resizeDuration': 200, 'wrapAround': true }); ///////////////////////////////////////////// map = L.map('map').setView([40.656620, -73.903810], 13); L.tileLayer.grayscale('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); let newIcon = new L.Icon ({ iconUrl: 'assets/plugins/leaflet_map/images/marker-icon3.png', iconSize: [106, 106] }); L.marker([40.672114, -73.920072], {icon: newIcon}).addTo(map); /////////////////////////////////////////////////////// $(function() { menu_top = $('.menu').offset().top; $(window).scroll(function () { if ($(window).scrollTop() > menu_top) { if ($('.menu').css('position') != 'fixed') { $('.menu').css('position','fixed'); $('.menu').css('top','0'); $('.menu').css('background','linear-gradient(45deg, #56B7FC 0%, #8265FD 100%)'); $('.menu').css('opacity','.9'); $('.blok1').css('margin-top','0px'); } } else { if ($('.menu').css('position') == 'fixed') { $('.menu').css('position',''); $('.menu').css('top',''); $('.menu').css('background','none'); $('.blok1').css('margin-top',''); } } }); }); $('.l-mnu ul li a').click(function(){ if($(this).parent().hasClass('active')){ return false; } $('.l-mnu ul li').removeClass('active'); $(this).parent().addClass('active'); }); ///////////////////////////////////////// $(".elips").on("click","a", function (event) { event.preventDefault(); let id = $(this).attr('href'), top = $(id).offset().top; $('body,html').animate({scrollTop: top}, 800); }); }); document.addEventListener("DOMContentLoaded", function() { var lazyloadImages = document.querySelectorAll("img.lazy"); var lazyloadThrottleTimeout; function lazyload () { if(lazyloadThrottleTimeout) { clearTimeout(lazyloadThrottleTimeout); } lazyloadThrottleTimeout = setTimeout(function() { var scrollTop = window.pageYOffset; lazyloadImages.forEach(function(img) { if(img.offsetTop < (window.innerHeight + scrollTop)) { img.src = img.dataset.src; img.classList.remove('lazy'); } }); if(lazyloadImages.length == 0) { document.removeEventListener("scroll", lazyload); window.removeEventListener("resize", lazyload); window.removeEventListener("orientationChange", lazyload); } }, 20); } document.addEventListener("scroll", lazyload); window.addEventListener("resize", lazyload); window.addEventListener("orientationChange", lazyload); }); /////////////////////////////////// document.addEventListener("DOMContentLoaded", function() { var lazyloadImages; if ("IntersectionObserver" in window) { lazyloadImages = document.querySelectorAll(".lazy"); var imageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { var image = entry.target; image.classList.remove("lazy"); imageObserver.unobserve(image); } }); }); lazyloadImages.forEach(function(image) { imageObserver.observe(image); }); } else { var lazyloadThrottleTimeout; lazyloadImages = document.querySelectorAll(".lazy"); function lazyload () { if(lazyloadThrottleTimeout) { clearTimeout(lazyloadThrottleTimeout); } lazyloadThrottleTimeout = setTimeout(function() { var scrollTop = window.pageYOffset; lazyloadImages.forEach(function(img) { if(img.offsetTop < (window.innerHeight + scrollTop)) { img.src = img.dataset.src; img.classList.remove('lazy'); } }); if(lazyloadImages.length == 0) { document.removeEventListener("scroll", lazyload); window.removeEventListener("resize", lazyload); window.removeEventListener("orientationChange", lazyload); } }, 20); } document.addEventListener("scroll", lazyload); window.addEventListener("resize", lazyload); window.addEventListener("orientationChange", lazyload); } });
export default { id: '19', title: 'HIGHBS-BOK : livret démo et refonte du site', date: '03/02/2021', tags: [ 'highbs-bok', 'publication', 'site' ], description: false }
const gulp = require("gulp"); const sass = require("gulp-sass"); const sourcemaps = require("gulp-sourcemaps"); const autoprefixer = require("gulp-autoprefixer"); const browserSync = require("browser-sync").create(); gulp.task("watch", function() { gulp.watch("./scss/**/*.scss", gulp.series("sass")); }); gulp.task("serve", function() { browserSync.init(null, {server: {baseDir: './'} }); gulp.watch("./scss/**/*.scss", gulp.series("sass")); gulp.watch("./*.html").on("change", browserSync.reload); gulp.watch("./js/*.js").on("change", browserSync.reload); }); // Compile sass into CSS & auto-inject into browsers gulp.task("sass", function() { return gulp .src("./scss/**/*.scss") .pipe(sass().on("error", sass.logError)) .pipe(sourcemaps.init()) .pipe( autoprefixer({ browsers: ["last 4 versions"] }) ) .pipe(sourcemaps.write()) .pipe(gulp.dest("./css")) .pipe(browserSync.stream()); }); gulp.task("default", gulp.series("serve"));
//modify bookings and communicate it to db const BookingModel = require("../../models/booking-model"); // const _ = require("lodash"); const createBooking = (parent, { bookingData }, context) => { const booking = new BookingModel(bookingData); booking.save(); return booking; }; const confirmBooking = async (parent, { bookingId, status }, context) => { const booking = await BookingModel.findOneAndUpdate( { _id: bookingId }, { confirmed: status } ); return booking; }; const deleteBooking = async (parent, { bookingId }, context) => { try { const booking = await BookingModel.findOne({ _id: bookingId }); if (!booking) { return { status: false, message: "Booking Doesn't Exists", }; } await BookingModel.deleteOne({ _id: bookingId }); } catch (e) { return { status: false, message: e.message }; } return { status: true, message: "" }; }; module.exports = { createBooking, confirmBooking, deleteBooking, };
let accessToken = null; const clientID = 'ebea4c0e5e584569a59af51fc0de20aa'; const redirectURI = 'http://localhost:3000/'; const Spotify = { getAccessToken: () => { if (accessToken) { return accessToken; } // check for access token in current url. let url = window.location.href; let token = null; let expiresIn = null; let tokenMatch = url.match(/access_token=([^&]*)/); if (tokenMatch) { token = tokenMatch[0].split("=")[1]; } let expireMatch = url.match(/expires_in=([^&]*)/); if (expireMatch) { expiresIn = expireMatch[0].split("=")[1]; } if (token && expiresIn) { window.setTimeout(() => accessToken = '', expiresIn * 1000); window.history.pushState('Access Token', null, '/'); accessToken = token; } // if token not in url then redirect to spotify for new token. if (!accessToken || accessToken.length === 0) { const getTokenURL = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`; window.location = getTokenURL; } else { return accessToken; } }, search: async (searchTerm) => { const fetchURL = `https://api.spotify.com/v1/search?type=track&q=${searchTerm}`; const accessToken = Spotify.getAccessToken(); let header = { headers: {Authorization: `Bearer ${accessToken}`} }; try { const response = await fetch(fetchURL, header); if (response.ok) { const jsonResponse = await response.json(); if (jsonResponse.tracks.items) { return jsonResponse.tracks.items.map(track => { return { id: track.id, name: track.name, artist: track.artists[0].name, album: track.album.name, uri: track.uri }; }); } else { return []; } } throw new Error('Request failed!'); } catch (error) { console.log(error) } }, savePlaylist: async (playListName, trackURIs) => { if ( !playListName || playListName.length === 0 || !trackURIs || trackURIs.length === 0) { return; } try { const accessToken = Spotify.getAccessToken(); const header = { headers: {Authorization: `Bearer ${accessToken}`} }; // Get User Id. let userId; const fetchUserIdURL = 'https://api.spotify.com/v1/me'; let response = await fetch(fetchUserIdURL, header); if (response.ok) { const jsonResponse = await response.json(); userId = jsonResponse.id; } else { throw new Error('Get User Id Request failed!'); } // Create Playlist space. let playlistId; const createPlaylistURL = `https://api.spotify.com/v1/users/${userId}/playlists`; const data = JSON.stringify({name: playListName}); response = await fetch(createPlaylistURL, { method: 'POST', body: data, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}` } }); if (response.ok) { const jsonResponse = await response.json(); playlistId = jsonResponse.id } else { throw new Error('Create Playlist space Request failed!'); } // Add tracks to playlist. const addTrackToPlaylistURL = `https://api.spotify.com/v1/playlists/${playlistId}/tracks`; const trackData = JSON.stringify({uris: trackURIs}); response = await fetch(addTrackToPlaylistURL, { method: 'POST', body: trackData, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}` } }); if (!response.ok) { throw new Error('Add tracks to playlist Request failed!'); } } catch (error) { console.log(error); } } }; export default Spotify;
app.controller('photoController', function($scope, $http, $modal) { $http.get(photoJson) .then(function(res){ $scope.albums = res.data; }); $scope.open = function (image) { var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: 'photoModalInstanceController', resolve: { image: function () { return image; } } }); }; }) app.controller('photoModalInstanceController', function($scope, $modalInstance, image) { $scope.image = image; })
import React, { Component } from 'react'; import logo from './logo.svg'; export default SvgIcon( { displayName: 'Logo' })(logo);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var app = getApp(); var api = require("../api.js"); var zjSubjectItem = [ "物理", "化学", "生物", "历史", "地理", "政治", "技术" ]; var shSubjectItem = [ "政治", "历史", "地理", "生命科学", "物理", "化学" ]; var subjectItem = [ "物理", "化学", "生物", "历史", "地理", "政治" ]; var newSubjectItem = [ "化学", "生物", "地理", "政治" ]; var zjSubject = [ { name: "物理", st: false }, { name: "化学", st: false }, { name: "生物", st: false }, { name: "历史", st: false }, { name: "地理", st: false }, { name: "政治", st: false }, { name: "技术", st: false } ]; var shSubject = [ { name: "政治", st: false }, { name: "历史", st: false }, { name: "地理", st: false }, { name: "生命科学", st: false }, { name: "物理", st: false }, { name: "化学", st: false } ]; var subject = [ { name: "物理", st: false }, { name: "化学", st: false }, { name: "生物", st: false }, { name: "历史", st: false }, { name: "地理", st: false }, { name: "政治", st: false } ]; Page({ data: { isshowSave: 1, isHide: 0, share: false, showLoad: true, VIPId: null, system: "android", payBtnText: app.globalData.payBtnText, vip: false, popup: { popupFlag: false, wrapAnimate: "", popupAnimate: "", bgOpacity: "" }, radarPath: "", currentTab: 0, matchDetail: { subject: [], majorCount: null, majorMatchCount: null, majorMatchRate: null, collegeCount: null, matchCollegeCount: null, collegeMatchRate: null, compositeMatchRate: null, subjectRelated: "-" } }, onShareAppMessage: function onShareAppMessage(res) { var that = this; if (res.from === "button") {} return { title: "我已生成[新高考选科]的报告", imageUrl: "http://wmei-appfile.cn-bj.ufileos.com/share_xk.png", path: "/packages/chooseSubjects/chooseSubPlan/chooseSubPlan?majors=" + JSON.stringify(that.majors) + "&subject=" + JSON.stringify(that.subject) + "&provinceId=" + that.provinceId + "&year=" + that.year + "&share=true" + "&type=" + that.type + "&isHide=" + that.data.isHide }; }, showPopup: function showPopup() { this.setData({ "popup.wrapAnimate": "wrapAnimate", "popup.bgOpacity": 0, "popup.popupFlag": true, "popup.popupAnimate": "popupAnimate" }); }, hidePopup: function hidePopup() { var _this = this; this.setData({ "popup.wrapAnimate": "wrapAnimateOut", "popup.bgOpacity": .4, "popup.popupAnimate": "popupAnimateOut" }); setTimeout(function() { _this.setData({ "popup.popupFlag": false }); }, 200); }, goChooseSubIndex: function goChooseSubIndex() { wx.navigateTo({ url: "../index/index" }); }, //获取单个选科方案详情 getChooseSubPlan: function getChooseSubPlan(id) { var that = this; var majorCodes = []; var major = []; api.getChooseSubPlan("Users/ChooseSubjectsSolution/Get?id=" + id, "POST").then(function(res) { that.setData({ matchDetail: res.result }); for (var i = 0; i < res.result.majors.length; i++) { majorCodes.push({ recommendRate: res.result.majors[i].recommendRate, majorCode: res.result.majors[i].majorCode }); major.push(res.result.majors[i].majorCode); } that.subject = res.result.subject; that.majors = majorCodes; that.majorCodes = major; app.globalData.chooseSubject.subject = res.result.subject; app.globalData.chooseSubject.majors = majorCodes; app.globalData.chooseSubject.majorCodes = major; app.globalData.chooseSubject.mateMajorList = res.result.majors; that.setData({ majors: res.result.majors }); if (that.data.isHide == 0) { that.queryRecommendSubject(); } switch (parseInt(that.provinceId)) { // 浙江 case 843: if (res.isSuccess) { that.resetArr(zjSubject); for (var _i = 0; _i < res.result.subject.length; _i++) { for (var j = 0; j < zjSubject.length; j++) { if (zjSubject[j].name == res.result.subject[_i]) { zjSubject[j].st = true; break; } } } } that.drawRadar(zjSubject); break; // 上海 case 842: if (res.isSuccess) { that.resetArr(shSubject); for (var _i2 = 0; _i2 < res.result.subject.length; _i2++) { for (var _j = 0; _j < shSubject.length; _j++) { if (shSubject[_j].name == res.result.subject[_i2]) { shSubject[_j].st = true; break; } } } } that.drawRadar(shSubject); break; default: if (res.isSuccess) { that.resetArr(subject); for (var _i3 = 0; _i3 < res.result.subject.length; _i3++) { for (var _j2 = 0; _j2 < subject.length; _j2++) { if (subject[_j2].name == res.result.subject[_i3]) { subject[_j2].st = true; break; } } } } that.drawRadar(subject); break; } }); }, //查询专业匹配 queryMatchRate: function queryMatchRate() { var that = this; api.queryMatchRate("ChooseSubject/Majors/QueryMatchRate", "POST", that.provinceId, that.year, [], that.data.matchDetail.subject, that.majors).then(function(res) { app.globalData.chooseSubject.mateMajorList = res.result; that.setData({ majors: res.result, showLoad: false }); }); }, //保存选科方案 saveChooseSubPlan: function saveChooseSubPlan() { var that = this; wx.showLoading({ title: "生成方案中..." }); var temp = this.data; var userNumId = temp.userInfo.UserId; var province = that.provinceId; var provinceName = ""; var chooseYear = that.year; var subject = temp.matchDetail.subject; var majorCount = temp.matchDetail.majorCount; var majorMatchCount = temp.matchDetail.majorMatchCount; var majorMatchRate = temp.matchDetail.majorMatchRate; var collegeCount = temp.matchDetail.collegeCount; var matchCollegeCount = temp.matchDetail.matchCollegeCount; var collegeMatchRate = temp.matchDetail.collegeMatchRate; var compositeMatchRate = temp.matchDetail.compositeMatchRate; var subjectRelated = temp.matchDetail.subjectRelated; var majors = temp.majors; var chooseSubType = 1; if (that.data.isHide == 1) { chooseSubType = 4; } var cityList = wx.getStorageSync("cityList"); cityList.forEach(function(ele) { if (ele.numId == province) { provinceName = ele.name; } }); api.saveChooseSubPlan("Users/ChooseSubjectsSolution/Insert", "POST", userNumId, province, provinceName, chooseYear, subject, majorCount, majorMatchCount, majorMatchRate, collegeCount, matchCollegeCount, collegeMatchRate, compositeMatchRate, subjectRelated, chooseSubType, majors).then(function(res) { wx.hideLoading(); if (res.isSuccess) { that.showPopup(); } }); }, onLoad: function onLoad(options) { var that = this; if (options && options.choosesubtype) { that.setData({ isshowSave: 0 }); } if (options && options.share) { that.setData({ isHide: options.isHide, share: true, vip: true, showLoad: false }, function() { that.provinceId = options.provinceId; that.year = options.year; that.type = options.type; if (options.isAndroid) { that.subject = JSON.parse(JSON.parse(options.subject)); that.majors = JSON.parse(JSON.parse(options.majors)); } else { that.subject = JSON.parse(options.subject); that.majors = JSON.parse(options.majors); } that.majorCodes = []; for (var i = 0; i < that.majors.length; i++) { that.majorCodes.push(that.majors[i].majorCode); } app.globalData.chooseSubject.provinceType = that.type; app.globalData.chooseSubject.provinceId = that.provinceId; app.globalData.chooseSubject.year = that.year; app.globalData.chooseSubject.subject = that.subject; app.globalData.chooseSubject.majorCodes = that.majorCodes; app.globalData.chooseSubject.majors = that.majors; // app.globalData.chooseSubject.mateMajorList = wx.setStorageSync("chooseSubjectInfo", { provinceId: that.provinceId, year: that.year, provinceType: that.type }); console.log("codes", that.majorCodes, "所有", options); if (that.data.isHide == 0) { that.queryRecommendSubject(); } else { that.queryMatchRate1(); } console.log("缓存"); console.log(wx.getStorageSync("chooseSubjectInfo")); }); } else { var _init = function _init() { that.setData({ vip: true, showLoad: false }, function() { that.provinceId = app.globalData.chooseSubject.provinceId; that.year = app.globalData.chooseSubject.year; var chooseSubProvinceList = wx.getStorageSync("chooseSubProvinceList"); for (var i = 0; i < chooseSubProvinceList.length; i++) { if (that.provinceId == chooseSubProvinceList[i].provinceId) { that.type = chooseSubProvinceList[i].type; app.globalData.chooseSubject.provinceType = chooseSubProvinceList[i].type; var chooseSubjectInfo = wx.getStorageSync("chooseSubjectInfo"); chooseSubjectInfo.provinceType = chooseSubProvinceList[i].type; wx.setStorageSync("chooseSubjectInfo", chooseSubjectInfo); console.log(chooseSubjectInfo); break; } } if (options.id) { that.getChooseSubPlan(options.id); } else if (that.data.isHide == 0) { that.subject = []; that.majorCodes = app.globalData.chooseSubject.majorCodes; that.majors = app.globalData.chooseSubject.majors; that.queryRecommendSubject(); } var userInfo = wx.getStorageSync("userInfo")[0]; that.setData({ userInfo: userInfo }); }); }; if (options && options.isHide) { that.setData({ isHide: 1 }); that.queryMatchRate1(); } if (options && options.choosesubtype == 4) { that.setData({ isHide: 1 }); } var userType = wx.getStorageSync("userInfo")[0].UserType; if (userType > 1) { _init(); } else { if (app.globalData.system == "ios") { that.setData({ system: "ios" }); } else { that.setData({ system: "android" }); } that.setData({ showLoad: false }); } } }, payBtn: function payBtn(e) { var bigType = e.currentTarget.dataset.bigtype; var id = e.currentTarget.dataset.id; wx.navigateTo({ url: "/packages/paySystem/memberCardDetail/memberCardDetail" }); }, noPay: function noPay() { app.payPrompt(); }, // 选择三个科目 chooseSub: function chooseSub(e) { var that = this; var index = e.currentTarget.dataset.index; var itemList = []; var subject = this.data.matchDetail.subject; console.log("选择省份开始"); console.log(that.provinceId); switch (parseInt(that.provinceId)) { // 浙江 case 843: console.log("浙江"); itemList = zjSubjectItem.filter(function(item) { return !subject.some(function(newItem) { return newItem === item; }); }); console.log(itemList); break; // 上海 case 842: itemList = shSubjectItem.filter(function(item) { return !subject.some(function(newItem) { return newItem === item; }); }); break; // 其他 default: if (this.type == 1) { itemList = subjectItem.filter(function(item) { return !subject.some(function(newItem) { return newItem === item; }); }); break; } else { switch (index) { case 0: console.log("普通"); itemList = that.data.matchDetail.subject[0] == "物理" ? [ "历史" ] : [ "物理" ]; console.log(itemList); break; default: itemList = newSubjectItem.filter(function(item) { return !subject.some(function(newItem) { return newItem === item; }); }); break; } } } wx.showActionSheet({ itemList: itemList, success: function success(res) { that.subject[index] = itemList[res.tapIndex]; that.setData(_defineProperty({}, "matchDetail.subject[" + index + "]", itemList[res.tapIndex]), function() { wx.showLoading({ title: "生成方案中..." }); if (!that.data.share) { that.setData({ isshowSave: 1 }); } app.globalData.chooseSubject.subject = that.data.matchDetail.subject; if (that.data.isHide == 1) { that.queryMatchRate1(); } else { that.queryRecommendSubject(); } }); } }); }, // 职业匹配跳转-暂未开放 careerDetail: function careerDetail() { wx.showToast({ title: "暂未开放", icon: "none" }); }, queryRecommendSubject: function queryRecommendSubject() { var that = this; that.setData({ "matchDetail.compositeMatchRate": null, "matchDetail.majorCount": null, "matchDetail.majorMatchCount": null, "matchDetail.majorMatchRate": null, "matchDetail.collegeCount": null, "matchDetail.matchCollegeCount": null, "matchDetail.collegeMatchRate": null }); api.queryRecommendSubject("ChooseSubject/QueryRecommendSubject", "POST", that.provinceId, that.year, that.majorCodes, that.subject).then(function(res) { if (res.isSuccess) { that.setData({ matchDetail: res.result }); that.subject = res.result.subject; app.globalData.chooseSubject.subject = res.result.subject; if (that.data.isHide == 0) { that.queryMatchRate(); } } else { wx.showToast({ title: res.message, icon: "none" }); that.setData({ "matchDetail.compositeMatchRate": 0 }); } switch (parseInt(that.provinceId)) { // 浙江 case 843: if (res.isSuccess) { that.resetArr(zjSubject); for (var i = 0; i < res.result.subject.length; i++) { for (var j = 0; j < zjSubject.length; j++) { if (zjSubject[j].name == res.result.subject[i]) { zjSubject[j].st = true; break; } } } } that.drawRadar(zjSubject); break; // 上海 case 842: if (res.isSuccess) { that.resetArr(shSubject); for (var _i4 = 0; _i4 < res.result.subject.length; _i4++) { for (var _j3 = 0; _j3 < shSubject.length; _j3++) { if (shSubject[_j3].name == res.result.subject[_i4]) { shSubject[_j3].st = true; break; } } } } that.drawRadar(shSubject); break; default: if (res.isSuccess) { that.resetArr(subject); for (var _i5 = 0; _i5 < res.result.subject.length; _i5++) { for (var _j4 = 0; _j4 < subject.length; _j4++) { if (subject[_j4].name == res.result.subject[_i5]) { subject[_j4].st = true; break; } } } } that.drawRadar(subject); break; } wx.hideLoading(); }); }, resetArr: function resetArr(subject) { for (var i = 0; i < subject.length; i++) { subject[i].st = false; } }, swiperNav: function swiperNav(e) { this.setData({ currentTab: e.detail.current }); }, // 返回选择意向专业 chooseMajor: function chooseMajor() { wx.redirectTo({ url: "../chooseMajor/chooseMajor" }); }, // 绘制雷达图 drawRadar: function drawRadar(data) { var that = this; var num = data.length; var ctx = wx.createCanvasContext("radar"); // 绘制六边形 function drawBg() { ctx.setStrokeStyle("#e7e7e7"); ctx.setFillStyle("rgba(228,228,228,0.1)"); //画6条线段 for (var j = -2; j < num - 2; j++) { //坐标 var x = 160 + 88 * Math.cos(Math.PI * 2 / num * j); var y = 110 + 88 * Math.sin(Math.PI * 2 / num * j); ctx.lineTo(x, y); } ctx.closePath(); ctx.stroke(); ctx.fill(); } function drawText() { ctx.beginPath(); ctx.setFontSize(23); var OffsetX = 0; var OffsetY = 0; for (var j = -2; j < num - 2; j++) { switch (j) { case -2: OffsetX = -50; break; case -1: OffsetX = 13; break; case 0: OffsetX = 10; OffsetY = 5; break; case 1: OffsetX = 13; OffsetY = 15; break; case 2: OffsetX = -50; OffsetY = 15; break; case 3: OffsetX = -50; OffsetY = 5; break; } //坐标 var x = 160 + 88 * Math.cos(Math.PI * 2 / num * j) + OffsetX; var y = 110 + 88 * Math.sin(Math.PI * 2 / num * j) + OffsetY; ctx.setLineDash([ 0, 0 ], 0); if (data[j + 2].st) { ctx.setStrokeStyle("#212121"); } else { ctx.setStrokeStyle("#757575"); } ctx.strokeText(data[j + 2].name, x, y); } } function drawRegion() { ctx.setLineDash([ 2, 5 ], 1); ctx.setStrokeStyle("#E9302D"); ctx.setFillStyle("rgba(255,190,155,0.3)"); for (var j = -2; j < num - 2; j++) { if (data[j + 2].st) { var x = 160 + 88 * Math.cos(Math.PI * 2 / num * j); var y = 110 + 88 * Math.sin(Math.PI * 2 / num * j); ctx.lineTo(x, y); } } ctx.closePath(); ctx.stroke(); ctx.fill(); } drawBg(); drawText(); drawRegion(); ctx.draw(false, function() { wx.canvasToTempFilePath({ x: 0, y: 0, width: 320, height: 220, destWidth: 320, destHeight: 220, canvasId: "radar", success: function success(res) { that.setData({ radarPath: res.tempFilePath }); } }); }); }, //查询专业匹配 queryMatchRate1: function queryMatchRate1() { wx.showLoading({ title: "生成方案中..." }); var that = this; var provinceId = app.globalData.chooseSubject.provinceId; var subject = app.globalData.chooseSubject.subject; var year = app.globalData.chooseSubject.year; api.queryMatchRate("ChooseSubject/Majors/QueryMatchRate", "POST", provinceId, year, [], subject, []).then(function(res) { var majorCodes = []; var mateMajorList = []; res.result.forEach(function(ele, index) { majorCodes.push(ele.majorCode); }); app.globalData.chooseSubject.mateMajorList = res.result; app.globalData.chooseSubject.majorCodes = majorCodes; that.majorCodes = majorCodes; that.majors = mateMajorList; that.subject = app.globalData.chooseSubject.subject; that.setData({ majors: res.result }, function() { that.queryRecommendSubject(); }); // api.queryRecommendSubject('ChooseSubject/QueryRecommendSubject', 'POST', provinceId, year, majorCodes, subject).then(res => { // if (res.isSuccess) { // that.setData({ // requestFlag: true, // majorMatch: res.result // }) // } // }) }); } });
import React, { PureComponent } from 'react'; import { Button, Form, Select, DatePicker } from 'antd'; // 查询订单 的表单 const FormItem = Form.Item; const Option = Select.Option; class FilterForm extends PureComponent{ //点击查询 处理订单查询 handleFilterSubmit = ()=>{ // console.log(this); let fieldsValue = this.props.form.getFieldsValue(['city_id']); console.log(fieldsValue) }; render(){ const { getFieldDecorator } = this.props.form; return ( <Form layout="inline"> <FormItem label="城市"> { getFieldDecorator('city_id')( <Select palceholder="全部" style={{width:90}}> <Option value="1">江苏省</Option> <Option value="2">安徽省</Option> <Option value="3">浙江省</Option> <Option value="4">河北省</Option> </Select> ) } </FormItem> <FormItem label="订单时间"> { getFieldDecorator('start_time')( <DatePicker showTime format="YYYY-MM-DD HH:mm" placeholder="From" // onChange={} // onOk={} /> ) } </FormItem> <FormItem> { getFieldDecorator('end_time')( <DatePicker showTime format="YYYY-MM-DD HH:mm" placeholder="To" // onChange={} // onOk={} /> ) } </FormItem> <FormItem label="订单状态"> { getFieldDecorator('status')( <Select palceholder="全部" style={{width:80}}> <Option value="">全部</Option> <Option value="1">进行中</Option> <Option value="2">结束行程</Option> </Select> ) } </FormItem> <FormItem> <Button type="primary" style={{margin:'0 20px'}} onClick={this.handleFilterSubmit}>查询</Button> <Button>重置</Button> </FormItem> </Form> ) }; }; FilterForm=Form.create({})(FilterForm); export default FilterForm;
import { DIRECTION_VERTICAL, DIRECTION_HORIZONTAL, DIRECTION_BOTH } from "../common/consts"; export class ScrollDirection { constructor(direction) { this.DIRECTION_HORIZONTAL = "horizontal"; this.DIRECTION_VERTICAL = "vertical"; this.DIRECTION_BOTH = "both"; this.direction = direction !== null && direction !== void 0 ? direction : DIRECTION_VERTICAL; } get isHorizontal() { return this.direction === DIRECTION_HORIZONTAL || this.direction === DIRECTION_BOTH; } get isVertical() { return this.direction === DIRECTION_VERTICAL || this.direction === DIRECTION_BOTH; } get isBoth() { return this.direction === DIRECTION_BOTH; } }
// detect whether passive events are supported by the browser const detectPassiveEvents = () => { let result = false; try { const opts = Object.defineProperty({}, 'passive', { get: function () { result = true; return false; } }); window.addEventListener('testpassive', null, opts); window.removeEventListener('testpassive', null, opts); } catch (e) {} return result; }; const ua = (typeof navigator !== 'undefined') ? navigator.userAgent : ''; const environment = (typeof window !== 'undefined') ? 'browser' : 'node'; // detect platform const platformName = (/android/i.test(ua) ? 'android' : (/ip([ao]d|hone)/i.test(ua) ? 'ios' : (/windows/i.test(ua) ? 'windows' : (/mac os/i.test(ua) ? 'osx' : (/linux/i.test(ua) ? 'linux' : (/cros/i.test(ua) ? 'cros' : null)))))); // detect browser const browserName = (environment !== 'browser') ? null : (/(Chrome\/|Chromium\/|Edg.*\/)/.test(ua) ? 'chrome' : // chrome, chromium, edge (/Safari\//.test(ua) ? 'safari' : // safari, ios chrome/firefox (/Firefox\//.test(ua) ? 'firefox' : 'other'))); const xbox = /xbox/i.test(ua); const touch = (environment === 'browser') && ('ontouchstart' in window || ('maxTouchPoints' in navigator && navigator.maxTouchPoints > 0)); const gamepads = (environment === 'browser') && (!!navigator.getGamepads || !!navigator.webkitGetGamepads); const workers = (typeof Worker !== 'undefined'); const passiveEvents = detectPassiveEvents(); /** * Global namespace that stores flags regarding platform environment and features support. * * @namespace * @example * if (pc.platform.touch) { * // touch is supported * } */ const platform = { /** * String identifying the current runtime environment. Either 'browser' or 'node'. * * @type {'browser' | 'node'} */ environment: environment, /** * The global object. This will be the window object when running in a browser and the global * object when running in nodejs. * * @type {object} */ global: (environment === 'browser') ? window : global, /** * Convenience boolean indicating whether we're running in the browser. * * @type {boolean} */ browser: environment === 'browser', /** * True if running on a desktop or laptop device. * * @type {boolean} */ desktop: ['windows', 'osx', 'linux', 'cros'].includes(platformName), /** * True if running on a mobile or tablet device. * * @type {boolean} */ mobile: ['android', 'ios'].includes(platformName), /** * True if running on an iOS device. * * @type {boolean} */ ios: platformName === 'ios', /** * True if running on an Android device. * * @type {boolean} */ android: platformName === 'android', /** * True if running on an Xbox device. * * @type {boolean} */ xbox: xbox, /** * True if the platform supports gamepads. * * @type {boolean} */ gamepads: gamepads, /** * True if the supports touch input. * * @type {boolean} */ touch: touch, /** * True if the platform supports Web Workers. * * @type {boolean} */ workers: workers, /** * True if the platform supports an options object as the third parameter to * `EventTarget.addEventListener()` and the passive property is supported. * * @type {boolean} * @ignore */ passiveEvents: passiveEvents, /** * Get the browser name. * * @type {'chrome' | 'safari' | 'firefox' | 'other' | null} * @ignore */ browserName: browserName }; export { platform };
import React, {useEffect, useRef} from 'react'; import useDropDown from './useDropDown'; import {useMutation} from "@apollo/client"; import {EDIT_STATUS_MUTATION} from "../../../graphql/mutations/mutations"; function CustomSelect(props) { const [editStatus] = useMutation(EDIT_STATUS_MUTATION); const dropDownOptions = ['UNA','ASD', 'COM'] const [dropDownValue, CustomDropDown] = useDropDown('', props.status, dropDownOptions, editStatus, props.id); console.log('Drop Down Value', dropDownValue); const ref = useRef(); return ( <div> <CustomDropDown ref={ref}/> </div> ); } export default CustomSelect;
"use strict"; exports.TopPocket = exports.TopPocketPropsType = exports.TopPocketProps = exports.viewFunction = void 0; var _inferno = require("inferno"); var _vdom = require("@devextreme/vdom"); var _load_indicator = require("../load_indicator"); var _type = require("../../../core/utils/type"); var _message = _interopRequireDefault(require("../../../localization/message")); var _base_props = require("../common/base_props"); var _combine_classes = require("../../utils/combine_classes"); var _consts = require("./common/consts"); var _excluded = ["pocketState", "pocketTop", "pullDownIconAngle", "pullDownOpacity", "pullDownTop", "pullDownTranslateTop", "pulledDownText", "pullingDownText", "refreshStrategy", "refreshingText", "topPocketRef", "topPocketTranslateTop", "visible"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } 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 _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var viewFunction = function viewFunction(viewModel) { var _viewModel$props = viewModel.props, refreshStrategy = _viewModel$props.refreshStrategy, topPocketRef = _viewModel$props.topPocketRef, pullDownClasses = viewModel.pullDownClasses, pullDownIconStyles = viewModel.pullDownIconStyles, pullDownRef = viewModel.pullDownRef, pullDownStyles = viewModel.pullDownStyles, pulledDownText = viewModel.pulledDownText, pullingDownText = viewModel.pullingDownText, readyVisibleClass = viewModel.readyVisibleClass, refreshVisibleClass = viewModel.refreshVisibleClass, refreshingText = viewModel.refreshingText, releaseVisibleClass = viewModel.releaseVisibleClass, topPocketStyles = viewModel.topPocketStyles; return (0, _inferno.createVNode)(1, "div", _consts.SCROLLVIEW_TOP_POCKET_CLASS, (0, _inferno.createVNode)(1, "div", pullDownClasses, [refreshStrategy !== "swipeDown" && (0, _inferno.createVNode)(1, "div", _consts.SCROLLVIEW_PULLDOWN_IMAGE_CLASS), refreshStrategy === "swipeDown" && (0, _inferno.createVNode)(1, "div", _consts.PULLDOWN_ICON_CLASS, null, 1, { "style": (0, _vdom.normalizeStyles)(pullDownIconStyles) }), (0, _inferno.createVNode)(1, "div", _consts.SCROLLVIEW_PULLDOWN_INDICATOR_CLASS, (0, _inferno.createComponentVNode)(2, _load_indicator.LoadIndicator), 2), refreshStrategy !== "swipeDown" && (0, _inferno.createVNode)(1, "div", _consts.SCROLLVIEW_PULLDOWN_TEXT_CLASS, [(0, _inferno.createVNode)(1, "div", releaseVisibleClass, pullingDownText, 0), (0, _inferno.createVNode)(1, "div", readyVisibleClass, pulledDownText, 0), (0, _inferno.createVNode)(1, "div", refreshVisibleClass, refreshingText, 0)], 4)], 0, { "style": (0, _vdom.normalizeStyles)(pullDownStyles) }, null, pullDownRef), 2, { "style": (0, _vdom.normalizeStyles)(topPocketStyles) }, null, topPocketRef); }; exports.viewFunction = viewFunction; var TopPocketProps = { pocketState: _consts.TopPocketState.STATE_RELEASED, pullDownTop: 0, pullDownTranslateTop: 0, pullDownIconAngle: 0, pullDownOpacity: 0, pocketTop: 0, topPocketTranslateTop: 0 }; exports.TopPocketProps = TopPocketProps; var TopPocketPropsType = { pocketState: TopPocketProps.pocketState, pullDownTop: TopPocketProps.pullDownTop, pullDownTranslateTop: TopPocketProps.pullDownTranslateTop, pullDownIconAngle: TopPocketProps.pullDownIconAngle, pullDownOpacity: TopPocketProps.pullDownOpacity, pocketTop: TopPocketProps.pocketTop, topPocketTranslateTop: TopPocketProps.topPocketTranslateTop, visible: _base_props.BaseWidgetProps.visible }; exports.TopPocketPropsType = TopPocketPropsType; var TopPocket = /*#__PURE__*/function (_BaseInfernoComponent) { _inheritsLoose(TopPocket, _BaseInfernoComponent); function TopPocket(props) { var _this; _this = _BaseInfernoComponent.call(this, props) || this; _this.state = {}; _this.pullDownRef = (0, _inferno.createRef)(); return _this; } var _proto = TopPocket.prototype; _proto.render = function render() { var props = this.props; return viewFunction({ props: _extends({}, props), pullDownRef: this.pullDownRef, releaseVisibleClass: this.releaseVisibleClass, readyVisibleClass: this.readyVisibleClass, refreshVisibleClass: this.refreshVisibleClass, pullingDownText: this.pullingDownText, pulledDownText: this.pulledDownText, refreshingText: this.refreshingText, pullDownClasses: this.pullDownClasses, pullDownStyles: this.pullDownStyles, topPocketStyles: this.topPocketStyles, pullDownIconStyles: this.pullDownIconStyles, restAttributes: this.restAttributes }); }; _createClass(TopPocket, [{ key: "releaseVisibleClass", get: function get() { return this.props.pocketState === _consts.TopPocketState.STATE_RELEASED ? _consts.SCROLLVIEW_PULLDOWN_VISIBLE_TEXT_CLASS : undefined; } }, { key: "readyVisibleClass", get: function get() { return this.props.pocketState === _consts.TopPocketState.STATE_READY ? _consts.SCROLLVIEW_PULLDOWN_VISIBLE_TEXT_CLASS : undefined; } }, { key: "refreshVisibleClass", get: function get() { return this.props.pocketState === _consts.TopPocketState.STATE_REFRESHING ? _consts.SCROLLVIEW_PULLDOWN_VISIBLE_TEXT_CLASS : undefined; } }, { key: "pullingDownText", get: function get() { var pullingDownText = this.props.pullingDownText; if ((0, _type.isDefined)(pullingDownText)) { return pullingDownText; } return _message.default.format("dxScrollView-pullingDownText"); } }, { key: "pulledDownText", get: function get() { var pulledDownText = this.props.pulledDownText; if ((0, _type.isDefined)(pulledDownText)) { return pulledDownText; } return _message.default.format("dxScrollView-pulledDownText"); } }, { key: "refreshingText", get: function get() { var refreshingText = this.props.refreshingText; if ((0, _type.isDefined)(refreshingText)) { return refreshingText; } return _message.default.format("dxScrollView-refreshingText"); } }, { key: "pullDownClasses", get: function get() { var _classesMap; var _this$props = this.props, pocketState = _this$props.pocketState, visible = _this$props.visible; var classesMap = (_classesMap = {}, _defineProperty(_classesMap, _consts.SCROLLVIEW_PULLDOWN, true), _defineProperty(_classesMap, _consts.SCROLLVIEW_PULLDOWN_READY_CLASS, pocketState === _consts.TopPocketState.STATE_READY), _defineProperty(_classesMap, _consts.SCROLLVIEW_PULLDOWN_LOADING_CLASS, pocketState === _consts.TopPocketState.STATE_REFRESHING), _defineProperty(_classesMap, "dx-state-invisible", !visible), _classesMap); return (0, _combine_classes.combineClasses)(classesMap); } }, { key: "pullDownStyles", get: function get() { if (this.props.refreshStrategy === "swipeDown") { return { opacity: this.props.pullDownOpacity, transform: "translate(0px, ".concat(this.props.pullDownTranslateTop, "px)") }; } return undefined; } }, { key: "topPocketStyles", get: function get() { if (this.props.refreshStrategy === "pullDown") { return { top: "".concat(this.props.pocketTop, "px"), transform: "translate(0px, ".concat(this.props.topPocketTranslateTop, "px)") }; } return undefined; } }, { key: "pullDownIconStyles", get: function get() { return { transform: "rotate(".concat(this.props.pullDownIconAngle, "deg)") }; } }, { key: "restAttributes", get: function get() { var _this$props2 = this.props, pocketState = _this$props2.pocketState, pocketTop = _this$props2.pocketTop, pullDownIconAngle = _this$props2.pullDownIconAngle, pullDownOpacity = _this$props2.pullDownOpacity, pullDownTop = _this$props2.pullDownTop, pullDownTranslateTop = _this$props2.pullDownTranslateTop, pulledDownText = _this$props2.pulledDownText, pullingDownText = _this$props2.pullingDownText, refreshStrategy = _this$props2.refreshStrategy, refreshingText = _this$props2.refreshingText, topPocketRef = _this$props2.topPocketRef, topPocketTranslateTop = _this$props2.topPocketTranslateTop, visible = _this$props2.visible, restProps = _objectWithoutProperties(_this$props2, _excluded); return restProps; } }]); return TopPocket; }(_vdom.BaseInfernoComponent); exports.TopPocket = TopPocket; TopPocket.defaultProps = _extends({}, TopPocketPropsType);
'use strict'; module.exports = { task: { options: { reporter: 'spec' }, src: ['test/*_test.js'] } };
//= link_directory ../stylesheets/flux_base .css
// -------------------------------------------------- // REBOOT :: FORMS PLUGIN // Create stylable form elements // ©2016 by Reactive Apps // MIT License // -------------------------------------------------- (function($) { // Modify all the form elements on document ready $(function() { // -------------------------------------------------- // SELECT ELEMENTS // Build the select wrappers var $select_wrapper = $(document.createElement('div')) .addClass('select-wrapper') .html('<div class="select-arrows"></div><div class="select-box"><span class="label"></span></div>'); // Wrap all the select elements $('select').each(function() { var $select = $(this).clone(); var $wrapper = $select_wrapper.clone(); // Replace the element $(this).replaceWith($wrapper.prepend($select)); // Add the onChange event $select.on('change', function() { $wrapper.find('.select-box .label').text($select.find('option:selected').text()); }) .trigger('change'); }); // END SELECT ELEMENTS // -------------------------------------------------- // -------------------------------------------------- // CHECKBOX ELEMENTS // Build the checkbox wrappers var $checkbox_wrapper = $(document.createElement('span')) .addClass('checkbox') .html('<span class="check"><i class="icon-check"></i></span><span class="box"></span>'); // Wrap all the checkbox elements $(':checkbox:not(.toggle)').each(function() { var $checkbox = $(this); var $wrapper = $checkbox_wrapper.clone(); var $parent = $checkbox.parent(); // Only modify properly nested elements if ($parent.is('label')) { // Add the .checkbox-wrapper class to the parent $parent.addClass('checkbox-wrapper'); // Detach the checkbox and add it to the wrapper $wrapper.prepend($checkbox); // Wrap the label text $parent.html('<span class="checkbox-label">' + $parent.html() + '</span>'); // Add the checkbox back in $parent.prepend($wrapper); } }); // END CHECKBOX ELEMENTS // -------------------------------------------------- // -------------------------------------------------- // TOGGLE ELEMENTS // Build the toggle wrappers var $toggle_wrapper = $(document.createElement('span')) .addClass('toggle') .html('<span class="toggle-handle"></span><span class="toggle-box"><span class="toggle-bkg"></span></span>'); // Wrap all the toggle elements $('.toggle:checkbox').each(function() { var $toggle = $(this); var $wrapper = $toggle_wrapper.clone(); var $parent = $toggle.parent(); // If the toggle is in a wrapper if ($parent.is('label')) { // Add the .toggle-wrapper class to the parent $parent.addClass('toggle-wrapper'); // Detach the wrapped input and add it to the wrapper $wrapper.prepend($toggle); // Wrap the label text $parent.html('<span class="toggle-label">' + $parent.html() + '</span>'); // Add the toggle back in $parent.append($wrapper); } // The element is not wrapped else { // Wrap the element in a span $toggle.wrap('<span class="toggle-wrapper"></span'); // Replace the input with the wrapped input $toggle.replaceWith($wrapper.prepend($toggle.clone())); } }); // END TOGGLE ELEMENTS // -------------------------------------------------- // -------------------------------------------------- // RADIO ELEMENTS // Build the radio wrappers var $radio_wrapper = $(document.createElement('span')) .addClass('radio') .html('<span class="radio-btn"></span>'); // Wrap all the radio elements $(':radio').each(function() { var $radio = $(this); var $wrapper = $radio_wrapper.clone(); var $parent = $radio.parent(); // Only modify properly nested elements if ($parent.is('label')) { // Add the .checkbox-wrapper class to the parent $parent.addClass('radio-wrapper'); // Detach the radio and add it to the wrapper $wrapper.prepend($radio); // Wrap the label text $parent.html('<span class="radio-label">' + $parent.html() + '</span>'); // Add the checkbox back in $parent.prepend($wrapper); } }); // END RADIO ELEMENTS // -------------------------------------------------- // -------------------------------------------------- // TEXTAREAS // Build the textarea wrappers var $textarea_wrapper = $(document.createElement('div')) .addClass('textarea-wrapper') .html('<div class="mirror"></div>'); // Just wrap the textareas $('textarea').each(function() { var $textarea = $(this).clone(); var $wrapper = $textarea_wrapper.clone(); var $mirror = $wrapper.find('.mirror'); // Add the textarea classes to the mirror element $mirror.addClass($textarea.attr('class')); // Mirror the content on change $textarea.on('input propertychange', function() { $mirror.html($textarea.val().replace(/\n/g, '<br>') + '<br>'); }); // Replace the textarea $(this).replaceWith($wrapper.prepend($textarea)); }); // END TEXTAREAS // -------------------------------------------------- }); })(jQuery);
//show the form when "New item" button is clicked function showForm() { document.getElementById("module-2").style.display = "block"; console.log(showForm); } //array that will hold the user generated objects var myArray = []; //film object (values to be populated by user input) var film = { };
import React from 'react'; import { ActivityIndicator, StatusBar, View } from 'react-native'; import { Text } from 'react-native-elements'; import data_manager from './data_manager'; export default class AuthLoadingScreen extends React.Component { constructor(props) { super(props); this._bootstrapAsync(); } _bootstrapAsync = async () => { let screen = 'Auth'; this.connectionState = data_manager.getConnectionState(); switch (this.connectionState) { case 'AUTH': screen = 'Auth'; break; case 'WAITING_RECIPIENT': data_manager.clearQueue(); try { const handshake = await data_manager.handshake(); if (handshake === true) { data_manager.setConnectionState('connected'); screen = 'App'; } } catch (e) { console.log(e); screen = 'Auth'; } break; case 'CONNECTED': screen = 'App'; break; } this.props.navigation.navigate(screen); }; renderTitle() { if (this.connectionState === 'WAITING_RECIPIENT') { return <Text h4 style={{ color: 'white', marginBottom: 40, }}>Waiting For Recipient</Text>; } return null; } render() { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }}> <StatusBar barStyle="default"/> {this.renderTitle()} <ActivityIndicator size="large" color="white"/> </View> ); } }
import './LineCaption.css'; import React, { PureComponent } from 'react'; export default class LineCaption extends PureComponent{ constructor(props) { super(props); } render(){ const { name } = this.props; return( <div className = "line-caption-block"> <span className = "line-caption-block__text">{name}</span> </div> ); } }
export const routes = { HOME: '/', HOME_PAGE: '/home', SIGN_IN: '/sign_in', REGISTRATION: '/registration', ADS: '/ads/:topic', CREATE_AD: '/create_ad', MY_ADS: '/my_ads', EMPTY_PAGE: '/empty', PROFILE: '/profile', USERS: '/users', MAIN: '/main', };
(function Preview (window){ this.init = function () { var aLinks = document.getElementsByTagName("a"); console.log(aLinks); for (var i= 0; i < aLinks.length; i++) { aLinks[i].onclick = this.preview; } var close = document.getElementsByClassName("close")[0]; console.log(close); close.onclick = this.close; } this.preview = function (e) { console.log("onclick"); e.preventDefault(); var preview = e.target.getAttribute("data-preview"); var el = document.querySelectorAll("[data-preview=" + preview + "]")[0]; var imageSrc = el.getAttribute("href"); var imageEl = document.getElementById("previewImage"); imageEl.setAttribute("src", imageSrc); var containerEl = document.getElementById("container"); containerEl.className = "showOverlay"; } this.close = function(e) { console.log("close function"); var containerEl = document.getElementById("container"); containerEl.className = ""; } // this.appendImage() = function() { // } window.Preview = this; })(window)
// init main module with dependecies var app = angular.module('starwars-info', [ 'ui.router', 'ngResource' ]); // configure ui-router: https://ui-router.github.io/ng1/ app.config(function($stateProvider){ $stateProvider .state({ name: 'home', url: '/home', templateUrl: './views/main.view.html' }) }); // service for getting data from swapi.co angular.module('starwars-info').factory('swApi', function($resource){ return { getPlanet: function(id) { var planet = $resource.get('//swapi.co/api/planet/'); return planet; }, getVehicle: function(id) { var VehicleResource = $resource('//swapi.co/api/vehicles/:id'); var vehicles = VehicleResource.get({id: id}); return vehicles.$promise; } } }); // controller for getting vehicles app.controller('tableRendererController', function($scope, swApi){ swApi.getVehicle().then(function(vehiclesResource){ $scope.vehicles = vehiclesResource.results; }); }); // directive for rendering vehicles app.directive('tableRenderer', function(){ return { restrict: 'E', templateUrl: './table-renderer.html', controller: 'tableRendererController' } });
const _ = require('lodash'); const { DAYS_FOR_HOT_FEED, DAYS_FOR_TRENDING_FEED, MEDIAN_USER_WAIVIO_RATE, HOT_NEWS_CACHE_SIZE, TREND_NEWS_CACHE_SIZE, } = require('utilities/constants'); const { ObjectId } = require('mongoose').Types; const { Post } = require('database').models; const hotTrandGetter = require('./feedCache/hotTrandGetter'); const objectIdFromDaysBefore = (daysCount) => { const startDate = new Date(); startDate.setDate(startDate.getDate() - daysCount); startDate.setMilliseconds(0); startDate.setSeconds(0); startDate.setMinutes(0); startDate.setHours(0); const str = `${Math.floor(startDate.getTime() / 1000).toString(16)}0000000000000000`; return new ObjectId(str); }; // eslint-disable-next-line camelcase const makeConditions = ({ category, user_languages }) => { let cond = {}; let sort = {}; switch (category) { case 'created': cond = { reblog_to: null }; sort = { _id: -1 }; break; case 'hot': cond = { _id: { $gte: objectIdFromDaysBefore(DAYS_FOR_HOT_FEED) }, author_weight: { $gte: MEDIAN_USER_WAIVIO_RATE }, reblog_to: null, }; sort = { children: -1 }; break; case 'trending': cond = { _id: { $gte: objectIdFromDaysBefore(DAYS_FOR_TRENDING_FEED) }, author_weight: { $gte: MEDIAN_USER_WAIVIO_RATE }, reblog_to: null, }; sort = { net_rshares: -1 }; break; } if (!_.isEmpty(user_languages)) cond.language = { $in: user_languages }; return { cond, sort }; }; module.exports = async ({ // eslint-disable-next-line camelcase category, skip, limit, user_languages, keys, }) => { // try to get posts from cache const cachedPosts = await getFromCache({ skip, limit, user_languages, category, }); if (cachedPosts) return { posts: cachedPosts }; const { cond, sort } = makeConditions({ category, user_languages }); let posts = []; try { posts = await Post .find(cond) .sort(sort) .skip(skip) .limit(limit) .populate({ path: 'fullObjects', select: '-latest_posts' }) .select(keys || {}) .lean(); } catch (error) { return { error }; } return { posts }; }; const getFromCache = async ({ skip, limit, user_languages: locales, category, }) => { let res; switch (category) { case 'hot': if ((skip + limit) < HOT_NEWS_CACHE_SIZE) { res = await hotTrandGetter.getHot({ skip, limit, locales }); } break; case 'trending': if ((skip + limit) < TREND_NEWS_CACHE_SIZE) { res = await hotTrandGetter.getTrend({ skip, limit, locales }); } break; } if (_.get(res, 'posts.length')) { return res.posts; } };
import { getNonce } from "lib/metamask"; import { updateUserWallet, requestWithdraw, finalizeWithdraw, cancelWithdraw, createBet, getMyBets, set2FA, userAuth, getCurrencyAddress, resendConfirmEmail, getTransactions, getJackpotPot, getProviderToken, sendFreeCurrencyRequest } from "lib/api/users"; import moment from "moment"; import { Numbers } from "../../lib/ethereum/lib"; import Cache from "../../lib/cache/cache"; import ChatChannel from "../Chat"; import store from "../../containers/App/store"; import { setProfileInfo } from "../../redux/actions/profile"; import { setStartLoadingProcessDispatcher } from "../../lib/redux"; import { setModal } from "../../redux/actions/modal"; import { processResponse } from "../../lib/helpers"; import _, { startCase } from 'lodash'; import Pusher from 'pusher-js'; import { apiUrl } from "../../lib/api/apiConfig"; import { setMessageNotification } from "../../redux/actions/message"; import { formatCurrency } from "../../utils/numberFormatation"; export default class User { constructor({ platformAddress, tokenAddress, decimals, appId, user, app }) { // Logged this.id = user.id; this.user_id = user.id; this.app_id = appId; this.platformAddress = platformAddress; this.tokenAddress = tokenAddress; this.decimals = decimals; this.bearerToken = user.bearerToken; this.balance = user.balance; this.username = user.username; this.integrations = user.integrations ? user.integrations : app.integrations; this.address = user.address; this.user = user; this.isLoaded = false; this.app = Cache.getFromCache("appInfo"); this.params = { deposits : [], } this.__init__(); } /** * @use Initialization Function */ __init__ = async () => { try{ setStartLoadingProcessDispatcher(1); await this.setupChat(); setStartLoadingProcessDispatcher(2); await this.getAllData(); setStartLoadingProcessDispatcher(3); this.listenAppPrivateChannel(); setStartLoadingProcessDispatcher(6); }catch(err){ console.log(err) } } getPusherAPIKey = () => { return this.app.integrations.pusher ? this.app.integrations.pusher.key : ''; } listenAppPrivateChannel = () => { this.pusher = new Pusher(this.getPusherAPIKey(), { cluster : 'eu', forceTLS: true, authEndpoint: `${apiUrl}/api/users/pusher/auth`, }); this.channel = this.pusher.subscribe(`private-${this.id}`); /* Listen to Deposits */ this.channel.bind('deposit', async (data) => { await store.dispatch(setMessageNotification(data.message)); this.getAllData(true); }); /* Listen to Withdraws */ this.channel.bind('withdraw', (data) => { }); /* Listen to Jackpot */ this.channel.bind('jackpot', async (data) => { await store.dispatch(setModal({key : 'JackpotModal', value : data.message})); }); /* Listen to Update Wallet */ this.channel.bind('update_balance', async (data) => { const resp = JSON.parse(data.message); const value = formatCurrency(resp.value); await this.updateBalance({ userDelta: Number(value) }); }); } hasLoaded = () => this.isLoaded; getBalance = (currency) => { const state = store.getState(); currency = currency ? currency : state.currency; if(_.isEmpty(currency)){ return 0;} const wallet = this.getWallet({currency}); if(_.isEmpty(wallet)){ return 0;} return wallet.playBalance; }; getBalanceWithBonus = (currency) => { const state = store.getState(); currency = currency ? currency : state.currency; if(_.isEmpty(currency)){ return 0;} const wallet = this.getWallet({currency}); if(_.isEmpty(wallet)){ return 0;} return wallet.playBalance + wallet.bonusAmount; }; getWallet = ({currency}) => {return this.user.wallet.find( w => new String(w.currency._id).toString().toLowerCase() == new String(currency._id).toString().toLowerCase())}; getWallets = () => this.user.wallet; getBalanceAsync = async () => Numbers.toFloat((await this.updateUser()).balance); getChat = () => this.chat; getChannel = () => this.channel; getDeposits = () => { if(!this.user.deposits) { return [] }; return this.user.deposits.sort(function(a,b){ return new Date(b.creation_timestamp) - new Date(a.creation_timestamp); }); } getID = () => this.id; getUsername = () => this.username; getAppCustomization = () => this.app.customization; getAllData = async (reloadUser=false) => { if(reloadUser === true){ await this.updateUser() }; setStartLoadingProcessDispatcher(6); this.isLoaded = true; await this.updateUserState(); } getBalanceData = async () => { await this.updateUser(); await this.updateUserState(); } updateBalance = async ({ userDelta, amount, totalBetAmount }) => { const state = store.getState(); const { currency } = state; this.user.wallet.forEach((w) => { if (new String(w.currency._id).toString().toLowerCase() == new String(currency._id).toString().toLowerCase()) { if (userDelta < 0) { const delta = w.playBalance + userDelta; if (_.has(w, 'bonusAmount') && w.bonusAmount > 0) { const newPlayBalance = delta < 0 ? 0 : delta; const newBonusAmount = delta < 0 ? w.bonusAmount + delta : w.bonusAmount; w.playBalance = Math.max(0, newPlayBalance); w.bonusAmount = Math.max(0, newBonusAmount); } else { const newPlayBalance = delta < 0 ? 0 : delta; w.playBalance = Math.max(0, newPlayBalance); } } else { if (_.has(w, 'bonusAmount') && w.bonusAmount > 0) { const newBonusAmount = w.bonusAmount + userDelta; w.bonusAmount = Math.max(0, newBonusAmount); } else { const newPlayBalance = w.playBalance + userDelta; w.playBalance = Math.max(0, newPlayBalance); } } if (w.incrementBetAmountForBonus > w.minBetAmountForBonusUnlocked) { const newPlayBalance = w.playBalance + w.bonusAmount; w.bonusAmount = 0; w.playBalance = Math.max(0, newPlayBalance); w.incrementBetAmountForBonus = 0; } else if (_.has(w, 'incrementBetAmountForBonus')) { const newIncrementBetAmountForBonus = w.incrementBetAmountForBonus + totalBetAmount; w.incrementBetAmountForBonus = Math.max(0, newIncrementBetAmountForBonus); } } }); if(this.app.addOn.pointSystem && (this.app.addOn.pointSystem.isValid == true) && amount) { const ratio = this.app.addOn.pointSystem.ratio.find( p => p.currency == currency._id ).value; const points = await this.getPoints(); this.user.points = points + (amount * ratio); } await this.updateUserState(); } updateBalanceWithoutBet = async ({amount}) => { const state = store.getState(); const { currency } = state; this.user.wallet.forEach((w) => { if(new String(w.currency._id).toString().toLowerCase() == new String(currency._id).toString().toLowerCase()) { w.playBalance = w.playBalance + amount; } }); await this.updateUserState(); } updateBalanceByWallet = async ({ currency, amount }) => { this.user.wallet.forEach((w) => { if(new String(w.currency._id).toString().toLowerCase() == new String(currency._id).toString().toLowerCase()) { w.playBalance = w.playBalance - amount; } }); await this.updateUserState(); } updateUserState = async () => { await store.dispatch(setProfileInfo(this)); } updateKYCStatus = status => { const verified = status.toLowerCase() === 'verified'; this.user = {...this.user, kyc_needed: !verified, kyc_status: status }; this.updateUserState(); } getMyBets = async ({size, game, slug, tag}) => { try{ // grab current state const state = store.getState(); const { currency } = state; if(!this.user_id){return []} if(currency && currency._id){ let res = await getMyBets({ currency : currency._id, user: this.user_id, size, game, slug, tag }, this.bearerToken); return await processResponse(res); }else{ return []; } }catch(err){ console.log(err) throw err; } } getMyTransactions = async ({ size, offset }) => { try{ if(!this.user_id || !this.app_id){return []} const res = await getTransactions({ user: this.user_id, app: this.app_id, size, offset }, this.bearerToken); return await processResponse(res); }catch(err){ throw err; } } setupChat = async () => { this.chat = new ChatChannel({ id : this.id, name : this.username, publicKey : this.integrations.chat.publicKey, token : this.user.integrations.chat.token }); await this.chat.__init__(); } getMessages = () => { return this.chat.getMessages(); } sendMessage = async ({message, data}) => { try{ return await this.chat.sendMessage({message, data}); } catch (err){ throw err; } } getCountry = () => { const { country, country_acronym } = this.user; if (country && country_acronym) { const countryRefactor = startCase(country.toLowerCase()); return { value: country_acronym, text: countryRefactor }; } return false; }; getBirthDate = () => { const { birthday } = this.user; if (birthday) { const birthDateRefactor = birthday.split("").splice(0, 10).join(""); const birthDateReformat = moment(birthDateRefactor).locale("pt").format("L"); return birthDateReformat; } return false; } updateUser = async () => { let user = await userAuth({ user: this.user_id, app: this.app_id }, this.bearerToken); this.user = user; return user; } getUserEmail = () => { return this.user.email } getTokenAmount = async () => { return 0; } confirmDeposit = async ({ amount, transactionHash, currency }) => { try { const nonce = getNonce(); /* Update API Wallet Update */ let res = await updateUserWallet( { user: this.user_id, amount, app: this.app_id, nonce : nonce, transactionHash: transactionHash, currency : currency._id }, this.bearerToken ); await processResponse(res); return res; } catch (err) { throw err; } }; getAddress = () => { return this.user.address; } askForWithdraw = async ({ amount, currency, address, isAffiliate }) => { try { var nonce = getNonce(); var res = { }; let timeout = false; try{ /* Ask Permission to Withdraw */ res = await requestWithdraw( { app: this.app_id, user: this.user_id, address, tokenAmount : parseFloat(amount), currency : currency._id, nonce, isAffiliate }, this.bearerToken ); }catch(err){ //Timeout Error - But Worked timeout = true; } // Get Withdraw //let withdraws = await this.getWithdrawsAsync(); //let withdraw = withdraws[withdraws.length-1]; // Process Ask Withdraw API Call since can have errors if(!timeout){ res = await processResponse(res); } return {...res}; } catch (err) { throw err; } } getAffiliateInfo = () => { return { id : this.user.affiliateId, userAmount : this.user.affiliateInfo.affiliatedLinks.length, percentageOnLevelOne : this.user.affilateLinkInfo.affiliateStructure.percentageOnLoss } } getAffiliateWallets = () => { return this.user.affiliateInfo.wallet; } getAppCurrencyTicker = () => { return this.app.currencyTicker; } getAppTokenAddress = () => { return this.tokenAddress; } finalizeWithdraw = async ({withdraw_id, tx}) => { try { /* Finalize Withdraw to API */ return await finalizeWithdraw( { app: this.app_id, withdraw_id : withdraw_id, user: this.user_id, transactionHash: tx }, this.bearerToken ); }catch(err){ throw err; } } getWithdraws = () => { if(!this.user.withdraws) { return [] }; return this.user.withdraws.sort(function(a,b){ return new Date(b.creation_timestamp) - new Date(a.creation_timestamp); }); } getWithdrawsAsync = async () => { let user = await this.updateUser(); return user.withdraws; } createBet = async ({ result, gameId }) => { let res; try { const nonce = getNonce(); // grab current state const state = store.getState(); const { currency } = state; /* Create Bet API Setup */ res = await createBet( { currency : currency._id, user: this.user_id, app: this.app_id, game: gameId, result, nonce }, this.bearerToken ); return res; } catch (err) { throw err; } }; getMessage = () => { return this.message; } setMessage = (message) => { this.message = message; } set2FA = async ({token, secret}) => { try{ let res = await set2FA({ '2fa_secret' : secret, '2fa_token' : token, user: this.user_id }, this.bearerToken); return res; } catch(err){ throw err; } } getCurrencyAddress = async ({currency_id}) => { try { if(!this.user_id){return []} const currencies = this.app.currencies; const currency = currencies.find(c => c._id === currency_id); if(currency){ let res = await getCurrencyAddress({ currency: currency._id, ticker: currency.ticker, erc20: currency.erc20, id: this.user_id, app: this.app_id }, this.bearerToken); return await processResponse(res); }else{ return []; } }catch(err){ return null; } } resendConfirmEmail = async () => { try { return await resendConfirmEmail( { app: this.app_id, user: this.user_id }, this.bearerToken ); }catch(err){ throw err; } }; getPoints = async () => { return this.user.points; } getExternalId = async () => { return this.user.external_id; } isEmailConfirmed = async () => { return this.user.email_confirmed; } isKycConfirmed = async () => { return this.user.kyc_needed; } kycStatus = async () => { return this.user.kyc_status; } lastTimeFree = async () => { return this.user.lastTimeCurrencyFree; } getJackpotPot = async ({currency_id}) => { try { if(!this.user_id){return []} if(currency_id){ let res = await getJackpotPot({ app: this.app_id, user: this.user_id, currency : currency_id }, this.bearerToken); //workaround to dont show "Jackpot not exist in App" error message notifitication //should be removed when Jackpot will be in the addOns list if(res.data.status == 56 || res.data.status == 45) { return { pot: 0 }; } //finish return await processResponse(res); }else{ return []; } }catch(err){ console.log(err) throw err; } } getProviderToken = async ({game_id, ticker}) => { try { if(!this.user_id){return []} let res = await getProviderToken({ app: this.app_id, user: this.user_id, game_id, ticker }, this.bearerToken); return await processResponse(res); }catch(err){ console.log(err) throw err; } } sendFreeCurrencyRequest = async ({currency_id}) => { try { if(!this.user_id){return []} let res = await sendFreeCurrencyRequest({ app: this.app_id, user: this.user_id, currency : currency_id }, this.bearerToken); return await processResponse(res); }catch(err){ console.log(err) throw err; } } }
$(document).ready(function () { insertNumber = $(".insertNumber") insertNumber.show(); reservationExists = $(".reservationExists") reservationExists.hide(); reservationDoesNotExists = $(".reservationDoesNotExists") reservationDoesNotExists.hide(); }); var rezId; $(document).on('click', '#btnSubmitReservation', function () { insertNumber = $(".insertNumber") insertNumber.show(); reservationExists = $(".reservationExists") reservationExists.hide(); reservationDoesNotExists = $(".reservationDoesNotExists") reservationDoesNotExists.hide(); var reservation = $("#chReservation").val(); var res = JSON.stringify({"id":reservation}); $.ajax({ type: "POST", url: "http://localhost:8081/reservations/checkIfReservationExists", dataType: "json", contentType: "application/json", data: res, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); }}, success: function (data) { console.log("SUCCESS : ", data); if( data['value'] == true) { rezId = reservation; console.log(rezId); console.log("SUCCESS : ", data); reservationExists.show(); }else { reservationDoesNotExists.show(); } }, error: function (data) { console.log("ERROR : ", data); } }); }); $(document).on('click', '#btnGiveReservation', function () { var res = JSON.stringify({"id":rezId}); $.ajax({ type: "POST", url: "http://localhost:8081/reservations/giveMedication", contentType: "application/json", data: res, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); }}, success: function () { console.log("SUCCESS : "); window.location.href="welcomePharmacist.html"; alert('Lek je izdat'); }, error: function () { console.log("ERROR : "); } }); }); $(document).on('click', '#btnBack', function () { window.location.href="welcomePharmacist.html"; }); $(document).on('click', '#btnBackk', function () { window.location.href="welcomePharmacist.html"; }); $(document).on('click', '#btnBackkk', function () { window.location.href="welcomePharmacist.html"; });
/* * This file is for the Waterville Valley Dynamic Ski Map * It will pull in a JSON file and load up the open / closed trails onto * an image displayed using HTML. * * File created: 1/28/2016 12:30PM EST * Last edited: 4/25/2016 12:30PM EST * Created by: Jason Downing * */ var ski_data; /* Global color variables Red = CLOSED Green = OPEN */ var open_color = "006600"; var closed_color = "A30002"; /****************************************************************************** This date has been FAKED to work for the demo. Since the ski season has ended, we had to resort to faked data. */ var nov15_json = { "waterville_closed": [ "Sun Run", "Ciao", "Tree Line", "Ruthies Run", "Scramble", "Tree Line", "Main Street", "True Grit", "Gema", "Oblivion", "Palmers Way", "Bail Out", "Upper Bobbys", "Lower Bobby's Run", "Psyched Out", "White Caps", "Terrys Trail", "And Tyler Too", "Tippecanoe", "Tangent", "Sidewinder", "Grimes Way", "Periphery", "Lower Tippecanoe", "Boneyard", "Siegel Street", "Old Tecumseh", "Lower Periphery - FT", "Sel's Choice", "Lower Sel's Choice", "Tommy's World Cup Run - FT", "The Chute", "Psyched ", "Utter Abandon - FT", "Lower White Caps - FT", "Mini Pipe", "Exhibition - FT", "The Pasture", "Kinderpark Lift**For lessons only, closed to the public.\n", "South Street", "Stillness - FT", "Lower Stillness", "No Grit", "Baseway", "Kinderpark Lift**For lessons only, closed to the public.\n", "Exhibition" ], "waterville_open": [ "Upper Valley Run", "Valley Run", "Rock Island", "Leroy's Loop", "Revelation", "Stemtation - FT" ] }; var dec15_json = { "waterville_closed": [ "Tree Line", "Ruthies Run", "Scramble", "Tree Line", "Main Street", "True Grit", "Gema", "Palmers Way", "Bail Out", "Upper Bobbys", "Lower Bobby's Run", "Psyched Out", "White Caps", "Terrys Trail", "And Tyler Too", "Tippecanoe", "Lower Tippecanoe", "Tangent", "Sidewinder", "Grimes Way", "Periphery", "Boneyard", "Siegel Street", "Old Tecumseh", "Lower Periphery - FT", "Sel's Choice", "Lower Sel's Choice", "Tommy's World Cup Run - FT", "The Chute", "Psyched ", "Utter Abandon - FT", "Lower White Caps - FT", "Mini Pipe", "Exhibition - FT", "The Pasture" ], "waterville_open": [ "Kinderpark Lift**For lessons only, closed to the public.\n", "South Street", "Oblivion", "Sun Run", "Ciao", "Upper Valley Run", "Valley Run", "Rock Island", "Leroy's Loop", "Revelation", "Stemtation - FT", "Stillness - FT", "Lower Stillness", "No Grit", "Baseway", "Kinderpark Lift**For lessons only, closed to the public.\n", "Exhibition" ] }; var jan15_json = { "waterville_closed": [ "Tree Line", "Ruthies Run", "Scramble", "Tree Line", "Main Street", "True Grit", "Palmers Way", "Bail Out", "Upper Bobbys", "Lower Bobby's Run", "Psyched Out", "White Caps", "Terrys Trail", "Tangent", "Sidewinder", "Grimes Way", "Periphery", "Boneyard", "Siegel Street", "Old Tecumseh", "Sel's Choice", "Lower Sel's Choice", "Tommy's World Cup Run - FT", "The Chute", "Psyched ", "Utter Abandon - FT", "Lower White Caps - FT" ], "waterville_open": [ "Exhibition - FT", "The Pasture", "Mini Pipe", "Lower Periphery - FT", "And Tyler Too", "Tippecanoe", "Lower Tippecanoe", "Gema", "Kinderpark Lift**For lessons only, closed to the public.\n", "South Street", "Oblivion", "Sun Run", "Ciao", "Upper Valley Run", "Valley Run", "Rock Island", "Leroy's Loop", "Revelation", "Stemtation - FT", "Stillness - FT", "Lower Stillness", "No Grit", "Baseway", "Kinderpark Lift**For lessons only, closed to the public.\n", "Exhibition" ] }; var feb15_json = { "waterville_closed": [ ], "waterville_open": [ "Sun Run", "Ciao", "Tree Line", "Ruthies Run", "Scramble", "Tree Line", "Main Street", "True Grit", "Gema", "Oblivion", "Palmers Way", "Bail Out", "Upper Bobbys", "Lower Bobby's Run", "Psyched Out", "White Caps", "Terrys Trail", "And Tyler Too", "Tippecanoe", "Tangent", "Sidewinder", "Grimes Way", "Periphery", "Lower Tippecanoe", "Boneyard", "Siegel Street", "Old Tecumseh", "Lower Periphery - FT", "Sel's Choice", "Lower Sel's Choice", "Tommy's World Cup Run - FT", "The Chute", "Psyched ", "Utter Abandon - FT", "Lower White Caps - FT", "Mini Pipe", "Exhibition - FT", "The Pasture", "Kinderpark Lift**For lessons only, closed to the public.\n", "Upper Valley Run", "Rock Island", "Valley Run", "South Street", "Stillness - FT", "Lower Stillness", "No Grit", "Leroy's Loop", "Revelation", "Stemtation - FT", "Baseway", "Kinderpark Lift**For lessons only, closed to the public.\n", "Exhibition" ] }; var mar15_json = { "waterville_closed": [ "Exhibition Poma", "Boneyard", "Lower Bobby's Run", "Closed" ], "waterville_open": [ "Psyched ", "Kinderpark Lift**For lessons only, closed to the public.\n", "The Pasture", "Baseway", "Kinder Park", "Leroy's Loop", "Revelation", "Stemtation", "Valley Run", "Main Street", "Ruthies Run", "Scramble", "Lower Stillness", "Rock Island", "Stillness", "And Tyler Too", "Bail Out", "Grimes Way", "Lower Periphery", "Lower Tippecanoe", "Lower White Caps", "No Grit", "Oblivion", "Old Tecumseh", "Palmers Way", "Periphery", "Higher Ground", "Sidewinder", "Siegel Street", "Sun Run", "Tangent", "Terrys Trail", "Tippecanoe", "Tree Line", "Upper Bobbys", "Upper Valley Run", "White Caps", "Psyched Out", "South Street", "Ciao", "Gema", "Lower Sel's Choice", "Psyched", "Sel's Choice", "The Chute", "Tommy's World Cup Run", "True Grit", "Utter Abandon", "Exhibition", "WV Progression Park", "Exhibition", "South Street", "Open", "Stillness - FT", "Tommy's World Cup Run - FT" ] }; var apr15_json = { "waterville_closed": [ "Exhibition Poma", "Boneyard", "Lower Bobby's Run", "Closed", "True Grit", "Gema", "Ciao" ], "waterville_open": [ "Psyched ", "Kinderpark Lift**For lessons only, closed to the public.\n", "The Pasture", "Baseway", "Kinder Park", "Leroy's Loop", "Revelation", "Stemtation", "Valley Run", "Main Street", "Ruthies Run", "Scramble", "Lower Stillness", "Rock Island", "Stillness", "And Tyler Too", "Bail Out", "Grimes Way", "Lower Periphery", "Lower Tippecanoe", "Lower White Caps", "No Grit", "Oblivion", "Old Tecumseh", "Palmers Way", "Periphery", "Higher Ground", "Sidewinder", "Siegel Street", "Sun Run", "Tangent", "Terrys Trail", "Tippecanoe", "Tree Line", "Upper Bobbys", "Upper Valley Run", "White Caps", "Psyched Out", "South Street", "Lower Sel's Choice", "Psyched", "Sel's Choice", "The Chute", "Tommy's World Cup Run", "Utter Abandon", "Exhibition", "WV Progression Park", "Exhibition", "South Street", "Open", "Stillness - FT", "Tommy's World Cup Run - FT" ] }; /* This function gets run on page load, and it sets up the defaults for the map highlighting. */ $(document).ready(function() { /* This is from the maphilight docs, and has been modified to fix some bugs with the highlighting. The alwaysOn and neverOn attributes have been modified to fix issues on the first page load. They are noted below in comments. */ $.fn.maphilight.defaults = { fill: true, fillColor: closed_color, fillOpacity: 0.5, stroke: false, strokeColor: '000000', strokeOpacity: 1, strokeWidth: 1, fade: false, alwaysOn: false, // This is set to "False" on page load to prevent the highlighting from showing up messed up. neverOn: true, // This is set to "True" on page load so no highlighting shows up at all until a button is clicked. groupBy: false, wrapClass: true, shadow: false, shadowX: 0, shadowY: 0, shadowRadius: 6, shadowColor: '000000', shadowOpacity: 0.8, shadowPosition: 'outside', shadowFrom: false } // Center the map using this helpful SO post // https://stackoverflow.com/questions/1760586/how-to-align-the-jquery-maphilight-to-center $('.map').maphilight().parent().addClass('center-map'); $('img[usemap]').rwdImageMaps(); // This is a total hack in order to fix the highlighting. // Not sure how this works, but calling the color functions seems to make // the highlighting work properly. color_yellow(); color_red(); }); // Change all the highlighting to GREEN. // This functions name should be changed. function color_yellow() { // This goes through and changes all the maphilight data "fillColor" properties // to "006600" which is the same yellow color I set as "default" for all areas. $("area").each(function(){ $(this).data('maphilight', {"fillColor":open_color}); }); // Must call this to update the map! // Center the map using this helpful SO post // https://stackoverflow.com/questions/1760586/how-to-align-the-jquery-maphilight-to-center $('.map').maphilight().parent().addClass('center-map'); return true; } // Change all the highlighting to red. function color_red() { // This goes through and changes all the maphilight data "fillColor" properties // to "A30002" which is a red color. $("area").each(function(){ $(this).data('maphilight', {"fillColor":closed_color}); }); // Must call this to update the map! // Center the map using this helpful SO post // https://stackoverflow.com/questions/1760586/how-to-align-the-jquery-maphilight-to-center $('.map').maphilight().parent().addClass('center-map'); return true; } // Change the highlighting given a list of trails. function color_list() { // List of trails open / closed. var open_trails = ski_data.waterville_open; var closed_trails = ski_data.waterville_closed; // Open Trails $("area").each(function(){ for (trail in open_trails) { var compare = open_trails[trail]; if(compare == $(this).attr("alt")) { $(this).data('maphilight', {"fillColor":open_color}); } } }); // Closed Trails $("area").each(function(){ for (trail in closed_trails) { var compare = closed_trails[trail]; if(compare == $(this).attr("alt")) { $(this).data('maphilight', {"fillColor":closed_color}); } } }); // Must call this to update the map! // Center the map using this helpful SO post // https://stackoverflow.com/questions/1760586/how-to-align-the-jquery-maphilight-to-center $('.map').maphilight().parent().addClass('center-map'); return true; } // Update map function. // Given a JSON file name, it will update the waterville valley page. function update_map(filename) { /* This is from the maphilight docs, and has been modified to fix some bugs with the highlighting. The alwaysOn and neverOn attributes have been modified to fix issues on the first page load. They are noted below in comments. They get reset to default values here so that the highlighting will work again when a user clicks on one of the date buttons. */ $.fn.maphilight.defaults = { fill: true, fillColor: closed_color, fillOpacity: 0.5, stroke: false, strokeColor: '000000', strokeOpacity: 1, strokeWidth: 1, fade: false, alwaysOn: true, // This gets set to true so that the highlighting will work again. neverOn: false, // This gets set to false so that the highlighting will show up again. groupBy: false, wrapClass: true, shadow: false, shadowX: 0, shadowY: 0, shadowRadius: 6, shadowColor: '000000', shadowOpacity: 0.8, shadowPosition: 'outside', shadowFrom: false } // List of trails open / closed. var open_trails = filename.waterville_open; var closed_trails = filename.waterville_closed; // Open Trails $("area").each(function(){ for (trail in open_trails) { var compare = open_trails[trail]; if(compare == $(this).attr("alt")) { $(this).data('maphilight', {"fillColor":open_color}); } } }); // Closed Trails $("area").each(function(){ for (trail in closed_trails) { var compare = closed_trails[trail]; if(compare == $(this).attr("alt")) { $(this).data('maphilight', {"fillColor":closed_color}); } } }); // Must call this to update the map! // Center the map using this helpful SO post // https://stackoverflow.com/questions/1760586/how-to-align-the-jquery-maphilight-to-center $('.map').maphilight().parent().addClass('center-map'); } // Update the sidebar with a list of trails based on filename given. // IDEA: ADD SCROLL WHEEL. function update_sidebar(filename) { // Empty IDs $( "#open_trails" ).empty(); $( "#closed_trails" ).empty(); // Add open trails. for(var open in filename.waterville_open) { $("#open_trails").append("<div>" + filename.waterville_open[open] + "</div>"); } // Add closed trails. for(var closed in filename.waterville_closed) { $("#closed_trails").append("<div>" + filename.waterville_closed[closed] + "</div>"); } } // This will be a demo function to change the map we have working, // with fake data. function change_day(date) { // Change date based on input. if(date == "nov15") { update_map(nov15_json); update_sidebar(nov15_json); return true; } if(date == "dec15") { update_map(dec15_json); update_sidebar(dec15_json); return true; } if(date == "jan15") { update_map(jan15_json); update_sidebar(jan15_json); return true; } if(date == "feb15") { update_map(feb15_json); update_sidebar(feb15_json); return true; } if(date == "mar15") { update_map(mar15_json); update_sidebar(mar15_json); return true; } if(date == "apr15") { update_map(apr15_json); update_sidebar(apr15_json); return true; } if(date == "may15") { update_map(nov15_json); // Nov15 because all closed. update_sidebar(nov15_json); return true; } else { console.log("Error, given invalid date.\n"); } }
export const ENTRIES = [ { title: 'Title 1', subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur', illustration: 'https://i.imgur.com/UYiroysl.jpg' }, { title: 'Title 2', subtitle: 'Lorem ipsum dolor sit amet', illustration: 'https://i.imgur.com/UPrs1EWl.jpg' }, { title: 'Title 3', subtitle: 'Lorem ipsum dolor sit amet et nuncat ', illustration: 'https://i.imgur.com/MABUbpDl.jpg' }, { title: 'Title 4', subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur', illustration: 'https://i.imgur.com/KZsmUi2l.jpg' }, { title: 'Title 5', subtitle: 'Lorem ipsum dolor sit amet', illustration: 'https://i.imgur.com/2nCt3Sbl.jpg' }, { title: 'Title 6', subtitle: 'Lorem ipsum dolor sit amet', illustration: 'https://i.imgur.com/lceHsT6l.jpg' }, { title: 'Title 7', subtitle: 'Lorem ipsum dolor sit amet', illustration: 'https://i.imgur.com/UPrs1EWl.jpg' }, { title: 'Title 8', subtitle: 'Lorem ipsum dolor sit amet et nuncat ', illustration: 'https://i.imgur.com/MABUbpDl.jpg' }, { title: 'Title 9', subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur', illustration: 'https://i.imgur.com/KZsmUi2l.jpg' }, { title: 'Title 10', subtitle: 'Lorem ipsum dolor sit amet', illustration: 'https://i.imgur.com/2nCt3Sbl.jpg' } ];
import * as types from '../mutation-types' const state = { artist: {} } const getters = { GET_ARTIST: (state) => state.artist } const actions = { } const mutations = { [types.SET_ARTIST] (state, artist) { state.artist = artist } } export default { state, getters, actions, mutations }
var url; function openCategorie(){ $('#dlg_categorie').dialog('open').dialog('setTitle','GESTISCI CATEGORIE'); } function newCategoria(){ $('#dlg_categoria').dialog('open').dialog('setTitle','INSERISCI UNA NUOVA CATEGORIA'); $('#form_categoria').form('clear'); url = 'data/categorie/newCategoria.cfm'; } function editCategoria(){ $('#form_categoria').form('clear'); var row = $('#grid_categorie').datagrid('getSelected'); if (row){ $('#dlg_categoria').dialog('open').dialog('setTitle','CATEGORIA DA MODIFICARE'); $('#form_categoria').form('load', row); url = 'data/categorie/editCategoria.cfm?id='+row.id; } } function saveCategoria(){ $('#form_categoria').form('submit',{ url: url, onSubmit: function(){ return $(this).form('validate'); }, success: function(result){ $('#dlg_categoria').dialog('close'); $('#grid_categorie').datagrid('reload'); $("#dlg_servizio").dialog('close'); $('#grid_servizi').datagrid('reload'); } }); }
const path = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: { // TODO: optimize: split vendor to avoid big size checkout: './public/checkout/index.js', // each page a script dashboard: './public/dashboard/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js' }, plugins: [ new CleanWebpackPlugin(), // Clean the dist folder new MiniCssExtractPlugin() // extract separatedly css files ], module: { rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' // Use babel to support react. see .babelrc }, { test: /\.css$/i, use: [{ loader: MiniCssExtractPlugin.loader, options: { publicPath: '/', }, }, 'css-loader'], }, { test: /\.(png|jpe?g|gif|woff2|woff|eot|ttf|svg)$/i, use: [ { loader: 'file-loader', }, ], }] }, optimization: { splitChunks: { cacheGroups: { commons: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } } } };
$(function () { initJQueryUIDatePicker(); initJQueryUIAutocomplete(); initJQueryUISelect(); initJQueryUICheckbox(); initJQueryUIButton(); }); function initJQueryUIDatePicker() { $("#departure-date").datepicker({ changeMonth: true, changeYear: true, showAnim: "slideDown", showButtonPanel: true }); $.datepicker._gotoToday = function (id) { var target = jQuery(id), inst = this._getInst(target[0]), date = new Date(); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); // the below two lines are new this._setDateDatepicker(target, date); this._selectDate(id, this._getDateDatepicker(target)); } this._notifyChange(inst); this._adjustDate(target); } } function initJQueryUIAutocomplete() { var airports = [ "[ATL] Hartsfield–Jackson Atlanta International Airport", "[PEK] Beijing Capital International Airport", "[LAX] Los Angeles International Airport", "[DXB] Dubai International Airport", "[HND] Tokyo Haneda Airport", "[ORD] O'Hare International Airport", "[LHR] London Heathrow Airport", "[PVG] Shanghai Pudong International Airport", "[CDG] Charles de Gaulle Airport", "[DFW] Dallas/Fort Worth International Airport", "[CAN] Guangzhou Baiyun International Airport", "[AMS] Amsterdam Airport Schiphol", "[HKG] Hong Kong International Airport", "[ICN] Seoul Incheon International Airport", "[FRA] Frankfurt Airport", "[DEN] Denver International Airport", "[DEL] Indira Gandhi International Airport", "[SIN] Singapore Changi Airport", "[BKK] Suvarnabhumi Airport", "[JFK] John F. Kennedy International Airport" ]; $("#reservation__find-airport-input").autocomplete({ source: airports }); } function initJQueryUISelect() { $("#meal-options").selectmenu(); } function initJQueryUICheckbox() { $("fieldset input").checkboxradio({ icon: false }); } function initJQueryUIButton() { $("#continue-reservation").button({ icon: "ui-icon-circle-arrow-e", iconPosition: "end" }); }
document.getElementById("Nueva-carta").addEventListener("submit", agregarCargta) var i = 0; function agregarCargta(event){ event.preventDefault(); var titulouser = document.getElementById("titulo").value; var preciouser = document.getElementById("precio").value; var descripcionuser = document.getElementById("descripcion").value; var datosCarta = new Object(); datosCarta.id = i; datosCarta.titulo = titulouser; datosCarta.precio = preciouser; datosCarta.descripcion = descripcionuser; var stored = localStorage.getItem("servicios"); var local = JSON.stringify(datosCarta); if(stored == "" || stored == null){ localStorage.setItem("servicios", local); } /*ACUMULA LOS SERVICIOC O CARTAS*/ else if(stored != local){ stored = stored + ", " + local; localStorage.setItem("servicios", stored); } console.log('servicios: ', JSON.parse(local)); i++; addItem(JSON.parse(local)); } function addItem(item){ const itemHTML = '<div class="card" style="width: 18rem;">\n' + ' <img src="/images/Seccion1/imagen1.jpeg" class="card-img-top" alt="image">\n' + ' <div class="card-body">\n' + ' <h5 class="card-title">'+item.titulo+'</h5>\n' + ' <h5 class="card-title">PRECIO: '+item.precio+'</h5>\n' + ' <p class="card-text">'+item.descripcion+'</p>\n' + ' <a href="#" class="btn btn-primary">Add</a>\n' + ' </div>\n' + '</div>\n' + '<br/>'; const itemsContainer = document.getElementById("list-items"); itemsContainer.innerHTML += itemHTML; } function addCarta(item){ const itemHTML = item.titulo const itemsContainer = document.getElementById("titulo1"); itemsContainer.innerHTML += itemHTML; } /* addItem({"name":"juice", 'img':'https://www.gs1india.org/media/Juice_pack.jpg', 'description':'Orange and Apple juice fresh and delicious'}); addItem({'name':'Tayto', 'img':'https://www.irishtimes.com/polopoly_fs/1.4078148!/image/image.jpg', 'description':'Cheese & Onion Chips'}); {"id":2,"titulo":"uñas","precio":"200","descripcion":"fa"} */
var User = require('../models/user'); // POST /users exports.postUsers = function(req, res) { var user = new User({ username: req.body.username, password: req.body.password, isSuperuser: false, dateJoined: Date.now(), email: req.body.email }); user.save(function(err) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'New user was added!'}); }); }; // GET /users exports.getUsers = function(req, res) { User.find(function(err, users) { if (err) { res.status = 400; return res.send(err); } res.json(users); }); }; // PUT /users/superuser/:userId exports.setSuperuser = function(req, res) { User.findById(req.params.userId, function(err, user) { if (err) { res.statusCode = 400; return res.send(err); } if (user === null || user === undefined) { res.statusCode = 404; return res.json('userId not found!'); } user.isSuperuser = true; user.save(function (err) { if (err) { res.statusCode = 400; return res.send(err); } res.json(user.username + " was set to Superuser"); }); }) }; // GET /user exports.getUser = function(req, res) { var user = new User(req.user); user.password = null; res.send(user); }; // PUT /user exports.putUser = function(req, res) { req.user.username = req.body.username; req.user.password = req.body.password; req.user.email = req.body.email; req.user.save(function (err) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'User updated!' }); }); }; // DELETE /user exports.deleteUser = function(req, res) { User.remove({ _id: req.user._id }, function (err, user) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'Successfully deleted user!' }); }); };
const { catalogue } = require('../mock'); const resolvers = { Query: { hello: (_, { name }) => `Hello ${name || 'World'}`, product: (_, { id }) => { const path = id && id.length > 0 && id[0] === '/'; const result = catalogue.product.items.find(product => path ? product.slug === id.substr(1) : product.id === id ); return result ? result : { id, slug: '' }; }, catalogue: (_, { amount, offset }) => { const begin = amount * offset; const end = amount * (offset + 1); const items = catalogue.product.items.slice(begin, end); const product = { ...catalogue.product, items, amount, offset, remaining: (catalogue.product.total - ((offset + 1) * amount)), }; return { ...catalogue, product, }; }, }, }; module.exports = { resolvers };
import { Box, Container, Stack, Text, useColorModeValue, Button, } from "@chakra-ui/react"; import { Link } from "react-router-dom"; import Logo from "./Header/Logo"; import { useAuth } from "../../contexts/AuthProvider"; import { useLocation } from "react-router-dom"; export default function SmallCentered() { const { isAuth, logout } = useAuth(); const { pathname } = useLocation(); if ( pathname == "/" || pathname == "/login" || pathname == "/how_it_works" || pathname == "/enroll" || pathname == "/join" || pathname == "/tasks" ) { return ( <Box bg={useColorModeValue("primary.500", "gray.900")} color={useColorModeValue("gray.200", "gray.200")} > <Container as={Stack} maxW={"6xl"} py={4} spacing={4} justify={"center"} align={"center"} > <Logo /> <Stack spacing={6} className="qfont" fontWeight="semibold" align="center" justify={["center", "space-between", "flex-end", "flex-end"]} direction={["column", "row", "row", "row"]} pt={[4, 4, 0, 0]} > <Link to="/">Home</Link> <Link to="/tasks">Tasks</Link> <Link to="/how_it_works">How It Works</Link> {!isAuth && ( <> {" "} <Link to="/join">Join</Link> <Link to="/enroll">Enroll</Link> <Link to="/login">Login</Link> </> )} {isAuth && ( <> <Link to="/dashboard">Dashboard</Link> <Button onClick={() => { logout(); }} size="sm" rounded="md" color={["primary.500", "primary.500", "white", "white"]} bg={["white", "white", "primary.500", "primary.500"]} _hover={{ bg: [ "primary.100", "primary.100", "primary.600", "primary.600", ], }} > Logout </Button> </> )} </Stack> </Container> <Box borderTopWidth={1} borderStyle={"solid"} borderColor={useColorModeValue("gray.200", "gray.700")} > <Container as={Stack} maxW={"6xl"} py={4} direction={{ base: "column", md: "row" }} spacing={4} justify={{ base: "center", md: "center" }} align={{ base: "center", md: "center" }} > <Text className="qfont">© 2021 Taskify. All rights reserved</Text> </Container> </Box> </Box> ); } else { return null; } }
import React from "react"; import { Modal, StyleSheet, Text, View } from "react-native"; import { PRIMARY_COLOR, PRIMARY_FONT } from "../../constants"; import MyButton from "./MyLoginButton"; import MyNoteButton from "./MyNoteButton"; import MySendButton from "./MySendButton"; const ConfirmModal = (props) => { return ( <Modal animationType="fade" visible={props.confirmModalVisible}> <View style={css.container}> <View style={css.body}> <MyButton iconName="question" /> <Text style={css.text}>Та итгэлтэй байна уу?</Text> <View style={css.closeButton}> <MyNoteButton title="Тийм" onPress={() => { props.getResult(true); props.hide(false); }} /> <MyNoteButton title="Үгүй" onPress={() => { props.getResult(false); props.hide(false); }} /> </View> </View> </View> </Modal> ); }; export default ConfirmModal; const css = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "white", }, body: { height: "30%", width: "90%", borderRadius: 25, borderColor: PRIMARY_COLOR, borderWidth: 1, alignItems: "center", justifyContent: "center", }, text: { fontFamily: PRIMARY_FONT, color: PRIMARY_COLOR, marginTop: 20, fontSize: 20, }, closeButton: { flexDirection: "row", height: "15%", marginTop: "10%", justifyContent: "center", alignItems: "center", }, });
const path = require("path"); require("dotenv").config({ path: "./.env", }); const web3 = require("web3"); const Tx = require("ethereumjs-tx").Transaction; const testContract = require("./abis/test-contract"); web3js = new web3( new web3.providers.WebsocketProvider( "wss://ropsten.infura.io/ws/v3/dedac6824bfa4dd5833903d6efa48af8" ) ); let transactionMinedBlockNumber = null; const blockDiff = 10; let isTransactionInProgress = false; const runTransaction = () => { console.log("Transaction Initiated"); var myAddress = process.env.MY_PUBLIC_ADDRESS; var privateKey = Buffer.from(process.env.MY_PRIVATE_KEY, "hex"); //contract abi is the array that you can get from the ethereum wallet or etherscan var contractABI = testContract.abi; var contractAddress = "0xB7B1200C5a343CaF399CF59a064223F2b9AfEE7f"; //creating contract object var contract = new web3js.eth.Contract(contractABI, contractAddress); var count; // get transaction count, later will used as nonce web3js.eth.getTransactionCount(myAddress).then(function (v) { // console.log("Count: " + v); count = v; //creating raw tranaction var rawTransaction = { from: myAddress, gasPrice: web3js.utils.toHex(20 * 1e9), gasLimit: web3js.utils.toHex(210000), to: contractAddress, value: "0x0", data: contract.methods.setName("FROM NODE").encodeABI(), nonce: web3js.utils.toHex(count), }; // console.log(rawTransaction); //creating tranaction via ethereumjs-tx var transaction = new Tx(rawTransaction, { chain: "ropsten", hardfork: "petersburg", }); //signing transaction with private key transaction.sign(privateKey); // sending transacton via web3js module web3js.eth .sendSignedTransaction("0x" + transaction.serialize().toString("hex")) .on("receipt", (res) => { transactionMinedBlockNumber = res.blockNumber; console.log("New Transaction Mined : " + transactionMinedBlockNumber); isTransactionInProgress = false; }); }); }; runTransaction(); web3js.eth.subscribe("newBlockHeaders", (err, res) => { const { number: currentBlockMined } = res; console.log( "Currently Mined Block : " + currentBlockMined + " Previous Transaction Mined in : " + transactionMinedBlockNumber ); if ( !isTransactionInProgress && transactionMinedBlockNumber && transactionMinedBlockNumber + blockDiff <= currentBlockMined ) { isTransactionInProgress = true; runTransaction(); } });
import React from 'react'; import { connect } from 'react-redux'; import { add_item, delete_item } from '../actions'; class ToDoList extends React.Component{ state = { item: "" }; renderedItem () { if(this.props.todolist.length===0) { return <div>Add item to your your Do list!</div> } return this.props.todolist.map((item)=>{ return ( <div className="item" key={this.props.todolist.indexOf(item)} > <div className="right floated content"> <div onClick={()=>this.props.delete_item(item)} className="ui button"> Delete </div> </div> <div className="left floated content"> {item}</div> </div> ); }); } onTextChange=(event)=>{ this.setState({item:event.target.value}); } onItemAdded=(event)=>{ if(this.state.item !== '') { this.props.add_item(this.state.item) this.setState({item:""}) } } render() { return ( <div className="ui center aligned container"> <div className="ui fluid focus input"> <input type='text' value={this.state.item} onChange={this.onTextChange} /> <div onClick={this.onItemAdded} className="ui button"> Add </div> </div> <div className="ui segment"> <div className="ui middle aligned big divided list">{this.renderedItem()} </div> </div> </div> ); } } const mapStateToProps = (state) => { return {todolist: state.itemList}; } export default connect(mapStateToProps,{add_item, delete_item})(ToDoList);
import React, {Component} from 'react'; import Highcharts from 'highcharts/highstock'; import HighchartsReact from 'highcharts-react-official'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; export class Pie extends Component { render() { if (!this.props.alumni.length) { return ( <div>Loading</div> ); } else { const data = this.props.alumni[0].reduce((accu, values) => { if (!accu[values.title]) { accu[values.title] = 0; } accu[values.title]++; return accu; }, {}); let options = { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: 'pie' }, title: { text: 'Job Titles of Turing Grads' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }, series: [{ name: 'Brands', colorByPoint: true, data: [{ name: 'Analyst', y: data.Analyst }, { name: 'Associate - Projects', y: data["Associate - Projects"], sliced: true, selected: true }, { name: 'Consultant', y: data.Consultant }, { name: 'Customer Support', y: data["Customer Support"] }, { name: 'DevOps', y: data.DevOps }, { name: 'Developer', y: data.Developer }, { name: 'Engineer', y: data.Engineer }, { name: 'Instructor', y: data.Instructor }, { name: 'QA/Tester', y: data["QA/Tester"] }, { name: 'Research Associate', y: data["Research Associate"] } ] }] }; return ( <div> <HighchartsReact highcharts={Highcharts} options={options} /> </div> ); } } } export const mapStateToProps = (store) => { return { alumni: store.alumData }; }; export default connect(mapStateToProps, null)(Pie); Pie.propTypes = { alumni: PropTypes.array }
var mongoose = require('mongoose'); var connect = process.env.MONGODB_URI; // If you're getting an error here, it's probably because // your connect string is not defined or incorrect. mongoose.connect(connect); // Step 1: Write your schemas here! // Remember: schemas are like your blueprint, and models // are like your building! var userSchema = mongoose.Schema({ username: { type: String, required: true }, password: String }); var puppySchema = mongoose.Schema({ name: String, brain: { type: String, enum: ['big', 'small', 'medium', 'pea-sized', 'peter-sized'] }, imageUrl: String, owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }) // Step 2: Create all of your models here, as properties. var User = mongoose.model('User', userSchema); var Puppy = mongoose.model('Puppy', puppySchema); // Step 3: Export your models object module.exports = { User: User, Puppy: Puppy }
import React from 'react'; import { connect } from 'react-redux'; const Navbar = ({}) => { return ( <header className="bg-primary"> <div className="navbar-container"> <h1 className="logo"> <img src="../../.././appIcons/weathe.png" alt="Cloud Icon" className='logo__cloudIcon' /> <div className='logo__weatherAppName'> Weather App </div> </h1> </div> </header> ); }; export default connect(null, {})(Navbar);
// sortAccommodation should go inside displayHotels function in index.js (just before for loop - this file should be required by index.js) var sortAccommodation = function(hotels, sortBy) { if (sortBy === "price") { hotels.sort(function(a, b) { return a.pricePerPerson-b.pricePerPerson; }) return hotels; } else if (sortBy === "stars") { hotels.sort(function(a, b) { return b.stars-a.stars; }) return hotels; }; } module.exports = sortAccommodation; // var hotels=[]; // hotels[0]={name:"CCC", pricePerPerson:32, stars: 3}; // hotels[1]={name:"BBB", pricePerPerson:17, stars: 2}; // hotels[2]={name:"AAA", pricePerPerson:58, stars: 1}; // hotels[3]={name:"DDD", pricePerPerson:62, stars: 4}; // var sorted = sortAccommodation(hotels, "price"); // console.log(sorted); // sorted = sortAccommodation(hotels, "stars"); // console.log(sorted);
import React from "react"; import styles from "./RegionsButton.module.css"; const RegionsButton = () => { return ( <button className={styles.region} type="button"> Region </button> ); }; export default RegionsButton;
var open_close = () => { var popup = document.getElementsByClassName("main-window")[0]; var icon = document.getElementsByTagName("i")[0]; var button = document.getElementById("mainBut"); if (screen && screen.width < 600){ // mobile var new_i = document.createElement("i"); new_i.className = "fas fa-times cross"; popup.prepend(new_i); new_i.onclick = open_close; } if(popup.style.display == 'none'){ popup.style.display = 'block'; icon.className = 'fas fa-times'; icon.style.fontSize = 17; button.className = "mainButton"; document.getElementsByClassName("askToHelp")[0].style.display = 'none'; } else{ popup.style.display = 'none'; icon.className = 'far fa-laugh'; icon.style.fontSize = 26; button.className+=" arrow"; document.getElementsByClassName("askToHelp")[0].style.display = 'block'; } }
import React, { Component } from "react" import PropTypes from "prop-types" import { Home } from "components" import { DataTableContainer } from "containers" import firebaseAuth from "config/constants" import { checkIfAuthed } from "config/auth.jsx" class HomeContainer extends Component { constructor(props) { super(props) this.onKeyPress = this.onKeyPress.bind(this) this.handleChange = this.handleChange.bind(this) this.state = { userName: "", password: "" } } componentDidMount() { document.addEventListener("keydown", this.onKeyPress, false) } componentWillUnmount() { document.removeEventListner("keydown", this.onKeyPress, false) } onKeyPress(e) { if (e.keyCode === 13) { e.preventDefault() firebaseAuth().onAuthStateChanged(user => { if (user) { // DOO SOMETHING } else { this.setState({ userName: "" }) this.setState({ password: "" }) } }) } } handleChange(e, id, userNameOrPassword) { if (id === "userName") { this.setState({ userName: userNameOrPassword }) } else { this.setState({ password: userNameOrPassword }) } } render() { return checkIfAuthed() === false ? ( <Home username={this.state.userName} password={this.state.password} onKeyPress={this.onKeyPress} handleChange={this.handleChange} /> ) : ( <DataTableContainer /> ) } } HomeContainer.propTypes = {} export default HomeContainer
window.onload = init; function init(){ var submit = document.getElementById("submit"); submit.onclick = calculate; } function calculate() { console.log("in here"); var operand1 = document.getElementById("operand1").value; console.log(operand1==false); var operand2 = document.getElementById("operand2").value; var operator = document.getElementById("operator").value; if (operand1 == false || operand2 == false || operator == false) { alert("please make sure to enter everything!"); } else { try { if (isNaN(operand1) || isNaN(operand2)) { throw new Error("the operands need to be numbers"); } else if (operand2 == 0) { throw new Error("the divident cannot be zero!"); } else if (operator == "+") { var result = parseInt(operand1)+parseInt(operand2); } else if (operator == "-") { var result = parseInt(operand1)-parseInt(operand2); } else if (operator == "*") { var result = parseInt(operand1)-parseInt(operand2); } else if (operator == "/") { var result = parseInt(operand1)/parseInt(operand2); } console.log(result); document.getElementById("result").innerHTML = result; } catch (ex) { alert(ex.message); } } }
OC.L10N.register( "core", { "Please select a file." : "Por favor esbilla un ficheru.", "File is too big" : "Ficheru ye demasiáu grande", "Invalid file provided" : "el ficheru apurríu nun ye válidu", "No image or file provided" : "Nun s'especificó nenguna imaxe o ficheru", "Unknown filetype" : "Triba de ficheru desconocida", "Invalid image" : "Imaxe inválida", "An error occurred. Please contact your admin." : "Hebo un fallu. Por favor, contauta col to alministrador", "No temporary profile picture available, try again" : "Nengún perfil d'imaxe temporal disponible, intentalo de nueves", "No crop data provided" : "Nun s'apurrió'l retayu de datos", "No valid crop data provided" : "El retayu de datos apurríu nun ye válidu", "Crop is not square" : "El retayu nun ye cuadráu", "%s password reset" : "%s restablecer contraseña", "Couldn't send reset email. Please contact your administrator." : "Nun pudo unviase'l corréu de reaniciu. Por favor, contauta col alministrador.", "Preparing update" : "Preparando anovamientu", "[%d / %d]: %s" : "[%d / %d]: %s", "Repair warning: " : "Reparar avisu:", "Repair error: " : "Reparar erru:", "Please use the command line updater because automatic updating is disabled in the config.php." : "Por favor, usa l'actualización de llínea de comandos porque l'actualización automática ta deshabilitada nel config.php.", "[%d / %d]: Checking table %s" : "[%d / %d]: Comprobando tabla %s", "Turned on maintenance mode" : "Activáu'l mou de caltenimientu", "Turned off maintenance mode" : "Apagáu'l mou de caltenimientu", "Maintenance mode is kept active" : "La mou de caltenimientu caltiense activu", "Updating database schema" : "Anovando esquema de base de datos", "Updated database" : "Base de datos anovada", "Checking whether the database schema can be updated (this can take a long time depending on the database size)" : "Comprobando si l'esquema de base de datos puede ser actualizáu (esto puede llevar tiempu abondo, dependiendo del tamañu la base de datos)", "Checked database schema update" : "Anovamientu del esquema de base de datos revisáu", "Checking updates of apps" : "Comprobando anovamientos d'aplicaciones", "Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)" : "Comprobando si l'esquema de base de datos para %s puede ser actualizáu (esto puede llevar tiempu abondo, dependiendo del tamañu la base de datos)", "Checked database schema update for apps" : "Anovamientu del esquema de base de datos p'aplicaciones revisáu", "Updated \"%s\" to %s" : "Anováu \"%s\" a %s", "Set log level to debug" : "Afita'l nivel de rexistru pa depurar", "Reset log level" : "Reafitar nivel de rexistru", "Starting code integrity check" : "Entamando la comprobación de la integridá del códigu", "Finished code integrity check" : "Finada la comprobación de la integridá del códigu", "%s (3rdparty)" : "%s (3rdparty)", "%s (incompatible)" : "%s (incompatible)", "Following apps have been disabled: %s" : "Siguientes aplicaciones deshabilitáronse: %s", "Already up to date" : "Yá ta actualizáu", "Sunday" : "Domingu", "Monday" : "Llunes", "Tuesday" : "Martes", "Wednesday" : "Miércoles", "Thursday" : "Xueves", "Friday" : "Vienres", "Saturday" : "Sábadu", "Sun." : "Dom.", "Mon." : "Llu.", "Tue." : "Mar.", "Wed." : "Mié.", "Thu." : "Xue.", "Fri." : "Vie.", "Sat." : "Sáb.", "Su" : "Do", "Mo" : "Llu", "Tu" : "Ma", "We" : "Mie", "Th" : "Xue", "Fr" : "Vie", "Sa" : "Sa", "January" : "Xineru", "February" : "Febreru", "March" : "Marzu", "April" : "Abril", "May" : "Mayu", "June" : "Xunu", "July" : "Xunetu", "August" : "Agostu", "September" : "Setiembre", "October" : "Ochobre", "November" : "Payares", "December" : "Avientu", "Jan." : "Xin.", "Feb." : "Feb.", "Mar." : "Mar.", "Apr." : "Abr.", "May." : "May.", "Jun." : "Xun.", "Jul." : "Xnt.", "Aug." : "Ago.", "Sep." : "Set.", "Oct." : "Och.", "Nov." : "Pay.", "Dec." : "Avi.", "<a href=\"{docUrl}\">There were problems with the code integrity check. More information…</a>" : "<a href=\"{docUrl}\">Hebo un problema cola comprobación de la integridá del códigu. Más información...</a>", "Settings" : "Axustes", "Problem loading page, reloading in 5 seconds" : "Problema al cargar la páxina, volver cargar en 5 segundos", "Saving..." : "Guardando...", "Dismiss" : "Encaboxar", "seconds ago" : "hai segundos", "The link to reset your password has been sent to your email. If you do not receive it within a reasonable amount of time, check your spam/junk folders.<br>If it is not there ask your local administrator." : "Unviósete al corréu l'enllaz pa reaniciar la to contraseña. Si nun lu recibes nuna cantidá razonable de tiempu, comprueba les tos carpetes de corréu puxarra. <br>Si nun ta ehí, entruga al to alministrador llocal", "Your files are encrypted. If you haven't enabled the recovery key, there will be no way to get your data back after your password is reset.<br />If you are not sure what to do, please contact your administrator before you continue. <br />Do you really want to continue?" : "Los tos ficheros tán crifraos. Si nun habilitesti la clave de recuperación, nun habrá forma de recuperar los tos datos dempués de que se reanicie la to contraseña.<br />Si nun tas seguru de qué facer, por favor contauta col to alministrador enantes que sigas. <br />¿De xuru quies siguir?", "I know what I'm doing" : "Sé lo que toi faciendo", "Password can not be changed. Please contact your administrator." : "Nun pue camudase la contraseña. Por favor, contauta col alministrador.", "No" : "Non", "Yes" : "Sí", "Choose" : "Esbillar", "Error loading file picker template: {error}" : "Fallu cargando'l ficheru de plantía d'escoyeta: {error}", "Ok" : "Aceutar", "Error loading message template: {error}" : "Fallu cargando'l mensaxe de la plantía: {error}", "read-only" : "namái llectura", "_{count} file conflict_::_{count} file conflicts_" : ["{count} conflictu de ficheru","{count} conflictos de ficheru "], "One file conflict" : "Conflictu nun ficheru", "New Files" : "Ficheros nuevos", "Already existing files" : "Ficheros qu'esisten yá", "Which files do you want to keep?" : "¿Qué ficheros quies caltener?", "If you select both versions, the copied file will have a number added to its name." : "Si seleiciones dambes versiones, el ficheru copiáu va tener un númberu amestáu al so nome", "Cancel" : "Encaboxar", "Continue" : "Continuar", "(all selected)" : "(esbillao too)", "({count} selected)" : "(esbillaos {count})", "Error loading file exists template" : "Falu cargando plantía de ficheru esistente", "Very weak password" : "Contraseña mui feble", "Weak password" : "Contraseña feble", "So-so password" : "Contraseña pasable", "Good password" : "Contraseña bona", "Strong password" : "Contraseña mui bona", "Your web server is not yet set up properly to allow file synchronization because the WebDAV interface seems to be broken." : "El to sirvidor web entá nun ta configuráu afayadizamente pa permitir la sincronización de ficheros porque la interfaz WebDAV paez tar rota.", "Your web server is not set up properly to resolve \"{url}\". Further information can be found in our <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>." : "El to sirvidor web nun ta configuráu correchamente pa resolver \"{url}\". Pues atopar más información en nuesa documentación <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\"></a>.", "This server has no working Internet connection. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. We suggest to enable Internet connection for this server if you want to have all features." : "Esti sirvidor nun tien conexón a Internet. Esto significa que dalgunes de les carauterístiques nun van funcionar, como'l montaxe d'almacenamiento esternu, les notificaciones sobre anovamientos, la instalación d'aplicaciones de terceros, l'accesu a los ficheros de mou remotu o l'unviu de correos-e de notificación. Suxerimos habilitar una conexón a Internet nesti sirvidor pa esfrutar de toles funciones.", "No memory cache has been configured. To enhance your performance please configure a memcache if available. Further information can be found in our <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>." : "Configuróse ensin la memoria caché. P'ameyorar el so rendimientu configure un Memcache si ta disponible. Puede atopar más información na nuesa <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentación</a>.", "/dev/urandom is not readable by PHP which is highly discouraged for security reasons. Further information can be found in our <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>." : "/dev/urandom nun ye llexible por PHP que amás nun ye recomendable por razones de seguridá. Pues atopar más información na nuesa <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentación</a>.", "You are currently running PHP {version}. We encourage you to upgrade your PHP version to take advantage of <a target=\"_blank\" rel=\"noreferrer\" href=\"{phpLink}\">performance and security updates provided by the PHP Group</a> as soon as your distribution supports it." : "Ta executándose anguaño la {version} PHP. Convidamoste a actualizar la to versión PHP p'aprovechate del <a target=\"_blank\" rel=\"noreferrer\" href=\"{phpLink}\"> rendimientu y actualizaciones de seguridá proporcionaes pol Grupu PHP</a> desque la so distribución sofitelo.", "The reverse proxy headers configuration is incorrect, or you are accessing ownCloud from a trusted proxy. If you are not accessing ownCloud from a trusted proxy, this is a security issue and can allow an attacker to spoof their IP address as visible to ownCloud. Further information can be found in our <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>." : "La configuración de les cabeceres de proxy inverses ye incorrecta , o tas aportando ownCloud dende un proxy d'enfotu . Si nun tas aportando a ownCloud dende un proxy d'enfotu, esto ye un problema de seguridá y puede dexar a un atacante falsificar la so dirección IP como visible pa ownCloud . Más información puede atopase na nuesa <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentación</a>.", "Memcached is configured as distributed cache, but the wrong PHP module \"memcache\" is installed. \\OC\\Memcache\\Memcached only supports \"memcached\" and not \"memcache\". See the <a target=\"_blank\" rel=\"noreferrer\" href=\"{wikiLink}\">memcached wiki about both modules</a>." : "Memcached configúrase como caché distribuyida, pero instalóse'l módulu de PHP \"Memcache\" equivocáu. \\OC\\Memcache\\Memcached namás almite \"memcached\" y non \"memcache\". Vea la <a target=\"_blank\" rel=\"noreferrer\" href=\"{wikiLink}\"> wiki memcached sobre ambos módulos</a> .", "Some files have not passed the integrity check. Further information on how to resolve this issue can be found in our <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\">List of invalid files…</a> / <a href=\"{rescanEndpoint}\">Rescan…</a>)" : "Dellos arquivos nun pasaron la comprobación d'integridá. Pues atopas más información sobre cómo resolver esti problema na nuesa <a target=\"_blank\" rel=\"noreferrer\" href=\"{docLink}\">documentation</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\"> Llista de ficheros non válidos...</a>/ <a href=\"{rescanEndpoint}\">Volver a guetar…</a>)", "Error occurred while checking server setup" : "Asocedió un fallu mientres se comprobaba la configuración del sirvidor", "Your data directory and your files are probably accessible from the Internet. The .htaccess file is not working. We strongly suggest that you configure your web server in a way that the data directory is no longer accessible or you move the data directory outside the web server document root." : "El direutoriu de datos y ficheros ye dablemente accesible dende Internet, darréu que'l ficheru .htaccess nun ta funcionando. Suxerímoste que configures el sirvidor web de mou que'l direutoriu de datos nun seya accesible o que muevas talu direutoriu fuera del raigañu de documentos del sirvidor web.", "The \"{header}\" HTTP header is not configured to equal to \"{expected}\". This is a potential security or privacy risk and we recommend adjusting this setting." : "La \"{header}\" HTTP nun ta configurada pa igualar a \"{expected}\". Esto ye una seguridá o privacidá potencial de riesgu y encamentamos axustar esta opción.", "The \"Strict-Transport-Security\" HTTP header is not configured to at least \"{seconds}\" seconds. For enhanced security we recommend enabling HSTS as described in our <a href=\"{docUrl}\" rel=\"noreferrer\">security tips</a>." : "La cabecera HTTP \"Estrictu-Tresporte-Seguridá\" nun ta configurada pa siquier \"{seconds}\" segundos. Pa mayor seguridá encamentámos-y habilitar HSTS como se describe en nuesos <a href=\"{docUrl}\" rel=\"noreferrer\">conseyos de seguridá</a>.", "You are accessing this site via HTTP. We strongly suggest you configure your server to require using HTTPS instead as described in our <a href=\"{docUrl}\">security tips</a>." : "Tas ingresando a esti sitiu vía HTTP. Encamentámoste que configures el sirvidor pa solicitar HTTPS como describimos en nuesos <a href=\"{docUrl}\">conseyos de seguridá</a>.", "Shared" : "Compartíu", "Shared with {recipients}" : "Compartío con {recipients}", "Error" : "Fallu", "Error while sharing" : "Fallu mientres la compartición", "Error while unsharing" : "Fallu mientres se dexaba de compartir", "The public link will expire no later than {days} days after it is created" : "L'enllaz públicu va caducar enantes de {days} díes dende la so creación", "Expiration" : "Caducidá", "Link" : "Enllaz", "Edit" : "Editar", "Remove" : "Desaniciar", "Copy to clipboard" : "Copiar al cartafueyu", "Copied!" : "¡Copiáu!", "Not supported!" : "¡Non soportáu!", "Press ⌘-C to copy." : "Calca ⌘-C pa copiar", "Press Ctrl-C to copy." : "Calca Ctrl-C pa copiar.", "Name" : "Nome", "Filename" : "Nome de Ficheru", "Password" : "Contraseña", "Share" : "Compartir", "Save" : "Guardar", "Email link to person" : "Enllaz de corréu-e a la persona", "Send link via email" : "Unviáu enllaz por email", "Shared with you and the group {group} by {owner}" : "Compartíu contigo y col grupu {group} por {owner}", "Shared with you by {owner}" : "Compartíu contigo por {owner}", "group" : "grupu", "notify by email" : "notificar per corréu", "Unshare" : "Dexar de compartir", "can share" : "pue compartir", "can edit" : "pue editar", "create" : "crear", "change" : "camudar", "delete" : "desaniciar", "access control" : "control d'accesu", "Could not unshare" : "Nun pudo dexase de compartir", "Share details could not be loaded for this item." : "Los detalles de les acciones nun pudieron cargase por esti elementu.", "No users or groups found for {search}" : "Nun s'atopó nengún usuariu o grupu por {search}", "No users found for {search}" : "Nun s'atoparon usuarios por {search}", "An error occurred. Please try again" : "Hebo un fallu. Por favor, inténtalo de nueves", "User" : "Usuariu", "Group" : "Grupu", "Share with people on other ownClouds using the syntax username@example.com/owncloud" : "Compartir con xente d'otros ownClouds usando la sintaxis usuariu@exemplu.com/owncloud", "Share with users…" : "Compartir con usuarios...", "Share with users, groups or remote users…" : "Compartir con usuarios, grupos o usuarios remotos...", "Share with users or groups…" : "Compartir con usuarios o grupos...", "Share with users or remote users…" : "Compartir con usuarios o usuarios remotos...", "Error removing share" : "Fallu desaniciando compartición", "Non-existing tag #{tag}" : "Nun esiste la etiqueta #{tag}", "restricted" : "torgáu", "invisible" : "invisible", "({scope})" : "({scope})", "Delete" : "Desaniciar", "Rename" : "Renomar", "Collaborative tags" : "Etiquetes colaboratives", "The object type is not specified." : "El tipu d'oxetu nun ta especificáu.", "Enter new" : "Introducir nueva", "Add" : "Amestar", "Edit tags" : "Editar etiquetes", "Error loading dialog template: {error}" : "Fallu cargando plantía de diálogu: {error}", "No tags selected for deletion." : "Nun s'esbillaron etiquetes pa desaniciar.", "unknown text" : "testu desconocíu", "Hello world!" : "¡Hola mundiu!", "sunny" : "soleyeru", "Hello {name}, the weather is {weather}" : "Hola {name}, el tiempu ta {weather}", "Hello {name}" : "Hola {name}", "new" : "nuevu", "_download %n file_::_download %n files_" : ["descargando %n ficheru","descargando %n ficheros"], "The upgrade is in progress, leaving this page might interrupt the process in some environments." : "L'actualización ta en cursu, salir d'esta páxina podría atayar el procesu en dellos entornos.", "Updating to {version}" : "Anovando a {version}", "An error occurred." : "Hebo un fallu", "Please reload the page." : "Por favor, recarga la páxina", "The update was unsuccessful. For more information <a href=\"{url}\">check our forum post</a> covering this issue." : "L'actualización nun tuvo ésitu . Pa más información <a href=\"{url}\">comprueba'l nuesu post del foro</a> falando d'esti tema.", "The update was unsuccessful. Please report this issue to the <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">ownCloud community</a>." : "L'anovamientu fízose con ésitu. Por favor, informa d'esti problema a la <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">comuña ownCloud</a>.", "The update was successful. There were warnings." : "L'anovamientu fízose con ésitu. Hai dellos avisos.", "The update was successful. Redirecting you to ownCloud now." : "L'anovamientu fízose con ésitu. Redirixiendo agora al to ownCloud.", "Searching other places" : "Guetando otros llugares", "No search results in other folders" : "Nengún resultáu en otros direutorios", "_{count} search result in another folder_::_{count} search results in other folders_" : ["Atopose {count} resultáu en otros direutorios","Atopáronse {count} resultaos en otros direutorios"], "Personal" : "Personal", "Users" : "Usuarios", "Apps" : "Aplicaciones", "Admin" : "Alministrador", "Help" : "Ayuda", "Access forbidden" : "Accesu denegáu", "File not found" : "Nun s'atopó el ficheru", "The specified document has not been found on the server." : "El documentu especificáu nun s'atopó nel servidor.", "You can click here to return to %s." : "Pues calcar equí pa volver a %s.", "Hey there,\n\njust letting you know that %s shared %s with you.\nView it: %s\n\n" : "Hola, ¿qué hai?\n\nnamái déxanos dicite que %s compartió %s contigo.\nVelu: %s\n\n", "The share will expire on %s." : "La compartición va caducar el %s.", "Cheers!" : "¡Salú!", "Internal Server Error" : "Fallu de Sirvidor Internu", "The server encountered an internal error and was unable to complete your request." : "El sirvidor atopó un erru internu y nun pudo completar la so solicitú.", "Technical details" : "Detalles teúnicos", "Remote Address: %s" : "Accesu Remotu: %s", "Request ID: %s" : "Solicitú d'ID: %s", "Type: %s" : "Triba: %s", "Code: %s" : "Códigu: %s", "Message: %s" : "Mensaxe: %s", "File: %s" : "Ficheru: %s", "Line: %s" : "Llínea: %s", "Trace" : "Traza", "Imprint" : "Imprint", "Create an <strong>admin account</strong>" : "Crea una <strong>cuenta d'alministrador</strong>", "Username" : "Nome d'usuariu", "Storage & database" : "Almacenamientu y Base de datos", "Data folder" : "Carpeta de datos", "Configure the database" : "Configura la base de datos", "Only %s is available." : "Namái ta disponible %s", "Install and activate additional PHP modules to choose other database types." : "Instalar y activar los módulos de PHP adicionales pa escoyer otra triba de bases de datos.", "For more details check out the documentation." : "Pa más detalles comprueba la documentación.", "Database user" : "Usuariu de la base de datos", "Database password" : "Contraseña de la base de datos", "Database name" : "Nome de la base de datos", "Database tablespace" : "Espaciu de tables de la base de datos", "Database host" : "Agospiador de la base de datos", "Performance warning" : "Avisu de rendimientu", "SQLite will be used as database." : "SQLite va utilizase como base de datos.", "For larger installations we recommend to choose a different database backend." : "Pa instalaciones más grandes encamiéntase escoyer un motor de base de datos distintu.", "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Especialmente cuando s'utiliza'l veceru d'escritoriu pa la sincronización de ficheros l'usu de SQLite ta desaconseyáu .", "Finish setup" : "Finar la configuración ", "Finishing …" : "Finando ...", "Need help?" : "¿Precises sofitu?", "See the documentation" : "Consulta la documentación", "Hey there,<br><br>just letting you know that %s shared <strong>%s</strong> with you.<br><a href=\"%s\">View it!</a><br><br>" : "Hola, ¿qué hai?,<br><br>namái déxamos dicite que %s compartió <strong>%s</strong> contigo.\n<br><a href=\"%s\">¡Velu!</a><br><br>", "This application requires JavaScript for correct operation. Please {linkstart}enable JavaScript{linkend} and reload the page." : "Esta aplicación rique JavaScript pal so correctu funcionamientu. Por favor {linkstart}habilitaJavaScript{linkend} y recarga la páxina.", "Menu" : "Menú", "Log out" : "Zarrar sesión", "Search" : "Guetar", "Server side authentication failed!" : "Falló l'autenticación nel sirvidor!", "Please contact your administrator." : "Por favor, contauta col to alministrador", "An internal error occurred." : "Hebo un fallu internu.", "Please try again or contact your administrator." : "Por favor, inténtalo de nueves o ponte en contactu col alministrador.", "Login" : "Entamar sesión", "Username or email" : "Nome d'usuariu o email", "Wrong password. Reset it?" : "Contraseña incorreuta. ¿Reafitala?", "Wrong password." : "Contraseña incorreuta.", "Stay logged in" : "Permanecer conectáu", "Alternative Logins" : "Anicios de sesión alternativos", "Use the following link to reset your password: {link}" : "Usa'l siguiente enllaz pa restablecer la to contraseña: {link}", "New password" : "Contraseña nueva", "New Password" : "Contraseña nueva", "Reset password" : "Restablecer contraseña", "This ownCloud instance is currently in single user mode." : "Esta instalación d'ownCloud ta en mou d'usuariu únicu.", "This means only administrators can use the instance." : "Esto quier dicir que namái pue usala un alministrador.", "Contact your system administrator if this message persists or appeared unexpectedly." : "Contauta col alministrador si esti problema sigui apaeciendo.", "Thank you for your patience." : "Gracies pola to paciencia.", "Two-step verification" : "Verificación de dos pasos", "Enhanced security has been enabled for your account. Please authenticate using a second factor." : "Habilitóse pa la so cuenta la seguridá ameyorada. Por favor autentica por aciu d'un segundu factor.", "Cancel login" : "Encaboxar aniciu de sesión", "Please authenticate using the selected factor." : "Por favor autentificate usando'l factor escoyíu.", "You are accessing the server from an untrusted domain." : "Tas accediendo al sirvidor dende un dominiu non confiáu.", "App update required" : "Actualización de l'aplicación riquida", "%s will be updated to version %s" : "%s anovaráse a la versión %s", "These apps will be updated:" : "Estes aplicaciones van anovase:", "The theme %s has been disabled." : "Deshabilitóse'l tema %s.", "Please make sure that the database, the config folder and the data folder have been backed up before proceeding." : "Enantes de siguir, asegúrate de que se fizo una copia de seguridá de la base de datos, la carpeta de configuración y la carpeta de datos.", "Start update" : "Aniciar anovamientu", "To avoid timeouts with larger installations, you can instead run the following command from your installation directory:" : "Pa evitar tiempos d'espera con instalaciones más grandes, nel so llugar puede executar el siguiente comandu dende'l directoriu d'instalación:", "Detailed logs" : "Rexistros detallaos", "Update needed" : "Anovamientu necesariu", "For help, see the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation</a>." : "Pa llograr sofitu, consulte la <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentación</a>.", "This %s instance is currently in maintenance mode, which may take a while." : "Esta instancia %s ta anguaño en mou de mantenimientu, polo que pue tardar un pocoñín.", "This page will refresh itself when the %s instance is available again." : "Esta páxina va anovase sola cuando la instancia %s tea disponible de nueves." }, "nplurals=2; plural=(n != 1);");
import React from 'react' import { makeStyles } from '@material-ui/core'; import { Link } from 'react-router-dom'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import htmlImage from '/Users/l/my-react-website/src/images/html_logo.png'; import cssImage from '/Users/l/my-react-website/src/images/css_logo.png'; import reactImage from '/Users/l/my-react-website/src/images/react_logo.png'; import javascriptImage from '/Users/l/my-react-website/src/images/javascript_logo.png'; import './Section.css'; const useStyles = makeStyles((theme) => ({ body: { marginTop: '1em', position: 'relative', bottom: '12rem' }, header: { display: 'flex', justifyContent: 'left', alignItems: 'center', position: 'relative', left: '200px', textAlign: 'center', marginTop: '25rem', marginBottom: '2rem', fontSize: '2.5rem', }, headerLine: { width: '65rem', borderColor: '#5288a4', position: 'relative', left: '0' }, container: { width: '100%', padding: '1rem 0 0', left: 0, right: 0, ['@media (max-width: 768px)']: { display: 'flex', flexDirection: 'column', position: 'relative', top: '250px' } }, containerOne: { ['@media (max-width: 768px)']: { position: 'relative', top: '275px' } }, text: { fontSize: '32px' }, root: { flexGrow: 1 }, paper: { padding: theme.spacing(2), textAlign: 'center', width: '10em', height: '7em', backgroundColor: 'white' }, } )) function Section() { const classes = useStyles(); return ( <div className={` ${classes.body} ${classes.container} `}> <div id='skills'><h1 className={classes.header}>Skills</h1></div> <hr className={classes.headerLine}></hr> <div className="skills-container"> <img className='html' src={htmlImage} alt='html logo' /> <img src={cssImage} alt='css logo' /> <img src={javascriptImage} alt='javascript logo' /> </div> <div className="skills-container-two"> <img src={reactImage} alt='react logo' /> </div> </div> ) } export default Section
define([ 'common/collections/availability' ], function (AvailabilityCollection) { describe('AvailabilityCollection', function () { var availabilityData = {'data': [ { 'uptime:sum': 9, 'downtime:sum': 1, 'unmonitored:sum': 1, 'avgresponse:mean': 321 }, { 'uptime:sum': 10, 'downtime:sum': 0, 'unmonitored:sum': 1, 'avgresponse:mean': 345 } ]}; var options = { checkName: 'anything', 'data-group': 'anything', 'data-type': 'monitoring', parse: true }; it('should be created with correct query parameters', function () { var collection = new AvailabilityCollection(null, { checkName: 'mycheck' }); var params = collection.queryParams; expect(params.collect).toEqual(['downtime:sum', 'uptime:sum', 'unmonitored:sum', 'avgresponse:mean']); }); it('should provide percentage of uptime for all models', function () { var collection = new AvailabilityCollection(availabilityData, options); var fractionOfUptime = collection.getFractionOfUptime(); expect(fractionOfUptime).toEqual(0.95); }); it('should provide total uptime', function () { var collection = new AvailabilityCollection(availabilityData, options); var totalUptime = collection._getTotalUptime(); expect(totalUptime).toEqual(19); }); it('should return null total uptime when no data is available', function () { var collection = new AvailabilityCollection(null, options); expect(collection._getTotalUptime()).toEqual(null); }); it('should provide total (monitored) time', function () { var collection = new AvailabilityCollection({'data': [{ 'uptime:sum': 1, 'downtime:sum': 2, 'unmonitored:sum': 3 }]}, options); var totalTime = collection._getTotalTime(); expect(totalTime).toEqual(3); }); it('should provide total monitored and unmonitored time when told to', function () { var collection = new AvailabilityCollection({'data': [{ 'uptime:sum': 1, 'downtime:sum': 2, 'unmonitored:sum': 3 }]}, options); var totalTime = collection._getTotalTime(true); expect(totalTime).toEqual(6); }); it('should provide total time for all models', function () { var collection = new AvailabilityCollection(availabilityData, options); var totalTime = collection._getTotalTime(); expect(totalTime).toEqual(20); }); it('should return null total time when no data is available', function () { var collection = new AvailabilityCollection(null, options); expect(collection._getTotalTime()).toEqual(null); }); it('should provide average response time', function () { var collection = new AvailabilityCollection(availabilityData, options); var averageResponseTime = collection.getAverageResponseTime(); expect(averageResponseTime).toEqual(333); }); it('should return null average response time when no data is available', function () { var collection = new AvailabilityCollection(null, options); expect(collection.getAverageResponseTime()).toEqual(null); }); it('should parse data with end_at as the timestamp and start at as an hour earlier', function () { var response = { data: [ { '_end_at': '2013-06-17T16:00:00+00:00', '_start_at': '2013-06-17T15:00:00+00:00', 'uptime:sum': 900, 'downtime:sum': 100, 'unmonitored:sum': 0, 'avgresponse:mean': 100 } ] }; var collection = new AvailabilityCollection(availabilityData, options); var data = collection.parse(response); expect(data[0]._start_at).toEqual(collection.moment('2013-06-17T15:00:00+00:00')); expect(data[0]._end_at).toEqual(collection.moment('2013-06-17T16:00:00+00:00')); }); it('should parse null data without resorting to NaN', function () { var response = { data: [ { '_count': 0, '_end_at': '2013-10-21T11:00:00+00:00', '_start_at': '2013-10-21T10:00:00+00:00', 'uptime:sum': null, 'downtime:sum': null, 'unmonitored:sum': null, 'avgresponse:mean': null } ] }; var collection = new AvailabilityCollection(availabilityData, options); var data = collection.parse(response); expect(data[0].total).toEqual(null); expect(data[0].uptimeFraction).toEqual(null); }); }); });
/** * Created by wo on 2016/8/15. */ import React, { Component, PropTypes } from 'react'; import s from "./Button.css" import withStyles from 'isomorphic-style-loader/lib/withStyles'; import className from 'classnames'; class Button extends Component { constructor(props) { super(props); this.state = { btnStyle: [] } } static propTypes = { btnText: PropTypes.string.isRequired, btnCB: PropTypes.func.isRequired, btnStyle: PropTypes.array, } renStyle(){ if (!!this.props.btnStyle) { this.props.btnStyle.forEach((val, index)=> { this.state.btnStyle[index] = s[val]; }); this.state.btnStyle.push(s["button"]); } } handleEvent() { this.props.btnCB(123); } render() { this.renStyle(); return ( <button disabled={this.props.disabled} className={className(this.state.btnStyle)} onClick={this.handleEvent.bind(this)}> {this.props.Icon}{this.props.children}{this.props.btnText}</button> ) } } export default withStyles(s)(Button);