text stringlengths 7 3.69M |
|---|
import React from "react";
import {
AppBar,
Button,
Toolbar,
Typography
} from "@material-ui/core";
import styled from "styled-components";
const StyledAppBar = styled(AppBar)`
flex-grow: 1;
& button {
margin: 0.5em;
}
`;
const StyledTitle = styled(Typography)`
flex-grow: 1;
`;
export default (props) => {
const toShoppingList = () => {
console.error("Not yet implemented");
};
return (
<StyledAppBar position="fixed">
<Toolbar>
<StyledTitle variant="h6">{props.title}</StyledTitle>
<Button variant="contained" color="secondary" onClick={toShoppingList}>To shopping list</Button>
<Button href="/all" variant="contained" color="secondary">All recipes</Button>
</Toolbar>
</StyledAppBar>
);
}; |
#!/usr/bin/env node
let child = require('child_process');
const task = process.argv[process.argv.length - 2]
const param = process.argv[process.argv.length - 1]
if (task === 'init' && !!param) {
const teskDir = process.cwd()
const localDir = __dirname
child.exec(`cp -r ${localDir}/demo ${teskDir}/${param}`, function(err, sto) {
if (!err) console.log(`\x1B[1;32mdemo build success!\x1B[0m`)
})
} |
'use strict';
app.controller('EmployeeDetails', function($http, $rootScope, $scope, $state) {
var id = sessionStorage.getItem("id");
if(!id){
$scope.return();
}
$http({
url: app.url.employee.api.edit,
data: {
id: id
},
method: 'POST'
}).then(function(dt) {
$scope.details = dt.data.editData;
$scope.details.gender = DataRender.Gender($scope.details.gender);
});
$scope.return = function(){
$state.go('app.employee.list');
$scope.$parent.reload();
};
}); |
import React from 'react';
import Select from 'react-select';
import { categories as categoryData } from '../../helpers/cmsCustomData';
export default class CategoryFilter extends React.Component {
static defaultProps = {
multiSelect: false,
placeholder: 'Select categories',
selected: []
};
state = {
categories: [],
loading: true,
};
componentDidMount = () => {
this.getCategories();
};
getCategories = () => {
setTimeout(() => {
this.setState({
categories: categoryData,
loading: false
});
}, 500);
};
render = () => {
return (
<div>
<Select
value={this.props.selected}
placeholder={this.props.placeholder}
isMulti={this.props.multiSelect}
isClearable
getOptionLabel={option => option.name}
getOptionValue={option => option.uuid}
isSearchable
isLoading={this.state.loading}
onChange={value => this.props.callback(value)}
name="author"
options={this.state.categories}
/>
</div>
);
}
}
|
import React from "react"
import { connect } from "react-redux";
import * as actions from '../../store/actions/general';
import Router from 'next/router'
import StreamData from "./StreamData"
import Channels from "./Channels"
import Videos from "./Videos"
import Movies from "./Movies"
import Playlists from "./Playlists"
import Audio from "./Audio"
import Blogs from "./Blogs"
import Members from "./Members"
import Ads from "./Ads"
import Delete from "./Delete"
import Verification from "./Verification"
import Password from "./Password"
import General from "./General"
import Profile from "./Profile"
import Cover from "../Cover/User"
import Alert from "./Alert"
import Monetization from "./Monetization"
import Balance from "./Balance"
import Translate from "../../components/Translate/Index"
import Purchase from "./Purchases";
import Earning from "./Earning"
import Points from "./Points"
class Index extends React.Component {
constructor(props) {
super(props)
this.state = {
filter: props.pageData ? props.pageData.filter : "",
type: props.pageData ? props.pageData.type : "general",
member: props.pageData ? props.pageData.member : {},
items: props.pageData ? props.pageData.items.results : null,
pagging: props.pageData ? props.pageData.items.pagging : null,
notificationTypes: props.pageData ? props.pageData.notificationTypes : null,
user:props.pageInfoData ? props.pageInfoData.user : "",
userShowBalance:props.pageInfoData ? props.pageInfoData.userShowBalance : "",
memberMonetization:props.pageInfoData ? props.pageInfoData.memberMonetization : "",
monetization_threshold_amount:props.pageInfoData ? props.pageInfoData.monetization_threshold_amount : null,
statsData:props.pageInfoData ? props.pageInfoData.statsData : null,
width:props.isMobile ? props.isMobile : 993
}
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
updateWindowDimensions() {
this.setState({localUpdate:true, width: window.innerWidth });
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
componentDidMount(){
if(this.props.pageInfoData.appSettings["fixed_header"] == 1 && this.props.hideSmallMenu && !this.props.menuOpen){
this.props.setMenuOpen(true)
}
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
this.props.socket.on('unfavouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (id == this.state.member.user_id && type == "members") {
if (this.state.member.user_id == id) {
const data = { ...this.state.member }
data.favourite_count = data.favourite_count - 1
if (this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
data.favourite_id = null
}
this.setState({localUpdate:true, member: data })
}
}
});
this.props.socket.on('favouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (id == this.state.member.user_id && type == "members") {
if (this.state.member.user_id == id) {
const data = { ...this.state.member }
data.favourite_count = data.favourite_count + 1
if (this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
data.favourite_id = 1
}
this.setState({localUpdate:true, member: data })
}
}
});
this.props.socket.on('likeDislike', data => {
let itemId = data.itemId
let itemType = data.itemType
let ownerId = data.ownerId
let removeLike = data.removeLike
let removeDislike = data.removeDislike
let insertLike = data.insertLike
let insertDislike = data.insertDislike
if (itemType == "members" && this.state.member.user_id == itemId) {
const item = { ...this.state.member }
let loggedInUserDetails = {}
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails) {
loggedInUserDetails = this.props.pageInfoData.loggedInUserDetails
}
if (removeLike) {
if (loggedInUserDetails.user_id == ownerId)
item['like_dislike'] = null
item['like_count'] = parseInt(item['like_count']) - 1
}
if (removeDislike) {
if (loggedInUserDetails.user_id == ownerId)
item['like_dislike'] = null
item['dislike_count'] = parseInt(item['dislike_count']) - 1
}
if (insertLike) {
if (loggedInUserDetails.user_id == ownerId)
item['like_dislike'] = "like"
item['like_count'] = parseInt(item['like_count']) + 1
}
if (insertDislike) {
if (loggedInUserDetails.user_id == ownerId)
item['like_dislike'] = "dislike"
item['dislike_count'] = parseInt(item['dislike_count']) + 1
}
this.setState({localUpdate:true, member: item })
}
});
this.props.socket.on('userCoverReposition', data => {
let id = data.user_id
if (id == this.state.member.user_id) {
const item = {...this.state.member}
item.cover_crop = data.image
item.showCoverReposition = false
this.setState({localUpdate:true, member: item, loadingCover: false })
this.props.openToast(Translate(this.props,data.message), "success");
}
});
this.props.socket.on('userMainPhotoUpdated', data => {
let id = data.user_id
if (id == this.state.member.user_id) {
const item = {...this.state.member}
item.avtar = data.image
this.setState({localUpdate:true, member: item, loadingCover: false })
this.props.openToast(Translate(this.props,data.message), "success");
}
});
this.props.socket.on('userCoverUpdated', data => {
let id = data.user_id
if (id == this.state.member.user_id) {
const item = {...this.state.member}
item.cover = data.image
item.usercover = true;
item.cover_crop = null;
item.showCoverReposition = true
this.setState({localUpdate:true, member: item, loadingCover: false })
this.props.openToast(Translate(this.props,data.message), "success");
}
});
}
static getDerivedStateFromProps(nextProps, prevState) {
if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){
return null;
}
if(prevState.localUpdate){
return {...prevState,localUpdate:false}
}else if (nextProps.type != prevState.type || nextProps.filter != prevState.filter) {
return {
filter: nextProps.pageData ? nextProps.pageData.filter : "",
type: nextProps.pageData ? nextProps.pageData.type : "general",
member: nextProps.pageData ? nextProps.pageData.member : {},
items: nextProps.pageData ? nextProps.pageData.items.results : null,
pagging: nextProps.pageData ? nextProps.pageData.items.pagging : null,
notificationTypes: nextProps.pageData ? nextProps.pageData.notificationTypes : null,
user:nextProps.pageData ? nextProps.pageData.user : "",
userShowBalance:nextProps.pageData ? nextProps.pageData.userShowBalance : "",
memberMonetization:nextProps.pageData ? nextProps.pageData.memberMonetization : "",
monetization_threshold_amount:nextProps.pageData ? nextProps.pageData.monetization_threshold_amount : null,
statsData:nextProps.pageData ? nextProps.pageData.statsData : null
}
}else{
return null
}
}
changeType(type, e) {
e.preventDefault()
let subtype = `/dashboard?type=${type}`
let asPath = `/dashboard/${type}`
if(this.state.user){
subtype = subtype+"&user="+this.state.user
asPath = asPath + "?user="+this.state.user
}
Router.push(
`${subtype}`,
`${asPath}`,
)
}
changeFilter = (e) => {
e.preventDefault()
let type = e.target.value
let subtype = `/dashboard?type=${type}`
let asPath = `/dashboard/${type}`
if(this.state.user){
subtype = subtype+"&user="+this.state.user
asPath = asPath + "?user="+this.state.user
}
Router.push(
`${subtype}`,
`${asPath}`,
)
}
render() {
let user = ""
let isOwner = true
if(this.state.user){
user = "?user="+this.state.user
if(this.state.user == this.props.pageInfoData.loggedInUserDetails.username){
isOwner = true
}else{
isOwner = false;
}
}
const options = {}
if(this.state.member.canEdit) {
options['general'] = Translate(this.props,'General');
options['profile'] = Translate(this.props,'Profile');
}
options['password'] = Translate(this.props,'Password');
if(this.state.memberMonetization && isOwner)
options['monetization'] = Translate(this.props,'Monetization');
if(this.state.userShowBalance && isOwner)
options['balance'] = Translate(this.props,'Balance');
if(this.state.member.verificationFunctionality && isOwner)
options['verification'] = Translate(this.props,'Verification');
if(isOwner){
options['notifications'] = Translate(this.props,'Notifications Alert');
options['emails'] = Translate(this.props,'Emails Alert');
options['videos'] = Translate(this.props,'Videos');
if(this.props.pageInfoData['livestreamingtype'] == 0 && this.props.pageInfoData.appSettings['antserver_media_singlekey'] == 1)
options['streamdata'] = Translate(this.props,'Default Stream Data');
if((this.props.pageData.levelPermissions["movie.edit"] == 1 || this.props.pageData.levelPermissions["movie.edit"] == 2) && this.props.pageData.appSettings["enable_movie"] == 1)
options['movies'] = Translate(this.props,'Movies');
if((this.props.pageData.levelPermissions["movie.edit"] == 1 || this.props.pageData.levelPermissions["movie.edit"] == 2) && this.props.pageData.appSettings["enable_movie"] == 1)
options['series'] = Translate(this.props,'Series');
if((this.props.pageData.levelPermissions["channel.edit"] == 1 || this.props.pageData.levelPermissions["channel.edit"] == 2) && this.props.pageData.appSettings["enable_channel"] == 1)
options['channels'] = Translate(this.props,'Channels');
if((this.props.pageData.levelPermissions["blog.edit"] == 1 || this.props.pageData.levelPermissions["blog.edit"] == 2) && this.props.pageData.appSettings["enable_blog"] == 1)
options['blogs'] = Translate(this.props,'Blogs');
options['members'] = Translate(this.props,'Members');
if((this.props.pageData.levelPermissions["playlist.create"] == 1 || this.props.pageData.levelPermissions["playlist.edit"] == 2) && this.props.pageData.appSettings["enable_playlist"] == 1)
options['playlists'] = Translate(this.props,'Playlists');
if((this.props.pageData.levelPermissions["audio.create"] == 1 || this.props.pageData.levelPermissions["audio.edit"] == 2) && this.props.pageData.appSettings["enable_audio"] == 1)
options['audio'] = Translate(this.props,'Audio');
options['purchases'] = Translate(this.props,'Purchases');
if(this.state.userShowBalance)
options['earning'] = Translate(this.props,'Earning');
if((this.props.pageData.levelPermissions["member.ads"] == 1) && this.props.pageData.appSettings["enable_ads"] == 1)
options['ads'] = Translate(this.props,'Advertisements');
}
if( this.state.member.canDelete)
options['delete'] = Translate(this.props,'Delete Account');
return (
<React.Fragment>
<Cover {...this.props} profile={true} settings={true} {...this.state.member} member={this.state.member} type="member" id={this.state.member.user_id} />
<div className="container-fluid mt-5">
<div className="row">
<div className="col-lg-2">
<div className="sdBarSettBox">
{
this.state.width > 992 ?
<ul className="nav nav-tabs tabsLeft">
{
this.state.member.canEdit ?
<li >
<a href={`/dashboard/general${user}`} onClick={this.changeType.bind(this, 'general')} className={this.state.type == "general" ? "active" : ""}>{Translate(this.props, "General")}</a>
</li>
: null
}
{
this.state.member.canEdit ?
<li >
<a href={`/dashboard/profile${user}`} onClick={this.changeType.bind(this, 'profile')} className={this.state.type == "profile" ? "active" : ""}>{Translate(this.props, "Profile")}</a>
</li>
: null
}
<li >
<a href={`/dashboard/password${user}`} onClick={this.changeType.bind(this, 'password')} className={this.state.type == "password" ? "active" : ""}>{Translate(this.props, "Password")}</a>
</li>
{
this.state.memberMonetization && isOwner ?
<li>
<a href={`/dashboard/monetization${user}`} onClick={this.changeType.bind(this, 'monetization')} className={this.state.type == "monetization" ? "active" : ""}>{Translate(this.props, "Monetization")}</a>
</li>
: null
}
{
this.state.userShowBalance && isOwner ?
<li>
<a href={`/dashboard/balance${user}`} onClick={this.changeType.bind(this, 'balance')} className={this.state.type == "balance" || this.state.type == "withdraw" ? "active" : ""}>{Translate(this.props, "Balance")}</a>
</li>
: null
}
{
this.props.pageInfoData.appSettings['enable_ponts'] == 1 && isOwner ?
<li>
<a href={`/dashboard/points${user}`} onClick={this.changeType.bind(this, 'points')} className={this.state.type == "points" ? "active" : ""}>{Translate(this.props, "Points")}</a>
</li>
: null
}
{
this.state.member.verificationFunctionality && isOwner ?
<li>
<a href={`/dashboard/verification${user}`} onClick={this.changeType.bind(this, 'verification')} className={this.state.type == "verification" ? "active" : ""}>{Translate(this.props, "Verification")}</a>
</li>
: null
}
{
isOwner ?
<li>
<a href={`/dashboard/notifications${user}`} onClick={this.changeType.bind(this, 'notifications')} className={this.state.type == "notifications" ? "active" : ""} >{Translate(this.props, "Notifications Alert")}</a>
</li>
: null
}
{
isOwner && this.props.pageInfoData['livestreamingtype'] == 0 && this.props.pageInfoData.appSettings['antserver_media_singlekey'] == 1 ?
<li>
<a href={`/dashboard/streamdata${user}`} onClick={this.changeType.bind(this, 'streamdata')} className={this.state.type == "streamdata" ? "active" : ""} >{Translate(this.props, "Default Stream Data")}</a>
</li>
: null
}
{
isOwner ?
<React.Fragment>
<li>
<a href={`/dashboard/emails${user}`} onClick={this.changeType.bind(this, 'emails')} className={this.state.type == "emails" ? "active" : ""} >{Translate(this.props, "Emails Alert")}</a>
</li>
<li>
<a href={`/dashboard/videos${user}`} onClick={this.changeType.bind(this, 'videos')} className={this.state.type == "videos" ? "active" : ""} >{Translate(this.props, "Videos")}</a>
</li>
</React.Fragment>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["movie.edit"] == 1 || this.props.pageData.levelPermissions["movie.edit"] == 2) && this.props.pageData.appSettings["enable_movie"] == 1 ?
<li>
<a href={`/dashboard/movies${user}`} onClick={this.changeType.bind(this, 'movies')} className={this.state.type == "movies" ? "active" : ""}>{Translate(this.props, "Movies")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["movie.edit"] == 1 || this.props.pageData.levelPermissions["movie.edit"] == 2) && this.props.pageData.appSettings["enable_movie"] == 1 ?
<li>
<a href={`/dashboard/series${user}`} onClick={this.changeType.bind(this, 'series')} className={this.state.type == "series" ? "active" : ""}>{Translate(this.props, "Series")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["channel.edit"] == 1 || this.props.pageData.levelPermissions["channel.edit"] == 2) && this.props.pageData.appSettings["enable_channel"] == 1 ?
<li>
<a href={`/dashboard/channels${user}`} onClick={this.changeType.bind(this, 'channels')} className={this.state.type == "channels" ? "active" : ""}>{Translate(this.props, "Channels")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["blog.edit"] == 1 || this.props.pageData.levelPermissions["blog.edit"] == 2) && this.props.pageData.appSettings["enable_blog"] == 1 ?
<li>
<a href={`/dashboard/blogs${user}`} onClick={this.changeType.bind(this, 'blogs')} className={this.state.type == "blogs" ? "active" : ""}>{Translate(this.props, "Blogs")}</a>
</li>
: null
}
{
isOwner ?
<li>
<a href={`/dashboard/members${user}`} onClick={this.changeType.bind(this, 'members')} className={this.state.type == "members" ? "active" : ""}>{Translate(this.props, "Members")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["playlist.create"] == 1 || this.props.pageData.levelPermissions["playlist.edit"] == 2) && this.props.pageData.appSettings["enable_playlist"] == 1 ?
<li >
<a href={`/dashboard/playlists${user}`} onClick={this.changeType.bind(this, 'playlists')} className={this.state.type == "playlists" ? "active" : ""}>{Translate(this.props, "Playlists")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["audio.create"] == 1 || this.props.pageData.levelPermissions["audio.edit"] == 2) && this.props.pageData.appSettings["enable_audio"] == 1 ?
<li >
<a href={`/dashboard/audio${user}`} onClick={this.changeType.bind(this, 'audio')} className={this.state.type == "audio" ? "active" : ""}>{Translate(this.props, "Audio")}</a>
</li>
: null
}
{
isOwner ?
<li >
<a href={`/dashboard/purchases${user}`} onClick={this.changeType.bind(this, 'purchases')} className={this.state.type == "purchases" ? "active" : ""}>{Translate(this.props, "Purchases")}</a>
</li>
: null
}
{
isOwner && this.state.userShowBalance ?
<li >
<a href={`/dashboard/earning${user}`} onClick={this.changeType.bind(this, 'earning')} className={this.state.type == "earning" ? "active" : ""}>{Translate(this.props, "Earning")}</a>
</li>
: null
}
{
isOwner && (this.props.pageData.levelPermissions["member.ads"] == 1) && this.props.pageData.appSettings["enable_ads"] == 1 && (this.props.pageData.appSettings['video_ffmpeg_path'] || this.props.pageData.loggedInUserDetails.level_id == 1) ?
<li >
<a href={`/dashboard/ads${user}`} onClick={this.changeType.bind(this, 'ads')} className={this.state.type == "ads" ? "active" : ""}>{Translate(this.props, "Advertisements")}</a>
</li>
: null
}
{
this.state.member.canDelete ?
<li >
<a href={`/dashboard/delete${user}`} onClick={this.changeType.bind(this, 'delete')} className={this.state.type == "delete" ? "active" : ""}>{Translate(this.props, "Delete Account")}</a>
</li>
: null
}
</ul>
:
<div className="formFields">
<div className="form-group">
<select className="form-control form-select" value={this.state.type} onChange={this.changeFilter}>
{
Object.keys(options).map(function(key) {
return (
<option value={key} key={key}>{options[key]}</option>
)
})
}
</select>
</div>
</div>
}
</div>
</div>
<div className="col-lg-10 bgSecondry">
<div className="tab-content dashboard">
{
this.state.type == "purchases" ?
<Purchase {...this.props} contentType={this.state.type} member={this.state.member} />
: null
}
{
this.props.pageInfoData.appSettings['enable_ponts'] == 1 && this.state.type == "points" ?
<Points {...this.props} contentType={this.state.type} member={this.state.member} />
: null
}
{
this.state.userShowBalance && this.state.type == "earning" ?
<Earning {...this.props} statsData={this.state.statsData} items={this.state.items} contentType={this.state.type} member={this.state.member} />
: null
}
{
this.state.type == "general" ?
<General {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "monetization" ?
<Monetization {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "balance" || this.state.type == "withdraw" ?
<Balance {...this.props} member={this.state.member} type={this.state.type} />
: null
}
{
this.state.type == "profile" ?
<Profile {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "streamdata" ?
<StreamData {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "password" ?
<Password {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "verification" ?
<Verification {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "notifications" ?
<Alert {...this.props} type={this.state.type} member={this.state.member} notificationTypes={this.state.notificationTypes} />
: null
}
{
this.state.type == "emails" ?
<Alert {...this.props} type={this.state.type} member={this.state.member} notificationTypes={this.state.notificationTypes} />
: null
}
{
this.state.type == "videos" ?
<Videos {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "movies" || this.state.type == "series"?
<Movies {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "channels" ?
<Channels {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "blogs" ?
<Blogs {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "members" ?
<Members {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "playlists" ?
<Playlists {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "audio" ?
<Audio {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "ads" ?
<Ads {...this.props} member={this.state.member} />
: null
}
{
this.state.type == "delete" ?
<Delete {...this.props} member={this.state.member} />
: null
}
</div>
</div>
</div>
</div>
</React.Fragment>
)
}
}
const mapStateToProps = state => {
return {
pageInfoData: state.general.pageInfoData,
menuOpen:state.search.menuOpen
};
};
const mapDispatchToProps = dispatch => {
return {
setMenuOpen: (status) => dispatch(actions.setMenuOpen(status)),
setPageInfoData: (data) => dispatch(actions.setPageInfoData(data)),
openToast: (message, typeMessage) => dispatch(actions.openToast(message, typeMessage)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Index) |
import { call, put, takeEvery } from 'redux-saga/effects';
import * as Toastr from 'toastr';
import HttpHelper from '../../utils/http-helper';
import { ADD_CALL_LOGS_URL } from '../../utils/urls';
import { ADD_CALL_LOGS_REQUEST } from './profile-constants';
import { addCallLogsSuccess, addCallLogsFailure } from './add-call-logs-action';
const { postRequest } = new HttpHelper();
export function* addCallLogs(action) {
try {
const response = yield call(postRequest, {
data: {
category: action.data.summary,
description: action.data.description,
status: action.data.status,
},
url: ADD_CALL_LOGS_URL,
});
if (response.error) {
const { data } = response.error.response;
yield put(addCallLogsFailure());
Toastr.error(
`${data.details[0].name} : ${data.details[0].message}`,
'Failure'
);
} else {
yield put(addCallLogsSuccess());
action.callLogSuccessCallback();
}
} catch (error) {
// Toastr.error(error, 'Failure Response');
}
}
export function* watchAddCallLogs() {
yield takeEvery(ADD_CALL_LOGS_REQUEST, addCallLogs);
}
|
const Router = require('koa-router')
const router = new Router()
router.use('/account', require('./account'))
router.use('/info', require('./info'))
module.exports = router.routes()
|
document.write('<script src="/common/frontia/src/base/frontia.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/error.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/gzip.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/util.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/ajax.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/jsonp.js">\x3C/script>');
document.write('<script src="/common/frontia/src/base/user.js">\x3C/script>');
document.write('<script src="/common/frontia/src/social/social.js">\x3C/script>');
document.write('<script src="/common/frontia/src/store/storage.js">\x3C/script>');
document.write('<script src="/common/frontia/src/store/personal_storage.js">\x3C/script>');
document.write('<script src="/common/frontia/src/push/push.js">\x3C/script>');
|
const screen = document.querySelector('#screen');
const guide = document.querySelector('#guide');
const result = document.querySelector('#result');
const startGame = document.querySelector('#startGame');
let startTime = 0;
let endTime = 0;
let 기록 = [];
let timeOut;
let stopflag = 0;
let count = 0;
let newGame = false;
screen.classList.remove('waiting');
screen.classList.remove('toClick');
screen.classList.add('result');
screen.textContent = '시작하려면 클릭';
screen.addEventListener('click', function () {
if (screen.classList.contains('waiting')) { // 빨 > 초록화면 toClick (저절로 넘어감)
//부정클릭 막기
if (stopflag !== 1) { // 0이면 클릭안됨
clearTimeout(timeOut);
console.log('block');
screen.textContent = '기다렸다가 누르세요';
screen.classList.remove('waiting');
screen.classList.add('result');
// stopflag = 1;
} else {
screen.classList.remove('waiting');
screen.classList.add('toClick');
screen.textContent = '클릭!!!!!!';
stopflag = 0;
count++;
}
} else if (screen.classList.contains('toClick')) { // 초 > 파랑화면 result
screen.classList.remove('toClick');
screen.classList.add('result');
stopflag = 0;
//끝시간 체크
endTime = new Date();
console.log('elapsed time', endTime - startTime)
screen.textContent = (endTime - startTime + "초 걸렸습니다. 다시");
기록.push(endTime - startTime);
if (count > 2) {
console.log('5times already')
기록.sort(function (p, c) {
return p - c
})
result.textContent = "기록 순서대로 " + 기록;
newGame = true;
}
} else if (screen.classList.contains('result')) { // 파 > 빨강화면 waiting
if (newGame) {
return;
}
screen.classList.remove('result');
screen.classList.add('waiting');
screen.textContent = '초록색이 되면 클릭하세요.';
stopflag = 0; //클릭가능
let randomSecond = (Math.random() * 2000) + 1000;
//빨강화면 넘어간 후 랜덤시간 후 클릭 (>> 초록색)
timeOut = setTimeout(function () {
//시작시간 체크
startTime = new Date();
stopflag = 1; //클릭가능
screen.click();
}, randomSecond);
}
});
startGame.addEventListener('click', function () {
newGame = false;
})
|
import React, { useState }from 'react';
import Header from './Components/Header';
import Hero from './Components/Hero';
import Tab from './Components/Tab'
import "./App.css";
import Planets from './Components/Planets';
import Favourite from './Components/Favourite';
const App = () => {
const [tab,settab] = useState('planet');
return(
<>
<Header />
<Hero />
<Tab />
</>
)
}
export default App; |
/**
* Common database helper functions.
*/
//import idb from 'idb';
class DBHelper {
/**
* Database URL.
* Change this to restaurants.json file location on your server.
*/
static get DATABASE_URL() {
const port = 1337; // Change this to your server port
return `http://localhost:${port}/`;
}
static OpenDbPromise () {
if (!navigator.serviceWorker) {
return Promise.resolve();
}
return idb.open('mws-restaurant', 2, function(upgradeDb) {
switch (upgradeDb.oldVersion) {
case 0:
upgradeDb.createObjectStore('restaurants', {
keyPath: 'id'
});
case 1:
upgradeDb.createObjectStore('reviews', {
keyPath: 'id'
}).createIndex('restaurant', 'restaurant_id');
upgradeDb.createObjectStore('offline-reviews', {
autoIncrement: true
}).createIndex('restaurant', 'restaurant_id');
}
});
}
/**
* Fetch all restaurants.
*/
static fetchRestaurants(callback) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
if (!db) {
DBHelper.fetchRestaurantsFromServer(callback);
}
const index = db.transaction('restaurants').objectStore('restaurants');
return index.getAll().then(restaurants => {
if ((!restaurants) || (!restaurants.length)) {
DBHelper.fetchRestaurantsFromServer(callback)
}
callback(null, restaurants);
});
});
}
static fetchRestaurantsFromServer(callback) {
fetch(DBHelper.DATABASE_URL + 'restaurants')
.then(function (response) {
return response.json();
})
.then(function (data) {
DBHelper.saveRestaurantsIdb(data);
callback(null, data);
});
}
static saveRestaurantsIdb(restaurants) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
let store = db.transaction('restaurants', 'readwrite').objectStore('restaurants');
restaurants.forEach(function(restaurant) {
store.put(restaurant);
});
});
}
/**
* Fetch a restaurant by its ID.
*/
static fetchRestaurantById(id, callback) {
// fetch all restaurants with proper error handling.
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
if (!db) {
DBHelper.fetchRestaurantByIdFromServer(id, callback);
}
const index = db.transaction('restaurants').objectStore('restaurants');
return index.get(id).then(restaurant => {
if (restaurant) {
DBHelper.fetchReviewsByRestaurantId(restaurant, callback);
}
DBHelper.fetchRestaurantByIdFromServer(id, callback);
});
});
}
static fetchRestaurantByIdFromServer(id, callback) {
fetch(DBHelper.DATABASE_URL + `restaurants/${id}`)
.then(function (response) {
return response.json();
})
.then(function (data) {
DBHelper.fetchReviewsFromServer(data, callback);
});
}
/**
* Fetch restaurants by a cuisine type with proper error handling.
*/
static fetchRestaurantByCuisine(cuisine, callback) {
// Fetch all restaurants with proper error handling
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Filter restaurants to have only given cuisine type
const results = restaurants.filter(r => r.cuisine_type == cuisine);
callback(null, results);
}
});
}
/**
* Fetch restaurants by a neighborhood with proper error handling.
*/
static fetchRestaurantByNeighborhood(neighborhood, callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Filter restaurants to have only given neighborhood
const results = restaurants.filter(r => r.neighborhood == neighborhood);
callback(null, results);
}
});
}
/**
* Fetch restaurants by a cuisine and a neighborhood with proper error handling.
*/
static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
let results = restaurants;
if (cuisine != 'all') { // filter by cuisine
results = results.filter(r => r.cuisine_type == cuisine);
}
if (neighborhood != 'all') { // filter by neighborhood
results = results.filter(r => r.neighborhood == neighborhood);
}
callback(null, results);
}
});
}
/**
* Fetch all neighborhoods with proper error handling.
*/
static fetchNeighborhoods(callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Get all neighborhoods from all restaurants
const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);
// Remove duplicates from neighborhoods
const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);
callback(null, uniqueNeighborhoods);
}
});
}
/**
* Fetch all cuisines with proper error handling.
*/
static fetchCuisines(callback) {
// Fetch all restaurants
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
// Get all cuisines from all restaurants
const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);
// Remove duplicates from cuisines
const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);
callback(null, uniqueCuisines);
}
});
}
static fetchReviewsByRestaurantId (restaurant, callback) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
if (!db) {
DBHelper.fetchReviewsFromServer(restaurant, callback);
}
const index = db.transaction('reviews').objectStore('reviews');
index.getAll(restaurant.id).then(reviews => {
if ((!reviews) || (!reviews.length)) {
DBHelper.fetchReviewsFromServer(restaurant, callback);
}
restaurant.reviews = reviews;
DBHelper.fetchOfflineReviews(restaurant, callback);
//callback(null, restaurant);
});
});
}
static fetchOfflineReviews (restaurant, callback) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
if (!db) {
DBHelper.fetchReviewsFromServer(restaurant, callback);
}
const index = db.transaction('offline-reviews').objectStore('offline-reviews');
index.getAll(restaurant.id).then(reviews => {
if ((reviews) && (reviews.length)) {
reviews.forEach(review => {
restaurant.reviews.push(review);
});
}
callback(null, restaurant);
//DBHelper.fetchReviewsFromServer(restaurant, callback);
});
});
};
static fetchReviewsFromServer (restaurant, callback) {
fetch(this.DATABASE_URL + `reviews/?restaurant_id=${restaurant.id}`)
.then(function (response) {
return response.json();
})
.then(function (data) {
DBHelper.saveReviewsIdb(data);
restaurant.reviews = data;
DBHelper.fetchOfflineReviews(restaurant, callback);
});
}
static saveReview (review) {
return fetch(this.DATABASE_URL + 'reviews', {
method: 'POST',
body: JSON.stringify(review),
headers: new Headers({
'Content-Type': 'application/json'
})
});
}
static saveReviewOffline (review) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
let store = db.transaction('offline-reviews', 'readwrite').objectStore('offline-reviews');
store.put(review);
});
}
static uploadOfflineReviews () {
const dbPromise = DBHelper.OpenDbPromise();
dbPromise.then(function(db) {
const index = db.transaction('offline-reviews', 'readwrite').objectStore('offline-reviews');
index.getAll().then(reviews => {
if (reviews) {
reviews.forEach(function (review) {
review.offline = false;
DBHelper.saveReview(review).then(function (response) {
return response.json();
}).then(function (data) {
DBHelper.saveReviewsIdb(data);
});
});
index.clear();
let offlineReviews = document.querySelectorAll('.review-offline');
offlineReviews.forEach(offRev => {
offRev.className = '';
});
}
});
});
}
static saveReviewsIdb (reviews) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
let store = db.transaction('reviews', 'readwrite').objectStore('reviews');
if (Array.isArray(reviews)) {
reviews.forEach(function(review) {
store.put(review);
});
}
else {
store.put(reviews);
}
});
}
/**
* Restaurant page URL.
*/
static urlForRestaurant(restaurant) {
return (`./restaurant.html?id=${restaurant.id}`);
}
/**
* Restaurant image URL.
*/
static imageUrlForRestaurant(restaurant) {
return (`/img/296/${restaurant.photograph}_296.jpg`);
}
static imageSrcSetForRestaurantMain(restaurant) {
return (`/img/400/${restaurant.photograph}_400.jpg 444w, /img/625/${restaurant.photograph}_625.jpg 549w, /img/296/${restaurant.photograph}_296.jpg 550w`);
}
static imageSrcSetForRestaurantDetail(restaurant) {
return (`/img/296/${restaurant.photograph}_296.jpg 336w, /img/400/${restaurant.photograph}_400.jpg 439w, /img/625/${restaurant.photograph}_625.jpg 440w`);
}
/**
* Map marker for a restaurant.
*/
static mapMarkerForRestaurant(restaurant, map) {
const marker = new google.maps.Marker({
position: restaurant.latlng,
title: restaurant.name,
url: DBHelper.urlForRestaurant(restaurant),
map: map,
animation: google.maps.Animation.DROP}
);
return marker;
}
static updateFavourite (restaurantId, isFavourite) {
fetch(this.DATABASE_URL + `restaurants/${restaurantId}/?is_favorite=${isFavourite}`, {
method: 'PUT'
}).then(
DBHelper.updateFavouriteIdb(restaurantId, isFavourite)
);
}
static updateFavouriteIdb (restaurantId, isFavourite) {
const dbPromise = this.OpenDbPromise();
dbPromise.then(function(db) {
let store = db.transaction('restaurants', 'readwrite').objectStore('restaurants');
store.get(restaurantId).then(restaurant => {
restaurant.is_favorite = isFavourite;
store.put(restaurant);
});
});
}
} |
// The only reason we need a React depencency here is because the base class
// provides the this.setState method.
import { Component } from "react";
// We can inline a named export call.
export class Button extends Component {
// Prop types are defined using built-in language support using a TypeScript
// compatible syntax. Notice the subtle syntax difference between the colon
// and the equal sign.
props : {
width: number
}
// Default properties can be defined as a static property initializer.
// The value of each property is shallow copied onto the final props object.
static defaultProps = {
width: 100
}
// Initial state is defined using a property initializer. In this simple
// form it behaves identical to TypeScript. You may refer to this.props
// within this initializer to make initial state a function of props.
state = {
counter: Math.round(this.props.width / 10)
}
// Instead of relying on auto-binding magic inside React, we use a property
// initializer with an arrow function. This effectively creates a single
// bound method per instance - the same as auto-binding.
handleClick = (event) => {
event.preventDefault();
this.setState({ counter: this.state.counter + 1 });
}
// Props, state and context are passed into render as a convenience to avoid
// the need for aliasing or referring to `this`.
render(props, state, context) {
return (
<div>
This button has been clicked: {state.counter} times
<button onClick={this.handleClick} style={{ width: props.width }} />
</div>
);
}
}
|
import React from "react";
import EmployeeFrom from "./component/EmployeeFrom";
function AddEmployee() {
return (
<div className="container mt-4">
<h1>Add Employee</h1>
<EmployeeFrom mode="add" />
</div>
);
}
export default AddEmployee;
|
var widgetConfig = {
title: 'My Diamond Story',
pages: [
{
title: 'Light',
code: 'light',
enableStoryline: true
},
{
title: 'Report',
code: 'report'
}
]
};
|
import React, { useState, useEffect, useCallback } from 'react';
import classes from './dailyGraphs.module.css';
import axios from 'axios';
import configureDailyGraphsStore from '../DailyAndProfileData/dailyGraphs-store';
import { useStore } from '../../Store/store';
import { DAILY_GRAPHS } from '../../constants';
import { sharedUtil } from '../../util-functions';
import SectionWrap from '../../UI/Sections/SectionWrap/sectionWrap';
import SectionWrapper from '../../UI/Sections/SectionWrapper/sectionWrapper';
import SectionMain from '../../UI/Sections/SectionMain/sectionMain';
import SectionSide from '../../UI/Sections/SectionSide/sectionSide';
import SectionHeader from '../../UI/Sections/SectionHeader/sectionHeader';
import LineGraphDaily from './LineGraphDaily/lineGraphDaily';
import AttributeBtns from '../../UI/Buttons/AttributeBtns/attributeBtns';
import ErrorComp from '../../UI/error';
import AltTextBox from '../../UI/AltTextBox/altTextBox';
configureDailyGraphsStore();
const { dailyStatsSoFarUrl } = DAILY_GRAPHS;
const { prepArrayToShowInTextBox } = sharedUtil;
const DailyGraphs = () => {
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const dispatch = useStore()[1];
const graphs = useStore()[0].dailyGraphsStore.graphs;
const getDailyStats = useCallback(async () => {
try {
const response = await axios.get(dailyStatsSoFarUrl);
return response.data.features;
} catch (e) {
setIsLoading(false);
setIsError(true);
}
}, []);
useEffect(() => {
(async () => {
setIsLoading(true);
setIsError(false);
try {
const data = await getDailyStats();
dispatch('SET_ALL_DAILY_GRAPHS', data);
dispatch('SET_DAILY_STORE_DATE_AND_DATA', {
latestDate: false,
storeName: 'dailyGraphsStore',
});
setIsLoading(false);
} catch (e) {
setIsLoading(false);
setIsError(true);
}
})();
// eslint-disable-next-line
}, []);
const handleSelectData = (e, graphId) => {
const fieldName = e.target.name;
dispatch('SELECT_DAILY_GRAPHS_ATTRS', {
fieldName,
graphId,
storeName: 'dailyGraphsStore',
});
};
const handleTextBox = (data, dateFieldName) => {
if (!data || !dateFieldName) return;
const dateToSelect = data[dateFieldName];
dispatch('SET_DAILY_STORE_DATE_AND_DATA', {
latestDate: dateToSelect,
storeName: 'dailyGraphsStore',
});
};
return graphs && graphs.length
? graphs.map((graph, index) => (
<SectionWrapper key={index}>
<SectionWrap>
<SectionSide>
{isError ? (
<ErrorComp msg="Could not load data." />
) : (
<>
<SectionHeader
title={graph.sectionName}
subtitle=""
description={graph.description}
/>
<div className={classes.forBreakPointBetween900And300}>
{!isLoading ? (
<AltTextBox
arrayToShowInTextBox={prepArrayToShowInTextBox(graph)}
selectedDate={graph.selectedDate}
numAvailableAttrs={graph.avail.length}
/>
) : (
'Loading...'
)}
<AttributeBtns
availableAttributes={graph.avail}
graphIndex={graph.id}
handleSelectData={handleSelectData}
/>
</div>
</>
)}
</SectionSide>
<SectionMain>
{!isLoading && graph ? (
<LineGraphDaily
graphId={graph.id}
storeName="dailyGraphsStore"
handleTextBox={handleTextBox}
/>
) : (
'Loading...'
)}
</SectionMain>
</SectionWrap>
</SectionWrapper>
))
: null;
};
export default DailyGraphs;
|
/*
src 参照元を指定
dest 出力さきを指定
watch ファイル監視
series(直列処理)とparallel(並列処理)
*/
const { src, dest, watch, series, parallel } = require('gulp');
// プラグインを呼び出し
const sass = require('gulp-sass');
const postcss = require("gulp-postcss"); // PostCSS利用
const cssnext = require("postcss-preset-env");
const sourcemaps = require("gulp-sourcemaps");
//画像圧縮
const imagemin = require("gulp-imagemin");
const imageminMozjpeg = require("imagemin-mozjpeg");
const imageminPngquant = require("imagemin-pngquant");
const imageminSvgo = require("imagemin-svgo");
//JSminify
const rename = require("gulp-rename");
const uglify = require("gulp-uglify");
//ejs
const ejs = require('gulp-ejs'); //ejsコンパイル
//サーバー起動
const webserver = require("gulp-webserver");
const GulpClient = require('gulp');
//postcss-cssnext ブラウザ対応条件 prefix 自動付与
const browsers = [
'last 2 versions',
'> 5%',
'ie = 11',
'not ie <= 10',
'ios >= 8',
'and_chr >= 5',
'Android >= 5',
]
const path = {
scss: 'src/scss/**/*.scss',
image: './src/image/**/**/*.{jpg,png,gif,svg}',
js: 'src/js/*.js',
ejs:'src/ejs/**/',
}
// プラグインの処理をまとめる
const Sass = () => {
return src(path.scss) //コンパイル元
.pipe(sourcemaps.init())//gulp-sourcemapsを初期化
.pipe(sass({ outputStyle: 'expanded' }))
.pipe(postcss([cssnext(browsers)]))
.pipe(sourcemaps.write('/maps'))
.pipe(dest('dist/css')) //コンパイル先
}
//画像圧縮(デフォルトの設定)
const imgImagemin = () => {
return src(path.image)
.pipe(
imagemin(
[
imageminMozjpeg({
quality: 80
}),
imageminPngquant(),
imageminSvgo()
]
)
)
.pipe(dest('./dist/image/'))
}
const JSminify = () => {
return src(path.js,'!'+path.js)
.pipe(uglify())
.pipe(rename({
extname: '.min.js'
}))
.pipe(dest('./dist/'));
}
const server = () => {
return src('dist')
.pipe(webserver({
livereload: true,
open:true
}))
}
const htmlFunc = () => {
return src([path.ejs + '*.ejs', '!' + path.ejs + '_*.ejs'])
.pipe(ejs({}, {}))
.pipe(rename({ extname: '.html' }))
.pipe(dest('./dist/'))
}
const Watch = () => {
watch(path.scss,series(Sass))
watch(path.image, series(imgImagemin))
watch(path.js, series(JSminify))
watch(path.ejs+'*.ejs',series(htmlFunc))
}
// タスクをまとめて実行
exports.default = series(series(Sass,imgImagemin,server,JSminify,htmlFunc),parallel(Watch)); |
import { isEmpty } from 'underscore';
import { getAllCareersApi, getAllDepartmentsApi } from 'apis';
import {
LOAD_CAREERS_SUCCESS,
LOAD_CAREERS_FAILURE,
UPDATE_CAREERS_LOADER_SUCCESS,
UPDATE_CAREERS_LOADER_FAILURE,
LOAD_DEPARTMENTS_SUCCESS,
LOAD_DEPARTMENTS_FAILURE,
} from './actions';
import { transformArray } from '../utils';
export const loadCareersListingData = () => async (dispatch) => {
dispatch({ type: UPDATE_CAREERS_LOADER_SUCCESS, payload: { loading: true } });
await getAllCareersApi()
.then((resData) => {
if (isEmpty(resData || [])) return;
dispatch({
type: LOAD_CAREERS_SUCCESS,
payload: transformArray(resData, 'unique_title'),
});
})
.catch((err) => {
dispatch({
type: LOAD_CAREERS_FAILURE,
payload: err && err.message,
});
});
dispatch({ type: UPDATE_CAREERS_LOADER_SUCCESS, payload: { loading: false } });
};
export const loadCareersDepartmentsData = () => async (dispatch) => {
await getAllDepartmentsApi().then((resData) => {
if (isEmpty(resData || [])) return;
dispatch({
type: LOAD_DEPARTMENTS_SUCCESS,
payload: resData,
});
})
.catch((err) => {
dispatch({
type: LOAD_DEPARTMENTS_FAILURE,
payload: err && err.message,
});
});
};
|
const crypto = require('crypto');
exports.login = function(con, username, password, callback) {
const hash = crypto.createHash('sha256');
hash.update(con.escape(escapeHtml(password)));
var username = con.escape(escapeHtml(username));
var cryptedPass = con.escape(escapeHtml(hash.digest('hex')));
var sql = "SELECT * FROM users WHERE username = "+username+" AND password = "+ cryptedPass;
con.query(sql, function(err, results, fields) {
if (err) callback(err);
if (results[0] == undefined) {
callback(err, "Username or login wrong");
} else {
var data = results[0]
callback(err, data);
}
});
}
exports.register = function(con, username, password, email, callback) {
const hash = crypto.createHash('sha256');
hash.update(con.escape(escapeHtml(password)));
var username = con.escape(escapeHtml(username));
var email = con.escape(escapeHtml(email));
var cryptedPass = con.escape(escapeHtml(hash.digest('hex')));
var sql = "INSERT INTO users (username, password, email) VALUES ("+username+", "+cryptedPass+", "+ email+")";
con.query(sql, function (error, results, fields) {
if (error) {
if (error.code == 'ER_DUP_ENTRY') {
callback(error);
} else {
throw error;
}
} else {
callback(error, true);
}
});
}
exports.pay = function(con, money, sender, receiver, callback) {
var sql1 = "SELECT money FROM users WHERE id = " + con.escape(sender);
con.query(sql1, function(err, senderData, fields) {
if (err) throw err;
if (senderData[0] != undefined) {
if (senderData[0].money > money) {
var newSenderMoney = senderData[0].money - money;
setMoney(con, newSenderMoney, sender);
addMoney(con, money, receiver);
callback(undefined);
} else {
callback("Sender dosen't have enought money");
}
} else {
callback('User does not exist');
}
});
}
exports.getUserIdByUsername = function(con, username, callback) {
username = con.escape(escapeHtml(username));
sql = "SELECT id FROM users WHERE username = " + username;
con.query(sql, function(err, results, fields) {
if (err) throw err;
if (results[0] != undefined) {
callback(undefined, results[0].id)
} else {
callback('User does not exist');
}
});
}
function addMoney(con, money, pid) {
id = con.escape(pid);
sql = "SELECT money FROM users WHERE id = " + id;
con.query(sql, function(err, results, fields) {
if (err) throw err;
money = parseInt(results[0].money) + parseInt(money);
setMoney(con, money, id)
});
}
exports.addMoney = function(con, money, pid) {
id = con.escape(pid);
sql = "SELECT money FROM users WHERE id = " + id;
con.query(sql, function(err, results, fields) {
if (err) throw err;
money = results[0].money.toString() + money.toString();
setMoney(con, money, id)
});
};
function setMoney(con, money, id) {
sql = "UPDATE users SET money = " + con.escape(money) + " WHERE id = " + id;
con.query(sql, function (err, results, fields) {
if (err) throw err;
});
}
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
|
"use strict";
var Dispatcher = require('../dispatcher/appDispatcher');
var ActionTypes = require('../constants/actionTypes');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var _ = require('lodash');
var CHANGE_EVENT = 'change';
var _fintracimports = [];
var FintracStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
getAllImports: function() {
console.log('got here');
return _fintracimports;
},
getFintracImportById: function(id) {
console.log('getFintracImportById :: id=' + id);
//return _.find(_fintracimports, {importid: id});
return _fintracimports[0];
}
});
Dispatcher.register(function(action) {
switch(action.actionType) {
case ActionTypes.INITIALIZE:
_fintracimports = action.initialData.fintracimports;
FintracStore.emitChange();
break;
case ActionTypes.UPDATE_FINTRAC:
var existingFintrac = _.find(_fintracimports, {id: action.fintrac.header.tradeid});
var existingFintracIndex = _.indexOf(_fintracimports, existingFintrac);
_fintracimports.splice(existingFintracIndex, 1, action.fintrac);
FintracStore.emitChange();
break;
default:
// no op
}
});
module.exports = FintracStore; |
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
var androidVer = device.version;
var androidVerInt = parseInt(androidVer, 10);
if(androidVerInt >= 4) {
console.log("Android version: " + androidVer);
console.log("PouchDB IS available");
$("#shareClasses").hide();
} else {
console.log("PouchDB is NOT available");
$("#myClassesBtn").hide();
}
navigator.splashscreen.hide();
// Ask for a user's name, save it to a localStorage object, then display it on-screen in a <span> placeholder with a Class
$("#btnGetName").on("click", function() { getName() });
function getName() {
localStorage.userName = prompt("What's your name?");
if((localStorage.userName == 'null') || (localStorage.userName == undefined) || (localStorage.userName == "")) {
// Nothing
console.log("Invalid name");
} else {
$(".welcomeMessage").html(", " + localStorage.userName + "!");
}
}
// Runs when project loads; checks to see if a username has been input or not; if so, display on-screen
function loadName() {
if((localStorage.userName == 'null') || (localStorage.userName == undefined) || (localStorage.userName == "")) {
// Do nothing; no name has been input
console.log("No name, yet");
} else {
$(".welcomeMessage").html(", " + localStorage.userName + "!");
}
}
$('.btnGetURL').on('click', function() { goToURL($(this)) });
function goToURL(url) {
cordova.InAppBrowser.open(url.data("url"), "_blank", "location=yes")
}
var db = new PouchDB("sdceClasses");
db.info(function callback(error, result) {
db.changes({
since: result.update_seq,
live: true
}).on("change", showClasses);
}
);
$("#addClasses").click(function () { addClasses() });
function addClasses() {
var classCRN = document.getElementById("crnField").value;
var classTitle = document.getElementById("titleField").value;
var classInstructor = document.getElementById("instructorField").value;
var aClass = {
_id: classCRN,
title: classTitle,
inst: classInstructor
};
console.log(aClass);
db.put(aClass,
function callback(error, result) {
if(!error) {
document.getElementById("theResult").innerHTML = "Class added!";
clearFields();
} else {
navigator.notification.alert(
'Please enter all fields',
function(result) { console.log(result) },
'Error'
);
}
}
);
} // End of addClasses() function!
function clearFields() {
document.getElementById("classForm").reset();
}
$("#showClasses").click(function () { showClasses() });
function showClasses() {
db.allDocs({include_docs: true, ascending: true},
function callback(error, result) {
showTableOfClasses(result.rows);
}
);
// $("#shareClasses").show(); // To-do: Share classes via jsPDF
} // End of showClasses() function
function showTableOfClasses(data) {
var div = document.getElementById("theResult");
var str = "<table border='1' id='classTable'><tr><th>CRN</th><th>Class</th><th>Instructor</th></tr>";
for(var i = 0; i < data.length; i++) {
str += "<tr><td>" + data[i].doc._id +
"</td><td>" + data[i].doc.title +
"</td><td>" + data[i].doc.inst +
"</td></tr>";
};
str += "</table>";
str += "<hr>";
str += "<input type='text' placeholder='123' id='deleteCRN'><button id='deleteClasses'>Delete CRN</button>";
str += "<hr>";
str += "<br style='clear: both;'><div class='divTwoCol'><div class='leftCol'><button id='updateClass'>Update Class</button></div><div class='rightCol'><input type='text' placeholder='CRN' id='updateCRN'><input type='text' placeholder='Class Title' id='updateTitle'><input type='text' placeholder='Instructor' id='updateInst'></div></div>";
div.innerHTML = str;
} // End of showTableOfClasses() function
$("#theResult").on("click", "tr", function() { deleteClassesPrep($(this)) });
function deleteClassesPrep(thisObj) {
var $editCRN = thisObj.find("td:eq(0)").text();
var $editTitle = thisObj.find("td:eq(1)").text();
var $editInst = thisObj.find("td:eq(2)").text();
$("#updateCRN").val($editCRN);
$("#updateTitle").val($editTitle);
$("#updateInst").val($editInst);
}
$("body").on("click", "#deleteClasses", function () { deleteClasses() });
function deleteClasses() {
var theClass = document.getElementById("deleteCRN").value;
db.get(theClass, function callback(error, result) {
db.remove(result, function callback(error, result) {
if(result) {
document.getElementById("deleteCRN").value = "";
showClasses();
} else {
document.getElementById("deleteCRN").value = "";
alert("The class CRN" + theClass + " does not exist. Try again!");
console.log(error);
}
}
);
}
);
} // End of deleteClasses() function
$("body").on("click", "#updateClass", function () { updateClass() });
function updateClass() {
var theCRN = document.getElementById("updateCRN").value;
var theTitle = document.getElementById("updateTitle").value;
var theInst = document.getElementById("updateInst").value;
db.get(theCRN, function callback(error, result) {
if(error) {
document.getElementById("updateCRN").value = "";
document.getElementById("updateTitle").value = "";
document.getElementById("updateInst").value = "";
alert("The class CRN" + theCRN + " does not exist. Try again!");
console.log(error);
} else {
db.put({
_id: theCRN,
_rev: result._rev,
title: theTitle,
inst: theInst
}, function callback(error, result){
if(error){ console.log(error); }
});
}
}
);
} // End of updateClass() function
$("#btnEmailUs").on('click', function() { emailUs() });
function emailUs() {
window.plugins.socialsharing.shareViaEmail(
'A comment about your app:<br>', // can contain HTML tags, but support on Android is rather limited: http://stackoverflow.com/questions/15136480/how-to-send-html-content-with-image-through-android-default-email-client
'mySDCE App Feedback',
['victor@pmdinteractive.com'], // TO: must be null or an array
null, // CC: must be null or an array
null, // BCC: must be null or an array
null, // FILES: can be null, a string, or an array
function(result) { console.log('result: ' + result) }, // called when sharing worked, but also when the user cancelled sharing via email (I've found no way to detect the difference)
function(error) { console.log('error: ' + error) } // called when sh*t hits the fan
);
}
$("#btnShareApp").on('click', function() { shareApp() });
function shareApp() {
window.plugins.socialsharing.share(
'Check out the mySDCE App!', // Message
'mySDCE App Download', // Subject
['www/images/sdce-logo-main.png'], // Image
'https://play.google.com/store/apps/details?id=com.pmdinteractive.mysdce', // Link
function(result) { console.log('result: ' + result) }, // called when sharing worked, but also when the user cancelled sharing via email (I've found no way to detect the difference)
function(error) { console.log('error: ' + error) } // called when sh*t hits the fan
);
}
// To-do: Share classes via email
// Maybe jsPDF? http://www.tricedesigns.com/2014/01/08/generating-pdf-inside-of-phonegap-apps/
// MAYBE: http://stackoverflow.com/questions/16858954/how-to-properly-use-jspdf-library
/*
$("#btnShareClasses").on('click', function() { shareClasses() });
function shareClasses() {
var div = document.getElementById("theResult");
console.log(div);
window.plugins.socialsharing.share(
div,
'Check out my classes!',
null,
null,
function(result) { console.log('result: ' + result) },
function(error) { console.log('error: ' + error) }
);
}
*/
loadName();
}
} )();
/*
Name: Victor Campos <victor@pmdinteractive.com>
Project: mySDCE
Desc: Proof of concept app: Cordova/Taco/PhoneGap + jQuery Mobile + PouchDB + Social Sharing Plugin
Date: 2016-02-15
Version: 1.0.20160215
*/ |
/**
* Created by SG0222865 on 4/11/2017.
*/
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#1D7CA7'
},
titleText: {
justifyContent: 'center',
top: 0,
textAlign: 'center',
color: '#EDF2F4',
fontSize: 40,
fontWeight: 'bold',
paddingBottom: 250,
paddingTop: 20
},
wordDescription: {
fontSize: 20,
fontWeight: 'bold',
},
quizWord: {
color: 'white',
textAlign: 'center',
fontSize: 28,
},
editWord: {
textAlign: 'center',
color:'white',
fontSize: 28,
},
editWordText: {
justifyContent: 'center',
top: 0,
textAlign: 'center',
color: '#EDF2F4',
fontSize: 40,
fontWeight: 'bold',
paddingBottom: 20,
paddingTop: 20
},
mainMenuButtonView: {
borderRadius: 10,
padding: 10,
color: '#8D99AE',
shadowOffset: {
width: 0,
height: 3
},
shadowRadius: 10,
shadowOpacity: 0.25
},
addNewWordViewContainer: {
justifyContent: 'center',
top: 0,
textAlign: 'center',
paddingBottom: 250,
},
editWordInfo:{
padding:20,
paddingBottom:40,
color:'white',
textAlign: 'center',
},
textInput: {
margin:10,
color:'white',
height: 50,
padding: 10,
},
editIputViewContainer:{
paddingBottom:50,
},
editInputText : {
margin:10,
borderColor: '#1D7CA7',
padding: 10,
paddingBottom:30,
borderWidth: 1
},
dictionaryListContainer:{
// color:'white',
},
defaultHeading:{
color:'white',
textAlign: 'center',
},
rowContainer: {
flex: 1,
padding: 10,
margin:5,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderWidth: 1,
borderColor: "#2D8DB8"
},
textGroup: {
marginLeft: 12,
},
wordText: {
fontSize: 16,
fontWeight: 'bold',
color:'white'
},
descriptionText: {
color:'white',
fontSize: 14,
fontStyle: 'italic',
},
icon: {
height: 25,
width: 25,
margin: 6,
},
iconsGroup: {
flex: 1,
justifyContent: 'flex-end',
flexDirection: 'row',
},
}); |
const mongoose = require('mongoose');
const Recipe = require('./models/Recipe'); // Import of the model Recipe from './models/Recipe'
const data = require('./data.js'); // Import of the data from './data.js'
// Connection to the database "recipeApp"
mongoose.connect('mongodb://localhost/recipeApp', { useNewUrlParser: true })
.then(() => {
console.log('Connected to Mongo!');
}).catch(err => {
console.error('Error connecting to mongo', err);
});
const newRecipe = {
title: 'Shrimp Risotto',
level: 'Amateur Chef',
ingredients: ['rice', 'shrimp', 'olive oil', 'white wine', 'onion', 'basil'],
cuisine: 'italian',
dishType: 'Dish',
image: 'https://tmbidigitalassetsazure.blob.core.windows.net/secure/RMS/attachments/37/1200x1200/Hearty-Shrimp-Risotto_exps134312_THHC2238742B09_19_5bC_RMS.jpg',
duration: 30,
creator: 'Julia Ramos',
}
const oneRecipe = Recipe.create(newRecipe)
// .then(recipe => { console.log('The recipe is saved and its title is: ', recipe.title) })
// .catch(err => { console.log('An error happened:', err) });
const allRecipes = Recipe.insertMany(data)
// .then(recipes => {
// console.log('The recipes are saved and its title are:');
// recipes.forEach(recipe => console.log(recipe.title));
// })
// .catch(err => { console.log('An error happened:', err) });
const update = Recipe.updateOne({ title: 'Rigatoni alla Genovese' }, { duration: 100 })
// .then(recipe => { console.log('The recipe has been updated') })
// .catch(err => { console.log('An error happened:', err) });
const deleteCake = Recipe.deleteOne({ title: 'Carrot Cake' })
// .then(recipe => { console.log('The recipe has been deleted') })
// .catch(err => { console.log('An error happened:', err) });
Promise.all([oneRecipe, allRecipes, update, deleteCake])
.then(response => {
console.log('The recipe is saved and its title is: ', response[0].title)
console.log('The recipes are saved and its title are:');
response[1].forEach(recipe => console.log(recipe.title));
console.log(response[2]);
console.log(`The recipe has been updated`);
console.log(`The recipe has been deleted`);
mongoose.connection.close();
})
.catch(err => { console.log('An error happened:', err) })
|
import { Entry } from './entry'
export class Migration extends Entry {
name
async getByName(name) {
const sql = `SELECT * FROM ${this.tableName} WHERE ${this.tableName}.name = ?;`
return await this.query(sql, [name])
}
get tableName() {
return 'migration'
}
}
|
mui.init({
keyEventBind : {
backbutton : false,
menubutton : false
}
});
mui.plusReady(function(){
// var list = $('#hisList');
// for(var i=0;i<d.length;i++){
// var li = '<li class="mui-table-view-cell mui-collapse"><a class="mui-navigate-right" href="#">'+d[i].psid+'</a></li>';
// $li = $(li);
// $li.append(genDetial(d[i]));
// $li.appendTo(list);
// }
});
function genDetial(data){
var html =
'<ul class="mui-table-view mui-table-view-chevron">'
+' <li class="mui-table-view-cell">完成时间 '+data.psid +' </li>'
+' <li class="mui-table-view-cell">任务接受时间 '+data.psid +' </li>'
+' <li class="mui-table-view-cell">司机 '+data.driver +' </li>'
+' <li class="mui-table-view-cell">司机 </li>'
+'</ul>';
return $(html);
}
|
$('document').ready(function() {
//If cookies are not enabled, then nothis is loaded
if (!navigator.cookieEnabled)
$('#box').html('Sorry, your browser seems to have Cookies disabled.');
else {
//Load the Header component
$.ajax({
url: "components/header.php",
success: function(result) {
let parsed = JSON.parse(result);
if(parsed.err === 0) {
$('#header').html(parsed.msg);
} else {
showResult(parsed.err, parsed.msg, false);
}
}
});
//Load the navBar component and assign all actions to each of its component
$.ajax({
url: "components/navbar.php",
success: function(result) {
//Set the content of the navBar
let parsed = JSON.parse(result);
if(parsed.err === 0) {
$('#navBar').html(parsed.msg);
navBarRegisterClick();
} else {
showResult(parsed.err, parsed.msg, false);
}
}
});
//Load the airplane map component
loadAirplane();
$("#box").css('visibility', 'hidden');
}
});
|
const express = require('express');
const router = express.Router();
const db = require('../models');
router.get('/list', async (req, res) => { //그룹 리스트
if (!req.user) {
return res.redirect('/');
}
const pageing = 1;
const group_list_gaci = await db.Group_list_gaci.findAll({
order: [['createdAt', 'DESC']]
});
if (req.user === undefined) {
res.render('group_list', {
logged: false,
username: '',
pageing: pageing,
rows: group_list_gaci,
});
} else {
res.render('group_list', {
logged: true,
username: req.user.nickname,
pageing: pageing,
rows: group_list_gaci,
});
}
});
router.get('/list/page/:id', async (req, res) => { //페이징
if (!req.user) {
return res.redirect('/');
}
const list_gorup = await req.params.id;
const pageing_list = await db.Group_list_gaci.findAll({
include: [{ //가져올때 작성자도 함께
model: db.User,
attributes: ['id', 'nickname'],
}],
order: [['createdAt', 'DESC']] //생성한 날짜 내림차순
});
if (req.user === undefined) {
res.render('group_list', {
logged: false,
username: '',
pageing: list_gorup,
rows: pageing_list,
});
} else {
res.render('group_list', {
logged: true,
username: req.user.nickname,
pageing: list_gorup,
rows: pageing_list,
});
}
});
router.get('/list/:id', async (req, res, next) => {
try {
if (!req.user) {
return res.redirect('/');
}
let group_list_id = await req.params.id;
const project_create = await db.Group_list_gaci.findOne({
where: {
id: group_list_id,
}
});
const project_user = await db.Group_list_gaci.findAll({
where: {
id: project_create.id,
}
});
if (req.user === undefined) {
res.render('group_list_chatting', {
logged: false,
username: '',
project_create: '',
project_user: '',
});
} else {
res.render('group_list_chatting', {
logged: true,
username: req.user.nickname,
project_create: project_create,
project_user: project_user,
});
}
} catch (e) {
console.error(e);
next(e);
}
});
router.get('/lists/create_project', async (req, res) => {
if (!req.user) {
return res.redirect('/');
}
const user_list_all = await db.User.findAll({})
if (req.user === undefined) {
res.render('group_list_create', {
logged: false,
username: '',
user_list_all: ''
});
} else {
res.render('group_list_create', {
logged: true,
username: req.user.nickname,
user_list_all: user_list_all,
});
}
});
router.post('/list/popup_pwd/:id', async (req, res, next) => {
try {
const popup_pwd_input = await req.body.group_pwd;
const db_group_list = await db.Group_list_gaci.findAll({
where: {
id: req.params.id
}
});
for (let post of db_group_list) {
if (popup_pwd_input === post.project_password) {
res.status(200).redirect(`/dinnoplus/group/list/${post.id}`);
} else {
res.redirect('/dinnoplus/group/list')
}
}
} catch (e) {
console.error(e);
next(e);
}
})
router.post('/list/project_create', async (req, res, next) => {
try {
const date = new Date();
const year = date.getFullYear(); // 년도
const month = date.getMonth() + 1; // 월
const month_date = date.getDate(); // 날짜
const today_group = year + '/' + month + '/' + month_date;
await db.Group_list_gaci.create({
project_name: req.body.project_name,
project_manager_name: req.body.project_manager_name,
project_password: req.body.project_password,
group_date: today_group,
project_attendants_1: req.body.project_attendants_1,
project_attendants_2: req.body.project_attendants_2,
project_attendants_3: req.body.project_attendants_3,
project_attendants_4: req.body.project_attendants_4,
project_attendants_5: req.body.project_attendants_5,
project_attendants_6: req.body.project_attendants_6,
project_attendants_7: req.body.project_attendants_7,
project_attendants_8: req.body.project_attendants_8,
});
res.status(200).redirect('/dinnoplus/group/list')
} catch (e) {
console.error(e);
next(e);
}
})
module.exports = router; |
import _ from 'lodash';
const PLAYER_1_TOKEN = 'O';
const PLAYER_2_TOKEN = 'X';
class XOBoard {
constructor() {
this.reset()
}
eachCell(callback) {
_.forEach(this.board, (arr, row) => {
_.forEach(arr, (value, col) => {
callback(value, row, col);
});
});
}
reset() {
this.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
this.eachCell((value, row, col) => {
$('#cell-' + row + '-' + col).html('').attr('disabled', false);
});
}
disable() {
this.eachCell((value, row, col) => {
$('#cell-' + row + '-' + col).attr('disabled', true);
});
}
set(row, col, player) {
this.board[row][col] = player;
let token = (player == 1) ? PLAYER_1_TOKEN : PLAYER_2_TOKEN;
$('#cell-' + row + '-' + col).html(token).attr('disabled', true);
}
isWinner(row, col, player) {
var num,
rowWin = true,
columnWin = true,
forwardDiagonalWin = true,
backwardDiagonalWin = true,
onDiagonal = (row === col) || (col == -1 * row + 2);
// check for row and column wins
for (num = 0; num < 3; num++) {
if (this.board[row][num] != player) {
rowWin = false;
}
if (this.board[num][col] != player) {
columnWin = false;
}
}
// check for diagonal wins
if (onDiagonal) {
for (num = 0; num < 3; num++) {
if (this.board[num][num] != player) {
forwardDiagonalWin = false;
}
if (this.board[num][-1 * num + 2] != player) {
backwardDiagonalWin = false;
}
}
} else {
forwardDiagonalWin = false;
backwardDiagonalWin = false;
}
// determine if a win was found
return rowWin || columnWin || forwardDiagonalWin || backwardDiagonalWin;
}
isTie() {
return $(".btn:disabled").length === 9;
}
}
export default XOBoard;
|
viewport = [-2, -2, 2, 2];
var w = 3, h = 3, tiles;
function make_tile(x, y) {
var tile = please.access('tile.jta').instance();
tiles.push(tile);
tile.location = [x - 1, y - 1, 0];
graph.add(tile);
// Set selectable to true to make it respond to pointer click events.
tile.selectable = true;
// The on_click function is called when the object is clicked.
tile.on_click = function() { server.flip(x, y); };
}
function init() {
tiles = [];
for (var y = 0; y < h; ++y) {
for (var x = 0; x < w; ++x)
make_tile(x, y);
}
// No clicks are handled unless this is set.
graph.picking.enabled = true;
}
function update() {
for (var y = 0; y < h; ++y) {
for (var x = 0; x < w; ++x) {
var p = w * y + x;
if ((tiles[p].rotation_x == 0) ^ Public.board[p])
continue;
var r = Public.board[p] ? 180 : 0;
tiles[p].rotation_x = please.shift_driver(180 - r, r, 1000);
}
}
}
function end(code) {
// Allow animation to complete before showing alert.
setTimeout(function() { alert('Well done!'); }, 1500);
}
|
'use strict'
module.exports = function (str) {
var parts = str.split(':')
var ms = 0
var mod = 3600000
while (parts.length > 0) {
ms += mod * parseInt(parts.shift(), 10)
mod /= 60
}
return ms
}
|
/**
* jQuery mCarousel plugin
* @version 1.1.2
*
* @author Timur R Mingaliev <timur@mingaliev.com>
*/
/*global jQuery*/
/*jslint browser: true, devel: true, vars: true, todo: true*/
(function ($) {
"use strict";
// TODO: Access to methods from $(element).mCarousel("method", "methodName", [arguments]);
$.fn.mCarousel = function (options) {
var Plugin = function (options) {
var self = this,
defaults = {
backButton: '.back', // selector or jquery-object of back button
forwardButton: '.forward', // selector or jquery-object of forward button
elementsContainer: '.wrapper', // selector of jquery-object of elements container (ul)
elements: 'li', // selector of elements (will be search in elements container)
slideCount: 1, // how many element to slide
duration: 500, // speed
// Soon:
easing: '',
loop: true,
beforeSlide: undefined,
afterSlide: undefined,
vertical: false
},
left = 0,
elementsContainer = $(options.elementsContainer),
elements = $(options.elements, elementsContainer),
elementsOuterWidth;
options = $.extend(defaults, options);
this.methods = {
// Get full outer width of element(s)
getOuterWidth: function (element) {
var width;
if (element !== undefined && element.length === undefined) {
width = $(element).width()
+ parseInt(element.css('margin-left'), 10)
+ parseInt(element.css('margin-right'), 10)
+ parseInt(element.css('border-left'), 10)
+ parseInt(element.css('border-right'), 10);
} else {
width = 0;
$(element).each(function () {
width += ($(this).width()
+ parseInt($(this).css('margin-left'), 10)
+ parseInt($(this).css('margin-right'), 10)
+ ($(this).css('border-left') ? parseInt($(this).css('border-left'), 10) : 0)
+ ($(this).css('border-right') ? parseInt($(this).css('border-right'), 10) : 0));
});
}
return width;
},
// Move elements to the end
moveEnd: function (count) {
var elementsContainer = $(options.elementsContainer),
elements = $(options.elements, elementsContainer),
movements = elements.slice(0, count);
elementsContainer
.append(movements.clone(true))
.css({
'left': parseInt(elementsContainer.css('left'), 10) + self.methods.getOuterWidth(movements)
});
movements.remove();
},
// Move elements to the begin
moveBegin: function (count) {
var elementsContainer = $(options.elementsContainer),
elements = $(options.elements, elementsContainer),
movements = elements.slice(elements.length - count, elements.length);
elementsContainer
.prepend(movements.clone(true))
.css({
'left': parseInt(elementsContainer.css('left'), 10) - self.methods.getOuterWidth(movements)
});
movements.remove();
},
// Slide back method
slideBack: function () {
var elementsContainer = $(options.elementsContainer),
elements = $(options.elements, elementsContainer),
movements = elements.slice(elements.length - options.slideCount, elements.length);
if (typeof options.beforeSlide === "function") {
options.beforeSlide.call(this, elementsContainer, options);
}
elementsContainer.animate({
'left': left + self.methods.getOuterWidth(movements)
}, {
duration: options.duration,
queue: true,
complete: function () {
self.methods.moveBegin(options.slideCount);
if (typeof options.afterSlide === "function") {
options.afterSlide.call(this, elementsContainer, options);
}
}
});
return false;
},
// Slide forward method
slideForward: function () {
var elementsContainer = $(options.elementsContainer),
elements = $(options.elements, elementsContainer),
movements = elements.slice(0, options.slideCount);
if (typeof options.beforeSlide === "function") {
options.beforeSlide.call(this, elementsContainer, options);
}
elementsContainer.animate({
'left': left - self.methods.getOuterWidth(movements)
}, {
duration: options.duration,
queue: true,
complete: function () {
self.methods.moveEnd(options.slideCount);
if (typeof options.afterSlide === "function") {
options.afterSlide.call(this, elementsContainer, options);
}
}
});
return false;
},
refreshPosition: function () {
elementsOuterWidth = self.methods.getOuterWidth(elements);
left = elementsOuterWidth * -1;
elementsContainer.css({'left': left});
},
/**
* Options getter/setter
* If value is defined, set new option value and return it
* Anyway method returns value of option
*
* @param name {String} Option name
* @param value {*} New option value
* @returns {*}
*/
// TODO: Set options by object
option: function (name, value) {
if (value) {
options[name] = value;
}
if (name === undefined) {
return "";
}
return options[name];
}
};
elementsContainer.prepend(elements.clone(true)).append(elements.clone(true));
this.methods.refreshPosition();
// Binding events for each carousel
return this;
},
plugin = new Plugin(options);
return this.each(function () {
var $self = $(this);
$(this).data("mCarousel", plugin);
$(window).on("resize", function () {
$self.data("mCarousel").methods.refreshPosition();
});
$(options.backButton).on('mousedown', $.proxy(plugin.methods.slideBack, this));
$(options.forwardButton).on('mousedown', $.proxy(plugin.methods.slideForward, this));
});
};
}(jQuery)); |
import React from 'react';
import $ from 'jquery'
import ResultsTable from './ResultsTable.js'
import firebase from 'firebase';
import './Add.css';
// var movieDBURL = 'https://api.themoviedb.org/3/search/movie?api_key=aadd317edcf7fded06137442eb497be2&query=';
// var movieDBImageURL = 'https://image.tmdb.org/t/p/w500/';
//for Google Place search
var googleMap;
// Gets data from GraceNote and puts it into
// a Map where the keys are Theatres, and the values are Maps of movie titles and showtimes.
var AddPage = React.createClass({
getInitialState: function() {
return ({searchResults: null, pins: []});
},
componentDidMount: function() {
this.L = window.L;
this.map = this.L.map(this.root).setView([
39.5, -98.4
], 3);
var tileLayer = this.L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png')
tileLayer.addTo(this.map);
},
componentWillMount: function() {
// Get Current StartDate
var date = new Date();
var startDay = date.getDate();
var endDay = startDay + 15;
if (startDay < 10) {
startDay = '0' + startDay;
}
if (endDay < 10) {
endDay = '0' + endDay;
}
this.startDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + startDay;
this.endDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + endDay;
},
getListings: function(event) {
//Clear Previous Markers
$('.leaflet-marker-icon').remove();
// url to get movie listings
var showTimes = new Map(); // holds current search results
var pins = {};
var url = 'http://data.tmsapi.com/v1.1/movies/showings?startDate=' + $('#startDate').val() + '&zip=' + $('#zipcode').val() + '&radius='+ $('#radius').val() + '&api_key=ywfnykbqh7mgmuuwt5rjxr56';
// var url = 'http://data.tmsapi.com/v1.1/movies/showings?startDate=' + $('#startDate').val() + '&zip=' + $('#zipcode').val() + '&radius='+ $('#radius').val() + '&api_key=razswfzzubnqy49ry2km9ce9';
$.get(url).then(function(data) {
// Populates showTimes and Map
data.forEach((d) => d.showtimes.forEach(function(s) {
var theatre_name = s.theatre.name;
var title = d.title;
var time = s.dateTime;
if (showTimes.has(theatre_name)) {
var listings = showTimes.get(theatre_name);
if (listings.has(title)) {
var movie = listings.get(title);
movie.push(time);
} else {
// var url = movieDBURL + title;
// $.get(url).then(function(data){
//
// }.bind(this))
var showtimes = [];
showtimes.push(time);
listings.set(title, showtimes);
}
} else {
var listings = new Map();
var showtimes = [];
showtimes.push(time);
listings.set(title, showtimes);
showTimes.set(theatre_name, listings);
// Google Places API
var seattle = new window.google.maps.LatLng(47.609895,-122.330259);
googleMap = new window.google.maps.Map(document.getElementById('gmap'), {
api_key: 'AIzaSyAiuF-jDh08voLNMBlWXDZUmv14EorSsoM',
// api_key: 'AIzaSyAiuF-jDh08voLNMBlWXDZUmv14EorSsoM',
center: seattle,
zoom: 15
});
var request = {
location: seattle,
radius: '100000',
query: theatre_name
};
var callback = function (results, status) {
if (status == window.google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var loc = results[i].geometry.location;
var lat = loc.lat();
var lng = loc.lng();
var loc_str = lat + ' ' + lng;
pins[loc_str] = theatre_name;
var marker = this.L.marker([lat, lng]);
marker.on('click', this.pinClick);
marker.addTo(this.map);
var latlng = this.L.latLng(lat, lng);
this.map.setView(latlng, 10);
}
}
}.bind(this)
var service = new window.google.maps.places.PlacesService(googleMap);
service.textSearch(request, callback);
}
}.bind(this)))
}.bind(this), function(error) {
alert('Error in grabbing movie listings');
});
this.setState({searchResults: showTimes, pins: pins});
},
showModal:function(){
var modal = document.getElementById('myModal');
modal.style.display= "block";
var toClose = document.getElementById("modalClose");
toClose.onclick = function() {
modal.style.display = "none";
}
},
addEvent:function(){
// console.log(window.newEvent);
var newEvent = window.newEvent;
var user = firebase.auth().currentUser.email;
var friends = [];
var newListing = {
'ListingInfo':newEvent,
'friends':[user],
'chat':['Start a conversation!']
}
var database = firebase.database();
var listings = database.ref('Listings');
listings.push(newListing);
this.showModal();
},
pinClick: function(event) {
var lat = event.target._latlng.lat;
var lng = event.target._latlng.lng;
var loc = lat + ' ' + lng;
var key = this.state.pins[loc];
var listings = this.state.searchResults.get(key);
this.setState({active:[key,listings]});
window.theatre = key;
},
render: function() {
var data = this.state.searchResults;
var pins = this.state.pins;
var active = this.state.active;
var results = null;
if(active){
results = <ResultsTable addEvent={this.addEvent} window={window} data={this.state.active}/>
}
else {
results =
<div className='col s12 m6 l6'>
<h4>To add movies</h4>
<p>
1. Enter Zipcode<br/>
2. Select the Date<br/>
3. Set Distance<br/>
4. Search!
</p>
</div>
}
return (
<div className='row'>
<div className='input-field col s6'>
<input id='zipcode' type='text' name='zip'></input>
<label htmlFor='zipcode'>Enter a ZIP Code</label>
</div>
<div className='col s6'>
<label htmlFor='startDate'>Enter Movie Date</label>
<input placeholder='StartDate' id='startDate' type="date" className="datepicker" min={this.startDate} max={this.endDate}/>
</div>
<div className="range-field col s9 m10 l11">
<label htmlFor='radius'>Max Radius (Miles)</label>
<input id='radius' type="range" min="5" max="15" />
</div>
<div className='col s1 m1 l1'>
<button id='searchButton' onClick={this.getListings} className="btn-floating btn-large waves-effect waves-teal"><i className="material-icons">search</i></button>
</div>
<div className='col s12 m6 l6' ref={(node) => {this.root = node;}}>
</div>
<div id="myModal" className="modal">
<div className="modal-content">
<div className="modal-header">
<h5>Success!</h5>
<span id="modalClose">×</span>
</div>
<div className="modal-body">
<p>Thank you.<br/>The movie has been successfully added to your page. Enjoy!</p>
</div>
</div>
</div>
{results}
</div>
)
}
})
export default AddPage;
|
import GenericHtmlBlock from '../../Html/GenericHtmlBlock';
const Small = GenericHtmlBlock('small');
export default Small;
|
"use strict";
var user = require('./routes/user');
var match = require('./routes/match');
var steamServer = require('./routes/steam-proxy');
var matchmakingStats = require('./routes/matchmaking-stats');
var steamAuth = require('./routes/steam-auth');
module.exports = function(app) {
app.use('/api/current-user', user);
app.use('/api/matches', match);
app.use('/api/steam-proxy', steamServer);
app.use('/api/matchmaking-stats', matchmakingStats);
app.use('/api/auth/steam', steamAuth);
};
|
"use strict";
class BubbleSort {
constructor(array) {
this.array = array;
}
sort() {
const length = this.array.length - 1;
for (let i = 0; i < length; i++) {
for(let j = 0; j < length; j++) {
if (this.array[j] > this.array[j + 1]) {
let swap = this.array[j];
this.array[j] = this.array[j + 1];
this.array[j + 1] = swap;
}
}
}
return this.array;
}
}
module.exports.sort = function sortInternal(array) {
const bubbleSort = new BubbleSort(array);
return bubbleSort.sort();
}
|
/**我的優惠券 */
import React,{Component} from 'react'
import{
View,Text,TouchableOpacity,
StyleSheet,FlatList
} from 'react-native'
import NormalHead from '@/components/tabbar/NormalHead'
import SplitView from '@/components/SplitView'
import {width, scale, colors} from '@/utils/device'
import TopView from './TopView'
const rowW = width-scale(30)
const col1W = rowW * 0.3
const col2W = rowW * 0.25
const col3W = rowW * 0.3
const col4W = rowW * 0.15
export default class MyCoupon extends Component{
constructor(props){
super(props)
this.state = {
data: [
{time: '2019-08-06 11:12:26', name:'Mandy Lee', type: '產品清單'},
{time: '2019-08-06 11:12:26', name:'Alice Keys', type: '個人卡片'},
{time: '2019-08-06 11:12:26', name:'Leona Lewis', type: '個人卡片'},
{time: '2019-08-06 11:12:26', name:'Mary Cary', type: '產品清單'},
{time: '2019-08-06 11:12:26', name:'Tony Jack', type: '產品清單'},
]
}
}
_renderItem=({ item, index })=>{
return(
<View style={styles.listRow}>
<View style={{width: col1W}}>
<Text style={styles.timeText}>{item.time.split(' ')[0]}</Text>
<Text style={styles.timeText}>{item.time.split(' ')[1]}</Text>
</View>
<Text style={[styles.nameText,{width: col2W}]}>{item.name}</Text>
<Text style={[styles.nameText,styles.typeText,{width: col3W}]}>{item.type}</Text>
<TouchableOpacity style={[styles.rightWrap,styles.textRight,{width: col4W}]}>
<Text style={styles.blueText}>刪除</Text>
</TouchableOpacity>
</View>
)
}
_renderHeader(){
return(
<View style={styles.header}>
<Text style={[styles.hText,{width: col1W}]}>時間</Text>
<Text style={[styles.hText,{width: col2W}]}>好友</Text>
<Text style={[styles.hText,styles.typeText,{width: col3W}]}>分享類型</Text>
<Text style={[styles.hText,styles.textRight,{width: col4W}]}>操作</Text>
</View>
)
}
render(){
return(
<View style={styles.container}>
<NormalHead title="分享清單" />
<TopView/>
<FlatList
style={styles.content}
data={this.state.data}
renderItem={this._renderItem}
keyExtractor={(item, index) => index.toString()}
horizontal={false}
ListHeaderComponent={this._renderHeader}
showsVerticalScrollIndicator={false}
/>
</View>
)
}
}
const styles = StyleSheet.create({
hText: {
color: colors.gray2,
fontSize: scale(16),
//borderWidth: StyleSheet.hairlineWidth
},
header:{
flexDirection:'row',
borderBottomColor: colors.gray1,
borderBottomWidth: 1,
padding: scale(15),
paddingRight: scale(15),
//backgroundColor:'red'
},
blueText:{
color: colors.blue2,
fontSize: scale(14),
textAlign: 'right',
paddingRight: scale(5)
},
textRight:{
textAlign: 'right'
},
rightWrap:{
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
marginLeft:1,
// padding: scale(15),
// paddingTop: scale(16),
// paddingBottom: scale(16),
},
typeText: {
textAlign: 'center'
},
nameText: {
color: colors.gray2
},
timeText:{
color:'#807D78'
},
listRow: {
flexDirection: 'row',
alignItems: 'center',
marginLeft: scale(15),
paddingRight: scale(15),
paddingTop: scale(15),
paddingBottom: scale(15),
borderBottomColor: colors.gray1,
borderBottomWidth: 1,
},
content: {
flex: 1,
backgroundColor: 'white',
},
container: {
flex: 1,
backgroundColor: colors.bgColor
}
}) |
var bodyParser = require('body-parser');
const omise = require('omise')({
'publicKey': "pkey_test_57vo88hrxzcpzuhzzrg",
'secretKey': "skey_test_57vo88hs85r8478o4oh"
})
const express = require('express')
const app = express()
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(bodyParser.urlencoded({
'extended': 'true'
}));
app.use(bodyParser.json());
app.post('/pay', (req, res) => {
let returnData;
let pay = omise.charges.create({
'amount': req.body.amount,
'currency': 'thb',
'card': req.body.tokenID
}, (err, resp) => {
if (!err) {
console.log(resp);
returnData = {
pay: "success"
};
res.send(returnData);
} else {
console.log(err)
returnData = {
pay: "failed"
};
res.send(returnData);
}
});
})
app.post('/addbank', (req, res) => {
omise.recipients.create({
'name': req.body.name,
'email': req.body.email,
'type': 'individual',
'bank_account': {
'brand': req.body.brand,
'number': req.body.number,
'name': req.body.name
}
}, (err, resp) => {
if (!err) {
console.log(resp);
returnData = {
pay: "success"
};
res.send(returnData);
} else {
console.log(err)
returnData = {
pay: "failed"
};
res.send(returnData);
}
});
})
app.post('/listRe', (req, res) => {
omise.recipients.list((err, resp) => {
if (!err) {
res.send(resp);
} else {
res.send(err);
}
});
})
app.post('/transfer', (req, res) => {
omise.transfers.create({
'amount': req.body.amount,
'recipient': req.body.recipient
}, function (error, transfer) {
if (!error) {
console.log(transfer);
res.send({pay:"success"});
} else {
console.log(error)
res.send({pay:"error"});
}
});
})
app.post('/checktransfer',(req , res)=>{
console.log(req.body)
omise.transfers.retrieve(req.body.transfer, function(error, transfer) {
console.log(transfer)
res.send(transfer)
});
})
app.get('/', (req, res) => {
res.send("demo Omise");
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
}) |
function doNavigate(pstrWhere, pintTot) {
var strTmp;
var intPg;
strTmp = document.frmMain.txtCurr.value;
intPg = parseInt(strTmp);
if (isNaN(intPg)) {
intPg = 1;
}
if ((pstrWhere == "F" || pstrWhere == "P") && intPg == 1) {
alert("You are already viewing first page!");
return;
} else {
if ((pstrWhere == "N" || pstrWhere == "L") && intPg == pintTot) {
alert("You are already viewing last page!");
return;
}
}
if (pstrWhere == "F") {
intPg = 1;
} else {
if (pstrWhere == "P") {
intPg = intPg - 1;
} else {
if (pstrWhere == "N") {
intPg = intPg + 1;
} else {
if (pstrWhere == "L") {
intPg = pintTot;
}
}
}
}
if (intPg < 1) {
intPg = 1;
}
if (intPg > pintTot) {
intPg = pintTot;
}
//check applied specifically for job admin screen to make pagination work after being returned from Re-calculation screen
if(document.getElementById("editJobBookingStatus")!=null && document.getElementById("editJobDemDetCalcStatus")!=null)
{
document.frmMain.editJobBookingStatus.value="";
document.frmMain.editJobDemDetCalcStatus.value="";
document.frmMain.action="VesselJobAdministration";
}
document.frmMain.txtCurr.value = intPg;
document.frmMain.submit();
}
function applyFilter(){
document.getElementById('txtCurr').value='1';
document.frmMain.editJobBookingStatus.value="";
document.frmMain.editJobDemDetCalcStatus.value="";
document.frmMain.action="VesselJobAdministration";
document.frmMain.submit();
}
function onFilterChange(){
document.getElementById('txtCurr').value='1';
document.frmMain.submit();
}
function goBack(){
document.frmBack.userIdFilter.value = document.frmMain.userIdFilter.value;
document.frmBack.vesselVoyageFilter.value = document.frmMain.vesselVoyageFilter.value;
document.frmBack.loadPortFilter.value = document.frmMain.loadPortFilter.value;
document.frmBack.gcssStatusFilter.value = document.frmMain.gcssStatusFilter.value;
document.frmBack.dndStatusFilter.value = document.frmMain.dndStatusFilter.value;
document.frmBack.startDateFilter.value = document.frmMain.startDateFilter.value;
document.frmBack.action="VesselJobAdministration";
document.frmBack.submit();
}
function doSort(pstrFld, pstrOrd) {
document.frmMain.txtSortCol.value = pstrFld;
document.frmMain.txtSortAsc.value = pstrOrd;
document.frmMain.submit();
}
function viewLog(JobId, UserId, JobType) {
document.frmViewBookingLog.jobId.value = JobId;
document.frmViewBookingLog.userId.value = UserId;
document.frmViewBookingLog.jobType.value = JobType;
document.frmViewBookingLog.submit();
}
function viewGeoLog(batchId, extractTime) {
document.frmViewGeoMessageLog.batchId.value = batchId;
document.frmViewGeoMessageLog.extractTime.value = extractTime;
document.frmViewGeoMessageLog.submit();
}
function updateIgnoreBatch(batchId,ignoreBatch) {
if(ignoreBatch=="N"){
var r=confirm("Confirm batch sequence to be ignored for Batch Id:- "+batchId);
if (r==true)
{
document.frmUpdateBatchSeq.batchId.value = batchId;
document.frmUpdateBatchSeq.numBatchFilter.value=document.frmMain.numBatchFilter.value;
document.frmUpdateBatchSeq.numDaysFilter.value=document.frmMain.numDaysFilter.value;
document.frmUpdateBatchSeq.processStateListFilter.value=document.frmMain.processStateListFilter.value;
document.frmUpdateBatchSeq.submit();
}
} else{
alert('Batch Id:- '+batchId+' already ignored.');
}
}
// function for persisting the state of view geo monitor screen while returning from viewgeo log screen////
function returntoGeoMonitor()
{
document.formBack.numDaysFilter.value = document.frmMain.numDaysFilter.value;
document.formBack.processStateListFilter.value = document.frmMain.processStateListFilter.value;
document.formBack.numBatchFilter.value = document.frmMain.numBatchFilter.value;
document.formBack.textCurr.value = document.frmMain.textCurr.value;
document.formBack.submit();
}
function showDivResponseMessage() {
value = document.getElementById('messageButton').value;
if (value == "Hide Response Message") {
document.getElementById('responseMessageDiv').style.display = 'none';
document.getElementById('messageButton').value = "View Response Message";
} else {
document.getElementById('responseText').style.width=window.screen.availWidth*94/100 + "px";
document.getElementById('responseMessageDiv').style.display = 'block';
document.getElementById('messageButton').value = "Hide Response Message";
}
}
function doEdit(jobId,bookingStatus,demDetCalcStatus,dueBillReady,restartStatus){
document.frmMain.editJobId.value=jobId;
document.frmMain.editJobBookingStatus.value=bookingStatus;
document.frmMain.editJobDemDetCalcStatus.value=demDetCalcStatus;
document.frmMain.editJobDueBillReady.value=dueBillReady;
document.frmMain.editJobRestartStatus.value=restartStatus;
document.frmMain.submit();
}
function openBill(container,bookingNumber,currency,loadPortCode,vesselCode,voyageNumber,imageUrl)
{
//RQ-9617
//Author: TCS
//Dated: 11th May,2011
//In the above function param <imageUrl> is a new addition.
//Description: Changes with respect to Action Button on Query Builder Report Screen
//Different conditional check applied for different action images,
//and therefore redirected to further screen accordingly.
// Added change to remove scroll bar from billing screen - RQ10255 - TCS
var w = 1100, h = 550, t=0; // default sizes
var t=(window.screen.height-window.screen.availHeight);
if (window.screen) {
w = window.screen.availWidth* 98/ 100;
h = window.screen.availHeight * 97 / 100;
}
if(imageUrl!="images/Act3.gif" && imageUrl!="images/Act4.gif")
{
url="populateBillingDetail.action?CON="+container+"&BON="+bookingNumber+"&CUR="+currency+"&LOP="+loadPortCode+"&VOC="+vesselCode+"&VON="+voyageNumber;
BillWindow=window.open(url,"mywindow","toolbar=no,scrollbars=yes,directories=no,location=no ,status=no,menubar=no,width="+w+",height="+h);
BillWindow.moveTo(0,t/3);
}
}
function exportVesselDetail(){
document.exportVesselDetails.txtSortCol.value=document.frmMain.txtSortCol.value;
document.exportVesselDetails.txtSortAsc.value=document.frmMain.txtSortAsc.value;
document.exportVesselDetails.billingStatusFilter.value=document.frmMain.billingStatusFilter.value;
document.exportVesselDetails.contrsizeFilter.value=document.frmMain.contrsizeFilter.value;
document.exportVesselDetails.officeFilter.value=document.frmMain.officeFilter.value;
document.exportVesselDetails.teamFilter.value=document.frmMain.teamFilter.value;
document.exportVesselDetails.recmodeFilter.value=document.frmMain.recmodeFilter.value;
document.exportVesselDetails.tariffFilter.value=document.frmMain.tariffFilter.value;
document.exportVesselDetails.contractualcustomerFilter.value=document.frmMain.contractualcustomerFilter.value;
document.exportVesselDetails.dueTypeFilter.value=document.frmMain.dueTypeFilter.value;
document.exportVesselDetails.submit();
}
// function for persisting the state of vessel summary screen when returning from vessel deatil screen////
function returntovesselsummary(){
document.returntovesselsum.completionStatusFilter.value = document.frmMain.completionStatusFilter.value;
document.returntovesselsum.loadPortFilter.value = document.frmMain.loadPortFilter.value;
document.returntovesselsum.vslVygFltr.value = document.frmMain.vslVygFltr.value;
document.returntovesselsum.bookingOfficeFilter.value = document.frmMain.bookingOfficeFilter.value;
document.returntovesselsum.bookingTeamFilter.value = document.frmMain.bookingTeamFilter.value;
document.returntovesselsum.departureStatusFilter.value = document.frmMain.departureStatusFilter.value;
document.returntovesselsum.textCurr.value = document.frmMain.textCurr.value;
document.returntovesselsum.submit();
}
function callExportQueryBuilderDetails()
{
document.exportQueryBuilderDetailsForm.action="exportQueryBuilderDetails";
document.exportQueryBuilderDetailsForm.submit();
}
function returnToQueryBuilder()
{
document.exportQueryBuilderDetailsForm.action="populateQueryBuilder";
document.exportQueryBuilderDetailsForm.submit();
}
function disableControls(){
document.getElementById('revisedLoadDate').childNodes[1].disable='true';
document.getElementById('revisedLoadDate').childNodes[1].readOnly='readonly';
document.getElementById('revisedLoadDate').childNodes[1].disable='';
}
function disableKeys(){
var keyCode=(document.all)?event.keyCode:e.which;
if(keyCode==9){
window.event.returnValue=true; //for allowing TAB
}else{
window.event.returnValue=false;
}
}
function disableControlsAddNewDet(){
document.getElementById('detEndEventDate').childNodes[1].disable='true';
document.getElementById('detEndEventDate').childNodes[1].readOnly='readonly';
document.getElementById('detEndEventDate').childNodes[1].disable='';
}
function disableControlsAddNewDem(){
document.getElementById('endDemEventDate').childNodes[1].disable='true';
document.getElementById('endDemEventDate').childNodes[1].readOnly='readonly';
document.getElementById('endDemEventDate').childNodes[1].disable='';
}
function disableControlsRecalcDet(){
document.getElementById('revDetEndEvntDate').childNodes[1].disable='true';
document.getElementById('revDetEndEvntDate').childNodes[1].readOnly='readonly';
document.getElementById('revDetEndEvntDate').childNodes[1].disable='';
}
function disableControlsRecalcDem(){
document.getElementById('revDemEndEvntDate').childNodes[1].disable='true';
document.getElementById('revDemEndEvntDate').childNodes[1].readOnly='readonly';
document.getElementById('revDemEndEvntDate').childNodes[1].disable='';
}
function resetForm()
{
document.addNewVesselForm.action="AddJob!clear.action";
document.addNewVesselForm.submit();
}
function openBillDetails() {
//alert('fooo');
var w = 1100, h = 550, t=0; // default sizes
var t=(window.screen.height-window.screen.availHeight);
if (window.screen) {
w = window.screen.availWidth* 98/ 100;
h = window.screen.availHeight * 97 / 100;
}
window.open('/bill-details',"mywindow","toolbar=no,scrollbars=yes,directories=no,location=no ,status=no,menubar=no,width="+w+",height="+h);
}
|
const rootCas = require('ssl-root-cas').create()
const https = require('https')
const http = require('http')
// const openssl = require('openssl-nodejs')
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const openssl = require('./openssl')
const { Certificate } = require('@fidm/x509')
const { URL } = require('url')
const forge = require('node-forge')
const pki = forge.pki
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
const makeRootCaList = () => {
return rootCas.map((ca) => Certificate.fromPEM(ca))
}
exports.rootCaList = makeRootCaList()
exports.makeRequestOption = async (uri) => {
const url = new URL(uri)
return {
hostname: url.hostname,
port: 443,
path: url.pathname,
method: 'GET'
}
}
exports.getCertificateBuf = async (res) => {
const certificate = res.socket.getPeerCertificate(true)
if (certificate == null || certificate == undefined){
return null
}
if (!('raw' in certificate)){
return null
} else {
return certificate.raw.toString('base64')
}
}
exports.makeCertificate = async (raw) => {
try {
const derKey = forge.util.decode64(raw)
const asnObj = forge.asn1.fromDer(derKey)
const asn1Cert = pki.certificateFromAsn1(asnObj)
const pemCert = pki.certificateToPem(asn1Cert)
return pki.certificateFromPem(pemCert)
} catch (err) {
console.log("err in convert - ", err)
}
}
// Recursive Function To Reach The Root CA Certificate
//
exports.getRootCaCertFrom = async (cert) => {
try {
const subject = cert.subject.getField('CN')
var issuer = cert.issuer.getField('CN')
if (issuer == null){
issuer = cert.issuer.getField('OU')
}
if (subject == null || issuer == null){
return null
}
const subjectCname = subject.value.split(' ')[0]
const issuerCname= issuer.value.split(' ')[0]
if (subjectCname == issuerCname) {
console.log(`루트 CA 인증서 가져오기 성공`)
return cert
}
const accessVal = cert.getExtension(AUTHORITY_INFO_ACCESS).value
// console.log("ACCESS VALUE : ", accessVal)
var targetUrl = await refineUnicode(accessVal)
// console.log("Target URL : ", targetUrl)
const protocolStart = targetUrl.indexOf("http")
if (protocolStart != 0) {
targetUrl = targetUrl.substring(
protocolStart,
targetUrl.length
)
}
console.log("다운받을 targetUrl - ", targetUrl)
if (targetUrl.includes('ocsp')) {
return cert
}
const certName = await downloadCertificate(
targetUrl
)
const pemCert = await crtToPem(certName)
console.log(`상위 CA 인증서 가져오기 성공 - ${targetUrl}`)
// No Callback for deleting file
fs.unlink(certName, (err)=> {})
if (pemCert == null) {
return null
}
// console.log("변환 완료!", pemCert)
const pemCertBuf = fs.readFileSync(pemCert)
fs.unlink(pemCert, (err)=> {})
return await exports.getRootCaCertFrom(
pki.certificateFromPem(pemCertBuf)
)
} catch (e) {
console.log('e - ', e)
return null
}
}
exports.verify = async (cert) => {
try {
const cNamePrefix = cert.subject.getField('CN').value.split(' ')[0]
const rootCa = exports.rootCaList.find((rootCa) => {
const cName = rootCa.subject.attributes.find(attr => {
return attr.shortName == 'CN'
})
if (cName) {
// 일단 prefix로 일치 시킴
const prefix = cName.value.split(' ')[0]
return prefix == cNamePrefix
} else {
return false
}
})
if (rootCa == undefined) {
return false
}
return true
} catch (e) {
console.log("verify () : ", e)
return false
}
}
// ***** HELPER FUNCTIONS ***************
// Supporting Certificate Types
const PKCS7 = "pkcs7"
const X509 = "X.509"
// Field to get the superioir CA's certificate
const AUTHORITY_INFO_ACCESS = "authorityInfoAccess"
const allCertTypes = [
X509,
PKCS7
]
const TEMPORARY_CERT_PATH = ''
const downloadCertificate = (uri) => new Promise((res, rej) => {
var words = uri.split('/')
const certName = TEMPORARY_CERT_PATH + uuidv4() + words[words.length - 1]
const file = fs.createWriteStream(certName);
http.get(uri, (response) => {
response.pipe(file).on("close", () => {
// console.log("파일 다운로드 완료 - "+uri)
res(certName)
})
})
})
const getOpenSslConvertCommand = async (crtName, fileName, certType) => {
switch (certType) {
case PKCS7:
return [
`openssl`,
`pkcs7`,
`-print_certs`,
`-inform`,
`DER`,
`-in`,
crtName,
`-out`,
fileName
]
case X509:
return [
`x509`,
`-inform`,
`DER`,
`-outform`,
`PEM`,
`-in`,
crtName,
`-out`,
fileName
]
}
}
// 확장자에 맞춰 forge 인증서를 생성한다
// 1) crt, cer, der 일 경우, pem 으로 변환 후 cert 생성
// 2) pem 일 경우, 바로 pem으로 변환 후 cert 생성
// 3) .spc, p7a. p7b, p7c => pkcs#7 로 cert생성
// 4) .p8 => pkcs#8 로 cert 생성
// 5) .p12, .pfx => pkcs #12 로 cert 생성
const getCertTypeFrom = async (extension) => {
switch (extension) {
case "der":
case "cer":
case "crt":
return X509
case "pem":
return null
case "spc":
case "p7a":
case "p7b":
case "p7c":
return PKCS7
case "p8":
return
case "p12":
case "pfx":
return
}
}
const openSslExec = (command, fileName) => new Promise(
(res, rej) => {
openssl(command, (errCode, buf) => {
// console.log("errcode?!", errCode, typeof errCode)
if (errCode == 0) {
// console.log(command + " 성공!")
res(fileName)
} else {
// console.log(command + " 실패!")
res(null)
}
})
}
)
const getCommandAllTypes = async (crtName) => {
return allCertTypes.map(async (certType, idx, arr) => {
const fileName = `${TEMPORARY_CERT_PATH}${crtName}.pem`
const command = await getOpenSslConvertCommand(
crtName,
fileName,
certType
)
return await openSslExec(command, fileName)
})
}
const crtToPem = (crtName) => new Promise(async (res, rej) => {
try {
const extension = await getExtension(crtName)
if (extension == null) {
// 성공할 떄 까지 모두 시도
const commandAllTypes = await getCommandAllTypes(crtName)
const results = await Promise.all(commandAllTypes)
const fileName = results.find((res) => res != null)
if (fileName) {
res(fileName)
} else {
rej(null)
}
} else {
const certType = await getCertTypeFrom(extension)
const fileName = `${TEMPORARY_CERT_PATH}${crtName}.pem`
const command = await getOpenSslConvertCommand(
crtName,
fileName,
certType
)
openssl(command, (errCode, buf) => {
if (errCode == 0) {
res(fileName)
} else {
rej(command + "openssl failed!")
}
})
}
} catch (e) {
console.log("error in openssl", e)
}
})
const isSupported = (extension) => {
switch (extension) {
case "der":
case "cer":
case "crt":
case "pem":
case "spc":
case "p7a":
case "p7b":
case "p7c":
case "p8":
case "p12":
case "pfx":
return true
default:
return false
}
}
const getExtension = async (fileName) => {
const splitted = fileName.lastIndexOf('.')
if (splitted == -1) {
return null
} else {
const ext = fileName.substring(
splitted + 1,
fileName.length
)
if (isSupported(ext)) {
return ext
} else {
return null
}
}
}
// 재귀 함수
// 일단 이름명 + uuid 으로 다운로드를 받는다
// 확장자에 맞춰 forge 인증서를 생성한다
// 1) crt, cer, der 일 경우, pem 으로 변환 후 cert 생성
// 2) pem 일 경우, 바로 pem으로 변환 후 cert 생성
// 3) .spc, p7a. p7b, p7c => pkcs#7 로 cert생성
// 4) .p8 => pkcs#8 로 cert 생성
// 5) .p12, .pfx => pkcs #12 로 cert 생성
// cert에서 subject와 issuer가 동일하면 탈출
// 디지털 시그니쳐를 뽑아내서, 내가 갖고 있는 public key랑 비교한다
const extractUrls = async (val) => {
const tmp = forge.asn1.fromDer(val)
// extracting arrays into one array
const objects = tmp.value.reduce((prev, cur) => {
prev = [
...prev,
...cur.value
]
return prev
}, [])
return objects.reduce((prev, cur) => {
if (cur.value.includes('http')) {
prev.push(cur.value)
}
return prev
}, [])
}
const refineUnicode = async (str) => {
if (str.includes('\u0006')) {
const urls = await extractUrls(str)
const url = urls.find((url) => !url.includes('ocsp'))
if (url == undefined) {
const ocsp = urls.find((url) => url.includes('ocsp'))
if (ocsp) {
return ocsp
} else {
return str
}
}
return url
} else {
return str
}
}
|
import dotenv from 'dotenv';
dotenv.config();
const artists = [
{
fbId: '4eYUL2dx05ZI53zXzOR0igMm6n62',
name: 'Wiley Ross',
initials: 'WR',
email: 'wross@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe: "I'm a painter, muralist and musician.",
moreInfo: 'wileyross.com',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1622603616/profile/ghy68fjpkmu2vdvyumks.jpg`,
],
},
{
fbId: '6nKIvi6JWWWojPn2mkH1P9aW31o1',
name: 'Drib',
initials: 'D',
email: 'drib@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe: 'Lorem ipsum dolor sit amet.',
moreInfo: 'instagram.com/this_bird_',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1622603616/profile/kickmspwqnqg4pslirkq.jpg`,
],
},
{
fbId: 'HnMUEwZJU0gtJznZ3miTddayOhq2',
name: 'David "MEGGS" Hooke',
initials: 'DH',
email: 'meggs@example.com',
displayEmail: true,
city: 'Melbourne',
state: '',
country: 'Australia',
tags: [],
aboutMe:
'David "MEGGS" Hooke is a mural, street and fine artist recognized for his large scale murals and detailed paintings that combine elements of nature, industry and abstraction to create imagery that evokes a sense of flowing movement and change. (artist website)',
moreInfo: 'davidmeggshooke.com',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1631911609/profile/rdca5neallfa5nddhd6n.jpg`,
],
},
{
fbId: 'bN5cRPjDSnSTKxwdlcn8TOha6VX2',
name: 'J Cappolino',
initials: 'JC',
email: 'jcapp@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe: 'Lorem ipsum domor sit amet.',
moreInfo: '',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1631911622/profile/slcdhhm6nhbpxdesgleg.jpg`,
],
},
{
fbId: 'bjRTyitlbya8TCoy6TWQckSdVLA2',
name: 'Jade Fusco',
initials: 'JF',
email: 'jfusc@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe:
'My name is Jade, and I create from the Muses of DMZL ("damsel", in delight, maybe disguise...but never in distress!) I create installation art, wearable art, talking art, costumes, songs, etc! (etsy.com/people/jadefusco1)',
moreInfo: 'instagram.com/DMZL_in_delight',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1631911287/profile/obmtqhb8sub813pbx6he.jpg`,
],
},
{
fbId: 'E5nG1mbSNeWVnEKxHqXj23Gt8xg1',
name: 'Nicholas Conrad Miller',
initials: 'NM',
email: 'nmill@example.com',
displayEmail: true,
city: 'Buffalo',
state: 'NY',
country: 'USA',
tags: [],
aboutMe: 'Lorem ipsum dolor sit amet. Photo credit: buffalonews.com',
moreInfo: 'instagram.com/teamrazorwire',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1622603617/profile/jou309gfut5vv9zhspl0.jpg`,
],
},
{
fbId: 'nPOC2SRFWhaJTSv2BlsN80sDcbE2',
name: 'Josef Kristofoletti',
initials: 'JK',
email: 'jkris@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe:
'Josef Kristofoletti is an internationally working mural artist. At the intersection of painting, architecture, and public space, his large scale site specific work creates a human related background that is worthy of daily life. (artist website)',
moreInfo: 'kristofoletti.com',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1622603616/profile/kpv9eezpv1a4xozqy9w9.jpg`,
],
},
{
fbId: 'tNNwY3ippxQWKbpIoVS4nWufX2J2',
name: 'Daniel Johnston',
initials: 'DJ',
email: 'djohn@example.com',
displayEmail: false,
city: 'Houston',
state: 'TX',
country: 'USA',
tags: [],
aboutMe:
'Daniel Johnston was an artist and musician who passed away in 2019. The city of Austin recognizes January 22, Johnston\'s birthday, as "Hi, How Are You Day" to encourage discussion of mental health issues.',
moreInfo: '',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1631911604/profile/u5bw8czmo8oxsodqlbzo.jpg`,
],
},
{
fbId: '9H9fx9RYAtOYleTZ7F4PzzReFuO2',
name: 'Larry Fitzgerald',
initials: 'LF',
email: 'lfitz@example.com',
displayEmail: true,
city: 'Paradise Valley',
state: 'AZ',
country: 'USA',
tags: [],
aboutMe: '#11',
moreInfo: '',
profilePhotoUrl: [],
},
{
fbId: 'i7JKWYHwDCb46axm3GOOWOaqcVs2',
name: 'Asher Feehan',
initials: 'AF',
email: 'afeehan@example.com',
displayEmail: true,
city: 'Austin',
state: 'TX',
country: 'USA',
tags: [],
aboutMe:
'Hi! My name is Asher, I’m a creative geek from Australia. I enjoy creating eye candy art for commercial and residential structures.',
moreInfo: 'asherfeehan.com',
profilePhotoUrl: [
`${process.env.CLOUD_UPLOAD_URL}/v1631822180/profile/ovexv2t2gzer1yekklwf.png`,
],
},
];
export default artists;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchRestaurant } from '../../actions/firebase_actions';
import { Link } from 'react-router';
class RestaurantShow extends Component {
componentWillMount() {
this.props.fetchRestaurant(this.props.params.id);
}
render() {
if (!this.props.restaurant) {
return (
<div>
Loading....
</div>
);
}else{
return (
<div>
<h2>Restaurant {this.props.restaurant.title}</h2>
<div className="row">
<div className="col-sm-3">
<div className="list-group">
<Link className="list-group-item list-group-item-action" to={"/restaurant/"+ this.props.params.id + "/products"}>Products</Link>
<Link className="list-group-item list-group-item-action" to={"/restaurant/"+ this.props.params.id + "/sections"}>Sections</Link>
</div>
</div>
<div className="col-sm-9">
{this.props.children}
</div>
</div>
</div>
);
}
}
}
function mapStateToProps(state){
return { restaurant: state.restaurants.restaurant };
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchRestaurant }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(RestaurantShow);
|
exports.up = function(knex) {
return knex.schema
.createTable('users', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.string('email').notNullable();
table.string('bio').notNullable();
table.string('postal').notNullable();
table.string('password').notNullable();
})
.createTable('skills', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
})
.createTable('interest', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
})
.createTable('users_interest', (table) => {
table.increments('id').primary()
table
.integer('user_id').unsigned().notNullable()
.references('id')
.inTable('users')
table
.integer('interest_id').unsigned().notNullable()
.references('id')
.inTable('interest')
})
.createTable('users_skills', (table) => {
table.increments('id').primary()
table
.integer('user_id').unsigned().notNullable()
.references('id')
.inTable('users')
table
.integer('skills_id').unsigned().notNullable()
.references('id')
.inTable('skills')
});
};
exports.down = function(knex) {
return knex.schema
.dropTableIfExists('users_skills')
.dropTableIfExists('users_interest')
.dropTableIfExists('users')
.dropTableIfExists('skills')
.dropTableIfExists('interest')
.catch(err => {
console.error(err)
throw err
});
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseController = void 0;
const service_1 = require("../../../app/persistance/common/service");
const BaseService_1 = require("../../../app/services/interfaces/base/BaseService");
class BaseController {
constructor(schemaModel) {
this.entityService = new BaseService_1.BaseService(schemaModel);
}
create(req, res) {
let user_params = req.body;
this.entityService.create(user_params, (err, user) => {
if (err) {
service_1.mongoError(err, res);
}
else {
service_1.successResponse('create user successfully', user, res);
}
});
}
update(req, res) {
const user_params = req.body;
this.entityService.update(req.params.id, user_params, (err, result) => {
if (err) {
service_1.mongoError(err, res);
}
else {
service_1.successResponse('update user successfully', null, res);
}
});
}
delete(req, res) {
this.entityService.delete(req.params.id, (err, result) => {
if (err) {
service_1.mongoError(err, res);
}
else {
service_1.successResponse('delete user successfully', null, res);
}
});
}
getAll(req, res) {
try {
this.entityService.getAll((error, result) => {
if (error)
res.send({ "error": "error" });
else
res.send(result);
});
}
catch (e) {
console.log(e);
res.send({ "error": "error in your request" });
}
}
findById(req, res) {
try {
var _id = req.params.id;
this.entityService.findById(_id, (error, result) => {
if (error)
res.send({ "error": "error" });
else
res.send(result);
});
}
catch (e) {
console.log(e);
res.send({ "error": "error in your request" });
}
}
}
exports.BaseController = BaseController;
|
function redirectOnClick( element ){
if ( $(element).attr("data-url") != undefined ){
var form = $('<form>',
{ 'action':$(element).attr("data-url"),
'method':'post'}
);
form.appendTo('body');
form.submit().remove();
}
} |
function i18n(token) {
return token;
}
Handlebars.registerHelper('i18n', i18n);
Handlebars.registerHelper('link', i18n);
Handlebars.registerHelper('url', i18n);
|
// @flow strict
import * as React from 'react';
import { Translation } from '@kiwicom/mobile-localization';
import { Text, StyleSheet, Price } from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import { View } from 'react-native';
import {
withHotelDetailScreenContext,
type HotelDetailScreenState,
} from '../HotelDetailScreenContext';
type Props = {|
+getPersonCount: () => number,
+numberOfRooms: number,
+price: $PropertyType<HotelDetailScreenState, 'price'>,
|};
function RoomSummary(props: Props) {
if (props.numberOfRooms === 0 || props.price == null) {
return null;
}
return (
<View style={styles.container}>
<View style={styles.content}>
<Text style={styles.summary}>
<Translation id="single_hotel.room_summary.summary" />
</Text>
<View style={styles.row}>
<Translation
id="single_hotel.book_now.description"
values={{
personCount: props.getPersonCount(),
numberOfRooms: props.numberOfRooms,
}}
/>
<Price price={props.price} style={styles.currency} />
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
borderWidth: StyleSheet.hairlineWidth,
borderColor: defaultTokens.paletteInkLighter,
borderBottomWidth: 0,
borderTopStartRadius: 6,
borderTopEndRadius: 6,
},
content: {
paddingHorizontal: 17,
paddingTop: 8,
paddingBottom: 12,
},
summary: {
color: defaultTokens.colorTextSecondary,
fontSize: 12,
marginEnd: 4,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
},
currency: {
fontWeight: '800',
},
});
const select = ({
numberOfRooms,
getPersonCount,
price,
}: HotelDetailScreenState) => ({
numberOfRooms,
getPersonCount,
price,
});
export default withHotelDetailScreenContext(select)(RoomSummary);
|
import Ember from 'ember';
export default Ember.Component.extend({
//elementId: 'regions_div',
didInsertElement: function(){
"use strict";
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(function () {
//var data = google.visualization.arrayToDataTable([
// ["NL"],
// ["BE"]
//]);
//var options = {};
//var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
//chart.draw(data, options);
});
}
});
|
$(document).on('ready', function(){
$('.translate').on('submit', function(e){
e.preventDefault();
var findWord = {
start: $('[name="startLanguage"]').val(),
end: $('[name="endLanguage"]').val(),
word: $('[name="word"]').val()
};
console.log(findWord);
//dataFromServer represents the content of the page requested
$.get('/translate', findWord, function(dataFromServer){
console.log('data: ' + dataFromServer);
$('h2').append(dataFromServer);
});
$('.translate')[0].reset();
});
$('.refresh').on('click', function(){
location.reload();
});
}); |
import en from './en.json';
import cn from './cn.json';
export const dictionaryList = { en, cn };
export const languageOptions = {
en: 'English',
cn: '中文',
};
|
import {arr, num} from 'types';
export default function inc(increment = 1) {
return function innerInc(n) {
return num(n) + num(increment);
};
};
|
import Vue from 'vue'
import Vuex from 'vuex'
import WidgetModule from '@/store/modules/widget.module'
Vue.use(Vuex)
Vue.config.devtools = true
export default new Vuex.Store({
modules: {
WidgetModule,
}
});
|
/**********************************************************************************************
* Copyright (C) 2013 - 2015
* United Services Automobile Association
* All Rights Reserved
*
* File: HealthIns_ToolRebrand.js
**********************************************************************************************
* Rls Date Chg Date Name Description
* ========== ========== ============== ==================
* 00/00/2015 04/13/2016 R.Luevano Initial creation
**********************************************************************************************/
/**
* @file this allows table cells be highlighted
* @requires no requirements
*/
var currentPanel ="";
var nextPanel ="";
var prevPanel ="";
var prescriptions;
var insurance;
var under30;
var medical;
var household;
var income;
var purchasing;
function next(){
document.getElementById("panel2").style.left="800px";
document.getElementById("panel3").style.left="800px";
document.getElementById("panel4").style.left="800px";
document.getElementById("panel5").style.left="800px";
if(document.querySelectorAll('.show').length == 2){
var currentPanelId = document.querySelectorAll('.show')[1].id;
}
else{
var currentPanelId = document.querySelectorAll('.show')[0].id;
}
console.log("The current Panel ID is " + currentPanelId);
var panelelement=document.getElementById(currentPanelId).nextSibling;
if(panelelement.nodeType=='3'){
var nextPanelId = document.getElementById(currentPanelId).nextElementSibling.id;
}
else{
var nextPanelId = document.getElementById(currentPanelId).nextSibling.id;
}
currentPanel = document.getElementById(currentPanelId);
nextPanel = document.getElementById(nextPanelId);
console.log("Next panel is:"+ nextPanelId);
var currentPanelRadioButtons = document.getElementsByName(currentPanelId + "_radio");
if (currentPanelRadioButtons.length != 0 ){
for (var i=0; i<currentPanelRadioButtons.length; i++){
if(currentPanelRadioButtons[i].checked){
if(currentPanelId =='panel1'){
prescriptions = currentPanelRadioButtons[i].value;
}
else if(currentPanelId == 'panel2'){
insurance = currentPanelRadioButtons[i].value;
}
else if(currentPanelId == 'panel3'){
under30 = currentPanelRadioButtons[i].value;
}
else if(currentPanelId == 'panel4'){
medical = currentPanelRadioButtons[i].value;
}
document.getElementById("errorMessage").style.display = "none";
currentPanel.className = "hidden";
nextPanel.className = "show";
document.getElementById(nextPanelId).focus();
document.getElementById("previouseButton").style.display = "inline-block";
if(nextPanelId == 'panel5'){
document.getElementById("nextButton").style.display = "none";
document.getElementById("previouseButton").style.display = "none";
document.getElementById("startOverButton").style.display = "inline-block";
document.getElementById("goToPlansButton").style.display = "inline-block";
document.getElementById("updateProfileTextH").style.display = "inline-block";
result (prescriptions, insurance, under30, medical);
}
console.log("Next panel ID is " + nextPanelId);
return;
}
}
document.getElementById("errorMessage").style.display = "block";
document.getElementById("panel2").style.left="0px";
document.getElementById("panel3").style.left="0px";
document.getElementById("panel4").style.left="0px";
document.getElementById("panel5").style.left="0px";
}
else{
currentPanel.className = "hidden";
nextPanel.className = "show";
document.getElementById("previouseButton").style.display = "none";
document.getElementById("errorMessage").style.display = "none";
return;
}
}
function previous(){
document.getElementById("panel2").style.left="-500px";
document.getElementById("panel3").style.left="-500px";
document.getElementById("panel4").style.left="-500px";
document.getElementById("panel5").style.left="-500px";
var currentPanelId = document.querySelectorAll('.show')[0].id;
var panelelement=document.getElementById(currentPanelId).previousSibling;
if(panelelement.nodeType=='3'){
/*var prevPanelId = document.getElementById(currentPanelId).previousSibling.previousSibling.id;*/
var prevPanelId = document.getElementById(currentPanelId).previousElementSibling.id;
}else{
var prevPanelId = document.getElementById(currentPanelId).previousSibling.id;
}
currentPanel = document.getElementById(currentPanelId);
prevPanel = document.getElementById(prevPanelId);
currentPanel.className = "hidden";
prevPanel.className = "show";
/*actb('m');*/
if(prevPanelId == 'panel1'){
document.getElementById("previouseButton").style.display = "none";
}
}
function clearRadioButtons(radioButtons){
radioButtons1 = document.querySelectorAll(radioButtons);
//alert(radioButtons1.length);
for (var i=0; i<radioButtons1.length; i++){
radioButtons1[i].checked = false;
}
}
function startOver(){
var currentPanelId = document.querySelectorAll('.show')[0].id;
currentPanel = document.getElementById(currentPanelId);
nextPanel = document.getElementById("panel1");
currentPanel.className = "hidden";
nextPanel.className = "show";
//document.getElementById("button_panel").className="prepend-23";
document.getElementById("nextButton").style.display = "inline-block";
document.getElementById("startOverButton").style.display = "none";
document.getElementById("goToPlansButton").style.display = "none";
document.getElementById("updateProfileTextH").style.display = "none";
clearRadioButtons(".panel_radio");
/* Set all panels left attribute to 650px */
document.getElementById("optionA").style.display = 'none';
document.getElementById("optionA-1").style.display = 'none';
document.getElementById("optionB").style.display = 'none';
document.getElementById("optionC").style.display = 'none';
document.getElementById("optionD").style.display = 'none';
document.getElementById("optionE").style.display = 'none';
document.getElementById("optionF").style.display = 'none';
document.getElementById("optionG").style.display = 'none';
document.getElementById("panel1").focus();
}
function result(prescriptions, insurance, under30, medical){
switch (prescriptions){
/*Question 1: Do you or any of your family members expect to have a lot of doctors visits or need regular prescriptions? - YES */
case 'yes':
switch (insurance){
/* Question 2: How much out-of-pocket expenses are you willing to pay before your health insurance starts to kick-in? - YES */
case 'a':
switch (under30){
case 'yes':
switch (medical){
case 'yes':
document.getElementById("optionA").style.display = 'block';
break;
case 'no':
document.getElementById("optionA-1").style.display = 'block';
break;
}
break;
case 'no':
document.getElementById("optionA-1").style.display = 'block';
break;
}
break;
case 'b':
document.getElementById("optionB").style.display = 'block';
break;
case 'c':
document.getElementById("optionB").style.display = 'block';
break;
case 'd':
document.getElementById("optionB").style.display = 'block';
break;
}
break;
/*Question 1: Do you or any of your family members expect to have a lot of doctors visits or need regular prescriptions? - NO */
case 'no':
switch (insurance){
/* Question 2: How much out-of-pocket expenses are you willing to pay before your health insurance starts to kick-in? - */
case 'a':
switch (under30){
case 'yes':
switch (medical){
case 'yes':
document.getElementById("optionE").style.display = 'block';
break;
case 'no':
document.getElementById("optionD").style.display = 'block';
break;
}
break;
case 'no':
document.getElementById("optionC").style.display = 'block';
break;
}
break;
case 'b':
switch (under30){
case 'yes':
document.getElementById("optionG").style.display = 'block';
break;
case 'no':
switch (medical){
case 'yes':
document.getElementById("optionE").style.display = 'block';
break;
case 'no':
document.getElementById("optionF").style.display = 'block';
break;
}
break;
}
break;
case 'c':
switch (under30){
case 'yes':
document.getElementById("optionG").style.display = 'block';
break;
case 'no':
switch (medical){
case 'yes':
document.getElementById("optionE").style.display = 'block';
break;
case 'no':
document.getElementById("optionF").style.display = 'block';
break;
}
break;
}
break;
case 'd':
switch (under30){
case 'yes':
document.getElementById("optionG").style.display = 'block';
break;
case 'no':
switch (medical){
case 'yes':
document.getElementById("optionE").style.display = 'block';
break;
case 'no':
document.getElementById("optionF").style.display = 'block';
break;
}
break;
}
break;
}
}
}
|
import * as glext from "./../../GLExt/GLExt.js"
import * as sys from "./../../System/sys.js"
import * as vMath from "./../../glMatrix/gl-matrix.js";
/*
command pattern
every (user) interaction needs to be recorded into "command" object
"command" object holds info about:
- which photo document (by document id)
- what object type (CBrush, CLayer, ...)
- what command (which method in object to call, or even if to create/delete object with new/delete)
- what command parameters (i.e. mouse status, what setting value to change to...)
- previous parameters (if applicible) (i.e. for setting change, record what previous value was set)
*/
//----------------------------------------------------------------------
export class CParam{
constructor(){
this.type = null;
this.value = null;
this.count = 0;
}
set(param){
if(param.length == undefined || typeof(param) == "string" || typeof(param) == "function"){
this.type = CParam.DecideParamType(param);
this.value = param;
this.count = 1;
}
else{
let paramType = CParam.DecideParamType(param[0]);
let bIsArray = false;
if(paramType == CParam.Type_number){
if(param.length == 2)
this.type = CParam.Type_vec2;
if(param.length == 3)
this.type = CParam.Type_vec3;
if(param.length == 4)
this.type = CParam.Type_vec4;
if(param.length >= 5){
this.type = CParam.Type_numArray; bIsArray = true; }
this.count = 1;
}
if(paramType == CParam.Type_string){
this.type = CParam.Type_stringArray; bIsArray = true; }
if(paramType == CParam.Type_bool){
this.type = CParam.Type_boolArray; bIsArray = true; }
if(paramType == CParam.Type_funct){
this.type = CParam.Type_functArray; bIsArray = true; }
if(paramType == CParam.Type_object){
this.type = CParam.Type_objectArray; bIsArray = true; }
//-----------------------------------------------------------
if(bIsArray == true){
this.count = param.length; }
else{
this.count = 1; }
this.value = [];
for(let i = 0; i < param.length; ++i){
this.value[i] = param[i];
}
}
}
static DecideParamType(param){
if(typeof(param) == "number")
return CParam.Type_number;
if(typeof(param) == "string")
return CParam.Type_string;
if(typeof(param) == "boolean")
return CParam.Type_bool;
if(typeof(param) == "object")
return CParam.Type_object;
if(typeof(param) == "function")
return CParam.Type_funct;
if(typeof(param) == "undefined")
return CParam.Type_void;
}
}
CParam.Type_void = 0;
CParam.Type_bool = 1;
CParam.Type_number = 2;
CParam.Type_string = 3;
CParam.Type_vec2 = 4;
CParam.Type_vec3 = 5;
CParam.Type_vec4 = 6;
CParam.Type_object = 7;
CParam.Type_funct = 8;
CParam.Type_boolArray = 1001;
CParam.Type_numArray = 1002;
CParam.Type_stringArray = 1003;
CParam.Type_vec2Array = 1004;
CParam.Type_vec3Array = 1005;
CParam.Type_vec4Array = 1006;
CParam.Type_objectArray = 1007;
CParam.Type_functArray = 1008;
export class CCommandParams{
constructor(){
this.type = "CCommandParams";
this.params = [];
}
add(param){
let cparam = new CParam();
cparam.set(param);
this.params[this.params.length] = cparam;
}
}
//----------------------------------------------------------------------
export class CCommand{
constructor(){
this.type = "CCommand";
this.objectId = "none";
this.objectType = "none";
this.command = "none";
this.commandParams = null;
++CCommand.createdCount;
this.commandId = CCommand.createdCount;
}
getObjectType(){ return this.objectType; }
getObjectId(){ return this.objectId; }
getCommandType(){ return this.command; }
getCommandParams(){ return this.commandParams.params; }
set(){ //objId, objType, cmd
this.objectId = arguments[0];
this.objectType = arguments[1];
this.command = arguments[2];
if(arguments.length > 3){
this.commandParams = new CCommandParams();
for(let i = 3; i < arguments.length; ++i){
this.commandParams.add(arguments[i]);
}
}
}
}
CCommand.createdCount = 0;
//----------------------------------------------------------------------
export class ICommandExecute{
constructor(){
this.type = "ICommandExecute";
++ICommandExecute.createdCount;
this.objectId = ICommandExecute.createdCount;
}
setType(typ){ this.type = typ; }
exec(){ console.log(this.type + "::exec() not implemented!, objectId == " + this.objectId); }
SaveAsCommand(){ console.log(this.type + "::SaveAsCommand() not implemented!, objectId == " + this.objectId); return null; }
LoadFromCommand(cmd){ console.log(this.type + "::LoadFromCommand() not implemented!, objectId == " + this.objectId); return false; }
}
ICommandExecute.createdCount = 0; |
const input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");
const firstLine = input[0].split(' ').map(item => parseInt(item))
const N = firstLine[0]
const Y = firstLine[1]
result = '-1 -1 -1'
for (i = 0; i <= N; i++) {
for (j = 0; j <= N - i; j++) {
for (k = N - (i + j); k <= N - (i + j); k++) {
if (10000 * i + 5000 * j + 1000 * k === Y) {
result = `${i} ${j} ${k}`
}
}
}
}
console.log(result)
|
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
admin: {
type: DataTypes.BOOLEAN,
allowNull: false
},
isEmailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false
},
contactwin: {
type: DataTypes.BOOLEAN,
allowNull: false
},
contactlose: {
type: DataTypes.BOOLEAN,
allowNull: false
}
})
User.associate = models => {
User.hasMany(models.Ticket, {
foreignKey: 'userID',
as: 'tickets'
})
}
return User
}
|
import { useRetailers } from "./RetailerDataProvider.js"
import { retailerHTML } from "./retailer.js"
import { useDistributors } from "../flowerDistributors/DistributorDataProvider.js"
const contentTarget = document.querySelector('.retailerContainer')
export const renderRetailerList = () => {
const distributors = useDistributors()
const retailers = useRetailers()
contentTarget.innerHTML = retailers.map(singleRetailer => {
const foundDistributor = distributors.find( (distributor)=>{
return (distributor.id === singleRetailer.distributor)
})
return retailerHTML(singleRetailer, foundDistributor)
}).join("")
} |
/**
* Created by chandan on 11/6/16.
*/
var fs = require('fs');
module.exports = {
readDataFromJsonFile: readDataFromJsonFile
};
function readDataFromJsonFile(fileName){
var allProcessedRequest=new Array();
try{
var jsonData=require(fileName);
var interestedParams=new Array("headers","url","pathVariables","method","data","dataMode","description","descriptionFormat","responses","name");
var allRawRequestObjects=jsonData.requests;
for(i=0;i<allRawRequestObjects.length;i++){
var requestObj={};
for(j=0;j<interestedParams.length;j++){
requestObj[interestedParams[j]]=allRawRequestObjects[i][interestedParams[j]];
}
allProcessedRequest[i]=requestObj;
}
//console.log(allProcessedRequest);
}
catch (e){
if( /^win/.test(process.platform)==true)
console.log("Windows path : C:\\\\file\\\\path\\\\file.json \n");
else
console.log("Unix path : /c/file/path/file.json");
}
return allProcessedRequest;
}
|
"use strict";
define(['service/logger'], function (logger) {
logger.debug('Common error module has initialized');
var errorLvl = {
high: 100,
medium: 50,
low: 25
};
function buildError(name, lvl, msg) {
return {
name: name,
level: lvl,
message: msg,
toString: function () {
return this.name + ": " + this.message;
}
};
}
return {
dataSave: function (msg) {
return buildError("Save Data", errorLvl.high, (msg) ? msg : "Unable to save data");
}, invalidType: function (msg) {
return buildError("Invalid data type", errorLvl.high, (msg) ? msg : "Invalid data type found");
}
}
});
|
"use strict";
function Time() {
this.startTime =
this.lastUpdate = Date.now();
this.allTime = 0;
};
Time.prototype.Update = function () {
this.now = Date.now();
this.allTime = (this.now - this.startTime) / 1000;
this.deltaTime = (this.now - this.lastUpdate) / 1000;
this.lastUpdate = this.now;
}; |
import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Tab from '../../components/tab/tab';
import * as tabActions from '../../actions/tabAction';
function mapStateToProps(state) {
return {
index: state.tabReducer.index
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(tabActions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Tab) |
;(function () {
'use strict';
var ServiceCalculatorDataManager = MINI.ServiceCalculatorDataManager = (function () {
function ServiceCalculatorDataManager(scope){
this.data = [] || [];
this.dataPlus = [] || [];
this.scope = scope;
this.init();
}
ServiceCalculatorDataManager.prototype = {
init : function () {
var that = this;
var url = '/Public/js/service-calculator/DATA.json'
$.ajax({
dataType: "json",
url: url,
success: function (d) { that.data = d; that.scope(d,''); }
});
var that = this;
var plusurl = '/Public/js/service-calculator/DATA-PLUS.json'
$.ajax({
dataType: "json",
url: plusurl,
success: function (d) { that.dataPlus = d; that.scope('',d); }
});
},
// RETURN DATA ARRAY
getData : function () {
return this.data;
}
}
return ServiceCalculatorDataManager;
})();
}).call(this); |
// Author: Luis Souza
// REMEMBRALL App - just a simple app that saves
// reminders and shows them using Local Notifications
let app = {
pages: [],
init: function () {
document.addEventListener('deviceready', app.ready, false);
},
ready: function () {
app.addListeners();
},
ftw: function () {
console.log("OK");
},
wtf: function (err) {
console.warn('failure');
console.error(err);
},
addListeners: function () {
document.addEventListener('pause', () => {
console.log('system paused');
});
document.addEventListener('resume', () => {
console.log('system resumed');
});
document.querySelector('#rem-add').addEventListener('click', app.add);
document.querySelector('#lblCancel').addEventListener('click', app.cancel);
document.querySelector('#lblDone').addEventListener('click', app.save);
app.loadEvents();
},
loadEvents: function () {
let remList = document.querySelector("#remList");
remList.innerHTML = "";
let notification = cordova.plugins.notification.local;
notification.getAll(elements => {
elements.sort((a, b) => {
return a.at - b.at;
}).forEach(item => {
let listLine = document.createElement("li");
listLine.setAttribute("class", "remind-item");
listLine.setAttribute("id", item.id);
let h4Line = document.createElement("h4");
h4Line.setAttribute("class", "remind-lbl");
h4Line.setAttribute("id", item.id);
h4Line.textContent = item.title;
let h5Line = document.createElement("h5");
h5Line.setAttribute("class", "remind-dt");
h5Line.setAttribute("id", item.id);
let ndate = new Date(item.at / 1000);
let newDate = ndate.toISOString().slice(0, 10);
let newTime = ndate.getUTCHours() + ':' + ndate.getUTCMinutes();
h5Line.textContent = moment(newDate).format('ll') + " @ " + newTime;
let btnDel = document.createElement("input");
btnDel.setAttribute("type", "button");
btnDel.setAttribute("class", "remind-del");
btnDel.setAttribute("id", item.id);
remList.appendChild(listLine);
listLine.appendChild(h4Line);
listLine.appendChild(h5Line);
listLine.appendChild(btnDel);
remList.addEventListener("click", app.update);
btnDel.addEventListener("click", app.delete);
});
})
},
add: function (e) {
e.stopPropagation();
e.preventDefault();
app.switchPages();
document.querySelector("#rem-lbl").focus();
},
update: function (e) {
e.stopPropagation();
e.preventDefault();
let notification = cordova.plugins.notification.local;
notification.get(e.target.id, function (notifications) {
let ndate = new Date(notifications.at);
let newDate = ndate.toISOString().slice(0, 10);
let newTime = ndate.getUTCHours() + ':' + ndate.getUTCMinutes();
document.querySelector("#lblDone").dataset.id = notifications.id;
document.querySelector("#rem-lbl").value = notifications.title;
document.querySelector("#rem-date").value = newDate;
document.querySelector("#rem-time").value = newTime;
});
app.switchPages();
},
cancel: function (e) {
e.stopPropagation();
e.preventDefault();
app.clearForm();
app.switchPages();
},
save: function (e) {
e.stopPropagation();
e.preventDefault();
let notification = cordova.plugins.notification.local;
let newId = new Date().getTime();
if (e.target.dataset.id != "") {
cordova.plugins.notification.local.cancel(e.target.dataset.id, app.doNothing, this);
}
let remDt = JSON.parse(moment(document.querySelector("#rem-date").value + "T" + document.querySelector("#rem-time").value + ":00.000Z").format("x"));
let newDt = new Date(remDt);
notification.schedule({
id: newId,
title: document.querySelector("#rem-lbl").value,
at: newDt * 1000
}, app.loadEvents);
document.querySelector("#lblDone").dataset.id = "";
app.clearForm();
app.switchPages();
},
delete: function (e) {
e.stopPropagation();
e.preventDefault();
let lblTitle = "Delete Event?";
let lblMessage = "Deleting this reminder will also remove it from the list";
let btnLabels = ["Cancel", "Delete"];
navigator.notification.confirm(lblMessage, function (btnIndex) {
if (btnIndex == 2) {
cordova.plugins.notification.local.cancel(parseInt(e.target.id), app.loadEvents, this);
}
}, lblTitle, btnLabels);
},
switchPages: function (e) {
pages = document.querySelectorAll(".top-banner");
pages[0].classList.toggle("hide");
pages[1].classList.toggle("hide");
pages = document.querySelectorAll(".pages");
pages[0].classList.toggle("hide");
pages[1].classList.toggle("hide");
},
clearForm: function () {
document.querySelector("#frmForm").reset();
},
doNothing: function () { console.log("ID Deleted"); }
};
app.init();
|
const express = require('express')
const bodyParser = require('body-parser')
const massive = require('massive')
require('dotenv').config();
const app = express()
app.use( express.static( `${__dirname}/../build` ) );
app.use(bodyParser.json())
app.use(express.static('/../public/build'))
// massive(process.env.CONNECTION_STRING).then((dbInstance) => {
// dbInstance.seedFile()
// .then(res => console.log('that sucSEEDed...'))
// .catch(err => console.log('aww shit..', err))
// app.set('db', dbInstance)
// }).catch(err => console.log(err))
const port = process.env.PORT
app.listen(port, (() => { console.log('YAY') })) |
import validator from 'validator'
class Utils {
static check = (input, newValue, fields) => {
if(input === 'address') return {
address: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
else if (input === 'city') return {
city: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
else if (input === 'province') return {
province: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
else if(input === 'country') return {
country: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
else if(input === 'postcode') return {
postcode: {
value: newValue,
error: Utils.checkPostcode(newValue)
}
};
else if(input === 'email') return {
email: {
value: newValue,
error: Utils.checkEmail(newValue)
}
};
else if(input === 'amount') return {
amount: {
value: parseInt(newValue),
error: Utils.checkQuantity(newValue)
}
};
else if (input === 'donorName') return {
donorName: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
else if (input === 'receiverName') return {
receiverName: {
value: newValue,
error: Utils.checkStandard(newValue)
}
};
};
static checkStandard = text => {
return !validator.isAscii(text)
|| !validator.isLength(text, {min: 1, max: 100})
};
static checkEmail = email => {
return !validator.isEmail(email)
};
static checkPostcode = postcode => {
return !validator.isNumeric(postcode)
};
static checkQuantity = quantity => {
return !validator.isNumeric(quantity) || quantity < 1 || quantity > 9999999 || !validator.isInt(quantity)
};
static errorOrEmptyFields = fields => {
return Object.entries(fields).find(field => field[1].error || field[1].value === '') !== undefined
};
}
export default Utils; |
// "devDependencies": {
// "@babel/preset-env": "^7.4.5",
// "@babel/preset-react": "^7.0.0",
// "babel-cli": "^6.26.0",
// "babel-core": "^6.23.1",
// "babel-jest": "^24.8.0",
// "babel-loader": "^6.3.2",
// "babel-preset-env": "^1.7.0",
// "babel-preset-es2015": "^6.22.1",
// "babel-preset-react": "^6.23.0",
// "enzyme": "^3.9.0",
// "enzyme-adapter-react-16": "^1.13.1",
// "jest": "^24.8.0",
// "sinon": "^7.3.2",
// "webpack": "^2.2.1",
// "webpack-cli": "^3.3.2"
// }, |
(function() {
var IRacing,
__slice = [].slice;
window.IRacing = IRacing = (function() {
function IRacing(requestParams, requestParamsOnce, fps, readIbt, server) {
this.requestParams = requestParams != null ? requestParams : [];
this.requestParamsOnce = requestParamsOnce != null ? requestParamsOnce : [];
this.fps = fps != null ? fps : 1;
this.readIbt = readIbt != null ? readIbt : false;
this.server = server != null ? server : 'localhost:8182';
this.data = {};
this.onConnect = null;
this.onDisconnect = null;
this.onUpdate = null;
this.ws = null;
this.reconnectTimeout = null;
this.permanentDisconnect = false;
this.connected = false;
this.firstTimeConnect = true;
this.connect();
}
IRacing.prototype.connect = function() {
this.ws = new WebSocket("ws://" + this.server + "/ws");
this.ws.onopen = (function(_this) {
return function() {
return _this.onopen.apply(_this, arguments);
};
})(this);
this.ws.onmessage = (function(_this) {
return function() {
return _this.onmessage.apply(_this, arguments);
};
})(this);
return this.ws.onclose = (function(_this) {
return function() {
return _this.onclose.apply(_this, arguments);
};
})(this);
};
IRacing.prototype.disconnect = function() {
this.ws.close();
this.ws = null;
this.connected = false;
this.permanentDisconnect = true;
if (this.reconnectTimeout != null) {
return clearTimeout(this.reconnectTimeout);
}
};
IRacing.prototype.status = function() {
if (this.ws) {
return this.ws.readyState;
} else {
return 3;
}
};
IRacing.prototype.onopen = function() {
var k;
if (this.reconnectTimeout != null) {
clearTimeout(this.reconnectTimeout);
}
for (k in this.data) {
delete this.data[k];
}
return this.ws.send(JSON.stringify({
fps: this.fps,
readIbt: this.readIbt,
requestParams: this.requestParams,
requestParamsOnce: this.requestParamsOnce
}));
};
IRacing.prototype.onmessage = function(event) {
var data, k, keys, v, _ref;
data = JSON.parse(event.data);
if (data.disconnected) {
this.connected = false;
if (this.onDisconnect) {
this.onDisconnect();
}
}
if (data.connected) {
for (k in this.data) {
delete this.data[k];
}
}
if (data.connected || (this.firstTimeConnect && !this.connected)) {
this.firstTimeConnect = false;
this.connected = true;
if (this.onConnect) {
this.onConnect();
}
}
if (data.data) {
keys = [];
_ref = data.data;
for (k in _ref) {
v = _ref[k];
keys.push(k);
this.data[k] = v;
}
if (this.onUpdate) {
return this.onUpdate(keys);
}
}
};
IRacing.prototype.onclose = function() {
if (this.ws) {
this.ws.onopen = this.ws.onmessage = this.ws.onclose = null;
}
if (this.connected) {
this.connected = false;
if (this.onDisconnect) {
this.onDisconnect();
}
}
if (!this.permanentDisconnect) {
this.reconnectTimeout = setTimeout(((function(_this) {
return function() {
return _this.connect.apply(_this);
};
})(this)), 2000);
}
return this.permanentDisconnect = false;
};
IRacing.prototype.sendCommand = function() {
var args, command;
command = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return this.ws.send(JSON.stringify({
command: command,
args: args
}));
};
return IRacing;
})();
}).call(this);
|
const AnnonceController = require("../controleur/annonceDB");
const MiddlewareId = require("../Middleware/Authorization");
const MiddlewareAuth = require("../Middleware/jwtAuth");
const Router = require("express-promise-router");
const router = new Router;
/**
* @swagger
* /annonce/{id}:
* get:
* tags:
* - Annonce
* summary: "permet de rechercher une annonce précise"
* parameters:
* - name: id
* description: id de l'annonce
* in: path
* required: true
* schema:
* type: integer
* responses:
* 200:
* $ref: '#/components/responses/annonceFound'
* 400:
* $ref: '#/components/responses/badId'
* 404:
* $ref: '#/components/responses/annonceNotFound'
*/
router.get('/:id', MiddlewareAuth.identification, MiddlewareId.mustbeAtLeastUSer, AnnonceController.getAnnonce);
/**
* @swagger
* /annonce:
* get:
* tags:
* - Annonce
* summary: "Recherche les annonces de l'utlisateur actif"
* parameters:
* - name: id
* description: id de l'utilisateurs connecté
* in: header
* required: true
* schema:
* type: integer
* responses:
* 200:
* $ref: '#/components/responses/mesAnnoncesTrouve'
* 404:
* $ref: '#/components/responses/annoncesNotFound'
* 500:
* description: Erreur serveur
*/
router.get('/', MiddlewareAuth.identification, MiddlewareId.mustbeAtLeastUSer, AnnonceController.getMesAnnonces);
/**
* @swagger
* /annonce:
* post:
* tags:
* - Annonce
* summary: "Ajoute une annonce dans la BD"
* parameters:
* - name: id
* description: id de l'utilisateurs connecté
* in: header
* required: true
* schema:
* type: integer
* responses:
* 201:
* $ref: '#/components/responses/annonceAdded'
* 404:
* $ref: '#/components/responses/annonceNotFound'
* 500:
* description: erreur serveur
*/
router.post('/', MiddlewareAuth.identification, MiddlewareId.mustbeAtLeastUSer, AnnonceController.postAnnonce);
/**
* @swagger
* /annonce:
* patch:
* tags:
* - Annonce
* summary: "Met à jour une annonce"
* parameters:
* - name: idUser
* description: "id de l'utilisateur connecté"
* in: header
* required: true
* schema:
* type: integer
* requestBody:
* $ref: '#/components/requestBodies/majAnnonce'
* responses:
* 201:
* $ref: '#/components/responses/annonceUpdated'
* 404:
* $ref: '#/components/responses/annonceNotFound'
* 500:
* description: erreur serveur
*/
router.patch('/', MiddlewareAuth.identification, MiddlewareId.mustbeAtLeastUSer, AnnonceController.updateAnnonce);
/**
* @swagger
* /annonce/{id}:
* delete:
* tags:
* - Annonce
* summary: "Supprime une annonce de la base de donnée"
* parameters:
* - name: id
* description: "identifiant de l'annonce"
* in: path
* required: true
* schema:
* type: integer
* - name: connectedId
* description: "identifiant de l'utilisateur connecté"
* in: header
* required: true
* schema:
* type: integer
* responses:
* 204:
* $ref: '#/components/responses/adDeleted'
* 500:
* description: Erreur Serveur
* 404:
* $ref: '#/components/responses/annonceNotFound'
* 403:
* $ref: '#/components/responses/notOwner'
*/
router.delete('/:id',MiddlewareAuth.identification, MiddlewareId.mustbeAtLeastUSer, AnnonceController.deleteAnnonce);
module.exports=router; |
(function () {
"use strict";
describe("AllCtrl", function () {
/* global $q, $httpBackend, $scope, mockModalInstance*/
var ctrl,
$state,
$modal,
deferred,
ContentsService,
AlertsService,
ResultsHandlerService;
beforeEach(function () {
inject(function (_$injector_) {
$state = _$injector_.get("$state");
$modal = _$injector_.get("$modal");
ContentsService = _$injector_.get("ContentsService");
AlertsService = _$injector_.get("AlertsService");
ResultsHandlerService = _$injector_.get("ResultsHandlerService");
});
deferred = $q.defer();
spyOn($state, "go");
$httpBackend.whenPOST("/services/ContentMgmtService/omi_getContentEvents").respond(200);
$httpBackend.whenPOST("/services/ContentMgmtService/omi_getContentList").respond(200);
ctrl = initializeCtrl();
});
describe("initialize", function () {
beforeEach(initializeCtrl);
it("should initialize ctrl.source with the expected properties", function () {
expect(ctrl.source).toEqual({
handler: ContentsService.getContent,
callback: ctrl.setContent,
});
expect(ctrl.source.handler).toEqual(jasmine.any(Function));
expect(ctrl.source.callback).toEqual(jasmine.any(Function));
});
it("should initialize ctrl.columns with the expected values", function () {
expect(ctrl.columns).toEqual([{
label: "Content ID",
field: "smsContentId",
}, {
label: "Description",
field: "description",
}, {
label: "Tag",
field: "tag",
}]);
});
it("should initialize ctrl.itemActions with the expected values", function () {
expect(ctrl.itemActions).toEqual([{
label: "Events & Services",
actions: [{
label: "Create Service",
handler: ctrl.openCreateServiceModal,
}, {
label: "View Associated Events",
handler: ctrl.viewAssociatedEvents,
}],
}, {
actions: [{
label: "Remove Content",
handler: ctrl.removeContent,
}]
}]);
expect(ctrl.itemActions[0].actions[0].handler).toEqual(jasmine.any(Function));
expect(ctrl.itemActions[0].actions[1].handler).toEqual(jasmine.any(Function));
expect(ctrl.itemActions[1].actions[0].handler).toEqual(jasmine.any(Function));
});
it("should initialize ctrl.otherActions with the expected values", function () {
expect(ctrl.otherActions).toEqual([{
label: "Create Content",
handler: ctrl.openCreateContentModal,
}]);
});
});
describe("setContent", function () {
var results;
beforeEach(function () {
results = [{id: "1"}, {id: "2"}];
initializeCtrl();
});
it("should call ResultsHandlerService.toArray with the given results", function () {
spyOn(ResultsHandlerService, "toArray").and.callThrough();
ctrl.setContent(results);
expect(ResultsHandlerService.toArray).toHaveBeenCalledWith(results);
});
it("should set ctrl.content to the return value of ResultsHandlerService.toArray", function () {
var res = ResultsHandlerService.toArray(results);
ctrl.setContent(results);
expect(ctrl.content).toEqual(res);
});
});
describe("refreshResults", function () {
it("should set ctrl.refresh to true", function () {
initializeCtrl();
expect(ctrl.source.refresh).toBeFalsy();
ctrl.refreshResults();
expect(ctrl.source.refresh).toBeTruthy();
});
});
describe("getChosenContent", function() {
var content;
beforeEach(function() {
content = [{smsContentId: "content1"}, {smsContentId: "content2"}];
ctrl.content = content;
});
it("should return the given array of content, if provided", function() {
var chosenContent = [{smsContentId: "content3"}];
expect(ctrl.getChosenContent(chosenContent)).toEqual(chosenContent);
});
it("should return all content if no array of content is provided", function() {
expect(ctrl.getChosenContent()).toEqual(content);
});
});
describe("opening the create service modal", function() {
beforeEach(function() {
spyOn(ctrl, "getChosenContent").and.callThrough();
});
it("should invoke getChosenContent with undefined if no chosen content is provided", function() {
ctrl.openCreateServiceModal();
expect(ctrl.getChosenContent).toHaveBeenCalledWith(undefined);
});
it("should invoke getChosenContent with the provided content", function() {
var chosenContent = [{smsContentId: "content1"}];
ctrl.openCreateServiceModal(chosenContent);
expect(ctrl.getChosenContent).toHaveBeenCalledWith(chosenContent);
});
});
describe("opening the create content modal", function() {
var rejectPromise, rejectPromiseWith;
beforeEach(function() {
rejectPromise = false;
rejectPromiseWith = undefined;
spyOn(ctrl, "refreshResults");
spyOn($modal, "open").and.callFake(function () {
return {
result: $q(function (resolve, reject) {
if (rejectPromise) {
return reject(rejectPromiseWith);
}
resolve();
})
};
});
});
it("should open the create content modal", function() {
ctrl.openCreateContentModal();
expect($modal.open).toHaveBeenCalled();
});
it("should call vm.refreshContent if the modal promise is resolved", function () {
ctrl.openCreateContentModal();
$scope.$digest();
expect(ctrl.refreshResults).toHaveBeenCalled();
});
it("should call vm.refreshContent if the modal promise is rejected with a truthy argument", function () {
rejectPromise = true;
rejectPromiseWith = "escape key pressed";
ctrl.openCreateContentModal();
$scope.$digest();
expect(ctrl.refreshResults).toHaveBeenCalled();
});
it("should not call vm.refreshResults if the modal promise is rejected with a falsy argument", function () {
rejectPromise = true;
rejectPromiseWith = false;
ctrl.openCreateContentModal();
$scope.$digest();
expect(ctrl.refreshResults).not.toHaveBeenCalled();
});
});
describe("opening the view content events modal", function() {
var actualOpts,
content;
beforeEach(function() {
spyOn($modal, "open").and.callFake(function (options) {
actualOpts = options;
return mockModalInstance;
});
content = {smsContentId: "content1"};
});
it("should call modal.open with the right properties", function() {
ctrl.viewAssociatedEvents(content);
expect($modal.open).toHaveBeenCalledWith({
templateUrl: "app/content/view_events_modal.html",
controller: "ViewAssociatedEventsModalCtrl as vm",
size: "lg",
resolve: {
parent: jasmine.any(Function),
events: jasmine.any(Function),
},
});
});
it("should resolve the content item with the chosen content", function() {
ctrl.viewAssociatedEvents(content);
expect(actualOpts.resolve.parent()).toEqual({id: content.smsContentId});
});
it("should retrieve all of the content events", function() {
spyOn(ContentsService, "getContentEvents");
ctrl.viewAssociatedEvents(content);
actualOpts.resolve.events();
expect(ContentsService.getContentEvents).toHaveBeenCalledWith(content);
});
});
describe("removeContent", function() {
var resolvePromise;
beforeEach(function () {
resolvePromise = true;
ctrl.content = [{
smsContentId: "1"
}, {
smsContentId: "2"
}, {
smsContentId: "3"
}];
spyOn($modal, "open").and.callFake(function () {
return {
result: $q(function (resolve) {
if (resolvePromise) {
resolve(["1", "3"]);
}
})
};
});
});
it("should call $modal.open with the expected configuration", function () {
ctrl.removeContent([ctrl.content[0], ctrl.content[2]]);
expect($modal.open).toHaveBeenCalledWith({
templateUrl: "app/content/confirm_content_delete.html",
controller: "ConfirmContentDeleteModalCtrl as vm",
resolve: {
contents: jasmine.any(Function),
},
});
});
it("should notify the user that the contents were removed", function () {
spyOn(AlertsService, "addSuccess");
ctrl.removeContent([ctrl.content[0], ctrl.content[2]]);
$scope.$digest();
expect(AlertsService.addSuccess.calls.count()).toEqual(2);
expect(AlertsService.addSuccess.calls.argsFor(0)).toEqual(["Successfully removed Content ID: 1"]);
expect(AlertsService.addSuccess.calls.argsFor(1)).toEqual(["Successfully removed Content ID: 3"]);
});
it("should remove the deleted contents from ctrl.contents", function () {
var content = ctrl.content[1];
ctrl.removeContent([ctrl.content[0], ctrl.content[2]]);
$scope.$digest();
expect(ctrl.content).toEqual([content]);
});
it("should not notify the user or remove contents if the promise does not resolve", function () {
var expected = [ctrl.content[0], ctrl.content[1], ctrl.content[2]];
resolvePromise = false;
spyOn(AlertsService, "addSuccess");
ctrl.removeContent([ctrl.content[0], ctrl.content[2]]);
$scope.$digest();
expect(AlertsService.addSuccess).not.toHaveBeenCalled();
expect(ctrl.content).toEqual(expected);
});
});
//////////
function initializeCtrl() {
return $controller("AllCtrl", {
$scope: $scope,
});
}
});
}());
|
import React from "react"
import styles from "./catalog-card.module.scss"
import Image from "gatsby-image"
const CatalogCard = ({ image, title, subtitle, pdf, onClick, index }) => {
return (
<div className={styles.container} onClick={() => onClick(subtitle, index)}>
<div className={styles.content}>
<Image fluid={image} className={styles.image} />
<div className={styles.text__container}>
<h2> {title} </h2>
<h5> {subtitle} </h5>
<a href={pdf} target="_blank" rel="noreferrer">
<h5> Download </h5>
</a>
</div>
</div>
</div>
)
}
export default CatalogCard; |
import validator from 'validator';
import {isEmpty as isEmptyLodash} from 'lodash';
export default function validateInput(inputs) {
let errors = {};
// console.log(inputs)
if (validator.isEmpty(inputs.firstName)) {
errors.firstName = 'This field is required';
}
if (validator.isEmpty(inputs.lastName)) {
errors.lastName = 'This field is required';
}
if (!validator.isEmail(inputs.email)) {
errors.email = 'Email is invalid';
}
if (validator.isEmpty(inputs.password1)) {
errors.password1 = 'This field is required';
}
if (validator.isEmpty(inputs.password2)) {
errors.password2 = 'This field is required';
}
if (!validator.equals(inputs.password1, inputs.password2)) {
errors.password2 = 'Passwords must match';
}
if (validator.isEmpty(inputs.timezone)) {
errors.timezone = 'This field is required';
}
return {
errors,
isValid: isEmptyLodash(errors)
}
} |
import { AiFillCaretDown,AiFillCaretUp } from "react-icons/ai";
const SortIcon = ({down}) => {
const Icon = down ? AiFillCaretDown : AiFillCaretUp;
return (
<Icon size = '1rem' color = 'white'/>
);
}
export default SortIcon; |
import styled from 'styled-components/native';
export const Card = styled.View`
width: 152px;
height: 188px;
background: #1E8B85;
border-radius: 15px;
margin-top: 20px;
margin-left: 12px;
margin-right: 12px;
shadow-opacity: 0.75;
shadow-radius: 5px;
shadow-offset: 15px 15px;
elevation: 7;
`;
export const TitleCard = styled.Text`
margin-top: 10px;
font-family: Neucha;
color: #FFFFFF;
text-align: center;
font-size: 16px;
`;
export const Line = styled.View`
border: 0.5px solid #FFFFFF;
margin: 5px;
`;
export const DescriptionCard = styled.Text.attrs({
numberOfLines: 6,
ellipsizeMode: 'tail'
})`
color: #000000;
text-align: justify;
margin-left: 8px;
margin-right: 8px;
`;
export const Footer = styled.TouchableOpacity`
width: 100%;
height: 31px;
background: #0C3937;
border-bottom-end-radius: 15px;
border-bottom-start-radius: 15px;
bottom: 0;
position: absolute;
justify-content: center;
align-items: center;
flex-direction: row;
`;
export const TextFooter = styled.Text`
color: #FFF;
font-size: 14px;
font-family: Neucha;
margin-left: 5px;
`;
|
$("table tbody").delegate(".del1","click",function(){
var number = $(this).attr("data_num");
var cont={"email":number};
$.ajax({
method:"post",
url:"/removes",
data:cont
}).done(function(data){
show(data)
})
});
$(".texts").blur(function () {
console.log("hhhh")
var texts=$(".texts").val();
if(texts==""){
$(".sp").html("不能为空")
}else{
var cont={email:texts}
$.ajax({
method:"post",
url:"/s",
data:cont
}).done(function(da){
console.log(da);
if(da.length == 1){
$(".sp").html("邮箱已注册")
}else{
$(".sp").html("")
}
})
}
})
$(".myform").submit(function(){
var data = $(this).serialize();
if($(".sp").html()==""){
$.ajax({
method:"post",
url:"/inserts",
data:data
}).done(function(data){
show(data)
})
}
return false;
})
ajax()
function ajax(){
$.ajax({
method:"get",
url:"/finds",
}).done(function(data){
show(data);
})
}
function show(elem){
$("table tbody tr").empty()
for( var i in elem){
var $tr=$("<tr>")
for(var j in elem[i]){
if(j!="_id"){
var text=elem[i][j]
var $td=$("<td>")
$td.text(text)
$tr.append($td)
}
}
$tr.append("<td><button class='del1' data_num='"+ elem[i].email +"'>删除</button></td>")
$("table tbody").append($tr)
}
} |
//Gestion des sessions
module.exports = {
//définit l'utilisateur comme authentifié en session
authenticate : function(req, res, user){
req.session.user = user;
req.session.authenticated = true;
console.log("authentification");
console.log("utilisateur : " + JSON.stringify(req.session.user));
console.log("authentifié : " + req.session.authenticated);
},
//définit l'utilisateur comme désauthentifié en session
unauthenticate : function(req, res){
req.session.user = undefined;
req.session.authenticated = false;
console.log("désauthentification");
console.log("utilisateur : " + JSON.stringify(req.session.user));
console.log("authentifié : " + req.session.authenticated);
},
//renvoie un booléen de si l'utilisateur est authentifié
isAuthenticated : function(req, res){
return req.session.authenticated;
console.log("authentification demandée, statut : " + req.session.authenticated);
},
//initialise une session anonyme
init : function(req, res){
console.log("initialisation de la session");
sails.controllers.session.unauthenticate(req, res);
},
//recharge les droits
reload : function(req, res){
//si on a l'utilisateur courant en session on recharge ses droits depuis la bdd via son id
if(req.session.user != undefined){
console.log("rechargement de la session");
User.findOne()
.where({id : req.session.user.id})
.then(function(user){
sails.controllers.session.authenticate(req,res,user);
}).catch(function(err){
console.log(err);
});
//sinon on est surement dans une session anonyme et on recharge une session anonyme
}else{
sails.controllers.session.init(req,res);
}
},
destroy: function(req, res){
req.session.destroy();
}
};
|
var News=artifacts.require("./News.sol");
module.exports =function(deployer,network,accounts){
deployer.deploy(News);
} |
$(function() {
//表格增加事件处理
$('#dg').datagrid({
onLoadSuccess : function(data) {
if (data.total == 0 && data.ERROR == 'No Login!') {
var user_id = localStorage.getItem('user_id');
var user_pwd = localStorage.getItem('user_pwd');
if(user_id==''||!user_id||user_pwd==''||!user_pwd){
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
relogin();
}
else{
$.post('loginAction!login1.zk',{user_id:user_id,user_pwd:user_pwd},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
}
},'json').complete(function(){
$('#dg').datagrid('reload');
});
}
}
$('#dg').datagrid('doCellTip', {
onlyShowInterrupt: false, //是否只有在文字被截断时才显示tip,默认值为false
position: 'bottom', //tip的位置,可以为top,botom,right,left
cls: { 'background-color': '#FFF' }, //tip的样式D1EEEE
delay: 100 //tip 响应时间
});
},
onLoadError : function() {
alert('出错啦');
},
onHeaderContextMenu: function(e, field){
e.preventDefault();
if (!cmenu){
createColumnMenu();
}
cmenu.menu('show', {
left:e.pageX,
top:e.pageY
});
}
});
//平台切换事件,自动搜索
$("#tb-platform").combobox({
onChange: function (n,o) {
var key = $("#txt_word").searchbox("getValue");
var type = $("#txt_word").searchbox("getName");
search(key,type);
}
});
});
//字段的处理
function formatReceiverName(value){
return value;
}
function formatAddress(value){
return value;
}
function formatProducts(value){
return '<a data-product=\''+JSON.stringify(value)+'\'onclick=\'seeProductList(this)\'>查看商品列表</a>';//\''+JSON.stringify(value)+'\'
}
function seeProductList(value){
//alert(JSON.stringify($(value).data('product')));
value = $(value).data('product');
//value = eval('('+value+')');
if(value&&value!=null){
var orders = value;
var dataList = [];
var product;
for(var j=0;j<orders.length;j++){
var theOrder = orders[j];
var types = eval('('+theOrder.goodsType+')');
var type="";
for(var k=0;k<types.length;k++){
if(types[k].id == theOrder.goodsTypeId){
type = types[k].name;
}
}
var theTotal = (parseFloat(theOrder.price)*parseInt(theOrder.count)).toFixed(2);
product = {
"goodsId": theOrder.goodsId,//产品id
"typeId": theOrder.goodsTypeId,
"count":theOrder.count,
"type":type,
"theTotal" :theTotal,
"name" : theOrder.goodsName,
"image" :theOrder.goodsImages
};
if(theOrder.logistics){
product.logistics = theOrder.logistics;
}
if(theOrder.logisticsNumber){
product.logisticsNumber = theOrder.logisticsNumber;
}
dataList.push(product);
}
$("#dlgProduct").empty();
$('#dlgProduct').dialog('open').dialog('setTitle','产品列表');
$.tmpl($("#productTmpl").html(),dataList).appendTo("#dlgProduct");
//$('#dlgProduct').show();
}
}
function formatDate(value){
var d = new Date(value);
return d.format("yyyy-MM-dd hh:mm:ss");
}
function formatStatus(value){
switch(parseInt(value)){
case 0:return '未付款';
case 1:return '待发货';
case 2:return '已发货';
case 3:return '已完成';
default:return '';
}
}
function formatReturnStatus(value){
switch(parseInt(value)){
case 0:return '无售后';
case 1:return '申请退货';
case 2:return '正在退款';
case 3:return '退款成功';
case 4:return '申请换货';
case 5:return '正在换货';
case 6:return '换货成功';
default:return '';
}
}
function formatTotal(value,row,index){
value = row.detail;
if(value&&value!=null){
var orders = value;
var dataList = [];
var allFare=0;
var allTotal = 0;
var product;
for(var j=0;j<orders.length;j++){
var theOrder = orders[j];
var types = eval('('+theOrder.goodsType+')');
var type="";
for(var k=0;k<types.length;k++){
if(types[k].id == theOrder.goodsTypeId){
type = types[k].name;
}
}
var theTotal = (parseFloat(theOrder.price)*parseInt(theOrder.count)).toFixed(2);
product = {
"goodsId": theOrder.goodsId,//产品id
"typeId": theOrder.goodsTypeId,
"count":theOrder.count,
"type":type,
"theTotal" :theTotal,
"name" : theOrder.goodsName,
"image" :theOrder.goodsImages
};
allFare += parseFloat(theOrder.freightPrice)*parseInt(theOrder.count);
allTotal += parseFloat(theTotal);
dataList.push(product);
}
allTotal += allFare;
return allTotal.toFixed(2);
//$('#dlgProduct').show();
}
return '';
}
//订单总金额
function total(detail){
value = detail;
if(value&&value!=null){
var orders = value;
var dataList = [];
var allFare=0;
var allTotal = 0;
var product;
for(var j=0;j<orders.length;j++){
var theOrder = orders[j];
var types = eval('('+theOrder.goodsType+')');
var type="";
for(var k=0;k<types.length;k++){
if(types[k].id == theOrder.goodsTypeId){
type = types[k].name;
}
}
var theTotal = (parseFloat(theOrder.price)*parseInt(theOrder.count)).toFixed(2);
product = {
"goodsId": theOrder.goodsId,//产品id
"typeId": theOrder.goodsTypeId,
"count":theOrder.count,
"type":type,
"theTotal" :theTotal,
"name" : theOrder.goodsName,
"image" :theOrder.goodsImages
};
allFare += parseFloat(theOrder.freightPrice)*parseInt(theOrder.count);
allTotal += parseFloat(theTotal);
dataList.push(product);
}
allTotal += allFare;
return allTotal;
//$('#dlgProduct').show();
}
return 0;
}
//总运费
function totalFare(detail){
value = detail;
if(value&&value!=null){
var orders = value;
var dataList = [];
var allFare=0;
var allTotal = 0;
var product;
for(var j=0;j<orders.length;j++){
var theOrder = orders[j];
var types = eval('('+theOrder.goodsType+')');
var type="";
for(var k=0;k<types.length;k++){
if(types[k].id == theOrder.goodsTypeId){
type = types[k].name;
}
}
var theTotal = (parseFloat(theOrder.price)*parseInt(theOrder.count)).toFixed(2);
product = {
"goodsId": theOrder.goodsId,//产品id
"typeId": theOrder.goodsTypeId,
"count":theOrder.count,
"type":type,
"theTotal" :theTotal,
"name" : theOrder.goodsName,
"image" :theOrder.goodsImages
};
allFare += parseFloat(theOrder.freightPrice)*parseInt(theOrder.count);
allTotal += parseFloat(theTotal);
dataList.push(product);
}
allTotal += allFare;
return allTotal;
//$('#dlgProduct').show();
}
return 0;
}
//修改运费后更新总金额
function reloadAmount(){
var total = parseInt($('#freightPrice').numberbox('getValue'))+ parseInt($('#price').numberbox('getValue'))-curOrderFare;
$('#price').numberbox('setValue',total);
curOrderFare = parseInt($('#freightPrice').numberbox('getValue'));
}
var url;
//新增订单
function newOrder(){
$('#fm').form('clear');
url="ShopOrderAction!add.zk";
$('#dlgOrder').dialog('open').dialog('setTitle','产品列表');
}
var curOrderFare;
//编辑订单
function updateOrder(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#fm').form('clear');
var data = {
id:row.id,
userId:row.userId,
returnReason:row.returnReason,
status:row.status,
returnStatus:row.returnStatus,
receiverName:row.receiverName,
receiverPhone:row.receiverPhone,
receiverAddress:row.receiverAddress,
freightPrice:row.freightPrice,
price:row.price,//total(row.detail),
gmtCreate:new Date(row.gmtCreate).format("yyyy-MM-dd hh:mm:ss")
};
$('#fm').form('load',data);
curOrderFare = parseInt(row.freightPrice);
$('#dlgOrder').dialog('open').dialog('setTitle','更新订单信息');
url = "ShopOrderAction!update.zk";
}else{
$.messager.alert('错误','请选择订单!','error');
}
}
//检查数据是否完善合理
function check(){
var receiverName = $('#receiverName').textbox('getValue');
if(!receiverName){
$('#receiverName').textbox().next('span').find('input').focus();
alert('收货人姓名不能为空!');
return false;
}
var receiverPhone = $('#receiverPhone').textbox('getValue');
if(!receiverPhone){
$('#receiverPhone').textbox().next('span').find('input').focus();
alert('收货人手机号不能为空!');
return false;
}
var receiverAddress = $('#receiverAddress').textbox('getValue');
if(!receiverAddress){
$('#receiverAddress').textbox().next('span').find('input').focus();
alert('收货人地址不能为空!');
return false;
}
var freightPrice = $('#freightPrice').numberbox('getValue');
if(!freightPrice){
$('#freightPrice').numberbox().next('span').find('input').focus();
alert('运费不能为空!');
return false;
}
var price = $('#price').numberbox('getValue');
if(!price){
$('#price').numberbox().next('span').find('input').focus();
alert('总金额不能为空!');
return false;
}
var gmtCreate = $('#gmtCreate').datetimebox('getValue');
if(!gmtCreate){
$('#gmtCreate').datetimebox().next('span').find('input').focus();
alert('下单日期不能为空!');
return false;
}
return true;
}
//保存订单
function saveOrder(){
if(check()){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return check();
},
success: function(result){
result = eval('('+result+')');
if (result.STATUS){
$('#dlgOrder').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: '错误',
msg: '系统繁忙!'
});
}
}
});
}
}
//删除订单
function del(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('删除订单', '确定删除该订单吗?', function(r){
if (r){
$.post('ShopOrderAction!delete.zk',{id:row.id},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
$.messager.show({
title : "消息",
timeout:2000,
msg : "删除成功!"
});
}else {
$.messager.alert('错误',data.INFO || data.ERROR,'error');
}
},'json');
}
});
}else{
$.messager.alert('错误','请先选择订单!','error');
}
}
//发货
function delivery(){
var row = $('#dg').datagrid('getSelected');
if (row){
if(parseInt(row.status)!=1){
$.messager.alert('警告','该订单无法发货!','error');
return;
}
$.messager.confirm('发货', '是否确认发货?', function(r){
if (r){
$.post('ShopOrderAction!update.zk',{id:row.id,status:2},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
$.messager.show({
title : "消息",
timeout:2000,
msg : "发货成功!"
});
}else {
$.messager.alert('错误',data.INFO || data.ERROR,'error');
}
},'json');
}
});
}else{
$.messager.alert('错误','请先选择订单!','error');
}
}
//确认付款
function payment(){
var row = $('#dg').datagrid('getSelected');
if (row){
if(parseInt(row.status)!=0){
$.messager.alert('警告','该订单已经付款!','error');
return;
}
$.messager.confirm('发货', '是否确认付款?', function(r){
if (r){
$.post('ShopOrderAction!update.zk',{id:row.id,status:1},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
$.messager.show({
title : "消息",
timeout:2000,
msg : "付款成功!"
});
}else {
$.messager.alert('错误',data.INFO || data.ERROR,'error');
}
},'json');
}
});
}else{
$.messager.alert('错误','请先选择订单!','error');
}
}
//退货
function refund(){
var row = $('#dg').datagrid('getSelected');
if (row){
if(parseInt(row.returnStatus)==0){
$.messager.alert('警告','该订单无法退货!','error');
return;
}
$('#fmReturn').form('clear');
var data = {
id:row.id,
userId:row.userId,
returnReason:((row.returnReason&&row.returnReason!=null&&row.returnReason!=undefined)?row.returnReason:''),
status:row.status,
returnStatus:row.returnStatus,
receiverName:row.receiverName,
receiverPhone:row.receiverPhone,
receiverAddress:row.receiverAddress
};
$('#fmReturn').form('load',data);
$('#dlgReason').dialog('open').dialog('setTitle','退货信息');
url = "ShopOrderAction!update.zk";
}else{
$.messager.alert('错误','请选择订单!','error');
}
}
//换货
function changeGoos(){
var row = $('#dg').datagrid('getSelected');
if (row){
if(parseInt(row.returnStatus)==0){
$.messager.alert('警告','该订单无法退货!','error');
return;
}
$('#fmReturn').form('clear');
var data = {
id:row.id,
userId:row.userId,
returnReason:((row.returnReason&&row.returnReason!=null&&row.returnReason!=undefined)?row.returnReason:''),
status:row.status,
returnStatus:row.returnStatus,
receiverName:row.receiverName,
receiverPhone:row.receiverPhone,
receiverAddress:row.receiverAddress
};
$('#fmReturn').form('load',data);
$('#dlgReason').dialog('open').dialog('setTitle','换货信息');
url = "ShopOrderAction!update.zk";
}else{
$.messager.alert('错误','请选择订单!','error');
}
}
//保存操作信息
function saveAction(){
$('#fmReturn').form('submit',{
url: url,
onSubmit: function(){
return;
},
success: function(result){
result = eval('('+result+')');
if (result.STATUS){
$('#dlgReason').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: '错误',
msg: '系统繁忙!'
});
}
}
});
}
//重新加载表格数据
function reloadData(word,status){
var data = {};
var startDate = $("#startDate").datebox("getValue");
var endDate = $("#endDate").datebox("getValue");
if(startDate&&startDate!=null)
data.startDate = startDate;
if(endDate&&endDate!=null)
data.endDate = endDate;
if(word&&word!=null)
data.key = word;
if(status&&status!=null){
if(parseInt(status)!=-1){
if(parseInt(status)>3)
data.returnStatus = parseInt(status)-3;
else
data.status = parseInt(status);
}
}
$("#dg").datagrid('load',data);
}
//搜索框点击和回车事件
function search(value,name){
reloadData(value, name);
}
//下拉选框改变事件
function menuHandler(item){
var word = $("#txt_word").val();
//if()
reloadData(word, item.name);
}
|
module.exports = [
// API V1 routes
// [/\/v1\/org\/(\w+)/, '/api/v1/org/public?action=:1', 'rest'],
// [/\/v1\/org(?:\/(\d+))?/, '/api/v1/org/public?orgId=:1', 'rest'],
// 机构管理 api
// 2 appid + 2 api + 3 postid + 4 action + status
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/(\w+)\/replies\/(\w+)?/, '/api/v1/app/posts/:3/mine?appId=:1&id=:2&action=:4', 'get, post'],
// ['/v1/apps/:app/users/login:user_id', '/api/v1/apps/users/login?appId=:1&id=:3', 'post'],
// POST
// /apps/$app/users/$user_ID/delete
// [/\/v1\/file?/, '/api/v1/file', 'rest'],
[/\/v1\/apps\/(\w+)\/taxonomies\/(\w+)\/terms\/slug:(\w+)$/, '/api/v1/apps/taxonomies/_slug?appId=:1&taxonomy=:2&slug=:3', 'get, post'],
[/\/v1\/apps\/(\w+)\/users\/(\d+)/, '/api/v1/apps/users/_id?appId=:1', 'get, post'],
[/\/v1\/apps\/(\w+)\/file?/, '/api/v1/apps/file?appId=:1', 'rest'],
[/\/v1\/apps\/(\w+)\/auth?(\/\w+)$/, '/api/v1/apps/auth/:2?appId=:1', 'get, post'],
[/\/v1\/apps\/(\w+)\/posts\/(\d+)\/replies?/, '/api/v1/apps/posts/replies?appId=:1&id=:2', 'get'],
[/\/v1\/apps\/(\w+)\/(\w+)\/(\d+)$/, '/api/v1/apps/:2/_id?appId=:1&id=:3', 'get, post'],
[/\/v1\/apps\/(\w+)\/(\w+)\/(\d+)\/(delete)$/, '/api/v1/apps/:2/_id/:4?appId=:1&id=:3', 'post'],
[/\/v1\/apps\/(\w+)\/comments\/(\d+)?/, '/api/v1/apps/comments?appId=:1&id=:2', 'get'],
[/\/v1\/apps\/(\w+)\/comments-(\w+)?/, '/api/v1/apps/comments?appId=:1&action=:2', 'get'],
[/\/v1\/apps\/(\w+)\/posts$/, '/api/v1/apps/posts?appId=:1', 'get'],
// LIKES API
[/\/v1\/apps\/(\w+)\/posts\/(\d+)\/(\w+)\/mine\/(\w+)?/, '/api/v1/apps/posts/:3/mine?appId=:1&id=:2&action=:4', 'get, post'],
[/\/v1\/apps\/(\w+)\/posts\/(\d+)\/(\w+)\/new?/, '/api/v1/apps/posts/:3/new?appId=:1&id=:2', 'post'],
[/\/v1\/apps\/(\w+)\/posts\/(\d+)\/likes?/, '/api/v1/apps/posts/likes?appId=:1&id=:2', 'get'],
[/\/v1\/apps\/(\w+)\/me\/likes?/, '/api/v1/apps/me/likes?appId=:1', 'get'],
[/\/v1\/apps\/(\w+)\/users\/login:(\w+)?/, '/api/v1/apps/users/login?appId=:1&user_login=:2', 'get'],
[/\/v1\/apps\/(\w+)\/(\w+)\/slug:([\w-]+)(?:\/(\w+))?/, '/api/v1/apps/:2/_slug/:4?appId=:1&slug=:3', 'get, post'],
// 分类法 api
[/\/v1\/apps\/(\w+)\/taxonomies\/(\w+)\/terms$/, '/api/v1/apps/taxonomies/terms?appId=:1&taxonomy=:2&action=:3', 'get, post'],
[/\/v1\/apps\/(\w+)\/taxonomies\/(\w+)\/terms\/slug:(\w+)$/, '/api/v1/apps/taxonomies/_slug?appId=:1&taxonomy=:2&slug=:3', 'get, post'],
// GET POST
// apps/$app/taxonomies/$taxonomy/terms/slug:$slug
[/\/v1\/apps\/(\w+)$/, '/api/v1/apps/app?appId=:1', 'get'],
[/\/v1\/apps\/(\w+)\/(\w+)\/(\w+)?/, '/api/v1/apps/:2/:3?appId=:1', 'post'],
[/\/v1\/apps\/(\w+)\/(\w+)$/, '/api/v1/apps/:2?appId=:1', 'get'],
// [/\/v1\/app\/(\w+)\/comments\/(\d+)?/, '/api/v1/app/comments?appId=:1&id=:2', 'get'],
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/replies?/, '/api/v1/app/posts/replies?appId=:1&id=:2', 'get'],
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/(\w+)\/mine\/(\w+)?/, '/api/v1/app/posts/:3/mine?appId=:1&id=:2&action=:4', 'get, post'],
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/(\w+)\/new?/, '/api/v1/app/posts/:3/new?appId=:1&id=:2', 'post'],
// [/\/v1\/app\/(\w+)\/me\/likes?/, '/api/v1/app/me/likes?appId=:1', 'get'],
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/likes?/, '/api/v1/app/posts/likes?appId=:1&id=:2', 'get'],
// [/\/v1\/app\/(\w+)\/posts\/(\d+)\/(\w+)\/(\w+)?/, '/api/v1/app/posts/:4?appId=:1&id=:3&action=:5', 'rest'],
[/\/v1\/org\/(\d+)(?:\/(subdomain_validation|signin|signout))?/, '/api/v1/org/public?orgId=:1&action=:2', 'rest'],
[/\/v1\/org\/(\w+)\/(\w+)(?:\/(\d+))?/, '/api/v1/org/:2?appId=:1&id=:3', 'rest'],
// [/\/v1\/app\/create?/, '/api/v1/app/public?action=create', 'rest'],
// [/\/v1\/app\/(\w+)\/auth\/(\w+)\/?/, '/api/v1/app/auth?appId=:1&action=:2', 'rest'],
// [/\/v1\/app\/(\w+)\/(wxlogin|signin|signout)\/?/, '/api/v1/app/public?appId=:1&action=:2', 'rest'],
// 分类方法 api
// [/\/v1\/app\/(\w+)\/taxonomy(?:\/(\w+))?/, '/api/v1/app/taxonomy?appId=:1&type=:2', 'rest'],
// [/\/v1\/app\/(\w+)\/posts(?:\/(\w+))?/, '/api/v1/app/posts?appId=:1&format=:2', 'rest'],
// [/\/v1\/app\/(\w+)\/(\w+)(?:\/(\d+))?/, '/api/v1/app/:2?appId=:1&id=:3', 'rest'],
// [/\/v1\/app\/(\w+)?/, '/api/v1/app/public?appId=:1', 'rest'],
// verify_code,request_code other public action
[/\/v1\/file?/, '/api/v1/file', 'rest'],
[/\/v1(?:\/(\w+))?/, '/api/v1/public?action=:1', 'rest'],
]
|
$(function() {
var firstRunResults = true;
var results = {};
$("#navBar a").click(function() {
var contentKey = $(this).attr("data-contentkey");
var contentPath = "ui/pages/" + contentKey + "Content.html";
$("#home .ui-content").load(contentPath, function() {
if (contentKey === "huntMate") {
if (firstRunResults) {
$.mobile.loading("show", {
text: "Matching...",
textVisible: true,
theme: 'z',
html: ""
});
setTimeout(function() {
$.ajax({
type: "GET",
dataType: "JSON",
url: "ui/mockupdata/recommendedResults.json",
success: function(data) {
firstRunResults = false;
results = data;
var content = $.render["recommendedResults"](data);
$("#roommateList ul").html(content);
$.mobile.loading("hide");
}
});
}, 2000);
} else {
var content = $.render["recommendedResults"](results);
$("#roommateList ul").html(content);
}
} else if (contentKey === "home") {
var totalHeight = $("#statistic").height();
var navHeight = $("#navBar").height();
var unitHeight = (totalHeight - navHeight) / 3;
$("#statistic > div").css({
height: unitHeight + "px"
});
}
});
});
$("#home").on("click", "a.headRight", function() {
var contentKey = $(this).attr("data-contentkey");
if (contentKey !== "save") {
var contentPath = "ui/pages/" + contentKey + "Content.html";
$("#home .ui-content").load(contentPath, function() {
if (contentKey === "huntMate") {
var content = $.render["recommendedResults"](results);
$("#roommateList ul").html(content);
}
});
if (contentKey === "huntMateTag") {
$("#footerInfo").hide();
} else {
$("#footerInfo").show();
}
} else {
$.mobile.loading("show", {
text: "Matching...",
textVisible: true,
theme: 'z',
html: ""
});
setTimeout(function() {
//fetch result by tags
var contentPath = "ui/pages/huntMateContent.html";
$("#home .ui-content").load(contentPath, function() {
$.ajax({
type: "GET",
dataType: "JSON",
url: "ui/mockupdata/recommendedResults2.json",
success: function(data) {
results = data;
var content = $.render["recommendedResults"](data);
$("#roommateList ul").html(content);
$.mobile.loading("hide");
$("#footerInfo").show();
}
});
});
}, 2000);
}
});
$("#home").on("click", ".tagAddBtn", function() {
var key = $(this).attr("data-key");
if (key === "room") {
$("#roomTags").toggleClass("selected", true);
$("#mateTags").toggleClass("selected", false);
} else {
$("#roomTags").toggleClass("selected", false);
$("#mateTags").toggleClass("selected", true);
}
$("#tagAddField").animate({
bottom: "0px"
}).data("key", key);
$("#tagAddField input").focus();
});
$("#home").on("click", "#addTagBtn", function() {
var key = $("#tagAddField").data("key");
var tag = $("#tagInput").val();
if (tag === "") {
return;
}
var ele = $("<span/>");
ele.text(tag);
if (key === "room") {
$("#roomTags").append(ele);
} else {
$("#mateTags").append(ele);
}
$("#tagInput").val("");
});
$("#home").on("click", "span.pre", function(event) {
//change the last element position to the fisrt
var parent = $(this).parents(".roommate")[0] || $(this).parents(".recommended")[0];
var container = $(parent).find(".list");
container.find("li:last").prependTo(container);
});
$("#home").on("click", "span.next", function(event) {
//change the last element position to the last
var parent = $(this).parents(".roommate")[0] || $(this).parents(".recommended")[0];
var container = $(parent).find(".list");
container.find("li:first").appendTo(container);
});
$("#home").on("click", ".likeBtn", function() {
$(this).toggleClass("selected");
var selected = $(this).hasClass("selected");
var parent = $(this).parents(".like-number");
if (parent) {
var val = +parent.find("span").text();
selected && parent.find("span").text(val + 1);
!selected && parent.find("span").text(val - 1);
}
});
//for detail
$("#home").on("click", ".housePhoto", function() {
var contentPath = "ui/pages/houseDetailContent.html";
$("#home .ui-content").load(contentPath, function() {
//fetch comments
$.ajax({
url: "ui/mockupdata/resultDetail.json",
type: "GET",
dataType: "JSON",
success: function(data) {
var content = $.render["resultDetail"](data);
$("#roommateList ul").html(content);
}
})
});
});
});
|
/*
* Copyright (c) 2015 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* eslint camelcase: 0, no-var: 0 */
/* eslint-env node */
"use strict";
module.exports = function(grunt) {
require("load-grunt-tasks")(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
babel: {
dist: {
files: {
"lib/<%= pkg.name %>.js": "src/<%= pkg.name %>.js",
},
},
},
eslint: {
target: ["src/<%= pkg.name %>.js"],
},
mochacli: {
options: {
require: ["should"],
files: "test/*.js",
compilers: ["js:babel/register"],
},
spec: {
options: {
reporter: "spec",
},
},
},
});
grunt.registerTask("default", ["babel"]);
grunt.registerTask("build", ["babel"]);
grunt.registerTask("test", ["mochacli:spec"]);
};
|
import React, { Component } from 'react';
import Data from "./Data";
import Dashboard from "./Dashboard";
import RetailAnalysis from "./RetailAnalysis";
import {Container, TabContent, TabPane, Nav, NavItem, NavLink} from 'reactstrap';
import classnames from 'classnames';
class Header extends Component {
constructor(props){
super(props);
this.changeTab = this.changeTab.bind(this);
this.state= {
activeTab: "Dashboard",
};
}
changeTab(tab){
if (this.state.activeTab !== tab){
this.setState({
activeTab: tab
})
}
}
render() {
return (
<div style={{backgroundColor: "#f2f2f2"}}>
<Container classname="header" fluid style={{backgroundColor: '#e6e6e6', position: "absolute", top:0, bottom:"90%", left:0, right:0}}>
<Nav tabs>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === 'Dashboard' })}
onClick={() => { this.changeTab('Dashboard'); }}>
Dashboard
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === 'Data' })}
onClick={() => { this.changeTab('Data'); }}>
Data
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === 'RetailAnalysis' })}
onClick={() => { this.changeTab('RetailAnalysis'); }}>
Retail Analysis
</NavLink>
</NavItem>
</Nav>
<TabContent activeTab={this.state.activeTab}>
<TabPane tabId = "Dashboard">
<Dashboard/>
</TabPane>
<TabPane tabId = "Data">
<Data/>
</TabPane>
<TabPane tabId = "RetailAnalysis">
<RetailAnalysis/>
</TabPane>
</TabContent>
</Container>
</div>
)}
}
export default Header;
|
var metricsCellTmpl = '<div class="ui-grid-cell-contents"><div class="status-block {{row.entity.metrics.class}}"><div class="progress-bar" style="width: {{row.entity.metrics.progress}}%"></div></div></div>';
var buildCellTmpl = '<div class="ui-grid-cell-contents"><div class="status-block {{row.entity.build.class}}"><div class="progress-bar" style="width: {{row.entity.build.progress}}%"></div></div></div>';
var utCellTmpl = '<div class="ui-grid-cell-contents"><div class="status-block {{row.entity.ut.class}}"><div class="progress-bar" style="width: {{row.entity.ut.progress}}%"></div></div></div>';
var ftCellTmpl = '<div class="ui-grid-cell-contents"><div class="status-block {{row.entity.ft.class}}"><div class="progress-bar" style="width: {{row.entity.ft.progress}}%"></div></div></div>';
var changeListCellTmpl = '<div class="ui-grid-cell-contents"><div class="build-type-icon {{row.entity.req_type}}"></div><span class="build-type-label">{{row.entity.req_name}}</span>';
angular.module('angularApp').controller('GridCtrl',
['$scope', '$http', '$log', '$templateCache', 'GridDataService', 'uiGridConstants', '$uibModal',
function ($scope, $http, $log, $templateCache, GridDataService, uiGridConstants, $uibModal) {
'use strict';
$templateCache.put('ui-grid/expandableRow',
"<div ui-grid-expandable-row ng-if=\"expandableRow.shouldRenderExpand()\" class=\"expandableRow\" ng-class=\"[row.entity.stateInfo.type]\" style=\"float:left; margin-top: 0px; margin-bottom: 1px\" ng-style=\"{width: (grid.renderContainers.body.getCanvasWidth()) + 'px', height: row.expandedRowHeight + 'px'}\"></div>"
);
$templateCache.put('ui-grid/uiGridViewport',
"<div role=\"rowgroup\" class=\"ui-grid-viewport\" ng-style=\"colContainer.getViewportStyle()\"><!-- tbody --><div class=\"ui-grid-canvas\"><div ng-repeat=\"(rowRenderIndex, row) in rowContainer.renderedRows track by $index\" class=\"ui-grid-row\" ng-class=\"{'row-expanded': row.isExpanded}\" ng-style=\"Viewport.rowStyle(rowRenderIndex)\"><div role=\"row\" ui-grid-row=\"row\" row-render-index=\"rowRenderIndex\"></div></div></div></div>"
);
$scope.gridOptions = {
enableSorting: false,
enableColumnMenus: false,
expandableRowTemplate: 'views/rowexpandtmpl.html',
expandableRowHeight: 210,
selectionRowHeaderWidth: 35,
enableExpandableRowHeader: false,
enableMinHeightCheck: false,
enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
enableVerticalScrollbar : uiGridConstants.scrollbars.NEVER,
rowHeight: 45,
onRegisterApi: function (gridApi){
$scope.gridApi = gridApi;
},
appScopeProvider: {
onClick : function(grid, row) {
grid.api.expandable.toggleRowExpansion(row.entity);
}
},
rowTemplate: "<div ng-click=\"grid.appScope.onClick(grid, row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"[{ 'ui-grid-row-header-cell': col.isRowHeader, 'row-expanded': row.isExpanded }, row.entity.stateInfo.type]\" ui-grid-cell ></div></div>"
};
$scope.$on('metrics_box_clicked', function(e) {
e.stopPropagation();
var row = e.targetScope.row;
$uibModal.open({
animation: true,
templateUrl: 'views/detailsviewmodaltmpl.html',
controller: 'DetailViewCtrl',
resolve: {
data: function(){
return {
box: 'Metrics',
row: row
};
}
}
});
});
$scope.$on('build_box_clicked', function(e) {
e.stopPropagation();
var row = e.targetScope.row;
$uibModal.open({
animation: true,
templateUrl: 'views/detailsviewmodaltmpl.html',
controller: 'DetailViewCtrl',
resolve: {
data: function(){
return {
box: 'Build',
row: row
};
}
}
});
});
$scope.$on('ut_box_clicked', function(e) {
e.stopPropagation();
var row = e.targetScope.row;
$uibModal.open({
animation: true,
templateUrl: 'views/detailsviewmodaltmpl.html',
controller: 'DetailViewCtrl',
resolve: {
data: function(){
return {
box: 'Unit Test',
row: row
};
}
}
});
});
$scope.$on('ft_box_clicked', function(e) {
e.stopPropagation();
var row = e.targetScope.row;
$uibModal.open({
animation: true,
templateUrl: 'views/detailsviewmodaltmpl.html',
controller: 'DetailViewCtrl',
resolve: {
data: function(){
return {
box: 'Functional Test',
row: row
};
}
}
});
});
$scope.gridOptions.columnDefs = [
{
name: 'Changelist / Build',
field: 'req_name',
cellTemplate: changeListCellTmpl,
cellClass: 'req-name-cell',
width: 200
},
{
name: 'Owner',
field: 'ownerName'
},
{
name: 'Time Started',
field: 'time_started',
type: 'date',
cellClass: 'time-started-cell',
cellFilter: 'date:"MM/dd/yyyy HH:mma"',
width:200
},
{
name: 'State',
field: 'stateName',
cellClass: 'state-cell'
},
{
name: 'Metrics',
field: 'metrics',
width: 100,
cellTemplate: metricsCellTmpl
},
{
name: 'Build',
field: 'build',
width: 100,
cellTemplate: buildCellTmpl
},
{
name: 'Unit Test',
field: 'ut',
width: 100,
cellTemplate: utCellTmpl
},
{
name: 'Functional Test',
field: 'ft',
width: 150,
cellTemplate: ftCellTmpl
}
];
GridDataService.getData().then( function( res ){
$scope.gridOptions.data = res.data;
});
}]);
|
/*
* File: app/view/StoreAreaPanel.js
*
* This file was generated by Sencha Architect version 3.2.0.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Ext JS 4.2.x library, under independent license.
* License of Sencha Architect does not include license for Ext JS 4.2.x. For more
* details see http://www.sencha.com/license or contact license@sencha.com.
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('platform.system.view.StoreAreaPanel', {
extend: 'Ext.panel.Panel',
requires: [
'Ext.toolbar.Toolbar',
'Ext.button.Button',
'Ext.tree.Panel',
'Ext.tree.View',
'Ext.tree.Column'
],
layout: 'border',
title: '库房区域',
initComponent: function() {
var me = this;
Ext.applyIf(me, {
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'button',
iconCls: 'icon-refresh',
text: '刷新',
listeners: {
click: {
fn: me.onRefreshClick,
scope: me
}
}
},
{
xtype: 'button',
iconCls: 'icon-add',
text: '新增',
listeners: {
click: {
fn: me.onAddClick,
scope: me
},
afterrender: {
fn: me.onAddAfterRender,
scope: me
}
}
},
{
xtype: 'button',
iconCls: 'icon-edit',
text: '修改',
listeners: {
click: {
fn: me.onEditClick,
scope: me
},
afterrender: {
fn: me.onEditAfterRender,
scope: me
}
}
},
{
xtype: 'button',
iconCls: 'icon-del',
text: '删除',
listeners: {
click: {
fn: me.onDelClick,
scope: me
},
afterrender: {
fn: me.onDelAfterRender,
scope: me
}
}
}
]
}
],
items: [
{
xtype: 'treepanel',
region: 'center',
border: false,
title: '库房区域树',
forceFit: true,
rootVisible: false,
viewConfig: {
},
columns: [
{
xtype: 'treecolumn',
dataIndex: 'name',
text: '区域名称'
},
{
xtype: 'gridcolumn',
dataIndex: 'code',
text: '区域编码'
},
{
xtype: 'gridcolumn',
dataIndex: 'memo',
text: '备注'
}
],
listeners: {
afterrender: {
fn: me.onTreePanelAfterRender,
single: true,
scope: me
},
itemclick: {
fn: me.onTreepanelItemClick,
scope: me
}
}
}
]
});
me.callParent(arguments);
},
onRefreshClick: function(button, e, eOpts) {
this.loadTreeGrid();
},
onAddClick: function(button, e, eOpts) {
this.showForm('');
},
onAddAfterRender: function(component, eOpts) {
Common.hidden({params : {url:'/store/area/save'},component:component});
},
onEditClick: function(button, e, eOpts) {
var me = this.treeGrid;
var selected = me.getSelectionModel().selected;
if(selected.items.length >1)
{
Common.setLoading({comp:me,msg:'只允许选择一个机构进行修改!'});
return;
}
else
{
var record = selected.items[0];
if(!Ext.isEmpty(record))
{
this.showForm(record.data.id);
}
else
{
Common.setLoading({comp:me,msg:'请选择要修改的机构!'});
}
}
},
onEditAfterRender: function(component, eOpts) {
Common.hidden({params : {url:'/store/area/save'},component:component});
},
onDelClick: function(button, e, eOpts) {
//Common.deleteSelectionIds(this.treeGrid,ctxp+'/system/organization/remove');
try{
var me = this;
var selected = me.treeGrid.getSelectionModel().selected;
var selecteditems = selected.items;
if (selecteditems.length === 0)
{
Ext.Msg.show(
{
title : "操作提示",
msg : "请选择要删除的区域!",
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
return;
}
var ids = [];
Ext.each(selecteditems, function()
{
var nd = this;
ids.push(nd.data.id);
});
Ext.Msg.confirm("确认提示", "确定要删除选中的区域吗?", function(button)
{
if (button == "yes")
{
try
{
Common.ajax({
component : me.treeGrid,
params : {
'id' : ids.join(",")
},
message : '正在删除选中的区域...',
url : ctxp+'/store/area/remove',
callback : function(result)
{
me.loadTreeGrid();
//me.expandSelected();
Common.setLoading({comp:me,msg:'区域删除成功!'});
}
});
}
catch (error)
{
Common.show({title:'操作提示',html:error.toString()});
}
}
});
}
catch (error)
{
Common.show({title:'操作提示',html:error.toString()});
}
},
onDelAfterRender: function(component, eOpts) {
Common.hidden({params : {url:'/store/area/remove'},component:component});
},
onTreePanelAfterRender: function(component, eOpts) {
this.treeGrid = component;
try{
this.loadTreeGrid();}
catch(e){
alert(e.toString());
}
},
onTreepanelItemClick: function(dataview, record, item, index, e, eOpts) {
Common.onTreeChildNodesChecked(dataview.node,false);
record.set('checked', true);
var items = this.treeGrid.getSelectionModel().selected.items;
if(items.length > 0) {
this.selectedParentNode = items[0].parentNode;
}else{
this.selectedParentNode = me.treeGrid.getRootNode();
}
},
loadTreeGrid: function() {
var me = this;
me.expandNode = true;
Common.bindTree({
treePanel:me.treeGrid,
url:ctxp + '/store/area/list',
pid:'',
fields:['id','sort','code','name','levelCode','memo'],
onload:function onload(treestore, node, records, successful, eOpts){
if(records.length>0 && me.expandNode){
Ext.defer(function(){me.treeGrid.expandNode(records[0]);},100);
me.expandNode = false;
}
}
});
},
showForm: function(id) {
try
{
var me = this;
var formwin = Ext.create('platform.system.view.StoreAreaWindow');
formwin.addListener('close', function(panel,opts)
{
me.loadTreeGrid();
//me.expandSelected();
});
formwin.show();
formwin.loadForm(id);
}
catch(error)
{
Common.show({title:'信息提示',html:error.toString()});
}
},
check: function() {
//用于防止重复提交
excel_flag ++;
if(excel_flag > 30)
{
//清空定时器
window.clearInterval(win_check);
//启用按钮
exportExcelBtn.enable();
}
Ext.Ajax.request(
{
url : 'check',
success : function (response, result)
{
if(response.responseText=="true")
{
//清空定时器
window.clearInterval(win_check);
//启用按钮
exportExcelBtn.enable();
}
}
});
},
expandSelected: function() {
try{
var me = this;
me.treeGrid.getStore().load({
node: me.selectedParentNode,
callback: function ()
{
try{
me.treeGrid.expandNode(me.selectedParentNode);
}catch(Ex){}
}
});
}catch(ee){}
}
}); |
import NivelJudete from './NivelJudete';
export default NivelJudete;
|
const { interfaceUser } = require('./ui');
interfaceUser();
|
import React from 'react'
import PropTypes from 'prop-types'
class List extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
const { title, merchantName, addressdetail, p0, p1 } = this.props
return (
<div>
<h4>{title}</h4>
<ul>
<li>
<span>商户名称:</span>
{merchantName}
</li>
<li>
<span>地址:</span>
{addressdetail}
</li>
<li>
<span>纬度、经度</span>
{p0},{p1}
</li>
</ul>
</div>
)
}
}
List.propTypes = {
merchantName: PropTypes.string,
addressdetail: PropTypes.string,
p0: PropTypes.number,
p1: PropTypes.number
}
export default List |
import React from 'react';
// import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import DatePicker from 'material-ui/DatePicker';
import { Button } from 'reactstrap';
import './index.css';
const DatePickerExampleSimple = () => (
<div>
<DatePicker hintText="Portrait Dialog" />
</div>
);
export class ButtonE extends React.Component {
render() {
return (
<div>
<MuiThemeProvider>
<div>
<div>
<DatePickerExampleSimple />
</div>
<div>
<Button color="danger">Danger!</Button>
</div>
</div>
</MuiThemeProvider>
</div>
);
}
}
export default DatePickerExampleSimple; |
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('db.sqlite3');
db.serialize(() => {
if(process.env.ID <= 0) {
console.log('Invalid argument `ID`')
return false;
}
const stmt = db.prepare('UPDATE users SET canceled_at = DATETIME("now", "localtime") WHERE id = ?');
stmt.run(process.env.ID, () => {
console.log('Compelete');
});
stmt.finalize();
});
db.close(); |
"use strict";
const superstatic = require( 'superstatic' );
const connect = require( 'connect' );
const app = connect().use( superstatic() );
app.listen( 8080, function () {
console.log( 'Server started. http://localhost:8080/' );
} );
|
import React, { useState } from 'react';
import axios from 'axios';
import './AddBook.css'
import { ToastContainer, toast } from 'react-toastify';
function AddBook(props){
const url_saveBook = "http://localhost:8080/bookapi/saveBook";
const [book, setBook] = useState({});
/*
const getTitle = (event) => {
event.preventDefault();
// setTitle(event.target.value)
setBook({...book, title: event.target.value})
}
const getAuthor = (event) => {
event.preventDefault();
// setAuthor(event.target.value)
setBook({...book, author: event.target.value})
}
const getDescription = (event) => {
event.preventDefault();
// setDescription(event.target.value)
setBook({...book, description: event.target.value})
}
const getPrice = (event) => {
event.preventDefault();
setBook({...book, price: event.target.value})
}
*/
const addNewBook = async (book) => {
try {
console.log("addNewBook: ", book);
let response = await axios.post(url_saveBook, book);
if(response.status == 200){
toast.success("Book added successfully")
}else{
toast.error("Oops something went wrong")
console.error("Oops something went wrong", response.statusText," ", response.status);
}
} catch (error) {
toast.error("Oops something went wrong - ERROR")
console.error("ERROR: ", error);
}
}
const addBookMethod = () => {
console.log("Book: ", book);
addNewBook(book);
}
return (
<div className="AddBook">
<ToastContainer />
<div className="container register">
<div className="row">
<div className="col-md-3 register-left">
<img src="https://image.ibb.co/n7oTvU/logo_white.png" alt="" />
<h3>Welcome</h3>
<p>You are 30 seconds away from publishing your own book!</p>
<input type="submit" name="" value="Login" /><br />
</div>
<div className="col-md-9 register-right">
<ul className="nav nav-tabs nav-justified" id="myTab" role="tablist">
<li className="nav-item">
<a className="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Enroll</a>
</li>
<li className="nav-item">
<a className="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Update</a>
</li>
</ul>
<div className="tab-content" id="myTabContent">
<div className="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<h3 className="register-heading">Enroll New Book</h3>
<div className="row register-form">
<div className="col-md-6">
<div className="form-group">
<input type="text" className="form-control"
placeholder="Book Title *"
onChange={ (event) => {
event.preventDefault();
setBook({...book, title: event.target.value})
}} />
</div>
<div className="form-group">
<input type="text" className="form-control" placeholder="Author Name *"
onChange={ (event) => {
event.preventDefault();
setBook({...book, author: event.target.value})
}} />
</div>
<div className="form-group">
<input type="text" className="form-control" placeholder="Description *"
onChange={ (event) => {
event.preventDefault();
setBook({...book, description: event.target.value})
}} />
</div>
<div className="form-group">
<input type="text" className="form-control" placeholder="Price *"
onChange={ (event) => {
event.preventDefault();
setBook({...book, price: event.target.value})
}} />
</div>
<div className="form-group">
<input type="submit" className="btnRegister" value="Register Book"
onClick={addBookMethod}/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default AddBook; |
const mysql = require('mysql');
const CrudProvider = require('./crudProvider');
const DataProvider = {};
let database = mysql.createConnection({
host: 'oege.ie.hva.nl',
user: 'jansenj031',
password: 'kKy+tS.GzMIP6e',
database: 'zjansenj031'
});
database.connect((err) => {
if (err) {
console.error('Error while connecting to database: ' + err.stack);
return;
}
console.log('Successfully connected to database as: ', database.threadId);
});
DataProvider.createToken = function(callback) {
console.log('DataProvider.createToken');
let token = new Date().getTime().toString();
token = new Buffer(token).toString('base64');
callback(token);
};
DataProvider.authenticate = function(hash, callback, error) {
console.log('DataProvider.authenticate', hash);
let query = 'SELECT ID, permissionLvl FROM user WHERE hash =' + database.escape(hash);
database.query('SELECT * FROM user', (err, result, fields) => { console.log(result); });
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
DataProvider.createToken((token) => {
console.log('Created token: ', token);
console.log('Result: ', result);
let response = {'data': result, '_token': token};
callback(JSON.stringify(response));
});
});
};
DataProvider.getProfile = function(userId, callback, error) {
console.log('DataProvider.getProfile', userId);
console.log('userId', userId);
let query = 'SELECT * FROM user WHERE ID =' + database.escape(userId);
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
result = JSON.stringify(result);
callback(result);
});
};
DataProvider.register = function(data, callback, error) {
console.log('DataProvider.register', data.firstName + ' ' + data.lastName);
let query = 'INSERT INTO user (firstName, lastName, email, gender, dateOfBirth, description, permissionLvl, hash) ' +
'VALUES (' +
'"' + data.firstName + '",' +
'"' + data.lastName + '",' +
'"' + data.email + '",' +
'"' + data.gender + '",' +
'"' + data.dateOfBirth + '",' +
'"' + data.description + '",' +
'"' + data.permissionLvl + '",' +
'"' + data._hash + '"'
+ ')';
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error();
}
DataProvider.createToken((token) => {
console.log('Created token: ', token);
console.log('Result: ', result);
let response = {'data': result, '_token': token};
callback(JSON.stringify(response));
});
});
};
DataProvider.changeAccountSettings = function(data, callback, error) {
console.log('DataProvider.changeAccountSettings');
let query = 'UPDATE user SET hash=' + database.escape(data.newHash) + ' WHERE hash =' + database.escape(data.hash);
// Validate existing hash before updating it to the new request
database.query('SELECT hash FROM user WHERE hash =' + database.escape(data.hash), (err, result) => {
let confirmedHash = result[0];
console.log('hash result:', confirmedHash);
if (!confirmedHash || confirmedHash.hash !== data.hash) return error('The current password you submitted is wrong');
});
// Update old email/pass hash with new one
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
callback('Account settings were successfully changed');
});
};
DataProvider.deleteAccount = function(userId, callback, error) {
console.log('DataProvider.deleteAccount', userId);
let query = 'DELETE FROM user WHERE ID =' + database.escape(userId);
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
callback('Your account has been deleted');
});
};
DataProvider.getChat = function(userId, partnerId, callback, error) {
console.log('DataProvider.getChat', 'userId: ' + userId + ', partnerId: ' + partnerId);
let query = 'SELECT * FROM message WHERE userID =' + database.escape(userId) + ' OR userID=' + database.escape(partnerId)
+ 'AND participant= ' + database.escape(userId) + ' OR participant=' + database.escape(partnerId);
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
console.log('result: ', result);
callback(JSON.stringify(result));
});
};
DataProvider.sendMessage = function(data, callback, error) {
console.log('DataProvider.sendMessage', data);
let query = 'INSERT INTO message (userID, participant, message, creationDate) VALUES(' +
database.escape(data.userId) + ', ' +
database.escape(data.partnerId) + ', ' +
database.escape(data.text) + ', ' +
database.escape(data.creationDate) + ')';
database.query(query, (err, result, fields) => {
if (err) {
console.log(err);
return error(err);
}
callback('Message was successfully changed');
});
}
module.exports = DataProvider; |
import { gql } from "apollo-server";
export const typeDef = gql`
extend type Query {
getAllNotifications: Notification
getNotifications(user: String!): [Notification]
}
extend type Mutation {
newNotifiaction(user: String!, notification: NotiInput): Notification
}
type Notification {
user: String!
notifications: [Notifications]
}
type Notifications {
data: Date!
title: String!
message: String!
target: String!
}
input NotiInput {
title: String!
message: String!
target: String!
}
`;
|
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('db.sqlite3');
module.exports = (parkingId) => {
return new Promise((resolve, reject) => {
if(!parkingId) {
reject({ code: 'missing_argument' });
}
else {
db.serialize(() => {
const stmt = db.prepare('SELECT is_parkable FROM parkings WHERE id = ?');
stmt.get(parkingId, (err, row) => {
resolve(row.is_parkable === 'true' ? true : false);
});
stmt.finalize();
});
}
});
} |
sap.ui.define([
"sap/ui/core/util/MockServer"
], function(MockServer){
return {
init: function(){
var oMockServer= new MockServer({
rootUri: "http://services.odata.org/Northwind/Northwind.svc/"
});
var _sMetadataPath = "sap/ui/demo/misha/localService/metadata";
var sMetadataUrl = jQuery.sap.getModulePath(_sMetadataPath, ".xml");
oMockServer.simulate(sMetadataUrl, {
sMockdataBaseUrl: "../localService/mockdata",
bGenerateMissingMockData: false
});
oMockServer.start();
console.log("Работает мок сервер");
jQuery.sap.log.info("Работает мок сервер");
}
}
})
|
import { TimelineMax } from "gsap";
import { loader, Rectangle } from "pixi.js";
import Button from "../../PixiUtility/Button";
export default class PlayButton extends Button {
constructor(onClickCallback) {
super(loader.resources.play_button.texture, onClickCallback);
}
onClick() {
const timeline = new TimelineMax();
timeline.to(this.scale, 0.4, { x: 0.9, y: 0.9 });
timeline.to(this.scale, 0.2, { x: 1.0, y: 1.0 });
timeline.call(this.onClickCallback);
timeline.play();
}
createHitArea() {
return new Rectangle(-32, -32, 64, 64);
}
} |
import React, { Component } from "react";
import styles from "./Browse.scss";
export default class Browse extends Component {
render() {
return (
<div className="browse-wrapper">
<p className="title">Browse By Genres <span id="show-more"><a href="#">Show more</a></span></p>
<div className="browse">
<div className="col">
<p>Action</p>
<p>Adventure</p>
<p>Police</p>
</div>
<div className="col">
<p>Demons</p>
<p>Drama</p>
<p>Comedy</p>
<p>Fantasy</p>
</div>
</div>
</div>
);
}
}
|
//Change the distance dropdown to default 100 miles, not Countrywide
$('.distance-dropdown option#radius_4').prop('selected', true);
|
import {FETCH_LESSONS_TEACHER, FETCH_LESSONS_TEACHER_SUCCESS, FETCH_LESSONS_TEACHER_FAIL} from "../actions/types";
const defaultState = {
lessons: [],
loading: true,
error: null,
}
export default function(state = defaultState, action) {
switch(action.type) {
case FETCH_LESSONS_TEACHER:
return {
...state,
loading: true,
error: null,
}
case FETCH_LESSONS_TEACHER_SUCCESS:
return {
...state,
loading: false,
lessons: action.payload,
}
case FETCH_LESSONS_TEACHER_FAIL:
return {
...state,
loading: true,
error: action.error,
lessons: {}
}
default:
return state;
}
} |
/**
* Created by natete on 02/11/15.
*/
(function () {
'use strict';
angular.module('corestudioApp.client')
.controller('ClientController', ClientController);
ClientController.$inject = ['Client'];
function ClientController(Client) {
var vm = this;
vm.data = {};
vm.search = search;
vm.isConsumedPass = isConsumedPass;
function search(tableState) {
var pagination = tableState.pagination;
var pageRequest = {};
pageRequest.page = pagination.start ? Math.floor((pagination.start + 1) / pagination.number) : 0;
pageRequest.size = pagination.number || 10;
pageRequest.sortBy = tableState.sort.predicate;
pageRequest.direction = tableState.sort.reverse ? 'DESC' : 'ASC';
Client.query(pageRequest, function (responseData) {
vm.data = responseData.content;
tableState.pagination.numberOfPages = responseData.totalPages;
});
}
function isConsumedPass(lastDate) {
return new Date(lastDate) < new Date();
}
}
})();
|
import React, { Component } from 'react';
class LeaveRecords extends Component {
render() {
return(
<div className="container-fluid">
<main className="adjust-top">
<h4 className="text-size">Leave Records</h4>
<div className="card shadow p-3 mt-3 mb-5">
<div className="table-responsive">
<table className="table table-bordered table-hover table-sm table-striped" id="myTable">
<thead className="thead-light">
<tr>
<th>Full Name</th>
<th>Leave Type</th>
<th>Leave Duration</th>
<th>Leave Start Date</th>
<th>Leave End Date</th>
<th>Reason</th>
<th>Approved By</th>
<th>Approved Date</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</main>
</div>
)
}
}
export default LeaveRecords; |
import React from 'react';
const MainPage = React.lazy(() => import('./views/pages/MainPage'));
const Film = React.lazy(() => import('./views/pages/Film'));
const LoginPage = React.lazy(() => import('./views/pages/LoginPage'));
const RegisterPage = React.lazy(() => import('./views/pages/RegisterPage'));
const ResetPassPage = React.lazy(() => import('./views/pages/ResetPassPage'));
const ResendEmailPage = React.lazy(() => import('./views/pages/ResendEmailPage'));
const MoviePage = React.lazy(() => import('./views/pages/MoviePage'));
const MovieNowPlayingPage = React.lazy(() => import('./views/pages/MovieNowPlayingPage'));
const MovieUpcomingPage = React.lazy(() => import('./views/pages/MovieUpcomingPage'));
const MovieTopRatedPage = React.lazy(() => import('./views/pages/MovieTopRatedPage'));
const TvPage = React.lazy(() => import('./views/pages/TvPage'));
const TvTopRatedPage = React.lazy(() => import('./views/pages/TvTopRatedPage'));
const TvAiringPage = React.lazy(() => import('./views/pages/TvAiringPage'));
const OnTvPage = React.lazy(() => import('./views/pages/OnTvPage'));
const Person = React.lazy(() => import('./views/pages/Person'));
const PersonDetailPage = React.lazy(() => import('./views/pages/PersonDetailPage'));
const SearchPage = React.lazy(() => import('./views/pages/SearchPage'));
const routes = [
{ path: '/', exact: true, name: 'MainPage', component: MainPage },
{ path: '/person/details/:id', exact: true, name: 'PersonPage', component: PersonDetailPage },
{ path: '/:type/details/:id', exact: true, name: 'FilmPage', component: Film },
{ path: '/login', exact: true, name: 'Login', component: LoginPage },
{ path: '/register', exact: true, name: 'Register', component: RegisterPage },
{ path: '/resetpass', exact: true, name: 'ResetPass', component: ResetPassPage },
{ path: '/resendemail', exact: true, name: 'ResendEmail', component: ResendEmailPage },
{ path: '/movie', exact: true, name: 'Movie', component: MoviePage },
{ path: '/movie/now-playing', exact: true, name: 'MovieNowPlaying', component: MovieNowPlayingPage },
{ path: '/movie/upcoming', exact: true, name: 'MovieUpcoming', component: MovieUpcomingPage },
{ path: '/movie/toprated', exact: true, name: 'MovieTopRated', component: MovieTopRatedPage },
{ path: '/tv', exact: true, name: 'Tv', component: TvPage },
{ path: '/tv/airingtoday', exact: true, name: 'TvAiring', component: TvAiringPage },
{ path: '/tv/toprated', exact: true, name: 'TvTopRated', component: TvTopRatedPage },
{ path: '/tv/ontv', exact: true, name: 'OnTv', component: OnTvPage },
{ path: '/person', exact: true, name: 'Person', component: Person },
{ path: '/search/:qry', exact: true, name: 'SearchPage', component: SearchPage },
];
export default routes;
|
const videoElement = document.getElementById('video');
const button = document.getElementById('button');
// Prompt to select media stream, pass to video element, then play
async function selectMediaStream() {
try {
//will hold our mediaStream data, we are waiting until the user has selected which screen or window they want to share
const mediaStream = await navigator.mediaDevices.getDisplayMedia();
//we are passing the mediaStream to the videoElement as its source object
videoElement.srcObject = mediaStream;
//when the video has loaded its metadata, it will call the function and play it
videoElement.onloadedmetadata = () => {
videoElement.play();
}
} catch (error) {
// Catch Error Here
}
}
button.addEventListener('click', async () => {
// Disable the button
button.disabled = true;
//Start Picture in Picture
await videoElement.requestPictureInPicture();
//Reset the button
button.disabled = false;
});
//On Load
selectMediaStream(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.