text stringlengths 7 3.69M |
|---|
import React, { useState, useEffect } from "react";
import MUIDataTable from "mui-datatables";
import axios from "axios";
import { token, API_SERVER } from "../../../helper/variable";
import {
Button,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
Col,
Input,
} from "reactstrap";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import CustomToolBar from "./CustomToolBar";
import { Link } from "react-router-dom";
export default function Index() {
const [data, setData] = useState([]);
const [dataProduct, setDataProduct] = useState([]);
const [modal, setModal] = useState(false);
const [modalEdit, setModalEdit] = useState(false);
const [name, setName] = useState(1);
const [amount, setAmount] = useState(0);
const [month, setMonth] = useState(1);
const [year, setYear] = useState(0);
useEffect(() => {
axios
.get(`${API_SERVER}/penjualan`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
console.log(res.data.data);
setData(res.data.data);
})
.catch((err) => console.log(err));
axios
.get(`${API_SERVER}/products`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
setDataProduct(res.data.data);
})
.catch((err) => console.log(err));
}, []);
const toggle = () => setModal(!modal);
const toggleEdit = () => setModalEdit(!modalEdit);
const deleteData = (item) => {
axios
.delete(`${API_SERVER}/delete-penjualan/${item}`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
setModal(!modal);
if (res.data.data) {
toast.success("Delete Data Penjualan Success", {
onClose: () => (window.location.href = "/sales"),
autoClose: 2000,
});
} else {
toast.error("Delete Data Penjualan Failed", {
onClose: () => (window.location.href = "/sales"),
autoClose: 2000,
});
}
})
.catch((err) => console.log(err));
};
const EditData = (item) => {
axios
.put(
`${API_SERVER}/update-penjualan/${item}`,
{
product_id: name,
jumlah: parseInt(amount),
bulan: parseInt(month),
tahun: parseInt(year),
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => {
setModalEdit(!modalEdit);
if (res.data.data) {
toast.success("Update Data Penjualan Success", {
onClose: () => (window.location.href = "/sales"),
autoClose: 2000,
});
} else {
toast.error("Update Data Penjualan Failed", {
onClose: () => (window.location.href = "/sales"),
autoClose: 2000,
});
}
})
.catch((err) => console.log(err));
};
const modalDelete = (item) => {
return (
<>
<Modal isOpen={modal} toggle={toggle}>
<ModalHeader toggle={toggle}>Delete Data Penjualan</ModalHeader>
<ModalBody>
Apakah anda yakin akan menghapus data penjualan ini?
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={() => deleteData(item)}>
Submit
</Button>{" "}
<Button color="secondary" onClick={toggle}>
Cancel
</Button>
</ModalFooter>
</Modal>
</>
);
};
const modalEditData = (item) => {
return (
<>
<Modal isOpen={modalEdit} toggle={toggleEdit}>
<ModalHeader toggle={toggleEdit}>Edit Data Penjualan</ModalHeader>
<ModalBody>
<div>
<Col>Nama Produk</Col>
<Col>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
type="select"
>
{dataProduct.map((item, index) => {
return <option value={item.id}>{item.name}</option>;
})}
</Input>
</Col>
</div>
<div>
<Col>Jumlah</Col>
<Col>
<Input
value={amount}
onChange={(e) => setAmount(e.target.value)}
type="number"
/>
</Col>
</div>
<div>
<Col>Bulan</Col>
<Col>
<Input
value={month}
onChange={(e) => setMonth(e.target.value)}
type="select"
>
<option value="1">Januari</option>
<option value="2">Februari</option>
<option value="3">Maret</option>
<option value="4">April</option>
<option value="5">Mei</option>
<option value="6">Juni</option>
<option value="7">Juli</option>
<option value="8">Agustus</option>
<option value="9">September</option>
<option value="10">Oktober</option>
<option value="11">November</option>
<option value="12">Desember</option>
</Input>
</Col>
</div>
<div>
<Col>Tahun</Col>
<Col>
<Input
value={year}
onChange={(e) => setYear(e.target.value)}
type="number"
/>
</Col>
</div>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={() => EditData(item)}>
Submit
</Button>{" "}
<Button color="secondary" onClick={toggleEdit}>
Cancel
</Button>
</ModalFooter>
</Modal>
</>
);
};
const showBulan = (item) => {
let month;
switch (item) {
case 1:
month = "Januari";
break;
case 2:
month = "Februari";
break;
case 3:
month = "Maret";
break;
case 4:
month = "April";
break;
case 5:
month = "Mei";
break;
case 6:
month = "Juni";
break;
case 7:
month = "Juli";
break;
case 8:
month = "Agustus";
break;
case 9:
month = "September";
break;
case 10:
month = "Oktober";
break;
case 11:
month = "November";
break;
case 12:
month = "Desember";
break;
default:
break;
}
return month;
};
const iterateData = () => {
if (data !== undefined || data !== null) {
return data.map((item, index) => {
return [
index + 1,
showBulan(item.bulan),
item.tahun,
item.product.name,
item.jumlah,
<Link to={`/detail-penjualan/${item.id}`}>
<Button size="md" color="success">
<i className="icon-pencil"></i> Edit
</Button>
</Link>,
];
});
}
};
const colums = ["#", "Bulan", "Tahun", "Nama Produk", "Jumlah", "Actions"];
const options = {
search: false,
filterType: "dropdown",
print: false,
download: false,
responsive: "scroll",
rowsPerPage: 100,
selectableRows: false,
rowsPerPageOptions: [10, 25, 50, 100],
customToolbar: () => {
return <CustomToolBar data={dataProduct} />;
},
// customFooter: (rowsPerPage) => {
// return(
// <CustomFooter
// page={page}
// add={buttonAdd}
// substract={buttonSubstract}
// rowsPerPage={rowsPerPage}
// />
// )
// }
};
return (
<div
className="animated fadeIn"
style={{ marginBottom: 30, marginRight: 20 }}
>
<ToastContainer position={toast.POSITION.TOP_CENTER} />
{/* <MuiThemeProvider theme={getMuiTheme()}> */}
<MUIDataTable
title={"Data Penjualan"}
options={options}
columns={colums}
data={iterateData()}
/>
{/* </MuiThemeProvider> */}
</div>
);
}
|
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import {
RadialChart,
} from 'react-vis';
export const TankChart = () => {
const [dataSet, setData] = useState([]);
const GetTanques = async () => {
const { data } = await axios.post(`/GetInventariosByUserKey`, { opc: 1 });
setData(data.data);
}
useEffect(() => {
GetTanques();
}, []);
return (
<>
<div className='gas-container'>
{dataSet.map(elm => {
return (
<RadialChart
data={[{ angle: elm.Porcentaje, color: elm.Color, label: `${elm.Porcentaje}%` }, { angle: elm.Total, color: '#F8F8F8'}]}
width={260}
height={240}
innerRadius={65}
radius={110}
colorType="literal"
labelsRadiusMultiplier={0.98}
labelsStyle={{fontSize: 12, fill: 'white'}}
showLabels
/>
)
})}
</div>
</>
)
} |
import DataType from 'sequelize';
import Model from '../sequelize';
// import { initializeDB } from '../config';
// import Pair from './Pair';
// import User from './User/User';
const Trade = Model.define('Trade', {
id: {
type: DataType.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
price: {
type: DataType.DECIMAL(21, 9),
allowNull: false,
defaultValue: '0.0000',
},
amount: {
type: DataType.DECIMAL(21, 9),
allowNull: false,
defaultValue: '0.0000',
},
sellOrderId: {
type: DataType.INTEGER(11),
unique: 'compositeIndex',
},
buyOrderId: {
type: DataType.INTEGER(11),
unique: 'compositeIndex',
},
});
// export const initialize = () => {
// if (initializeDB) {
// const data = [
// {
// id: 1,
// pairId: 1,
// sellOrderId: 1,
// buyOrderId: 2,
// price: 110,
// amount: 200,
// },
// ];
// Trade.bulkCreate(data, {
// fields: Object.keys(data[0]),
// updateOnDuplicate: 'id',
// include: [Pair, User],
// })
// .then(() => {
// console.warn(`initial rows added to Trade table successfully.`);
// })
// .catch(error => {
// console.warn(
// `problem with adding initial rows to Trade table: `,
// error,
// );
// });
// }
// };
export default Trade;
|
import ShopPage from 'layouts/shopPage'
import ProductList from 'pages/product/productList'
import ProductPage from 'pages/product/productPage'
import AboutPage from 'pages/aboutPage'
const routes = [
{ // Auth Routes
path: '/auth',
redirect: 'auth/sign-in',
component: () => import('layouts/auth'),
children: [{
path: 'sign-in',
name: 'signIn',
component: () => import('pages/auth/sign-in')
}
]
},
{ // Main Routes
path: '/',
component: () => import('layouts/MyLayout.vue'),
children: [
{
path: '',
name: 'dashboard',
component: () => import('pages/Index.vue')
}
]
},
{ // rout for shop
path: '/shop',
component: ShopPage,
children: [
{ // list of product
path: 'catalog-list', // here it is, route /shop/catalog-list
component: ProductList // we reference /pages/product/ProductList.vue imported above
},
{ // single product
path: 'single-product', // here it is, route /shop/single-product
component: ProductPage // we reference /pages/product/productPage.vue imported above
}
]
},
{ // page about user
path: '/about',
name: 'aboutPage',
component: AboutPage
}
]
// Always leave this as last one
if (process.env.MODE !== 'ssr') {
routes.push({
path: '*',
component: () => import('pages/Error404.vue')
})
}
export default routes
|
import {Component} from "react";
const Dialog = class extends Component{
constructor(props){
super(props);
this.state = {
html : props.html
};
}
componentDidUpdate(){
if(this.state.html){
document.querySelector(".shadow").style.display = "block";
}
let domShadow = document.querySelector(".shadow");
domShadow.onclick = () => {
if(this.state.enableClose){
domShadow.style.display = "none";
}
};
}
render(){
return (
<div className="dialog">
{this.state.html}
</div>
);
}
}
Dialog.defaultProps = {
html : ""
};
export default Dialog; |
$(function () {
$('.b-comment__btn').on('click', function (e) {
e.preventDefault();
var d = new Date();
var month = d.getMonth() + 1,
day = d.getDate(),
output = d.getFullYear() + ' ' + (month < 10 ? '0' : '') + month + ' ' + (day < 10 ? '0' : '') + day;
var getText = $('.b-comment__form-text'),
ms = getText.val();
getText.val('');
$('.b-message').append('<div class="l-container"> <div class="b-message__item"> <div class="b-message__item-title"> <span class="b-name">Лилия Семёновна </span><span class="b-date"> ' + output + '</span> </div> <p class="b-message__item-text">' + ms + '</p> </div> </div>');
});
}); |
'use strict';
/**
* Currently used plugins:
* - gulp-lazypipe
* - gulp-sass
* - gulp-autoprefixer
* - gulp-combine-media-queries
* - gulp-minify-css
* - gulp-rename
*/
// ---------------------------------------------------------------------
// Components
// ---------------------------------------------------------------------
var css = function(options, $) {
var apOptions = options.ap || {
browsers: ['last 3 versions', 'Android 3', 'ie 8', 'ie 9']
};
var cmqOptions = options.cmq || {
log: true
};
return $.lazypipe()
.pipe($.autoprefixer, apOptions)
.pipe($.combineMediaQueries, cmqOptions)
();
};
// ---------------------------------------------------------------------
// Export
// ---------------------------------------------------------------------
module.exports = function(options, config, $) {
if (options.useRuby) {
$.sass = require('gulp-ruby-sass');
} else {
$.sass = require('gulp-sass');
}
options = $.merge({
useRuby: false,
ap: {},
cmq: {},
min: {},
name: {}
}, options);
options.sass = options.sass || {};
if (options.useRuby) {
options.sass = $.merge({
loadPath: [
config.src.sass,
config.bowerFolder
],
}, options.sass);
} else {
options.sass = $.merge({
outputStyle: 'expanded',
precision: 4,
sourceMap: false,
includePaths: config.bowerFolder,
}, options.sass);
}
var merged = $.mergeStream(),
$manifest = $.assetBuilder(config.manifest, { paths: config.base });
;
$manifest.forEachDependency('css', function(dep) {
// Prepend absolute paths
for (var i=0; i < dep.globs.length; i++) {
if (dep.globs[i].substring(0, config.base.length) != config.base) {
dep.globs[i] = config.base + dep.globs[i];
}
}
if (options.useRuby) {
var startStream = $.sass(dep.globs, options.sass)
.on('error', $.sass.logError)
;
} else {
var startStream = $.gulp.src(dep.globs, { cwd: config.base })
.pipe($.plumber({
handleError: function(err) {
this.emit('end');
}
}))
.pipe($.sass(options.sass).on('error', $.sass.logError))
;
}
merged.add(startStream
.pipe($.concat(dep.name))
.pipe(css(options, $))
.pipe($.gulp.dest(config.dest.css))
.pipe($.minifyCss())
.pipe($.rename({ suffix: '.min' }))
.pipe($.gulp.dest(config.dest.css))
);
});
return merged;
} |
const express = require('express');
const User = require('../models/user');
const uploadCloud = require('../config/cloudinary.js');
const isEmpty = require('../helpers/helpers');
const router = express.Router();
/* GET Profile page */
router.get('/', (req, res, next) => {
const session = req.session.currentUser;
User.findById(session._id)
.populate('myFriends')
.then((friends) => {
const friendsNames = friends.myFriends;
res.render('profile/profile', { session, friendsNames });
})
.catch(next);
});
/* POST Add friend page */
router.post('/search', (req, res, next) => {
const searchField = req.body.search;
const myfriends = req.session.currentUser.myFriends;
const friendsStrings = [];
myfriends.forEach((friendId) => {
friendsStrings.push(friendId.toString());
});
User.find({ username: searchField })
.then((user) => {
if (isEmpty(user)) {
req.flash('warning', `User ${searchField} doesn't exist`);
res.redirect('/profile');
} else if (user[0].status === false) {
req.flash('warning', `User ${searchField} doesn't exist`);
res.redirect('/profile');
} else if (friendsStrings.includes(user[0]._id.toString())) {
req.flash('warning', `You are already friends with ${user[0].username}`);
res.redirect('/profile');
} else {
res.render('profile/search', { user });
}
})
.catch(next);
});
/* POST Add friend to friend list */
router.post('/', (req, res, next) => {
const friendId = req.body.id;
const userName = req.session.currentUser.username;
User.findOneAndUpdate({ username: userName }, { $push: { myFriends: friendId } })
.then(() => {
req.flash('success', 'Friend added successfully');
res.redirect('/profile');
})
.catch(next);
});
/* POST delete friend from friend list */
router.post('/:id/delete', (req, res, next) => {
const friendId = Object.values(req.params);
const userName = req.session.currentUser.username;
User.findOneAndUpdate({ username: userName }, { $pullAll: { myFriends: friendId } })
.then(() => {
req.flash('success', 'Friend removed sucessfully');
res.redirect('/profile');
})
.catch(next);
});
module.exports = router;
/* POST user profile image */
router.post('/add-profile-photo', uploadCloud.single('photo'), (req, res, next) => {
const userId = req.session.currentUser._id;
const imagePath = req.file.url;
User.findByIdAndUpdate(userId, { imgPath: imagePath }, { new: true })
.then((user) => {
const session = user;
User.findById(session._id)
.populate('myFriends')
.then((friends) => {
const friendsNames = friends.myFriends;
res.render('profile/profile', { session, friendsNames });
})
.catch(next);
})
.catch(next);
});
/* POST user */
router.post('/deleteUser', (req, res, next) => {
const userId = req.session.currentUser._id;
User.findByIdAndDelete(userId)
.then(
req.session.destroy(() => {
// cannot access session here
res.redirect('/');
}),
).catch(next);
});
|
var yellow = function() {
var yellowBg = document.getElementById("background").style.backgroundColor = "yellow";
}
var red = function() {
var redBg = document.getElementById("background").style.backgroundColor = "red";
}
var blue = function() {
var blueBg = document.getElementById("background").style.backgroundColor = "blue";
} |
const express = require('express');
const config = require('./config/server.js');
const app = express();
const helloWorldRoutes = require('./routes/hello.js');
app.use(helloWorldRoutes);
app.listen(config.port, () => console.log(`App listening on port ${config.port}!`));
|
var classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1playground_1_1_play_ground_activity =
[
[ "onCreate", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1playground_1_1_play_ground_activity.html#a0f484216846cf0cc88f2dc0881a80237", null ],
[ "LOG_TAG", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1playground_1_1_play_ground_activity.html#a803db2da5a18156900d4499baa6c5179", null ]
]; |
const React = require('react');
const Rating = require('react-rating');
const DrinkStore = require('../../stores/drink_store');
const DrinkActions = require('../../actions/drink_actions');
const CheckinIndex = require('../checkin/checkin_index');
const DrinkPage = React.createClass({
getInitialState(){
return {drink: {}};
},
componentDidMount(){
window.scrollTo(0,0);
this.drinkListener = DrinkStore.addListener(this._onChange);
DrinkActions.fetchSingleDrink(this.props.params.drinkId);
},
componentWillUnmount(){
this.drinkListener.remove();
},
componentWillReceiveProps(newProps){
window.scrollTo(0,0);
const drink = DrinkStore.find(newProps.params.drinkId);
this.setState({drink: drink});
},
_onChange(){
this.setState({drink: DrinkStore.find(this.props.params.drinkId)});
},
render(){
return(
<div className="drink-img">
<div className="venue-flex">
<div className="venue-sidebar">
<div className="venue-info">
<p className="venue-name">{this.state.drink.name}</p>
<p>{this.state.drink.description}</p>
<Rating className="venue-rating" placeholderRate={parseFloat(this.state.drink.rating)}
fractions={parseInt("10")} empty="fa fa-glass grey fa-2x"
placeholder="fa fa-glass red-gold fa-2x" readonly={true}/>
</div>
<div className="venue-info">
<img src={this.state.drink.image_url} />
</div>
</div>
<div className="venue-feed">
<CheckinIndex source={{loc: "drink", id: this.props.params.drinkId}}/>
</div>
</div>
</div>
);
}
});
module.exports = DrinkPage;
|
// Une varias capas
// Se comunica con el modelo
// *Pendiente: Añadir capa de validación a todos los controladores
const rodentMonitoringGatheringCenterModel = require('./rodent-monitoring-gathering-center.model');
module.exports = {
// Crear un nuevo registro monitoreo roedor centro acopio
async createRodentMonitoringGatheringCenter(req, res) {
// Añadir capa de validación
const { monitoreoroedorid, centroacopioid } = req.body;
try {
await rodentMonitoringGatheringCenterModel.createRodentMonitoringGatheringCenter({
monitoreoroedorid: monitoreoroedorid,
centroacopioid: centroacopioid
});
} catch (error) {
return res.status(500).send({ message: "Registro fallido" });
}
return res.status(201).send({ message: "Registro exitoso" });
},
// Obtener todos los registros de monitoreo roedor centro acopio
async getRodentMonitoringGatheringCenters(req, res) {
const rodentMonitoringGatheringCenter = await rodentMonitoringGatheringCenterModel.getRodentMonitoringGatheringCenters()
return res.status(200).send(rodentMonitoringGatheringCenter); // <--
},
// Obtener registro de monitoreo roedor centro acopio por id
async getRodentMonitoringGatheringCenter(req, res) {
const { id } = req.params;
const rows = await rodentMonitoringGatheringCenterModel.getRodentMonitoringGatheringCenter(id);
return rows != null ? res.status(200).send(rows) : res.status(404).send({ message: "Registro no encontrado" });
},
// Actualiza informacion de un registro de monitoreo roedor centro acopio
async updateRodentMonitoringGatheringCenter(req, res) {
const { id } = req.params;
const { monitoreoroedorid, centroacopioid } = req.body;
const rowCount = await rodentMonitoringGatheringCenterModel.updateRodentMonitoringGatheringCenter(id, {
monitoreoroedorid: monitoreoroedorid,
centroacopioid: centroacopioid
});
return rowCount == 1 ? res.status(200).send({ message: "Actualizado con éxito" }) : res.status(404).send({ message: "Registro no encontrado" });
},
// Elimina un registro de monitoreo roedor centro acopio
async deleteRodentMonitoringGatheringCenter(req, res) {
const { id } = req.params;
try {
let rowCount = await rodentMonitoringGatheringCenterModel.deleteRodentMonitoringGatheringCenter(id);
return res.json(rowCount == 1 ? { message: "Eliminado exitosamente", tipo: "exito" } : { message: "No registrado", tipo: "error" });
} catch (err) {
return res.json({ message: "Error al tratar de eliminar registro", tipo: "error" });
}
}
}
|
var q = require('q')
var crypto = require('crypto')
// var keys = require('../keys')
var moment = require('moment')
var request = require('request')
var qs = require('querystring')
var ENDPOINT_API = 'https://www.mercadobitcoin.net/api/'
var ENDPOINT_TRADE_API = 'https://www.mercadobitcoin.net/tapi/v3/'
// DOCS:
// https://www.mercadobitcoin.com.br/trade-api/v2/
// Credentials
let key
let secret
let pairsDictPublic = {
BTCBRL: 'BTC',
LTCBRL: 'LTC'
}
let pairsDictPrivate = {
BTCBRL: 'BRLBTC',
LTCBRL: 'BRLLTC'
}
function MercadoBitcoin (config) {
this.name = 'MercadoBitcoin'
this.config = config
key = this.config.mbtc.id
secret = this.config.mbtc.secret
}
MercadoBitcoin.prototype.setOrderbookListener = function (pairs, callback) {
setInterval(function () {
var promises = []
// console.log(pairs.BTCUSD.alias);
Object.keys(pairs).forEach(function (pair) {
promises.push(this.getOrderbook(pair))
})
q.all(promises)
.then(function (res) {
callback(res)
})
}, 5000)
}
MercadoBitcoin.prototype.setBalanceListener = function (pairs, callback) {
setInterval(function () {
this.getBalance().then(res => {
callback(res)
}).catch(err => {
console.error('ERROR MBTC ' + err)
})
}, 10000)
}
MercadoBitcoin.prototype.setTradesListener = function (pairs, callback) {
setInterval(function () {
var promises = []
Object.keys(pairs).forEach(function (pair) {
promises.push(this.getTrades(pair))
})
q.all(promises)
.then(function (res) {
res.forEach(r => {
callback(r)
})
})
.catch(function (err) {
console.log(err)
})
}, 9000)
}
MercadoBitcoin.prototype.clearOrders = function (pair) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
this.getOpenOrders(pair).then((orders) => {
// console.log(JSON.stringify(orders));
let cancels = []
orders.buy.forEach(order => {
// CANCELLING BUY ORDERS
cancels.push(this.cancelOrder.bind(null, pair, order.id))
})
orders.sell.forEach(order => {
// CANCELLING SELL ORDERS
cancels.push(this.cancelOrder.bind(null, pair, order.id))
})
return cancels.reduce(q.when, q())
}).then((res) => {
resolve(res)
}).catch(err => {
console.log('ERR = ' + JSON.stringify(err))
reject(err)
})
})
}
MercadoBitcoin.prototype.getOrderbook = function (pair) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
try {
publicRequest('orderbook', pairsDictPublic[pair], function (data) {
var orderbook = {}
orderbook.buy = data.bids.map(function (bid) {
var b = { price: bid[0], amount: bid[1] }
return b
})
orderbook.sell = data.asks.map(function (ask) {
var a = { price: ask[0], amount: ask[1] }
return a
})
resolve(orderbook)
}, function (err) {
reject(new Error('ERR = ' + JSON.stringify(err)))
})
} catch (err) {
reject(err)
}
})
}
MercadoBitcoin.prototype.getBalance = function () {
return new Promise((resolve, reject) => {
privateRequest('get_account_info', null, function (data) {
var balance = {}
balance.BRL = parseFloat(data.response_data.balance.brl.total)
balance.BTC = parseFloat(data.response_data.balance.btc.total)
resolve(balance)
}, function (err) {
reject(err)
})
})
}
MercadoBitcoin.prototype.getOpenOrders = function (pair) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
var params = {
coin_pair: pairsDictPrivate[pair],
status_list: '[2]'
}
privateRequest('list_orders', params, function (data) {
let orders = { buy: [], sell: [] }
data.response_data.orders.forEach((order) => {
var orderStruct = {
id: order.order_id,
side: order.order_type === 1 ? 'buy' : 'sell',
pair: pair,
price: order.limit_price,
amount: order.quantity,
from: order.coin_pair.substring(3, 6),
to: order.coin_pair.substring(0, 3)
}
orders[orderStruct.side].push(orderStruct)
})
resolve(orders)
}, function (err) {
reject(err)
})
})
}
MercadoBitcoin.prototype.getTrades = function (pair, since) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
var params = {
coin_pair: pairsDictPrivate[pair],
has_fills: true,
from_timestamp: moment().subtract(2, 'days').format('X')
}
if (since !== undefined) params.since = since
privateRequest('list_orders', params, function (data) {
let orders = []
data.response_data.orders.forEach((order) => {
order.operations.forEach((trade) => {
var orderStruct = {
id: order.order_id,
side: order.order_type === 1 ? 'buy' : 'sell',
pair: pair,
price: trade.price,
amount: trade.quantity,
fee: trade.quantity * (trade.fee_rate * 0.01),
timestamp: moment(trade.executed_timestamp, 'X'),
from: order.coin_pair.substring(3, 6),
to: order.coin_pair.substring(0, 3)
}
orderStruct.amount -= orderStruct.fee
orders.push(orderStruct)
})
})
// console.log(orders, undefined, 2);
resolve(orders)
}, function (err) {
reject(err)
})
})
}
MercadoBitcoin.prototype.sendOrder = function (pair, side, price, volume) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
let method = side === 'buy' ? 'place_buy_order' : 'place_sell_order'
var params = {
coin_pair: pairsDictPrivate[pair],
quantity: volume,
limit_price: price.toFixed(6)
}
privateRequest(method, params, function (data) {
console.log('ORDER CREATED MBTC: ' + data.response_data.order.order_id)
resolve(data.response_data.order.order_id)
}, function (err) {
reject(err)
})
})
}
MercadoBitcoin.prototype.cancelOrder = function (pair, id) {
return new Promise((resolve, reject) => {
if (pair === undefined) pair = 'BTCBRL'
var params = {
coin_pair: pairsDictPrivate[pair],
order_id: id
}
privateRequest('cancel_order', params, function (data) {
console.log('ORDER REMOVED MBTC: ' + data.response_data.order.order_id)
resolve(data.response_data.order.order_id)
}, function (err) {
reject(err)
})
})
}
function privateRequest (method, parameters, success, error) {
setTimeout(() => {
var now = Math.round(new Date().getTime())
let params = {
tapi_method: method,
tapi_nonce: now
}
params = Object.assign(params, parameters)
let query = '?' + qs.stringify(params)
var signature = crypto.createHmac('sha512', secret)
.update('/tapi/v3/' + query)
.digest('hex')
let options = {
method: 'POST',
url: ENDPOINT_TRADE_API + query,
form: params,
headers: {
'TAPI-ID': key,
'TAPI-MAC': signature
}
}
// console.log(options.form);
request(options, function (err, response, body) {
if (err) throw err
try {
body = JSON.parse(body)
if (body.status_code !== 100) {
error(body.error_message)
return
}
success(body)
} catch (err) {
error(err)
}
})
}, getWaitTime())
}
function publicRequest (method, pair, success, error) {
let options = {
method: 'GET',
headers: {
'Accept': 'application/json'
},
url: ENDPOINT_API + pair + '/' + method + '/'
}
request(options, function (err, response, body) {
if (err) return
try {
body = JSON.parse(body)
success(body)
} catch (err) {
error(body)
}
})
}
let lastMBTC = new Date().getTime()
let getWaitTime = function () {
let now = moment()
let diff = moment().diff(moment(lastMBTC))
let wait = 0
if (diff < 1000) {
wait = 1000 - diff
}
lastMBTC = now.valueOf() + wait
return wait
}
module.exports = MercadoBitcoin
|
const initialState = {
songs: [],
artist: ''
}
export default (state = initialState, action) => {
switch (action.type) {
case 'SEARCH_ARTIST':
return {
...state,
songs: action.payload.songs,
artist: action.payload.artist
}
default:
return state
}
} |
var searchData=
[
['settings',['settings',['../namespaceIITBPortal_1_1settings.html',1,'IITBPortal']]],
['urls',['urls',['../namespaceIITBPortal_1_1urls.html',1,'IITBPortal']]],
['wsgi',['wsgi',['../namespaceIITBPortal_1_1wsgi.html',1,'IITBPortal']]]
];
|
var express = require('express');
var roomsRouter = express.Router();
//------------------------------------------------------------------------
// Models
var Room = Utils.getModel('Room');
//------------------------------------------------------------------------
// Validator
var validator = Utils.getValidator('rooms');
//------------------------------------------------------------------------
// API paths
roomsRouter.get('/', validator.validateGetRequest, (req, res, next) => {
Room
.find({propertyId: req.query.propertyId})
.exec((err, rooms) => {
if (err) return next(err);
res.status(200).json({rooms: rooms});
});
});
roomsRouter.post('/', validator.validatePostRequest, (req, res, next) => {
var room = new Room(req.body);
room.save((err) => {
if (err) return next(err);
res.status(200).json({roomId: "/api/rooms/" + room._id});
});
});
roomsRouter.put('/:roomId', validator.validatePutRequest, (req, res, next) => {
Room
.findById(req.params.roomId)
.exec((err, room) => {
if (err) return next(err);
if (!room) return res.status(404).json({message: 'can\'t find any room by provided id'});
Object.assign(room, req.body);
room.save((err) => {
if (err) return next(err);
res.status(200).json({roomId: '/api/rooms/' + room._id});
});
});
});
roomsRouter.delete('/:roomId', validator.validateDeleteRequest, (req, res, next) => {
Room
.findById(req.params.roomId)
.exec((err, room) => {
if (err) return next(err);
if (!room) return res.status(404).json({message: 'can\'t find any room by provided id'});
room.remove((err) => {
if (err) return next(err);
res.status(200).json({message: 'removed'});
});
})
});
//------------------------------------------------------------------------
// Exports
module.exports = roomsRouter; |
// Require jQuery
ihl0700_cTable = function(){
// Sample Request Format
/*
http://localhost/api?
queries[search]=keyword
&sorts[title]=1
&page=1
&perPage=20
&offset=0
*/
this.constructor = function(o){
this.url = o.url;
this.requestFunction = o.requestFunction;
this.callbackFunction = o.callbackFunction;
this.$table = o.$table;
//
this.initTable(o);
}
this.getTableElementIndex = function(){
var $t = $("table");
for(var x=0; x<$t.length; x++){
var t = $($t[x]);
if(t.get(0) == this.$table.get(0)){
return x;
break;
}
}
}
//---------------------------------------------------------------------------------------------------------------------------------------
this.initTable = function(opt){
var id = (this.$table.attr("id") && this.$table.attr("id")!="") ? this.$table.attr("id") : this.getTableElementIndex();
this.$table.parent().append("<div class='ihl0700_cTable'></div>");
this.$container = this.$table.parent().find("div.ihl0700_cTable");
this.$container.attr("id", "ihl0700_cTable_container_"+id);
this.$container.attr("idx", id);
//
this.$table.appendTo(this.$container);
//
this.setupWidget_search();
this.setupWidget_display();
this.setupWidget_paging();
// Init initial params
var total = (opt && Number(opt.total)) ? opt.total : this.$table.find("tbody tr").length;
var page = (opt && Number(opt.page)) ? opt.page : 1;
var display = (opt && Number(opt.display)) ? opt.display : 20;
var search = (opt && opt.search) ? opt.search : "";
var sorts = (opt && opt.sorts) ? opt.sorts : "";
//
this.$table.attr("total", total);
this.$table.attr("page", page);
this.$table.attr("display", display);
this.$table.attr("search", search);
this.$table.attr("sorts", sorts);
}
this.setupWidget_search = function(){
this.$container.prepend("<div class='ihl0700_cTable_top'/>");
this.$tc = this.$container.find("div.ihl0700_cTable_top");
this.$tc.prepend("<div class='ihl0700_cTable_search' style='position:relative;'><span>Search</span> <input type='search' name='search'></div>");
this.$widget_search = this.$tc.find("div.ihl0700_cTable_search");
this.$widget_search.find('input[type=search]').keyup(search_handler.bind(this));
function search_handler(ev){
var $i = $(ev.target).closest("input");
var key = String($i.val());
if(ev.which == 13 || key == "") {
this.$table.attr("search", key);
this.$table.attr("page", 1);
this.request_data();
}
};
}
this.setupWidget_display = function(){
this.$tc = this.$container.find("div.ihl0700_cTable_top");
//
this.$tc.prepend("<div class='ihl0700_cTable_display'><span>Display</span> <select><option>20</option><option>50</option><option>100</option></select></div>");
this.$widget_display = this.$tc.find("div.ihl0700_cTable_display");
this.$widget_display.unbind();
this.$widget_display.change(display_change_handler.bind(this));
//
function display_change_handler(e){
this.$table.attr("display", $(e.target).find("option:selected").text());
this.$table.attr("page", 1);
this.request_data();
}
}
this.setupWidget_paging = function(){
this.$container.append("<div class='ihl0700_cTable_paging'/>");
var $p = this.$container.find("div.ihl0700_cTable_paging");
//
$p.append("<div class='paging_text'><span>Showing </span><span class='limit'>1</span> of <span class='total'>1</span></div>");
this.$widget_paging = $p.find("div.paging_text");
//
$p.append("<div class='paging_list'><ul class='list'></ul></div>");
this.$widget_list = $p.find("div.paging_list");
}
/* Request data */
this.request_data = function(){
if(this.requestFunction){
// Sample
// http://localhost/api/branchs?queries[search]=keyword&sorts[title]=1
var search = this.$table.attr("search");
//var sorts = String(this.$table.attr("sorts");
var page = this.$table.attr("page");
var perPage = this.$table.attr("display");
var offset = (Number(this.$table.attr("page"))-1)*Number(this.$table.attr("display"));
//
var o = new Object();
o.page = page;
o.perPage = perPage;
o.offset = offset;
o.search = search;
this.requestFunction(o);
}else{
this.static_update();
}
}
//
this.get = function(){
return this.$table;
}
this.reset = function(){
this.$table.find("tbody").empty();
return true;
}
this.update = function(o){
this.update_paging(o);
// static page rearrangement
this.static_rearrange();
}
this.update_paging = function(o){
var po = (o && o.pagination && o.pagination.current_number) ? o.pagination : new Object({current_number:1});
var limit = Number(this.$table.attr("display"));
var total = (o && o.count) ? Number(o.count) : this.$table.attr("total");
var currPage = this.$table.attr("page");
//
var d = ((po.current_number-1)*limit)+1;
var e = d+limit-1;
if(e>total) e = total;
this.$widget_paging.find(".limit").text(d+" - "+e);
this.$widget_paging.find(".total").text(total);
// Clear paging list and recreate new one
this.$widget_list.find("ul.list li[data-page]").unbind();
this.$widget_list.find("ul.list").empty();
var p=1;
var x = 0;
while(x<total){
var list="";
if(p == currPage){
list = "<li data-id='"+p+"' class='active'><strong>"+p+"</strong></li>";
}else{
list = "<li data-id='"+p+"' class='selectable' data-page='"+p+"'>"+p+"</li>";
}
x+=limit;
p++;
//
this.$widget_list.find("ul.list").append(list);
}
var $li = this.$widget_list.find("ul.list li");
$li.unbind();
$li.click(this.paging_list_click.bind(this));
if($li.length>9){
$li.addClass("hidden");
var $liA = this.$widget_list.find("ul.list li.active");
var ai = Number($liA.attr("data-id"));
var show;
if(ai > 6 && ai <= (p-6)){
show = [1,(ai-3),(ai-2),(ai-1),ai,(ai+1),(ai+2),(ai+3),(p-1)]; // Show the active, the first, the last and 2 nearest page link
this.$widget_list.find("ul.list li[data-id=1]").after("<li>..</li>");
this.$widget_list.find("ul.list li[data-id="+(p-1)+"]").before("<li>..</li>");
}else if(ai > (p-6) && ai <= (p-1)){
show = [1,ai,(p-1),(p-2),(p-3),(p-4),(p-5),(p-6)];
this.$widget_list.find("ul.list li[data-id=1]").after("<li>..</li>");
}else if(ai<=6){
show = [1,2,3,4,5,6,7,8,(p-1)];
this.$widget_list.find("ul.list li[data-id="+(p-1)+"]").before("<li>..</li>");
}
if(show){
while(show.length>0){
var sid = show.pop();
this.$widget_list.find("ul.list li[data-id="+sid+"]").removeClass("hidden");
}
}
}
}
this.paging_list_click = function(ev){
var $li = $(ev.target).closest("li[data-page]");
var np = $li.attr("data-page");
this.$table.attr("page", np);
this.request_data();
}
/* Static */
this.static_rearrange = function(){
// Only for static table
if(!this.requestFunction){
var $tr = this.$table.find("tbody tr").filter(":not(.findhide)");
$tr.addClass("rowhide");
//
var limit = Number(this.$table.attr("display"));
this.$table.attr("total", $tr.length);
this.update_paging();
//
var currPage = this.$table.attr("page");
var offset = Number((currPage-1) * limit);
for(var idx=offset; idx<(offset+limit) && idx<$tr.length; idx++){
if($($tr[idx]).length>0) $($tr[idx]).removeClass("rowhide");
}
}
}
this.static_search = function(){
var search = this.$table.attr("search");
var key = String(search).toLowerCase();
//var $tr = this.$table.find("tbody tr").filter(":not(.hide)");
var $tr = this.$table.find("tbody tr");
//
if(key && key!=""){
this.$table.attr("searchmode", 1);
$tr.addClass("findhide");
for(var idx=0; idx<$tr.length; idx++){
var $item = $($tr.get(idx));
if(String($item.text().toLowerCase()).indexOf(key)>=0){
$item.removeClass("findhide");
$item.removeClass("rowhide");
}
this.$table.attr("page",1);
}
}else{
this.$table.attr("searchmode", 0);
$tr.removeClass("findhide");
}
}
this.static_update = function(){
var search = this.$table.attr("search");
var sorts = String(this.$table.attr("sorts"));
var page = this.$table.attr("page");
var perPage = this.$table.attr("display");
var offset = (Number(this.$table.attr("page"))-1)*Number(this.$table.attr("display"));
//
this.static_search();
this.update();
}
};
|
/**
*检验用户输入是否合法
*/
var blogurl_err='';
function check()
{
fields=document.getElementsByTagName("input");
for(i=0;i<fields.length-2;i++)
{
val=fields[i].getAttribute('name');
if(fields[i].value=='')
{
alert('每一项都必须填写');
eval('document.form1.'+val).focus();
return false;
}
else if(t(val+'_tip').className=='tip_err')
{
alert(t(val+'_tip').innerHTML);
return false;
}
}
return true;
}
/**
*检验邮件地址是否合法
*/
function ismail(mail)
{
return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
}
/**
*检查是否博客用户
*/
function isGroup(url)
{
return (new RegExp(/^http:\/\/group.bokee.com\/[A-Za-z0-9]+$/).test(url));
}
/**
*检查是否合法电话号码
*/
function isphone(num)
{
return (new RegExp(/^((0(\d{2,3})[_\--]?(\d{7,8}))|(1[35](\d{9})))$/).test(num));
//这里要求包含区号,如果可以不包含区号,可以这样写:/^((0\d{2,3})|(0\d{2,3}-))?[1-9]\d{6,7}$/
//后面是手机号判断,座机(含区号)必须以0开头,手机必须以13或15开头
}
function foc(obj)
{
var val=obj.getAttribute('name');
switch (val)
{
case 'username':
tips='只能使用小写字母,数字和下划线(_)的混合!';
break;
case 'password':
tips='可以输入任意字符,不少于6个字符!';
break;
case 'repassword':
tips='请重复输入一次上面的密码以确认!';
break;
case 'nickname':
tips='请设定一个昵称,以后将在评论中显示!可以是中文';
break;
case 'email':
tips='请填写您常用的E-mail,以方便接受最新消息!';
break;
}
t(val+'_tip').style.display='';
t(val+'_tip').className='tip';
t(val+'_tip').innerHTML=tips;
}
function blu(obj)
{
var val=obj.getAttribute('name');
if(obj.value=='')
{
// foc(obj);
t(val+'_tip').style.display='none';
return;
}
switch (val)
{
case 'username':
if(!new RegExp(/^[a-z]+/).test(obj.value))
{
t(val+'_tip').className='tip_err';
tips='您的输入不合要求,只能以小写字母开头!';
}
else if(!new RegExp(/^[a-z]+[a-z0-9_]+$/).test(obj.value))
{
t(val+'_tip').className='tip_err';
tips='您的输入不合要求,只能输入数字,字母或下划线!';
}
else if(obj.value.length<4 || obj.value.length>16)
{
t(val+'_tip').className='tip_err';
tips='你输入的长度不符合要求,请输入4-16个字符!';
}
else
{
res=parseInt(checkUsername(obj.value));
if(res==0)
{
t(val+'_tip').className='tip_ok';
tips='恭喜,您的用户名符合要求,并可以使用!';
setTimeout("hidden_tip('"+val+"')",2000);
}
else
{
t(val+'_tip').className='tip_err';
tips='抱歉,您选择的用户名已被注册!';
}
}
break;
case 'password':
if(obj.value.length<6)
{
t(val+'_tip').className='tip_err';
tips='你输入的密码太短,应至少6个字符!';
}
else
{
t(val+'_tip').className='tip_ok';
tips='密码设置符合要求!';
setTimeout("hidden_tip('"+val+"')",2000);
}
break;
case 'repassword':
if(obj.value!=document.getElementById('password').value)
{
t(val+'_tip').className='tip_err';
tips='两次密码输入不一致,请检查确认!';
}
else
{
t(val+'_tip').className='tip_ok';
tips='两次输入的密码一致!';
setTimeout("hidden_tip('"+val+"')",2000);
}
break;
case 'nickname':
if(obj.value.length<2)
{
t(val+'_tip').className='tip_err';
tips='您的昵称太短了!';
}
else
{
t(val+'_tip').className='tip_ok';
tips='ok!';
setTimeout("hidden_tip('"+val+"')",2000);
}
break;
case 'email':
if(!ismail(obj.value))
{
t(val+'_tip').className='tip_err';
t(val+'_tip').innerHTML='您填写的不是E-mail地址!';
}
else
{
t(val+'_tip').className='tip_ok';
t(val+'_tip').innerHTML='E_mail地址符合规范!';
setTimeout("hidden_tip('"+val+"')",2000);
}
break;
}
t(val+'_tip').style.display='';
t(val+'_tip').innerHTML=tips;
}
var xmlhttp = createXMLHTTP();
function checkUsername(str)
{
xmlhttp.open("get","../checkUsername/?username="+str,false);
xmlhttp.send(null);
return str=xmlhttp.responseText;
}
function hidden_tip(val)
{
t(val+'_tip').style.display='none';
}
function checknum(num)
{
if(num.length<10)
{
showMsg('telenum_msg','请输入含区号的电话号码或手机号码');
}
else if(num.length>9 && isphone(num))
{
showMsg('telenum_msg','联系电话符合要求!');
}
else
{
showMsg('telenum_msg','您输入的号码不符合要求');
}
}
/**
*显示提示信息
*/
function showMsg(id,str)
{
document.getElementById(id).innerHTML=str;
return;
}
function setErr(str)
{
blogurl_err=str;
}
function createXMLHTTP() {
var XMLHTTP=null;
try {
XMLHTTP=new ActiveXObject("Msxml2.XMLHTTP");//适用IE
}
catch(e) {
try {
XMLHTTP=new ActiveXObject("Microsoft.XMLHTTP");//适用IE
}
catch(oc) {
XMLHTTP=null;
}
}
if ( !XMLHTTP && typeof XMLHttpRequest != "undefined" ) {
XMLHTTP=new XMLHttpRequest();//适用Firefox
}
return XMLHTTP;
}
function t(obj)
{
return document.getElementById(obj);
}
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,"");
} |
import path from 'path';
import convert from 'koa-convert';
import koaStatic from 'koa-static';
const cwd = process.cwd();
const ENV = process.env.NODE_ENV;
const prod = ENV === 'production' ? 'publish' : '';
const staticServer = convert(koaStatic(path.join(cwd, prod, 'static')));
export default staticServer;
|
/**
Program for finding even number in given array using forEach
**/
function fnFindEvenNumber(array_element) {
var even_number = [];
array_element.forEach(function(items){
if(items%2 == 0) {
even_number.push(items)
}
})
return even_number;
}
var array_element=[12,14,3,5]
alert(fnFindEvenNumber(array_element)); |
$("li").click(function() {
$(this).addClass("completed");
});
$("li > span").click(function() {
$(this).parent()
.fadeOut(1000, function() {
this.remove();
})
});
$("input").keypress(function(event) {
if (event.which === 13 && this.value !== "") {
$("ul").append("<li><span><i class=\"fa fa-trash\"></i></span>" + this.value + "</li>");
this.value = "";
}
$("li").click(function() {
$(this).addClass("completed");
});
$("li > span").click(function() {
$(this).parent()
.fadeOut(1000, function() {
this.remove();
})
});
});
$("h1 > i").click(function() {
$("input").toggle({ duration: 'slow' });
}); |
var assert = require("../assert.js");
var test = require("../test.js");
module.exports.runTests = runTests;
function runTests() {
// assert.True() tests
test.run(function () { assert.True(true); });
test.run(function () { assert.Throws(function () { assert.True(false); }); });
// assert.False() tests
test.run(function () { assert.False(false); });
test.run(function () { assert.Throws(function () { assert.False(true); }); });
// assert.Null() tests
test.run(function () { assert.Null(null); });
test.run(function () { assert.Throws(function () { assert.Null(""); }); });
test.run(function () { assert.Throws(function () { assert.Null(50); }); });
test.run(function () { assert.Throws(function () { assert.Null(true); }); });
test.run(function () { assert.Throws(function () { assert.Null({}); }); });
// assert.Empty() tests
test.run(function () { assert.Empty(null); });
test.run(function () { assert.Empty(); });
test.run(function () { assert.Empty([]); });
test.run(function () { assert.Throws(function () { assert.Empty([1, 2, 3]); }); });
// assert.Equal() tests
test.run(function () { assert.Equal(null, null); });
test.run(function () { assert.Equal(); });
test.run(function () { assert.Equal(1, 1); });
test.run(function () { assert.Equal("1", "1"); });
test.run(function () { assert.Throws(function () { assert.Equal(1, "1"); }); });
test.run(function () { assert.Equal({ "name": "Dan" }, { "name": "Dan" }); });
test.run(function () { assert.Throws(function () { assert.Equal({}, { "name": "Dan" }); }); });
test.run(function () { assert.Equal([], []); });
test.run(function () { assert.Equal([1], [1]); });
test.run(function () { assert.Throws(function () { assert.Equal([1], [1, 2]); }); });
test.run(function () { assert.Equal({ "a": { "b": "bValue" } }, { "a": { "b": "bValue" } }); });
test.run(function () { assert.Throws(function () { assert.Equal({ "a": { "b": "bValue" } }, { "a": { "b": "notBValue" } }); }); });
}
if (require.main === module) {
runTests();
test.showResults();
} |
process.env.DEBUG = "mongo-seeding";
const { Seeder } = require("mongo-seeding");
const path = require("path");
(async () => {
try {
const seeder = new Seeder({
database: process.env.MONGODB_URI,
dropDatabase: true
});
const pathToSeeds = path.join(__dirname, "../seeds");
const collections = seeder.readCollectionsFromPath(pathToSeeds);
await seeder.import(collections);
} catch (err) {
console.log("Error", err);
}
})();
|
/**
* Created by cl-macmini-63 on 1/10/17.
*/
'use strict';
const responseFormatter = require('Utils/responseformatter.js');
const adminSchema = require('schema/mongo/adminschema');
const codeSchema = require('schema/mongo/stateCodes');
const constantSchema = require('schema/mongo/constantsschema');
const mapperSchema = require('schema/mongo/serviceLocationMapper');
const userSchema = require('schema/mongo/userschema');
const SPProfileSchema = require('schema/mongo/SPprofile');
const log = require('Utils/logger.js');
const logger = log.getLogger();
const mongoose=require('mongoose');
const async=require('async');
//auth token module
const jwt = require('jsonwebtoken');
//custom modules
const storageService = require('model/storageservice.js');
const privateKey = '_1.2v^:69F61n151EodW+!925;-Cx-;m.*Z2=^y463B+9Z.49^%7I%3b62%z%;+I';
module.exports={};
module.exports.privateKey = privateKey;
var decodeToken = function(token, callback){
//check if token is valid
var options={}
jwt.verify(token, privateKey, options, callback);
}
module.exports.decodeToken = decodeToken;
module.exports.createAuthToken = function(email,role,privateKey, callback){
console.log('email : ',email," role : ",role);
var authToken = jwt.sign({email: email , role: role}, privateKey);
console.log("in createAuthToken () - auth Token :",authToken);
if(authToken == null || authToken == undefined){
callback();
}
else{
callback(authToken);
}
}
module.exports.authenticateAdmin = function(adminId, password, current_role,callback){
logger.debug('AuthService authentication...');
var self = this;
var authToken;
//var userService = require('../user/userservice.js');
checkPassword(adminId, password, function(response){
console.log('response **** ',response);
if (response.status == 'success'){
//if successful add token
self.createAuthToken(response.data.email,response.data.role[0], privateKey ,function (response){
if(response == null || response == undefined){
console.log("Auth token could not be created ");
responseFormatter.formatServiceResponse(new Error('Error while creating auth-token'), callback);
}else{
authToken = response;
}
});
storageService.store(authToken, response.data.user_id, function(storageResponse){
if (storageResponse.status=='error'){
callback(storageResponse);
}
else if (storageResponse.status == 'success'){
var retData = {}
retData.admin = response.data;
retData.authToken = authToken;
console.log("*********response.data ::",response.data);
responseFormatter.formatServiceResponse(retData, callback);
}
else{
responseFormatter.formatServiceResponse(new Error('Unidentified response'), callback);
}
});
}
else{
//send error straight through
callback(response);
}
});
}
function checkPassword(email, password, callback){
logger.debug('admin id in checkPassword:', email);
logger.debug('Password in checkPassword : ', password);
adminSchema.Admin.findOne({ email: email}, function(err, admin) {
// logger.debug('User found in authenticate admin', admin);
if (err){
logger.error('Error finding admin', err.message);
responseFormatter.formatServiceResponse(err, callback);
return;
}
// keep the message same for both invalid id and password to make it
// more secure
if (admin == null || admin == undefined){
console.log("In admin service :Admin not found");
var authenticationError = new Error('Invalid email or password');
authenticationError.name='AuthenticationError';
responseFormatter.formatServiceResponse(authenticationError, callback);
return;
}
/*if(admin.is_email_verified == false){
var authenticationError = new Error('Please verify your email before login. We have sent verification link to your email.');
authenticationError.name='AuthenticationError';
responseFormatter.formatServiceResponse(authenticationError, callback);
return;
}*/
// match the password
admin.comparePassword(password, function(err, isMatch) {
if (err){
logger.error('Error matching password', err.message);
responseFormatter.formatServiceResponse(err, callback);
return;
}
if (isMatch){
responseFormatter.formatServiceResponse(admin.toJSON(), callback);
}
else{
console.log("In admin service :Password does not match");
var authenticationError = new Error('Invalid email or password');
authenticationError.name='AuthenticationError';
responseFormatter.formatServiceResponse(authenticationError, callback);
}
});
});
}
module.exports.signout = function(authToken, callback){
logger.debug('AuthService Signout...');
storageService.remove(authToken, function(storageResponse){
if (storageResponse.status=='error'){
logger.error('Error removing token', storageResponse)
callback(storageResponse);
}
else if (storageResponse.status == 'success'){
var retData = {'signout': true}
responseFormatter.formatServiceResponse(retData, callback);
}
else{
responseFormatter.formatServiceResponse(new Error('Unidentified response'), callback);
}
});
}
var checkAdmin = function(id, role , callback){
console.log("Searching for Admin : id : ",id," roles :: ",role);
adminSchema.Admin.count({'email':id, 'role': role}, function (err, count) {
logger.debug('Admin returned', count)
if (err){
logger.error("Find failed", err);
responseFormatter.formatServiceResponse(err, callback);
}
else {
if (count > 0){
responseFormatter.formatServiceResponse({exists: true}, callback);
}
else{
responseFormatter.formatServiceResponse({exists: false}, callback);
}
}
});
};
var validateToken = function(token, callback){
//check if token is valid
decodeToken(token, function(err, decodedToken){
// logger.debug('*******Running validation...');
// logger.debug('*******token:', token); // should be your token
// logger.debug('decoded:', decodedToken); // should be {accountId : 123}.
if (err){
callback(null, false);
return;
}
if (decodedToken) {
console.log('Admin Service validate: ', decodedToken);
}
//check if Admin exists
checkAdmin(decodedToken.email, decodedToken.role, function(response){
if (response.status == 'error'){
callback(null, false);
return;
}
if (response.data == null || response.data == undefined) {
callback(null, false);
return;
}
//if user exists
if (response.data.exists == true){
callback(null, true, {user_id:decodedToken.email,role : decodedToken.role});
return;
}
callback(null, false);
});
});
}
/**
* Validates token. Check if token exists in storage and then also
* verifies the validity. Returns user object if token is valid
* This also acts as hook for hapi-bearer-token plugin to call for
* token validation
*
*/
module.exports.validate = function(token, callback){
//check if token exists in storage or not
logger.debug('Auth token received: ', token);
storageService.get(token, function(storageResponse){
if (storageResponse.status=='error'){
logger.error('Token lookup failed', storageResponse);
callback(null, false);
}
else if (storageResponse.status == 'success'){
//do further checks
validateToken(token, callback);
}
else{
logger.error('Unidentifid response from storage service');
callback(null, false);
}
});
}
module.exports.createAdmin = function(payload, callback) {
var admin = new adminSchema.Admin(payload);
var adminEmail = admin.email.toLowerCase();
admin.email = adminEmail;
admin.role = 'ADMIN';
console.log('admin :: ',admin);
admin.on('error', function(err){logger.error('Error saving admin: ', err);})
logger.debug("admin information: ", admin);
admin.save(function(err,admin){
if (err){
responseFormatter.formatServiceResponse(err, callback);
}
else {
console.log("in success :admin created successfully");
responseFormatter.formatServiceResponse(admin, callback);
}
});
};
module.exports.addCodesModel=function(payload,callback){
let codes= new codeSchema.CodeSchema(payload)
codes.save(function(err,data){
if(err){
callback(err)
}
else{
callback(null,data)
}
})
}
module.exports.addConstantModel=function(payload,callback){
let constant= new constantSchema.constantSchema(payload)
constant.save(function(err,data){
if(err){
callback(err)
}
else{
callback(null,data)
}
})
}
module.exports.updateConstantModel=function(payload,callback){
console.log("updateConstantModel function start >>>",payload)
var id=mongoose.Types.ObjectId(payload.constants_id)
constantSchema.constantSchema.findOneAndUpdate({_id:id},{ payload /*booking_timer:payload.booking_timer*/},{lean:true,new:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data)
}
})
}
module.exports.getConstantModel=function(callback){
constantSchema.constantSchema.find({},{},{lean:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data[0])
}
})
}
module.exports.getCodesModel = function(callback){
//codeSchema.CodeSchema.find({}, function (err, data) {
// if (err){
// logger.error("Find failed", err);
// responseFormatter.formatServiceResponse(err, callback);
// }
// else {
// console.log(data)
// responseFormatter.formatServiceResponse(data, callback ,'','success',200);
// }
//});
codeSchema.CodeSchema.aggregate([
{ "$project": {
place:1,
code:1,
placeType:1,
country:1,
"insensitive": { "$toLower": "$place" }
}},
{ "$sort": { "insensitive": 1 } }
]).exec(function(err,data){
if(err){
callback(err)
}
else{
console.log("in getCodesModel aggregation>>>>>",data)
callback(data)
}
})
}
module.exports.getMappedCodesModel = function(callback){
mapperSchema.Mapper.distinct("location",function(err,mapperData){
if(err)
callback(err);
else{
let loc=[]
mapperData.forEach(function(res){
console.log("res",res)
loc.push(function(cb){
codeSchema.CodeSchema.find(res,function(err,location)
{
if(err){
cb(err);
}
else
cb(null,location[0]);
})
})
})
async.parallel (loc,function(error, data) {
console.log('error data : ------', error, data);
if (error) {
console.log('error : ', error);
return callback(err);
}
else {
console.log("final data in format", data)
callback(null,data);
}
})
}
})
};
module.exports.getAllSeekers = function(callback){
userSchema.User.find({role : 'SEEKER'},{},{lean:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data)
}
})
}
module.exports.getAllProviders=function(callback){
const parallelF = [];
async.waterfall([
function (cb) {
userSchema.User.find({role : 'PROVIDER'}, {
}, {lean: true}, function (err, data) {
console.log('err~~~~~', err, ' All provider found data ~~~~~~~ ', data.length);
if (err) {
cb(err);
}
else {
cb(null, data);
}
})
},
function (providers, cb) {
providers.forEach(function (result) {
console.log('result.provider_id :: ', result.user_id);
parallelF.push(function (cbb) {
SPProfileSchema.SPProfile.findOne({provider_id :result.user_id },{is_approved:1,profile_id:1},function(err,data){
if(err){
cbb(err)
}
else{
if(data){
result.is_approved = data.is_approved;
result.profile_id = data.profile_id;
cbb(null,result);
}else{
result.is_approved = false;
cbb(null,result);
}
}
})
})
});
async.parallel(parallelF, function (error, data) {
console.log('in async paraller result -- error data : ------', error, data);
if (error) {
console.log('error : ', error);
return cb(error);
}
else {
//console.log("final", data)
cb(null , data);
}
});
}
], function (err, data) {
console.log("in waterfall final", err, data);
if (err) {
console.log("err+++++++", err);
callback(err);
}
else {
//console.log("data+++++++", data);
callback(null , data);
}
});
}
module.exports.getUserDetailsByUserId = function(user_id , callback){
userSchema.User.find({user_id :user_id },{},{lean:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data);
}
})
}
module.exports.AddOrDeductWalletAmountByUserId = function(payload, callback){
let count = 0;
if(payload.add_flag){
count = Number(payload.amount);
}
if(payload.deduct_flag){
count = Number(-payload.amount);
}
userSchema.User.findOneAndUpdate({user_id :payload.user_id },{ $inc: { wallet_amount : count } },{projection: { "wallet_amount" : 1 },new:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data);
}
})
}
module.exports.approveProviderByProfileId = function(profile_id, callback){
SPProfileSchema.SPProfile.findOneAndUpdate({profile_id :profile_id },{ $set: { is_approved : true } },{new:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data);
}
})
}
module.exports.changeUserStatusByUserId = function(payload, callback){
userSchema.User.findOneAndUpdate({user_id :payload.user_id },{ $set: { is_active : payload.is_active } },{new:true},function(err,data){
if(err){
callback(err)
}
else{
callback(null,data);
}
})
}
|
const express = require('express')
const path = require('path')
const cors = require('cors')
const bodyParser = require('body-parser')
const fs = require('fs')
const app = express()
const port = 433
app.use(cors())
app.get('/api/list', (req, res) => {
fs.readdir('./assets/', (err, items) => {
result = items.map(el => 'image/' + el)
const pageSize = req.query.size || 3;
const pagesAmount = Math.ceil(items.length / pageSize );
const page = (req.query.page > pagesAmount) ? pagesAmount : req.query.page || 1;
console.log(`Page=${page}, server acessed`)
res.json({
"page": page,
"pagesAmount": pagesAmount,
"list": result.slice(page * pageSize - pageSize, page * pageSize),
})
})
})
app.get('/image/:name.:subname', (req, res) => {
res.sendFile(__dirname + '/assets/' + req.params.name + '.' + req.params.subname, (err) => {
console.log(__dirname + '/assets/' + req.params.name + '.' + req.params.subname)
if (err) {
next(err)
} else {
console.log('Sent:', req.query.path)
}
})
})
app.use(express.static(path.join(__dirname, '../build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '../build', 'index.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`)) |
/**
* Created by bastien on 09/06/2017.
*/
import {html} from 'snabbdom-jsx';
import xs from 'xstream';
export const FormUser = (sources) => {
const submit$ = sources.DOM.select('submit-new-user').events('click');
const sendDataBack = 4;
const vTree$ = xs.of(
<form className="ui form">
<div className="field">
<label htmlFor="name">Name</label>
<input type="text" name="name" id="name"/>
</div>
<div className="field">
<label htmlFor="email">Email</label>
<input type="email" name="email" id="email"/>
</div>
<div className="field">
<label htmlFor="password">Password</label>
<input type="password" name="password" id="password"/>
</div>
<div className="field">
<div className="ui checkbox">
<input type="checkbox"
name="terms"
id="terms"
tabIndex="0"
className="hidden"/>
<label htmlFor="terms">I agree with the terms and condition</label></div>
</div>
<button className="ui button submit-new-user" type="submit">Submit</button>
</form>
);
return {
DOM: vTree$
};
}; |
/* vim: et sw=4 ts=4 */
jQuery(function($){
var debug = null;
var features = {};
var newfeature = function( name , type, config ){
features[name] = { enabled: null };
var feature = features[name];
if ( type == "name" ) {
feature.name = config;
}
if ( type == "code" ) {
feature.code = config;
}
};
newfeature( 'console', 'code',function() {
jQuery.console = function(){};
if ( debug ){
if ( console ){
jQuery.console = function(){ console.log.apply( $, arguments ); };
} else {
jQuery.console = function(){ alert( arguments ); };
}
}
return 1;
});
newfeature('localscript', 'code', function(){
jQuery.localscript = function(){
var callparams = arguments;
callparams[0] = 'http://static.fox.geek.nz/' + callparams[0];
return $.getScript.apply( $, callparams );
};
return 1;
});
newfeature('beautyOfCode', 'name','jquery.beautyOfCode.js');
newfeature('beautyConf', 'name','beautyconf.js' );
newfeature('googleanalytics', 'name','gat.js' );
var toCallback = function( arg ){
if ( ! arg ){
return function(){ };
}
return arg;
};
var logFail = function( name ){
if ( jQuery.hasFeature( "console" ) ) {
jQuery.console("Enabling feature " + name + " Did not work");
} else {
alert("Enabling feature " + name + " did not work");
}
};
jQuery.hasFeature = function( name ) {
return features[name].enabled !== null;
}
jQuery.enableFeature = function ( name, callback, xargs ) {
if( jQuery.hasFeature(name) ) { return toCallback(callback).apply(this,xargs); }
var feature = features[name];
if ( feature.code ) {
if ( feature.code() ){
features[name].enabled = 1;
return toCallback(callback).apply(this,xargs);
} else {
return logFail( name );
}
}
if ( feature.name ){
jQuery.enableFeature('localscript', function(){
jQuery.localscript(feature.name, function(){
features[name].enabled = 1;
toCallback(callback).apply(this, xargs );
});
});
return;
}
}
$.enableFeature('console');
$.enableFeature('beautyConf');
$.enableFeature('googleanalytics');
});
|
export * as h1ActionTypes from "./h1ActionTypes";
export * as h1Actions from "./h1Actions";
export * as h1Selectors from "./h1Selectors";
export * as h1Constants from "./h1Constants";
export * as h1Reducer from "./h1Reducer";
export { default as H1 } from "./components/H1.jsx";
|
import { execSync } from 'child_process'
import prompt from 'prompt'
import { checkError, confirmResponsePattern, isPositiveResponse } from './utils'
import { version as packageVersion } from '../../package.json'
prompt.message = 'Confirm'
const confirmRelease = {
name: `This will publish version ${packageVersion} of the Snacks package to the public npm registry. Are you sure you want to publish a new release of Snacks?`,
type: 'string',
pattern: confirmResponsePattern,
required: true,
default: 'yes',
}
const confirmReleaseCheck = userResponse => {
if (!isPositiveResponse(userResponse)) {
console.log('Release confirmation failed. Exiting build...')
return false
}
return true
}
const confirmBuildPassing = {
name: 'Is the circleCi build passing? (https://circleci.com/gh/instacart/Snacks/tree/master)',
type: 'string',
pattern: confirmResponsePattern,
default: 'yes',
}
const confirmBuildCheck = userResponse => {
if (!isPositiveResponse(userResponse)) {
console.log('CircleCi test passing confirmation failed. Exiting build...')
return false
}
return true
}
const confirmTwoAuthCode = {
name: 'Two factor authenticator code',
type: 'string',
required: true,
}
const checkoutAndPullMaster = () => execSync('git checkout master && git pull origin master')
const buildProject = () => execSync('npm run build')
const verifyBuild = () => execSync('npm run release:verifyBuild')
const publishRelease = authCode => execSync(`npm publish --otp ${authCode}`)
console.log('Beginning npm publish for Snacks 🥕 🍿 🍪 🥜 🍎 🥨 ')
console.log('Press ctrl+c at any point to abort release')
checkoutAndPullMaster()
prompt.start()
prompt.get([confirmRelease, confirmBuildPassing, confirmTwoAuthCode], (err, result) => {
if (checkError(err)) {
return prompt.stop()
}
if (!confirmReleaseCheck(result[confirmRelease.name])) {
return prompt.stop()
}
if (!confirmBuildCheck(result[confirmBuildPassing.name])) {
return prompt.stop()
}
buildProject()
verifyBuild()
publishRelease(result[confirmTwoAuthCode.name])
prompt.stop()
})
|
var fs = require('fs');
var shell = require("shelljs");
var os = require('os');
var ifaces = os.networkInterfaces();
var request = require('request');
var IPs = [];
module.exports = {
// searches all the ip addresses to the devices that is connected on the same network
FindIPs : function(){
IPs = [];
var localIP = this.FindLocalIP();
var res_dir = shell.pwd() + '/resources';
if(shell.ls('-A', res_dir)) {
shell.echo(shell.ls('-A', res_dir));
if(shell.exec( 'sudo nmap -sn '+ localIP + '/24 -oN ' + res_dir+'/ips').code != 0) {
shell.echo('Error: nmap command failed.');
shell.exit(1);
}
var readMe = fs.readFileSync(res_dir + "/ips" , 'utf8');
var arrayOfLines = readMe.split("\n");
for(var i = 1;i < arrayOfLines.length -1;i++){
var line = arrayOfLines[i];
if(line.includes('Nmap scan')){
var first;
var last;
var found = false;
for(var j = 0; j < line.length ; j++){
if(line.substring(0,j).includes('192') && found == false){
found = true;
first = j-3;
}
}
if(line.substring(line.length-1,line.length) == ')'){
last = line.length -1;
}
else{
last = line.length;
}
ip = line.substring(first,last);
if(ip != localIP){
this.FindActiveIP(ip);
}
}
}
} else {
}
},
//finds the local ip address of the current device
FindLocalIP : function(){
var localIP;
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
console.log(ifname + ':' + alias, iface.address);
} else {
// this interface has only one ipv4 adress
console.log(ifname, iface.address);
localIP = iface.address;
}
++alias;
});
});
return localIP;
},
// find active ips by sending an http request to them. if the response to the to the request valid system will add that ip to the ip list
FindActiveIP : function(ip){
var url = "http://" + ip +":3000/api/ip/" + this.FindLocalIP();
request(url, function(error , response , body){
if(response != undefined){
if(JSON.parse(response.body).ip!= undefined){
console.log("this ip is active : " + JSON.parse(response.body).ip);
if(IPs.length == 0){
IPs.push(JSON.parse(response.body).ip);
}
else{
for(var i = 0 ; i < IPs.length ; i++){
if(!IPs.includes(JSON.parse(response.body).ip)){
IPs.push(JSON.parse(response.body).ip);
}
}
}
}
}
});
},
//get the found ips
GetIPs : function(){
return IPs;
},
//set the found ips
SetIPs : function(ip){
if(IPs.length == 0){
IPs.push(ip);
}
else{
for(var i = 0 ; i < IPs.length ; i++){
if(!IPs.includes(ip)){
IPs.push(ip);
}
}
}
}
}; |
import React from 'react';
import RecentPostsPageMobile from './RecentPostsPageMobile';
import RecentPostsPageDesktop from './RecentPostsPageDesktop';
export default class RecentPostsPage extends React.Component {
constructor(props) {
super(props);
}
render() {
if (this.props.isMobile) {
return (
<RecentPostsPageMobile
pageParam={this.props.match.params.page}
staticContext={this.props.staticContext}
/>
)
} else {
return (
<RecentPostsPageDesktop
pageParam={this.props.match.params.page}
staticContext={this.props.staticContext}
/>
);
}
}
} |
import axios from 'axios'
axios.defaults.baseURL = 'http://api.k-hansol.com/'
axios.defaults.withCredentials = true;
export const initialState = {
};
const ADD_POST = 'ADD_POST';
const POST_LOAD = 'POST_LOAD';
const ADD_POST_REQUEST = 'ADD_POST_REQUEST';
const ADD_POST_FAILURE = 'ADD_POST_FAILURE';
const ADD_POST_SUCCESS = 'ADD_POST_SUCCESS';
const LOAD_POST_REQUEST = 'LOAD_POST_REQUEST';
const LOAD_POST_FAILURE = 'LOAD_POST_FAILURE';
const LOAD_POST_SUCCESS = 'LOAD_POST_SUCCESS';
const LOAD_SINGLE_POST_REQUEST = 'LOAD_SINGLE_POST_REQUEST';
const LOAD_SINGLE_POST_SUCCESS = 'LOAD_SINGLE_POST_SUCCESS';
const LOAD_SINGLE_POST_FAILURE = 'LOAD_SINGLE_POST_FAILURE';
const ADD_COMMENT_REQUEST = 'ADD_COMMENT_REQUEST';
const ADD_COMMENT_SUCCESS = 'ADD_COMMENT_SUCCESS';
const ADD_COMMENT_FAILURE = 'ADD_COMMENT_FAILURE';
const UPDATE_POST_REQUEST = 'UPDATE_POST_REQUEST';
const UPDATE_POST_SUCCESS = 'UPDATE_POST_SUCCESS';
const UPDATE_POST_FAILURE = 'UPDATE_POST_FAILURE';
const DELETE_POST_REQUEST = 'DELETE_POST_REQUEST';
const DELETE_POST_SUCCESS = 'DELETE_POST_SUCCESS';
const DELETE_POST_FAILURE = 'DELETE_POST_FAILURE';
export const addPostRequestAction = (data) => {
return {
type: ADD_POST_REQUEST,
data,
};
};
export const addPostSuccessAction = (data) => {
return {
type: ADD_POST_SUCCESS,
data,
};
};
export const addPostFailureAction = (data) => {
return {
type: ADD_POST_FAILURE,
data,
};
};
export const addPostAction = (data) => {
return (dispatch) => {
dispatch(addPostRequestAction());
axios.post('/post/add', data)
.then(() => {
dispatch(addPostSuccessAction(data));
})
.catch(() => {
dispatch(addPostFailureAction())
})
}
};
export const loadPostRequestAction = (data) => {
return {
type: LOAD_POST_REQUEST,
data,
};
};
export const loadPostSuccessAction = (data) => {
return {
type: LOAD_POST_SUCCESS,
data,
};
};
export const loadPostFailureAction = (data) => {
return {
type: LOAD_POST_FAILURE,
data,
};
};
export const loadPostAction = (data) => {
return (dispatch) => {
dispatch(loadPostRequestAction());
axios.post('/post', data)
.then((posts) => {
dispatch(loadPostSuccessAction(posts.data));
})
.catch(() => {
dispatch(loadPostFailureAction())
})
}
};
export const loadsinglePostRequestAction = (data) => {
return {
type: LOAD_SINGLE_POST_REQUEST,
data,
};
};
export const loadsinglePostSuccessAction = (data) => {
return {
type: LOAD_SINGLE_POST_SUCCESS,
data,
};
};
export const loadsinglePostFailureAction = (data) => {
return {
type: LOAD_SINGLE_POST_FAILURE,
data,
};
};
export const loadsinglePostAction = (data) => {
console.log(data)
return (dispatch) => {
dispatch(loadsinglePostRequestAction());
axios.get(`/post/${data.category}/${data.id}`)
.then((posts) => {
console.log(posts)
dispatch(loadsinglePostSuccessAction(posts));
})
.catch(() => {
dispatch(loadsinglePostFailureAction())
})
}
};
export const addCommentRequestAction = (data) => {
return {
type: ADD_COMMENT_REQUEST,
data,
};
};
export const addCommentSuccessAction = (data) => {
return {
type: ADD_COMMENT_SUCCESS,
data,
};
};
export const addCommentFailureAction = (err) => {
return {
type: ADD_COMMENT_FAILURE,
err,
};
};
export const addCommentAction = (data) => {
return (dispatch) => {
dispatch(addCommentRequestAction());
axios.post(`/post/${data.id}/comment`, data)
.then((comment) => {
dispatch(addCommentSuccessAction(comment.data));
})
.catch((err) => {
console.error(err)
dispatch(addCommentFailureAction(err.response.data))
})
}
};
export const updatePostRequestAction = (data) => {
return {
type: UPDATE_POST_REQUEST,
data,
};
};
export const updatePostSuccessAction = (data) => {
return {
type: UPDATE_POST_SUCCESS,
data,
};
};
export const updatePostFailureAction = (data) => {
return {
type: UPDATE_POST_FAILURE,
data,
};
};
export const updatePostAction = (data) => {
return (dispatch) => {
dispatch(updatePostRequestAction());
axios.post(`/post/${data.id}/update`, data)
.then((posts) => {
console.log(posts)
dispatch(updatePostSuccessAction(posts));
})
.catch(() => {
dispatch(updatePostFailureAction())
})
}
};
export const deletePostRequestAction = (data) => {
return {
type: DELETE_POST_REQUEST,
data,
};
};
export const deletePostSuccessAction = (data) => {
return {
type: DELETE_POST_SUCCESS,
data,
};
};
export const deletePostFailureAction = (data) => {
return {
type: DELETE_POST_FAILURE,
data,
};
};
export const deletePostAction = (data) => {
return (dispatch) => {
dispatch(deletePostRequestAction());
axios.delete(`/post/${data.id}/delete`, data)
.then(() => {
console.log()
dispatch(deletePostSuccessAction());
})
.catch(() => {
dispatch(deletePostFailureAction())
})
}
};
export const postLoaded = {
type: POST_LOAD,
}
const dummyPost = {
id: 2,
content: '1',
User: {
id: 1,
nickname: '1',
},
Images: [],
Comments: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case LOAD_POST_SUCCESS: {
return {
...state,
mainPosts: action.data,
postAdded: false,
postdelete: false,
};
}
case ADD_POST_SUCCESS: {
return {
...state,
mainPosts: [action.data, ...state.mainPosts],
postAdded: true,
postdelete: false,
};
}
case ADD_POST_REQUEST: {
return {
...state,
postAdded: false,
postdelete: false,
};
}
case ADD_POST_FAILURE: {
return {
...state,
postAdded: false,
postdelete: false,
postAddError: action.err
};
}
case LOAD_SINGLE_POST_SUCCESS: {
return {
...state,
singlePost: action.data,
postdelete: false,
};
}
case UPDATE_POST_SUCCESS: {
return { //post
singlePost: {
...state.singlePost,
data: {
...state.singlePost.data,
title: action.data.data.title,
content: action.data.data.content
}
}
};
}
case ADD_COMMENT_SUCCESS: {
return { //post
singlePost: {
...state.singlePost,
data: {
...state.singlePost.data,
Comments: [action.data, ...state.singlePost.data.Comments]
}
}
};
}
case DELETE_POST_REQUEST: {
return { //post
...state
};
}
case DELETE_POST_SUCCESS: {
return { //post
...state,
postdelete: true,
};
}
case DELETE_POST_FAILURE: {
return { //post
...state,
};
}
default: {
return {
...state,
};
}
}
};
|
import * as actionTypes from '../../types';
/**
*
* @param {object} data
* @returns {object} object
*/
const getProductDetailSuccess = (data) => {
return {
type: actionTypes.GET_PRODUCT_DETAIL_SUCCESS,
payload: {
product: data,
loadingProductDetail: false,
productDetailError: false,
}
}
}
export default getProductDetailSuccess;
|
/*
Title:redpackets
Author:cui xu
Date:2017-7-22 11:22:45
Version:v1.0
*/
var REDPACKET = {
init: function(data,func) {
this.couponTimes = 0;
this.getCouponActivity(data,func);
},
//执行检测红包
getCouponActivity: function(data,func) {
var _this = this;
GHutils.load({
url: GHutils.API.USER.registerCoupon,
params: {
eventType: data.type,
singleInvestAmount: data.singleInvestAmount
},
type: 'post',
callback: function(result) {
console.log(JSON.stringify(result));
console.log(JSON.stringify(data));
if(result && result.errorCode == 0) {
if(result.couponList && result.couponList.length > 0) {
_this.couponTimes = 0;
_this.setRedPackets(data, result)
} else {
_this.couponTimes++
setTimeout(function() {
if(_this.couponTimes <= 10) {
_this.getCouponActivity(data,func)
} else {
_this.couponTimes = 0;
if(func && typeof(func) == "function"){func.apply(null,arguments)}
}
}, 1000)
}
} else {
_this.couponTimes++
setTimeout(function() {
if(_this.couponTimes <= 10) {
_this.getCouponActivity(data,func)
} else {
if(func && typeof(func) == "function"){func.apply(null,arguments)}
_this.couponTimes = 0;
}
}, 1000)
}
},
errcallback: function() {
_this.couponTimes++
setTimeout(function() {
if(_this.couponTimes <= 10) {
_this.getCouponActivity(data,func)
} else {
if(func && typeof(func) == "function"){func.apply(null,arguments)}
_this.couponTimes = 0;
}
}, 1000)
}
})
},
setRedPackets: function(data, result) {
var _this = this;
//初始化红包弹窗
console.log(JSON.stringify(data)+'33333333');
_this.buildRedPackets();
if(data.couponType == 'random' || data.type == 'random') {
console.log('33333333');
$('#red_container').removeClass('gh_hidden').addClass('gh_show');
$('.hongbao.noSuccess').removeClass('gh_none');
$('.couponCheck1').removeClass('gh_none');
$('#chai').off().on('click', function() {
if($(this).hasClass("app_btn_loading")) {
return
}
$('#chai').addClass("rotate");
_this.receiveCoupon(data.couponOid, data.amountModal,'random');
if(result){
_this.receiveCoupon(result.couponOid, result.amountModal,'random');
}
})
} else if(data.couponType == 'fixed' || data.type == 'fixed') {
console.log(data.couponOid);
_this.receiveCoupon(data.couponOid, data.amountModal,'fixed');
if(result){
_this.receiveCoupon(result.couponOid, result.amountModal,'fixed');
}
} else if(result.couponList && result.couponList.length > 0) {
if("random" == _this.hasRedPackets(result.couponList)) {
$('#red_container').removeClass('gh_hidden').addClass('gh_show');
$('.hongbao.noSuccess').removeClass('gh_none');
$('#chai').off().on('click', function() {
if($(this).hasClass("app_btn_loading")) {
return
}
$('#chai').addClass("rotate");
_this.receiveCoupon(result.couponList[0].couponOid, result.couponList[0].couponAmount,'random');
})
} else if("fixed" == _this.hasRedPackets(result.couponList)) {
_this.receiveCoupon(result.couponList[0].couponOid, result.couponList[0].couponAmount, "fixed");
} else {
$('#red_container').removeClass('gh_hidden').addClass('gh_show');
$('.hongbao.success').removeClass('gh_none');
$('.description').html('您收到优惠券')
$('#redpacket_num').html(result.couponList.length + '<span style="font-size:18px;margin-left:5px;">张</span>');
$('#red_container .couponCheck').removeClass('gh_none').html('<button>立即查看</button>');
$('#red_container .couponCheck').off().on('click', function() {
window.location.href="account-myCoupon.html";
})
}
}
},
receiveCoupon: function(couponOid, amountModal,fixed) {
var _this = this;
$('#chai').addClass("app_btn_loading");
GHutils.load({
url: GHutils.API.ACCOUNT.useRedPackets+"?couponId="+couponOid,
type: "post",
callback: function(result) {
console.log(JSON.stringify(result))
if(GHutils.checkErrorCode(result)) {
if(window.init && typeof(window.init.successCallback) == "function"){
window.init.successCallback();
}
if(fixed == 'fixed') {
$('#red_container').removeClass('gh_hidden').addClass('gh_show');
$('.hongbao.success').removeClass('gh_none');
$('.description').html('您收到1个现金红包')
$('#redpacket_num').html(amountModal + '<span style="font-size:20px;margin-left:5px;">元</span>');
$('#red_container .couponCheck1').removeClass('gh_none');
}else if(fixed == 'random') {
setTimeout(function() {
$('#red_container').addClass('gh_show').removeClass('gh_hidden');
$('.hongbao.noSuccess').addClass('gh_none');
$('.hongbao.success').removeClass('gh_none');
$('#chai').removeClass("app_btn_loading");
$('.description').html("您收到1个随机红包")
$('.couponCheck1').removeClass('gh_none');
$('#redpacket_num').html(GHutils.formatCurrency(amountModal) + '<span style="font-size:18px;margin-left:5px;">元</span>');
$('#nowCheck').off().on('click', function() {
window.location.href="account-myCoupon.html"
})
}, 1500)
}
}else {
setTimeout(function() {
$('#red_container').removeClass('gh_show').addClass('gh_hidden');
}, 1500);
}
},
errcallback: function() {
if(fixed) {
setTimeout(function() {
GHutils.toast("网络错误,请稍后重试");
}, 200)
} else {
setTimeout(function() {
$('#red_container').removeClass('gh_show').addClass('gh_hidden');
$('#chai').removeClass("app_btn_loading");
}, 1500)
setTimeout(function() {
GHutils.toast("网络错误,请稍后重试");
}, 1500)
}
}
})
},
hasRedPackets: function(couponList) {
var hasRed = false,_this = this
if(couponList && couponList.length == 1) {
if(couponList[0].couponType == "fixed") {
hasRed = "fixed"
} else if(couponList[0].couponType == "random") {
hasRed = "random"
}
}
return hasRed;
},
//拆红包弹层
buildRedPackets: function() {
var _this = this;
if($('#red_container').length > 0) {
$('#red_container').remove();
}
var firsthtml = '';
firsthtml += '<div class="red_container gh_active gh_hidden" id="red_container">';
firsthtml += ' <div class="hongbao noSuccess gh_none">';
firsthtml += ' <div class="topcontent">';
firsthtml += ' <div class="avatar">';
firsthtml += ' <span class="close close_txt">+</span>';
firsthtml += ' </div>';
firsthtml += ' <h3 id="sendName">国槐科技</h3>';
firsthtml += ' <span class="gh_cf gh_f20">给您发了一个红包</span>';
firsthtml += ' <div class="description">投资到产品,会是一笔不小的收益</div>';
firsthtml += ' </div>';
firsthtml += ' <div class="chai_redPackets" id="chai">';
firsthtml += ' <span>拆</span>';
firsthtml += ' </div>';
firsthtml += ' <div class="bottom_img">';
firsthtml += ' <img src="static/images/redPackets_bottom_img.png" alt="" />';
firsthtml += ' </div>';
firsthtml += ' </div> ';
firsthtml += ' <div class="hongbao success gh_none">';
firsthtml += ' <div class="topcontent success ">';
firsthtml += ' <div class="avatar">';
firsthtml += ' <span class="close"></span>';
firsthtml += ' </div>';
firsthtml += ' <h3 id="sendName">恭喜您</h3>';
firsthtml += ' <div class="description gh_f15" style="margin:0px;"></div>';
firsthtml += ' <div class="chai_success">';
firsthtml += ' <span id="redpacket_num"> </span>';
firsthtml += ' </div>';
firsthtml += ' </div>';
firsthtml += ' <div class="couponCheck gh_none"></div>';
firsthtml += ' <div class="couponCheck1 gh_f16 gh_none"><span>已存入可用余额</span><br><span>可直接使用</span></div>';
firsthtml += ' <div class="bottom_img success ">';
firsthtml += ' <img src="static/images/redPackets_bottom_img.png" alt="" />';
firsthtml += ' </div>';
firsthtml += ' </div>';
firsthtml += '</div>';
$("body").append(firsthtml);
_this.bindEvent();
},
//红包显示弹层
bindEvent: function() {
$('#red_container .close').off().on("click", function() {
$('#red_container').remove();
// window.location.href = 'account-myCoupon.html'
});
}
} |
let express = require('express');
let router = express.Router();
const yelp = require('yelp-fusion');
const token = 'Y8s6dW3uAs-TZ34YRekghk7llJxJuj3JjNAcLtADi-OZ02Dl66_soagZHv-eTyQFHC8fGWfxblXrZxyW3msB1GARItcv2KG0qhzgowweVi4qxdw3fijzXeIyKKd2XXYx';
const client = yelp.client(token);
router.use(function(req, res, next){
client.search({
location: 'Alpharetta',
categories: 'icecream',
sort_by: 'review_count'
}).then(response => {
res.data = response.jsonBody.businesses;
next();
}).catch(e => {
console.log(e);
});
})
//Sort top five businesses algorithm
router.use(function(req, res, next){
let data = res.data;
let countCriteria = 5;
let topFiveBusinesses = [];
if(data.length > 50){
data.length = 50;
}
while(countCriteria !== 3){
if(topFiveBusinesses.length === 5 ){
break;
}else{
data.map(function(business){
if(business.rating === countCriteria){
topFiveBusinesses.push(business);
}
if(topFiveBusinesses.length === 5){
break;
}
})
countCriteria = countCriteria - 0.5;
}
}
res.data = topFiveBusinesses;
next();
})
router.get('/', function(req, res, next) {
console.log(res.data);
res.send(res.data);
});
router.get('/details/:id', function(req, res, next) {
console.log(req.params.id);
client.business(req.params.id).then(response => {
console.log(response.jsonBody);
res.send(response.jsonBody);
}).catch(e => {
console.log(e);
});
});
router.get('/reviews/:id', function(req, res, next) {
console.log(req.params);
client.reviews(req.params.id).then(response => {
console.log(response.jsonBody.reviews);
res.send(response.jsonBody.reviews);
}).catch(e => {
console.log(e);
});
});
module.exports = router;
|
import React from "react";
import {Collapse, NavbarBrand, Navbar, NavItem, NavLink, Nav, Container} from "reactstrap";
// Import child components
import NavbarProfile from "./dashboard/Navbar.Profile.components"
// Import authContext
import {useAuthContext, fetchUserProfile} from "../services/AuthReducer"
// Create Navbar context for child components
export const NavbarContext = React.createContext();
export const useNavbarContext = () => {return React.useContext(NavbarContext)}
// Logo var
const navbarLogoPath = require("./../assets/img/stream-logo-white-text.png");
function IndexNavbar () {
const auth = useAuthContext();
const [navbarColor, setNavbarColor] = React.useState("navbar-transparent");
const [collapseOpen, setCollapseOpen] = React.useState(false);
// Set user state for Navbar
const [userState, setUserState] = React.useState({
'username':"",
})
React.useEffect(() => {
// Fetch username of currently logged in user
(async () => {
if (auth.state.isAuthenticated) {
const user = await fetchUserProfile(auth);
setUserState({'username':user.username})
}
})();
const updateNavbarColor = () => {
if (document.documentElement.scrollTop > 399 || document.body.scrollTop > 399) {
setNavbarColor("");
} else if (document.documentElement.scrollTop < 400 || document.body.scrollTop < 400) {
setNavbarColor("navbar-transparent");
}};
window.addEventListener("scroll", updateNavbarColor);
return function cleanup() {
window.removeEventListener("scroll", updateNavbarColor);
};
}, [auth]);
return (
<>
<NavbarContext.Provider value ={{userState}}>
{collapseOpen ? (<div id="bodyClick" onClick={() => {
document.documentElement.classList.toggle("nav-open");
setCollapseOpen(false);
}}/>) : null}
<Navbar className={"navbar-dark fixed-top " + navbarColor} expand="lg" color="info">
<Container>
<div className="navbar-translate">
<NavbarBrand href={auth.state.isAuthenticated ? ("/dashboard") : ("/")} id="navbar-brand"><img alt="logo" src={navbarLogoPath} style={{width: "20%", height:"20%"}} /></NavbarBrand>
<button className="navbar-toggler navbar-toggler-icon" onClick={() => {
document.documentElement.classList.toggle("nav-open");
setCollapseOpen(!collapseOpen);
}} aria-expanded={collapseOpen} type="button"></button>
</div>
<Collapse className="justify-content-end" isOpen={collapseOpen} navbar>
<Nav navbar>
<NavItem>
<NavLink href="/about" hidden={auth.state.isAuthenticated}><p>About</p></NavLink>
</NavItem>
<NavItem>
<NavLink href="/" hidden={!auth.state.isAuthenticated}><p>Dashboard</p></NavLink>
</NavItem>
<NavItem>
<NavLink href="/register" hidden={auth.state.isAuthenticated}><p>Register</p></NavLink>
</NavItem>
<NavItem>
<NavLink href="/login" hidden={auth.state.isAuthenticated}><p>Login</p></NavLink>
</NavItem>
{/* <NavItem>
<NavLink href="/projects" hidden={!auth.state.isAuthenticated}><p>Projects</p></NavLink>
</NavItem>
<NavItem>
<NavLink href="/teams" hidden={!auth.state.isAuthenticated}><p>Teams</p></NavLink>
</NavItem> */}
<NavItem>
<NavbarProfile></NavbarProfile>
</NavItem>
</Nav>
</Collapse>
</Container>
</Navbar>
</NavbarContext.Provider>
</>
);
}
export default IndexNavbar;
|
const errors = require('../index');
describe('Error Tests', () => {
it('Should export an object', () => {
expect(errors).toBeDefined();
expect(errors).toBeInstanceOf(Object);
});
it('Should export more than one property', () => {
expect(errors).toBeDefined();
expect(errors).toBeInstanceOf(Object);
const keys = Object.keys(errors);
expect(keys).toBeDefined();
expect(keys).toBeInstanceOf(Array);
expect(keys.length).toBeGreaterThan(0);
});
});
|
import React, { useState } from 'react';
import styles from '../styles/pages/Portfolio.module.scss';
import Rectangle from '../components/Rectangle';
import TextTitle from '../components/TextTitle';
import { useSelector } from 'react-redux';
import AwesomeSlider from 'react-awesome-slider';
import AwsSliderStyles from 'react-awesome-slider/src/styles';
import img1 from '../assets/img/1.jpeg';
import img2 from '../assets/img/2.jpeg';
import img3 from '../assets/img/3.jpeg';
import {
FaCheck,
FaWarehouse,
FaHandHoldingUsd,
FaShoppingCart,
FaCalculator,
FaCar,
FaGavel,
FaChartLine,
FaLandmark,
FaSearchDollar,
FaCopy,
FaUserFriends,
} from 'react-icons/fa';
import { IoIosGlobe } from "react-icons/io";
const listIcons = [
{
name: 'Almoxarifado',
icon: <FaWarehouse size={'3rem'}/>,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Arrecadação',
icon: <FaHandHoldingUsd size={'3rem'} />,
description: `
Permite a gestão das Taxas e Impostos municipais, efetuando
cálculos automáticos de acordo com o código tributário vigente
no município. Possui opções de acesso público aos contribuintes
para consulta de débitos no município, dentre outras funcionalidades.
<br />
<br />
<strong> Nota Fiscal Eletrônica:</strong> Permite a Gestão e fiscalização do ISS
do município, a partir da emissão de Notas Fiscais Eletrônicas. O
módulo permite que o próprio contribuinte possa realizar a emissão
da Nota Eletrônica e o sistema realiza o cálculo automático dos impostos
de acordo com a alíquota do serviço selecionado.
`,
listVantagens: [
{title:'Emissão de Taxas', iconTam:'15px'},
{title:'Lançamento de IPTU, ITBI e outros', iconTam:'15px'},
{title:'Consulta de débitos geral e por contribuinte', iconTam:'15px'},
{title:'REFIS', iconTam:'15px'},
{title:'Emissão de Nota Eletrônica e Avulsa', iconTam:'15px'},
{title:'Emissão de Guias de Taxas e Impostos', iconTam:'15px'},
{title:'Relatórios de Gestão', iconTam:'15px'}
]
},
{
name: 'Compras',
icon: <FaShoppingCart size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Contábil',
icon: <FaCalculator size={'3rem'} />,
description: `
O sistema de contabilidade foi desenvolvido para atender as
necessidades dos usuários das entidades Públicas Municipais,
facilitando o seu dia a dia. Todas as telas foram criadas
utilizando uma linguagem simples e de fácil aprendizado
permitindo uma maior facilidade na operacionalização do sistema
`,
listVantagens: [
{title:'Suporte técnico eficiente', iconTam:'15px'},
{title:'Módulo Web sem limite de usuários', iconTam:'15px'},
{title:'Integração com os módulos de Orçamento, Portal da Transparência RH, Arrecadação, Protocolo, dentre outros', iconTam:'25px'},
{title:'Layouts atualizados de acordo com as legislações vigentes', iconTam:'15px'},
{title:'Relatórios gerencias desenvolvidos de acordo com a necessidade do cliente', iconTam:'17px'},
{title:'Filtros diversos para consulta de dados', iconTam:'15px'},
{title:'Exportação de arquivos para Prestação de Contas', iconTam:'15px'}
]
},
{
name: 'Frotas',
icon: <FaCar size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Licitação',
icon: <FaGavel size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Orçamentário',
icon: <FaChartLine size={'3rem'} />,
description: `
Permite a gestão e o planejamento do orçamento público, bom como
o gerenciamento de Programas, Ações, Receitas e Despesas Públicas.
Possui integração completa com o módulo de Contabilidade e Compras
permitindo um maior controle nas gestão dos recursos municipais.
`,
listVantagens: [
{title:'Cadastro do PPA, LDO e LOA', iconTam:'15px'},
{title:'Lançamento do PPA, Orçamento da Receita e Despesa', iconTam:'15px'},
{title:'Anexos do PPA, Lei 4.320, LRF dentre outros', iconTam:'15px'}
]
},
{
name: 'Patrimônio',
icon: <FaLandmark size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Portal da Transparência',
icon: <FaSearchDollar size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Protocolo',
icon: <FaCopy size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Recursos Humanos',
icon: <FaUserFriends size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
{
name: 'Serviços de acesso pelo Cidadão via Internet',
icon: <IoIosGlobe size={'3rem'} />,
description: `
[DESCRIÇÃO]
`,
listVantagens: [
{title:'VATAGEM 1', iconTam:'15px'},
{title:'VATAGEM 2', iconTam:'15px'},
{title:'VATAGEM 3', iconTam:'15px'},
{title:'VATAGEM 4', iconTam:'15px'},
]
},
]
const ContainerInfosProd = props => (
<div
key={props.index}
>
<div
style={{
display: 'flex',
alignItems:'center',
justifyContent:'space-around',
flexDirection:'column'
}}
>
<h1 style={{marginBottom:'1.5rem', color: '#2d3a6a',}}> {props.icons.name} </h1>
<p
id="textDescript"
style={{
width:'70%',
marginTop:'1rem',
textAlign:'justify',
fontSize:'1.6rem',
color: '#2d3a6a',
}}
dangerouslySetInnerHTML={{__html:props.icons.description}}
/>
<h3 style={{marginTop:'2rem', fontSize:'1.6rem', marginBottom:'2.5rem', color: '#2d3a6a',}}> Vantagens do módulo </h3>
<div style={{
display: 'grid',
gridGap:'1rem',
width:'50%',
color: '#2d3a6a',
}}>
{props.icons.listVantagens.map(vantagem => (
<span className={styles.containerVantagens}> <FaCheck size={vantagem.iconTam} /> <p> {vantagem.title} </p> </span>
))}
</div>
</div>
</div>
)
export default function Portfolio() {
const [infoPort, setPort] = useState(0);
const globalState = useSelector(state=>state);
var theme = globalState.theme;
var themeText = globalState.themeText;
return(
<div className={styles.container}>
<div className={styles.containerRectangle}>
<Rectangle
cor={{'gradient':true,'colorStart':theme.colorStart, 'colorEnd':theme.colorEnd}}
width={window.screen.availWidth < 560 ? false :'45%'}
left={false}
height='80%'
pos={{'right':'-20px', 'position':'absolute'}}
>
<div className={styles.containerRectangleTwo}>
<div className={styles.textTitle}>
<TextTitle color={{'gradient':true, 'colorStart':themeText.colorStart, 'colorEnd':themeText.colorEnd}}>Portfólio</TextTitle>
</div>
</div>
</Rectangle>
</div>
<Rectangle
width={window.screen.availWidth < 560 ? false : '60%'}
height={window.screen.availWidth < 560 ? '50%' : '70%'}
left={true}
cor={'#fff'}
pos={{'left':'0px', 'position':'absolute'}}
style={{overflow:'hidden'}}
>
<AwesomeSlider
style={{
flex: 10,
}}
mobileTouch={true}
selected={infoPort}
>
{listIcons.map((icons, index) => (
<div key={index}>
<ContainerInfosProd icons={icons} index={index} />
</div>
))}
</AwesomeSlider>
<div style={{
display: 'flex',
flex:1,
alignItems:'flex-end',
justifyContent:'space-around',
flexDirection:'column',
width: '100%',
height: '100%',
transition: 'ease-in-out'
}}>
{listIcons.map((icons, index) => (
<div
key={index}
onClick={() => setPort(index)}
style={{
backgroundColor: theme.type === 'gestao' ? infoPort === index ? '#fff' : '#D8A72C' : infoPort === index ? '#fff' : '#2d3a6a',
width:'100%',
height:'100%',
display:'flex',
alignItems:'center',
justifyContent:'center',
color: theme.type === 'gestao' ? infoPort === index ? '#2d3a6a': '#fff' : infoPort === index ? '#D8A72C': '#fff',
cursor: 'pointer'
}}>
{icons.icon}
</div>
))}
</div>
</Rectangle>
</div>
)
}
/**
* <div className={styles.gridPort}>
{listImgs.map((imgs, index) => (
<a href="#portifolio">
<img src={imgs} alt="imgs"/>
</a>
))}
</div>
{listIcons.map((icons, index) => (
<ContainerInfosProd icons={icons} index={index} />
))}
*/ |
import isClass from './isClass';
export default function isStatelessComponent( element ) {
return !isClass(element) && typeof element === 'function';
} |
module.exports = [{
folder: 'user',
route: 'user.route.js',
controller: 'user.controller.js',
model: 'user.model.js',
url: '/user'
}]
|
#!/usr/bin/env node
'use strict';
const script = process.argv[2];
require(`./scripts/${script}`);
|
var btnElement = document.getElementById('btn');
btnElement.onclick = function () {
var firstNameValue = document.getElementById('firstName').value;
var lastNameValue = document.getElementById('lastName').value;
var fullNameValue = firstNameValue+' '+lastNameValue;
document.getElementById('fullName').value = fullNameValue;
};
var summationElement = document.getElementById('summation');
summationElement.onclick = function () {
var firstNumber = document.getElementById('firstNumber').value;
var secondNumber = document.getElementById('secondNumber').value;
var summationResult = firstNumber+secondNumber;
document.getElementById('result').value = summationResult;
}; |
import React from "react";
import {Route, Switch} from "react-router-dom";
import eCommerce from "./eCommerce";
import ErrorPages from "./errorPages";
import Extras from "./extras";
import ListType from "./listType";
import UserAuth from "./userAuth";
const CustomViews = ({match}) => (
<Switch>
<Route path={`${match.url}/eCommerce`} component={eCommerce}/>
<Route path={`${match.url}/error-pages`} component={ErrorPages}/>
<Route path={`${match.url}/extras`} component={Extras}/>
<Route path={`${match.url}/list-type`} component={ListType}/>
<Route path={`${match.url}/user-auth`} component={UserAuth}/>
</Switch>
);
export default CustomViews;
|
var myApp = angular
.module("myModule",[])
.controller("myController", function($scope, $http){
$scope.location = "";
$scope.displayWeather = false;
var getWeather = function(){
$scope.weatherURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+$scope.location+"%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$http({
method:"GET",
url: $scope.weatherURL
}).then(function successW(response){
$scope.result = response.data;
$scope.displayWeather = true;
},function failureW(response){
$scope.result = response.statusText;
});
}
$scope.getWeather = getWeather;
}); |
// Globals:
const url = "https://600ff44f6c21e1001704fac2.mockapi.io/minor-web/api/";
// GET REQUEST
const teams = fetch(`${url}/squads/1/teams/1/members`)
.then((response) => response.json())
.then((data) => {
console.log(data);
const person = getPerson(data, "Veerle");
createElements(person[0]);
});
const getPerson = (data, person) => {
return data.filter((item) => item.name === person);
};
const createElements = (data) => {
changeImg(`${data.mugshot}`, "img");
changeText(`${data.name} ${data.surname}`, "h2");
changeText(`Frontend developer`, "h3");
changeText(`${data.other.workplace}`, "p");
changeText(`${data.other.music}`, "p", 1);
changeText(`${data.other.movie}`, "p", 2);
changeHref(
`https://github.com/${data.githubHandle}`,
"a",
`github.com/${data.name + data.surname}`
);
changeHref(`mailto:${data.other.mail}`, "a", data.other.mail, 1);
};
const changeImg = (link, element, index = 0) => {
const elements = Array.from(document.getElementsByTagName(element));
elements[index].src = link;
};
const changeText = (text, element, index = 0) => {
const elements = Array.from(document.getElementsByTagName(element));
elements[index].innerHTML = text;
};
const changeHref = (link, element, text, index = 0) => {
const elements = Array.from(document.getElementsByTagName(element));
elements[index].href = link;
elements[index].innerHTML = text;
};
// PUT REQUEST
const putData = {
id: 1,
teamId: 1,
name: "Veerle",
prefix: "",
surname: "Prins",
mugshot:
"https://avatars.githubusercontent.com/u/35265583?s=400&u=47b65ecd0d19e635807f65efbaed120170425a9d&v=4",
githubHandle: "veerleprins",
url: "https://veerleprins.github.io/kickoff-2021/",
other: {
age: "23",
music: "House, Lo-Fi beats",
pet: "Hond",
sport: "Geen sport",
workplace: "Op mijn slaapkamer aan mijn bureau.",
mail: "info@veerleprins.nl",
movie: "Horror, Thriller, Komedie, Actie",
},
};
async function postData(url = "", data = {}) {
const response = await fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return response.json();
}
postData(`${url}/squads/1/teams/1/members/47`, putData).then((data) => {
console.log("put", data);
});
|
var text,
word;
function wordOccur(text, word) {
var arr = [],
count = 0,
len,
i,
resCheck,
resArr;
arr = text.split(" ");
len = arr.length;
for (i = 0; i < len; i++) {
resCheck = word.toLowerCase();
resArr = arr[i].toLowerCase();
if (resCheck == resArr) {
count++;
}
}
console.log(count);
}
a = "The toLowerCase() method converts a string to lowercase letters. Note: The toLowerCase() method does not change the original string.Tip: Use the toUpperCase() method to convert a string to uppercase letters.";
b = 'Method';
wordOccur(a, b); |
/**
* Created by Wwei on 2016/9/1.
*/
Ext.define('Admin.view.brand.BrandController', {
extend: 'Admin.view.BaseViewController',
alias: 'controller.brand',
requires: ['Admin.view.brand.BrandForm'],
search: function () {
var me = this,
grid = me.lookupReference('grid'),
form = me.lookupReference('form');
if (!form.isValid()) {
return false;
}
grid.getStore().loadPage(1);
},
/** grid 渲染之前 初始化操作
* add beforeload listener to grid store
* @param {Ext.Component} component
*/
gridBeforeRender: function () {
var me = this,
form = me.lookupReference('form'),
grid = me.lookupReference('grid');
grid.getStore().addListener({
'beforeload': function (store) {
grid.getScrollTarget().scrollTo(0, 0); //每次加载之前 scrolly to 0
Ext.apply(store.getProxy().extraParams, form.getValues(false, true));
return true;
},
'load': function (store) {
store.getProxy().extraParams = {};
},
'beginupdate': function () {
grid.setHeight(grid.getHeight()); //设置grid height,如果不这样则一页显示数据多了则不显示scrolly 估计是extjs6的bug
return true;
}
});
grid.getStore().reload();
},
/**
*
* @param grid
* @param rowIndex
*/
deleteBrand: function (grid,rowIndex) {
Ext.Msg.confirm(
"请确认"
, "要删除该品牌吗?"
, function (button, text) {
if (button == 'yes') {
var rec = grid.getStore().getAt(rowIndex);
Common.util.Util.doAjax({
url: Common.Config.requestPath('Brand', 'deleteBrand'),
method: 'post',
params: {
id:rec.get('id')
}
}, function (data) {
grid.getStore().reload();
Common.util.Util.toast("删除成功");
});
}
}, this);
},
/**
*添加品牌
*/
addBrand: function () {
Ext.create('Admin.view.brand.BrandForm', {
action: 'create',
store: this.lookupReference('grid').getStore()
}).show();
},
/**
* 修改品牌
* @param grid
* @param rowIndex
* @param colIndex
*/
modifyBrand: function (grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
Ext.create('Admin.view.brand.BrandForm', {
action: 'update',
title: '品牌修改',
store: this.lookupReference('grid').getStore(),
viewModel: {
links: {
theBrand: {
type: 'brand.Brand',
create: rec.data
}
}
}
}).show();
},
/**
* 关闭窗口
*/
closeWindow: function () {
this.getView().close();
},
/** 清除 查询 条件
* @param {Ext.button.Button} component
* @param {Event} e
*/
reset: function () {
this.lookupReference('form').reset();
}
}); |
import { tagName } from '@ember-decorators/component';
import BaseDropdownMenuItem from 'ember-bootstrap/components/base/bs-dropdown/menu/item';
@tagName('li')
export default class DropdownMenuItem extends BaseDropdownMenuItem {}
|
const intialState = {
openModalForTeacher : true,
teacherDetails : {}
}
const sliderReducer = (state = intialState, action) => {
switch (action.type) {
case 'OPEN_MODAL':
return { ...state,
openModalForTeacher : !openModalForTeacher
};
default:
return state;
}
};
export default sliderReducer; |
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import { apiDelete } from 'utils/axios';
import * as Sentry from '@sentry/browser';
import 'draft-js/dist/Draft.css';
import 'draftail/dist/draftail.css';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
MenuItem,
} from '@material-ui/core/';
import styles from './styles';
class DeleteModal extends React.Component {
constructor(props) {
super(props);
this.state = {
message: this.props.message,
req: this.props.req,
body: this.props.body,
open: false,
};
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleOpen() {
this.setState({ open: true });
}
handleClose() {
this.setState({ open: false });
}
handleSubmit() {
const { body } = this.state;
const { req } = this.state;
apiDelete(req, { case_note: body })
.then(() => window.location.reload())
.catch(error => {
Sentry.configureScope(function(scope) {
scope.setExtra('file', 'DeleteModal');
scope.setExtra('action', 'apiDelete');
scope.setExtra('case_note', JSON.stringify(body));
});
Sentry.captureException(error);
});
}
render() {
const { classes } = this.props;
const dialog = (
<Dialog
className={classes.dialogStyle}
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
maxWidth="sm"
fullWidth
>
<DialogContent maxwidth="sm">
<DialogContentText className={classes.dialogContentTextStyle}>
{this.state.message}
</DialogContentText>
</DialogContent>
<DialogActions className={classes.dialogActionsStyle}>
<Button
onClick={this.handleClose}
variant="contained"
color="secondary"
>
Cancel
</Button>
<Button
onClick={this.handleSubmit}
variant="contained"
color="primary"
>
Delete
</Button>
</DialogActions>
</Dialog>
);
return (
<div>
<MenuItem onClick={this.handleOpen}>Delete</MenuItem>
{dialog}
</div>
);
}
}
DeleteModal.propTypes = {
classes: PropTypes.object.isRequired,
body: PropTypes.object.isRequired,
req: PropTypes.string.isRequired,
message: PropTypes.string,
};
export default withStyles(styles)(DeleteModal);
|
define('TopHudView', [
'createjs',
'TopHudPlayerView',
'ViewConstants'
], function (createjs, TopHudPlayer, ViewConstants) {
var container;
var TopHud = function() {
this.playerHuds = [];
};
TopHud.prototype.initialize = function (assets, parent, players) {
container = new createjs.Container();
container.x = ViewConstants.CONTENT_WIDTH - ViewConstants.HUD_WIDTH;
parent.addChild(container);
var count = 2;
for (var i in players) {
this.playerHuds[players[i].id] = new TopHudPlayer();
this.playerHuds[players[i].id].initialize(assets, container, players[i], count--);
}
};
TopHud.prototype.update = function (players) {
var player;
for (var i in players) {
player = players[i];
this.playerHuds[player.id].update(player);
}
};
return TopHud;
});
|
const mysqlUtil = require('../utils/MySQLUtil');
const _ = require('lodash')
const moment = require('moment')
class Message {
async createChat(params) {
const { from, to, subject } = params;
const result = await mysqlUtil.query('INSERT INTO `chat` (fromuser, touser, subject) VALUES (?, ?, ?);', [from, to, subject]);
if (result && result.length) {
return result[0].insertId;
}
return null;
}
async sendMessage(params) {
const { chatId, from, text } = params;
const result = await mysqlUtil.query('INSERT INTO `message` (chat_id, user_id, text) VALUES (?, ?, ?);', [chatId, from, text]);
return result[0].insertId;
}
async updateChatTime(params) {
const { chatId } = params;
const result = await mysqlUtil.query('UPDATE `chat` set date = CURRENT_TIMESTAMP where id = ?', [chatId]);
console.log(result);
return result;
}
async getChat(params) {
const { userId } = params;
const result = await mysqlUtil.query('SELECT c.id chat_id, c.date, c.fromuser, c.touser, c.subject, u.id, u.img_url, u.firstname, u.lastname FROM `chat` c \
LEFT JOIN \
`user` u \
on c.fromuser = u.id or \
c.touser = u.id \
where (c.`fromuser`=? or c.`touser`=?) \
and u.`id` != ? \
ORDER BY c.date DESC;', [userId, userId, userId]);
const chats = result[0];
return (chats);
}
async getMessages(params) {
const { chatId, userId } = params;
const result = await mysqlUtil.query('SELECT DISTINCT m.chat_id, m.user_id, m.text, m.date, u.id, u.img_url, u.firstname, u.lastname FROM `chat` c \
LEFT JOIN \
`message` m \
on m.chat_id = c.id \
LEFT JOIN \
`user` u \
on u.`id` = m.`user_id` \
where (c.`fromuser`=? or c.`touser`=?) and m.`chat_id`=? \
ORDER BY m.date ASC;', [userId, userId, chatId]);
const messages = result[0];
const messagesByDate = _.groupBy(messages, function(message) {
return moment(message.date).subtract(8, 'hours').format("YYYY-MM-DD")
})
return messagesByDate;
}
}
module.exports = new Message(); |
import React from "react"
import { Article, Title, Link, Image, Category, Excerpt } from "./style"
import parse from "html-react-parser"
const Teaser = ({ data }) => {
return (
<Article>
<Image
style={{ marginBottom: "18px" }}
fluid={{
...data.featuredImage,
sizes: "(max-width: 1024px) 100vw, 360px",
}}
/>
<div style={{ display: "flex", marginBottom: "10px" }}>
{data.categories.nodes.map((item, index) => (
<Category key={index} style={{ fontWeight: "600" }}>
{item.name}
</Category>
))}
</div>
<div>
<Title style={{ marginBottom: "15px" }}>{parse(data.title)}</Title>
</div>
<div>
<Excerpt style={{ fontSize: "15px", marginBottom: "10px" }}>
{data.excerpt}
</Excerpt>
</div>
<div style={{ marginBottom: "-25px" }}>
<Link to={data.uri} style={{ color: "black", fontWeight: "bold" }}>
Read More
</Link>
</div>
</Article>
)
}
export default Teaser
|
/*============================================================================
MessageGate Request Module
============================================================================*/
let jsforce = require('jsforce');
let secrets = require("../../secrets/secrets.js");
let fs = require("fs");
let mailer = require("../modules/mail/mail.js");
/*============================================================================
Init
============================================================================*/
function init(pass_express) {
allObject(pass_express);
// singleObject(app);
}
/*============================================================================
Messages
============================================================================*/
let SMS_DELIVERY_FAIL = `Warning! An SMS recently triggered a failure flag.
See message contents below.` + "\n\n";
let SMS_DELIVERY_FAIL_SUBJECT = "MessageG8 - Delivery Failure";
let SMS_REPLY = `Hi there! You've recently received a reply to an Abalobi SMS. See message contents below.` + "\n\n";
let SMS_REPLY_SUBJECT = `MessageG8 - SMS Reply` + "\n\n";
/*============================================================================
Functions
============================================================================*/
function allObject(app){
app.post('/messagegate', function(req, resMain) {
console.log("Received POST for MESSAGEG8");
console.log("PROTOCOL: " + req.protocol + '://' + req.get('host') + req.originalUrl + "\n");
let protocolString = "PROTOCOL: " + req.protocol + '://' + req.get('host') + req.originalUrl + "\n";
let requestInfo = req.body;
let filter = req.body.message_type;
let email = {};
//Decide what to do based on filter
switch (filter){
case "message_reply":
let MESSAGE_DETAILS = "" +
"Sender: " + req.body.message_sender + "" +
"\nContent: " + req.body.message_body;
email.SUBJECT = SMS_REPLY_SUBJECT;
email.BODY = SMS_REPLY + MESSAGE_DETAILS;
break;
case "delivery_report":
let ERROR_REPORT = "" +
"Recipient: " + req.body.message_recipient + "" +
"\nError log: " + req.body.messages;
email.SUBJECT = SMS_DELIVERY_FAIL_SUBJECT;
email.BODY = SMS_DELIVERY_FAIL + ERROR_REPORT;
break;
}
mailer.mailSimple(email.SUBJECT, email.BODY, secrets.TEST_RECIPIENT);
//DEBUG STUFF
console.log(JSON.stringify(requestInfo, null, 4));
console.log(JSON.stringify(email, null, 4));
resMain.statusCode = 200;
resMain.body = {
protocolString : protocolString,
email: email
};
resMain.send();
});
}
module.exports = {
init: init
};
|
const ERC4907Demo = artifacts.require("ERC4907Demo");
module.exports = function (deployer) {
deployer.deploy(ERC4907Demo, "ERC4907Demo", "ERC4907Demo");
};
|
/**
* Calculates the euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} distance between a and b
*/
export default function distance(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1]
return Math.sqrt(x*x + y*y)
} |
import React, { useState } from 'react'
import {useHistory} from 'react-router-dom'
import styled from 'styled-components'
// action
import { addEvent } from '../store/action/eventAction'
// Redux hook
import { useDispatch } from 'react-redux'
const StyledAddEvent = styled.div`
background-color: #202C59;
min-height: 80vh;
display: flex;
justify-content: center;
align-items: center;
form {
background-color: #581F18;
box-shadow: 3px 3px 3px black;
padding: 1% 3%;
color: white;
min-width: 35%;
text-align: center;
text-shadow: 1px 1px 1px black;
input {
margin: 3%;
padding: 2%;
text-align: center;
font-size: 1.5rem;
@media(max-width: 500px) {
margin: 2%;
padding: .5%;
font-size: 1rem;
}
}
button {
padding: 2% 5%;
font-size: 2rem;
background-color: #F0A202;
color: white;
margin-bottom: 4%;
box-shadow: 1px 1px 3px black;
transition: all .2s;
cursor: pointer;
@media(max-width: 500px) {
padding: .5% 2.5%;
font-size: 1rem;
margin-top: 2%;
}
&:hover {
box-shadow: 3px 3px 5px black;
background-color: #D95D39;
}
}
}
`
function AddEvent() {
const dispatch = useDispatch()
const history = useHistory()
const [events, setEvents] = useState({
name: '',
date:'',
time: '',
location: '',
})
const handleChange = (e) => {
setEvents({
...events,
[e.target.name]: e.target.value,
})
}
const handleSubmit = (e) => {
e.preventDefault()
dispatch(addEvent(events))
history.push('/events')
}
return (
<StyledAddEvent className='add___events'>
<form onSubmit={handleSubmit}>
<h1>Add An Event</h1>
<div>
<input name='name' placeholder="Event Name" value={events.name} onChange={handleChange} />
</div>
<div>
<input name='date' placeholder="Event Date" value={events.date} onChange={handleChange} />
</div>
<div>
<input name='time' placeholder="Event Time" value={events.time} onChange={handleChange} />
</div>
<div>
<input name='location' placeholder="Event Location" value={events.location} onChange={handleChange} />
</div>
<div>
<button type='submit'>Add</button>
</div>
</form>
</StyledAddEvent>
)
}
export default AddEvent
|
module.exports.createControllers = function(app, properties, serviceLocator, bundleManager) {
bundleManager.forEachProperty('controllerFactories', function(bundle, factory) {
serviceLocator.logger.verbose('Adding controllers from: ' + bundle.name);
factory(app, properties, serviceLocator, bundle.path + '/views');
});
// Make the bundle manager avaialbe to views
app.configure(function() {
app
.dynamicHelpers({
bundleManager: function(req, res) {
return bundleManager;
}
});
});
}; |
import styled from 'styled-components'
import homepic from '@a/images/iconku/u3225.png'
import companypic from '@a/images/iconku/u3827.png'
const Wrap=styled.div`
height: 100%;
width:100%;
display:block;
position: relative;
background-color:rgba(242, 242, 242, 0.6);
.back{
display:block;
position: absolute;
left:.15rem;
top:.15rem;
}
.create{
position: absolute;
left: 2.66rem;
top: .15rem;
width: .92rem;
height: .17rem;
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 14px;
color: #00CC99;
text-align: right;
}
.head{
display:border-box;
position:absolute;
width:.82rem;
height:.82rem;
border:4px solid #fff;
border-radius:.4rem;
left:50%;
transform:translateX(-50%);
top:.8rem;
background-color:#00CC99;
.headPic{
display:block;
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
width:.4rem;
height:.32rem;
}
}
.form{
position: absolute;
top:1.8rem;
left:50%;
transform:translateX(-50%);
width: 3.4rem;
height: 2.05rem;
background: inherit;
background-color: rgba(255, 255, 255, 1);
border: none;
border-radius: 3px;
-moz-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
.phone{
border-width: 0px;
display:block;
position: absolute;
left: .25rem;
top: .35rem;
width: .14rem;
height: .24rem;
}
.tel{
position: absolute;
left: .6rem;
top: .32rem;
width: 2.57rem;
height: 0.34rem;
background-color: transparent;
font-family: 'ArialMT', 'Arial';
font-weight: 400;
font-style: normal;
font-size: 14px;
text-decoration: none;
text-align: left;
border-color: transparent;
outline-style: none;
}
.line{
display:block;
border-width: 0px;
position: absolute;
left: .25rem;
top: .7rem;
width: 2.96rem;
height: 2px;
}
.lock{
border-width: 0px;
display:block;
position: absolute;
left: .24rem;
top: 1rem;
width:17px;
height:13px;
}
.lock1{
border-width: 0px;
display:block;
position: absolute;
left: .27rem;
top: .94rem;
width:11px;
height:10px;
}
.line1{
display:block;
border-width: 0px;
position: absolute;
left: .25rem;
top: 1.3rem;
width: 2.96rem;
height: 2px;
}
.password{
position: absolute;
left: .6rem;
top: .92rem;
width: 2.57rem;
height: 0.34rem;
background-color: transparent;
font-family: 'ArialMT', 'Arial';
font-weight: 400;
font-style: normal;
font-size: 14px;
text-decoration: none;
text-align: left;
border-color: transparent;
outline-style: none;
}
.eyeC{
border-width: 0px;
display:block;
position: absolute;
left: 2.9rem;
top: 1.05rem;
width:20px;
height:11px;
}
.eyeO{
border-width: 0px;
display:block;
position: absolute;
left: 2.9rem;
top: 1.0rem;
width:20px;
height:13px;
}
.forget{
border-width: 0px;
position: absolute;
left: 2.6rem;
top: 1.55rem;
width: .57rem;
height: .2rem;
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 14px;
color: #00CC99;
}
}
.button{
border-width: 0px;
position: absolute;
left: 50%;
transform:translateX(-50%);
top: 4.1rem;
width: 3.4rem;
height: .5rem;
background: inherit;
background-color: rgba(0, 204, 153, 1);
border: none;
border-radius: 3px;
-moz-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 16px;
text-align:center;
line-height:.5rem;
color: #FFFFFF;
}
.wechat{
border-width: 0px;
display:block;
position: absolute;
left: 20%;
transform:translateX(-50%);
top: 5.2rem;
width:29px;
height:24px;
}
.qq{
border-width: 0px;
display:block;
position: absolute;
left: 50%;
transform:translateX(-50%);
top: 5.2rem;
width:24px;
height:24px;
}
.sina{
border-width: 0px;
display:block;
position: absolute;
left: 80%;
transform:translateX(-50%);
top: 5.2rem;
width:31px;
height:24px;
}
.weichat1{
border-width: 0px;
position: absolute;
left: 20%;
transform:translateX(-50%);
top: 5.5rem;
width: 25px;
height: 17px;
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 12px;
color: #AEAEAE;
text-align: center;
}
.qq1{
border-width: 0px;
position: absolute;
left: 50%;
transform:translateX(-50%);
top: 5.5rem;
width: 25px;
height: 17px;
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 12px;
color: #AEAEAE;
text-align: center;
}
.sina1{
border-width: 0px;
position: absolute;
left: 80%;
transform:translateX(-50%);
top: 5.5rem;
width: 25px;
height: 17px;
font-family: 'PingFangSC-Regular', 'PingFang SC';
font-weight: 400;
font-style: normal;
font-size: 12px;
color: #AEAEAE;
text-align: center;
}
`
const Main = styled.div`
`
export {
Wrap,
Main
}; |
export const Formatter = {
formatTime(d){
if (!(d instanceof Date)) {
d = new Date(d)
}
var h = d.getHours(),
m = d.getMinutes()
return h + ':' + (m < 10 ? '0' + m : m)
},
formatDate(d){
if (!(d instanceof Date)) {
d = new Date(d)
}
return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`
}
} |
function receivesAFunction(callback) {
callback();
}
function returnsANamedFunction(){
return function index(){
}
}
function returnsAnAnonymousFunction(){
return function(){
}
} |
const isPrime = test => {
if(test === 2){return true}
else if(test % 2 === 0 || test < 2){return false}
else{
for(let i = 3; i <= Math.sqrt(test); i = i+2){
if(test % i === 0){
return false
}
}
return true
}
}
const circularPrimesBelow = limit => {
let count = 0
for(let i = 2; i < limit; i++){
let number = i
let circular = true
if(isPrime(number)){
let digits = i.toString().split("")
for(let rotations = 0; rotations < digits.length-1; rotations++){
digits.push(digits.shift())
if(!isPrime(Number(digits.join("")))){
circular = false
break
}
}
if(circular){
count += 1
}
}
}
return count
}
console.log(circularPrimesBelow(1000000)) //55
|
import React from "react";
import { Link } from "react-router-dom";
import DevelopmentPlan from "../../containers/DevelopmentPlan";
import TopBar from "./TopBar";
const NeedsBox = props => (
<div className="needs-box">
<div className="label">{props.label}</div>
{props.errors.map(error => (
<div className="error-msg">{error}</div>
))}
<textarea
value={props.value}
onChange={props.onChange}
onBlur={props.updateReview}
className={props.errors.length ? "error" : ""}
/>
</div>
);
const ReviewPage = props => (
<div className="review-page">
<h3 style={{ textAlign: "center" }}>EMPLOYEE DEVELOPMENT PLAN REVIEW
<Link to="/development" className="exit">×</Link>
</h3>
<TopBar {...props} />
{props.jobSpecific && (
<NeedsBox
label="Job-Specific Development Needs:"
value={props.job_specific_dev_needs}
onChange={props.jobSpecificNeedsChanged}
updateReview={props.updateReview}
errors={props.job_specific_dev_needs_errors}
/>
)}
{!props.jobSpecific && (
<NeedsBox
label="Future Opportunities Development Needs:"
value={props.future_opportunities}
onChange={props.futureOpportunitiesNeedsChanged}
updateReview={props.updateReview}
errors={props.future_opportunities_errors}
/>
)}
<DevelopmentPlan personId={props.personAssessed.id} reviewType={'DEVELOPMENT'} reviewId={props.reviewId} />
</div>
);
export default ReviewPage;
|
import React from "react";
import { compose, withProps } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
Circle
} from "react-google-maps";
const MapComponent = compose(
withProps({
googleMapURL:
"https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `500px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={7} defaultCenter={{ lat: 65.603, lng: -16.996 }}>
{props.isMarkerShown &&
<Marker
position={{ lat: 65.603, lng: -16.996 }} defaultDraggable={true}
/>}
<Circle
defaultCenter={{ lat: 65.603, lng: -16.996 }} visible={true} radius={props.radius}
/>
</GoogleMap>
));
export default MapComponent;
//defaultRadius={6000} |
var all________________f________8js____8js__8js_8js =
[
[ "all________f____8js__8js_8js", "all________________f________8js____8js__8js_8js.html#a0597c9ee061a805e54a5d0c6365b249f", null ]
]; |
import React from "react";
import SocialIcons from "../../UI/SocialIcons/SocialIcons";
import styles from '../Header/Header.module.css'
const Header = (props) => {
let niza = ["container-fluid", styles.Content];
return (
<header>
<div className={niza.join(" ")}>
<div className="row bg-light">
<SocialIcons space="small" />
<div className="col text-center align-self-center">
<span className={styles.smallHeaderText}>
Shipping deals different with each shop
</span>
</div>
<div className="col-md-auto text-center align-self-center">
<div className="row text-center align-self-center">
<div className="col-md-auto">
<span className={styles.smallHeaderText}>
sellVintage@example.com
</span>
</div>
<div className="col-md-auto">
<select className="bg-light">
<option>US</option>
<option>EUR</option>
</select>
</div>
</div>
</div>
</div>
</div>
</header>
)
};
export default Header |
(function(){
var World = {
Food:{
x:null,
y:null,
generate:function(){
}
},
Size:{
width: 100,
height: 100
}
}
var Center = {
x: 9,
y:9
};
var Direction = {
up:1,
right:2,
left:-2,
down:-1
}
function gameOver(length){
alert("Your Score:"+length);
}
function Snake(){
var self = this;
function die(){
gameOver(self.body.part.length);//TODO
}
function Head(){
this.x = Center.x;
this.y = Center.y;
this.direction = null;
this.get=function(){
return {
x:this.x,
y:this.y
}
}
this.move = function(direction){
if(!direction){
return true;
}
var head = this.get();
this.direction = direction = direction+this.direction?direction:this.direction;
switch(direction){
case Direction.up:
this.y--;
break;
case Direction.right:
this.x++;
break;
case Direction.left:
this.x--;
break;
case Direction.down:
this.y++;
break;
}
//todo
if(eat(this.x,this.y)){
self.body.increase(head);//todo
World.Food.generate(self);
}else if(hitCheck(this.x,this.y)||eatSelfCheck(this.x,this.y)){
die();
return false;
}else{
self.body.move(head);
}
}
function eat(x,y){
return x==World.Food.x&&y=World.Food.y;
}
function hitCheck(x,y){
return(x<0||y<0||x==World.Size.width||y==World.Size.height){
}
function eatSelfCheck(x,y){
var part = self.body.part;
for(var i =0; i<part.length;i++){
if(x==part[i]&&y==part[i]){
return true;
}
}
return false;
}
}
function Body(){
this.part = [];
this.move = function(head){
if(part.length>0){
part.pop();
this.increase(head);
}
}
this.increase = function(head){
this.part.unshift(head);
}
}
this.body = new Body();
this.head = new Head();
}
})() |
/* CC3206 Programming Project
Lecture Class: 203
Lecturer: Dr Simon WONG
Group Member: CHAN You Zhi Eugene (11036677A)
Group Member: FONG Chi Fai (11058147A)
Group Member: SO Chun Kit (11048455A)
Group Member: SO Tik Hang (111030753A)
Group Member: WONG Ka Wai (11038591A)
Group Member: YEUNG Chi Shing (11062622A) */
var polling, request;
// Server request
var server = (function() {
// Get xmlhttp object
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
// Send JSON
function sendJSON(action, data, async) {
try {
polling = GetXmlHttpObject();
polling.open("POST", action, async);
polling.send(data);
} catch (exception) {
alert("Browser does not support HTTP Request.");
}
}
// Get JSON
function getJSON(action, async) {
try {
request = GetXmlHttpObject();
request.open("GET", action, async);
request.send(null);
return request.responseText;
} catch (exception) {
alert("Browser does not support HTTP Request.");
}
}
return {
// get profile
get_profile : function() {
var p_name = document.getElementById('pname').innerHTML;
var postData = JSON.parse('{"name":"' + p_name + '"}');
var dataString = JSON.stringify(postData);
var url = "get_profile.php";
sendJSON(url, dataString, false);
document.getElementById("profile").innerHTML = polling.responseText;
},
// Renew game status from server to client
renewGame : function(table) {
var url = "renew_game.php";
url = url + "?table=" + table;
return getJSON(url, false);
},
// Update game status from client to server
updateGame : function(table, cardlist, cardcount, crystal, landfill, stack, discard, totalcrystal, playerenable, cardtypeisexist) {
var cardlistStr = new Array();
for (var i = 0; i < cardlist.length; i++) {
cardlistStr[i] = '';
for (var j = 0; j < cardlist[i].length; j++) {
cardlistStr[i] = cardlistStr[i] + "#" + cardlist[i][j].id + "#";
}
}
var stackStr = '';
for (var i = 0; i < stack.length; i++) {
stackStr = stackStr + "#" + stack[i].id + "#";
}
var discardStr = '';
for (var i = 0; i < discard.length; i++) {
discardStr = discardStr + "#" + discard[i].id + "#";
}
var cardtypeisexistStr = new Array();
for (var i = 0; i < cardtypeisexist.length; i++) {
if (cardtypeisexist[i] == true)
cardtypeisexistStr[i] = 1;
else if (cardtypeisexist[i] == false)
cardtypeisexistStr[i] = 0;
}
var str = "{\"table\":\"" + table + "\", \"stack\":\"" + stackStr + "\", \"discard\":\"" + discardStr + "\", \"totalcrystal\":" + totalcrystal + ", \"playerinfo\":[";
for (var i = 0; i < cardlist.length; i++) {
if (i == cardlist.length - 1) {
str = str + "{\"cardlist\":\"" + cardlistStr[i] + "\", \"cardcount\":" + cardcount + ", \"crystal\":" + crystal[i] + ", \"landfill\":" + landfill[i] + ", \"playerenable\":" + playerenable[i] + "}], ";
}
else {
str = str + "{\"cardlist\":\"" + cardlistStr[i] + "\", \"cardcount\":" + cardcount + ", \"crystal\":" + crystal[i] + ", \"landfill\":" + landfill[i] + ", \"playerenable\":" + playerenable[i] + "}, ";
}
}
str = str + "\"cardtype\":[";
for (var i = 0; i < cardtypeisexist.length; i++) {
if (i == cardtypeisexist.length - 1) {
str = str + "{\"cardtypeisexist\":" + cardtypeisexistStr[i] + "}]}"
}
else {
str = str + "{\"cardtypeisexist\":" + cardtypeisexistStr[i] + "}, ";
}
}
var postData = JSON.parse(str);
var dataString = JSON.stringify(postData);
sendJSON("update_game.php", dataString, false);
},
renewUi : function(table) {
var url = "renew_ui.php";
url = url + "?table=" + table;
return getJSON(url, false);
},
releaseTable : function(table) {
var postData = JSON.parse('{"table":"' + table + '"}');
var dataString = JSON.stringify(postData);
sendJSON("release_table.php", dataString, true);
},
// Get player enable status
getPlayerEnableStatus : function(table, player) {
var url = "get_enable_status.php";
url = url + "?table=" + table + "&player=" + player;
return getJSON(url, false);
},
// Update player win and lose record
setWinLose : function(table, winner, player) {
var str = '{"table":"' + table + '", "winnerinfo":[';
for (var i = 0; i < winner.length; i++) {
if (i == winner.length - 1) {
str = str + '{"winner":"' + winner[i] + '"}], ';
}
else {
str = str + '{"winner":"' + winner[i] + '"}, ';
}
}
str = str + '"playerinfo":[';
for (var i = 0; i < player.length; i++) {
if (i == player.length - 1) {
str = str + '{"player":"' + player[i] + '"}]}';
}
else {
str = str + '{"player":"' + player[i] + '"}, ';
}
}
alert(str);
var postData = JSON.parse(str);
var dataString = JSON.stringify(postData);
sendJSON("set_win_lose.php", dataString, true);
}
};
})(); |
/**
* Created by michael on 5/16/2017.
*/
import React, {PureComponent} from "react";
import {FlatList, View} from "react-native";
import CONSTANTS, {MainTheme} from "../../Constants";
import NotifInListItem from "../../components/NotifInListItem";
import ListLoadMoreView from "../../components/ListLoadMoreView";
import {Env} from "../../utils/EnumHelper";
import StringHelper from "../../utils/StringHelper";
import FontAwesome from "react-native-vector-icons/FontAwesome";
// Header
import {mainStyle} from "../../styles/Style";
import {Title} from "../../components/HeaderCenterView";
// Dummy
import {ecqDummyListNotif} from "../../dummies/Dummy";
export default class HomeNotif extends PureComponent {
static navigationOptions = ({navigation}) => ({
headerTitle: <Title title={StringHelper.sceneNotifications}/>,
headerStyle: mainStyle.mainHeader,
tabBarLabel: 'Notif',
tabBarIcon: ({tintColor}) => (
<FontAwesome name="bell" size={20} color={tintColor}/>
),
});
constructor(props) {
super(props);
this.state = {
selected: (new Map(): Map<string, boolean>),
data: [],
page: 1,
error: null,
loading: false,
refreshing: false,
}
}
componentDidMount() {
this._onRefresh();
}
_wsRequest() {
// const {page, seed} = this.state;
// const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
// this.setState({loading: true});
// fetch(url)
// .then(res => res.json())
// .then(res => {
// this.setState({
// data: page === 1 ? res.results : [...this.state.data, ...res.results],
// error: res.error || null,
// loading: false,
// refreshing: false
// });
// })
// .catch(error => {
// this.setState({error, loading: false});
// });
}
_keyExtractor = (item, index) => item.notificationId;
_onRefresh = () => {
this.setState(
{
page: 1,
refreshing: true
},
() => {
switch (CONSTANTS.Env) {
case Env.DEV_DUMMY:
let newData = ecqDummyListNotif(0, CONSTANTS.numberOfListItemPerPage);
this.setState({
data: newData,
loading: false,
refreshing: false,
});
break;
case Env.DEV:
case Env.PROD:
this._wsRequest();
break;
}
}
);
};
_handleLoadMore = () => {
this.setState(
{
page: this.state.page + 1
},
() => {
switch (CONSTANTS.Env) {
case Env.DEV_DUMMY:
this.setState({loading: true});
setTimeout(() => {
let newData = ecqDummyListNotif(
this.state.data.length,
CONSTANTS.numberOfListItemPerPage);
this.setState({
data: [...this.state.data, ...newData],
loading: false,
refreshing: false,
});
}, 1500);
break;
case Env.DEV:
case Env.PROD:
this._wsRequest();
break;
}
}
);
};
_renderFooter = () => {
if (!this.state.loading) return null;
return (
<ListLoadMoreView />
);
};
_renderItem = ({item, index}) => {
return (
<NotifInListItem
item={item}
onCasePress={this._onCasePressed}
onUserPress={this._onUserPressed}
selected={!!this.state.selected.get(item.notificationId)}
/>
);
};
_onUserPressed = () => {
console.log("_onUserPressed");
};
_onCasePressed = (notificationId: string) => {
console.log("_onCasePressed");
this.setState((state) => {
let newState = state;
const selected = new Map(state.selected);
selected.set(notificationId, !selected.get(notificationId)); // toggle
newState.selected = selected;
return {newState};
});
};
render() {
return (
<View style={{flex: 1, backgroundColor: 'white', paddingTop: 10, paddingRight: 10, paddingLeft: 10}}>
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={this._renderItem}
keyExtractor={this._keyExtractor}
onRefresh={this._onRefresh}
refreshing={this.state.refreshing}
onEndReached={this._handleLoadMore}
onEndReachedThreshold={(CONSTANTS.numberOfListItemPerPage / 2)}
ListFooterComponent={this._renderFooter}
/>
</View>
);
}
} |
const AWS = require('aws-sdk');
const jwt = require('jsonwebtoken');
const BaseAuthorizer = require('./baseAuthorizer');
const { policyEffects, jwtOptions, authorizerTypes } = require('../constants/auth');
class UserAuthorizer extends BaseAuthorizer {
constructor(event) {
super();
this.event = event;
const [, path] = event.methodArn.split(/(?<=id\/)/);
if (path) {
const [id] = path.split('/');
this.id = id;
} else {
this.id = 0;
}
this.ssm = new AWS.SSM();
}
async authorize() {
const policyEffect = await this.validateToken(this.event.authorizationToken);
const policy = super.generatePolicy('service', policyEffect);
policy.context = { userId: this.id }
return policy;
}
validateToken(authorizationToken) {
return new Promise(async (resolve) => {
this.token = authorizationToken.replace(/Bearer/g, '').trim();
const cert = await this.ssm.getParameters({ Names: ['jwtRS256.key.pub'] }).promise();
jwt.verify(this.token, cert.Parameters[0].Value, { algorithms: jwtOptions.allowedAlgorithms },
(err, res) => {
if (err) {
console.log('Validation Error:', err);
return resolve(policyEffects.deny);
}
if (res.aut === authorizerTypes.userAuthorizer
&& parseInt(res.sub, 10) === parseInt(this.id, 10)) {
return resolve(policyEffects.allow);
}
return resolve(policyEffects.deny);
});
});
}
}
module.exports = UserAuthorizer;
|
'use strict';
// 批次处理开始时间(生成),批次处理完成时间(生成),当前处理进度(状态位,记录当前处理到第几个步骤),批次状态(状态位,0未开始,1运行中,2已完成,3挂起,4废止)
module.exports = app => {
const tableName = 'aux_repeat_result';
const { STRING, BIGINT, INTEGER } = app.Sequelize;
const Repeat = app.model1.define(
'Repeat',
{
/* 通用字段 */
dataId: { type: BIGINT(19), primaryKey: true },
groupId: { type: BIGINT(19) },
mergedId: { type: BIGINT(19) },
result: {
type: INTEGER(10),
},
memo: {
type: STRING(1000),
} },
{
freezeTableName: true,
tableName,
createdAt: false,
updatedAt: false,
});
return Repeat;
};
|
import styled from "styled-components";
const NumberForms = styled.div`
display: block;
margin-right: auto;
margin-left: auto;
`;
const Form = styled.form`
text-align: center;
margin: auto;
width: 50%;
margin-bottom: 50px;
`;
const Label = styled.label`
color: #d31027;
display: block;
font-size: 15px;
text-align: center;
`;
const NumberInput = styled.input`
font-size: 20px;
color: #d31027;
height: 50px;
border-color: #d31027;
text-align: center;
margin: auto;
width: 50%;
`;
export { NumberForms, Form, Label, NumberInput };
|
(function() {
var lati;
var long;
var city;
var state;
var country;
var latlon;
var count = 0;
var places;
var i;
var address1 = "1121%20Lady%20Carol%20Dr.";
const document = window.document
console.log(window)
const $locationid = document.querySelector('#locationid')
const $weatherid = document.querySelector('#weatherid')
const $tempid = document.querySelector('#tempid')
const placesAutocomplete = window.places({
appId: 'plM1C22AF7T3',
apiKey: '0d5f9f947ee21cf9bd711ab72ce5d8b9',
container: document.querySelector('#address')
});
console.log(placesAutocomplete)
const $address = document.querySelector('#address-value')
placesAutocomplete.on('change', (e) => {
$address.textContent = e.suggestion.value
console.log("hello")
count = 0;
});
placesAutocomplete.on('clear', () => {
$address.textContent = 'none';
$locationid.textContent = '';
$weatherid.textContent = '';
$tempid.textContent = '';
count = 0;
});
placesAutocomplete.on('change', (e) => {
lati = e.suggestion.latlng.lat || '';
long = e.suggestion.latlng.lng || '';
latlon = String(lati) + long;
console.log(latlon)
return cityResult = fetch("https://wft-geo-db.p.rapidapi.com/v1/geo/locations/" + latlon + "/nearbyCities?limit=10&minPopulation=80000&radius=200", {
"method": "GET",
"headers": {
"x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
"x-rapidapi-key": "5179f5814dmsh5139c561fbe52afp1a5112jsn0ca7d3210219"
} // make a 2nd request and return a promise
}).then(response => {
return response.json();
}).then(data => {
console.log(data)
console.log(data.data)
data.data.forEach(element => {
console.log(element);
console.log(element.city);
city = element.city;
state = element.regionCode;
country = element.countryCode;
weatherInfo = fetch("http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + state + "," + country + "&units=imperial&APPID=8266711937dd0c587290c3b4a86c6b7c", {
method: 'get',
}).then(response => {
return response.json();
}).then(data => {
console.log(data)
city = data.name
let weatherCondition = data.weather[0].main;
console.log(city + " " + weatherCondition)
count++;
console.log(count)
if (weatherCondition == "Rain" && $weatherid.textContent == '') {
var location = "lat: " + data.coord.lat + " long: " + data.coord.lon;
$(".location").append(location);
var weather = data.weather[0].main;
$(".weather").append("It is raining in " + city);
var temp = Math.round(data.main.temp) + "F°";
count = 0;
$(".temp").replaceAll(temp);
} else if ($weatherid.textContent == '' && $tempid.textContent == "" && $locationid.textContent == "" && count <= 9) {
$(".temp").append("No Rain within 100 miles.");
count = 0;
}
})
})
})
});
})();
// ------------FAILED ATTEMPTS--------------
// placesAutocomplete.on('change', (e) => {
// lati = e.suggestion.latlng.lat || '';
// long = e.suggestion.latlng.lng || '';
// latlon = String(lati) + long;
// console.log(latlon)
// return cityResult = fetch("https://wft-geo-db.p.rapidapi.com/v1/geo/locations/" + latlon + "/nearbyCities?limit=10&radius=200", {
// "method": "GET",
// "headers": {
// "x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
// "x-rapidapi-key": "5179f5814dmsh5139c561fbe52afp1a5112jsn0ca7d3210219"
// } // make a 2nd request and return a promise
// }).then(response => {
// return response.json();
// }).then(data => {
// console.log(data)
// for (i =0; i < 10; i++) {
// console.log(data.data[i].city);
// city = data.data[i].city;
// weatherInfo = fetch("http://api.openweathermap.org/data/2.5/weather?q=" + city + ",tx,us&units=imperial&APPID=8266711937dd0c587290c3b4a86c6b7c", {
// method: 'get',
// }).then(response => {
// return response.json();
// }).then(data => {
// let weatherCondition = data.weather[0].main
// console.log(city + weatherCondition)
// if (weatherCondition == "Rain") {
// var location = "lat: " + data.coord.lat + " long: " + data.coord.lon;
// $(".location").append(location);
// var weather = data.weather[0].main;
// $(".weather").append(weather);
// var temp = Math.round(data.main.temp) + "F°";
// $(".temp").append(temp);
// }
// })
// }
// })
// });
// var result = fetch("https://us1.locationiq.com/v1/search.php?key=7110bd3965f2c9&q=" + address1 + "&format=json", {
// method: 'get',
// }).then(response => {
// return response.json(); // pass the data as promise to next then block
// }).then(data => {
// var latlon = (data[0].lat + data[0].lon);
// console.log(latlon);
// return cityResult = fetch("https://wft-geo-db.p.rapidapi.com/v1/geo/locations/" + latlon + "/nearbyCities?radius=100", {
// "method": "GET",
// "headers": {
// "x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
// "x-rapidapi-key": "5179f5814dmsh5139c561fbe52afp1a5112jsn0ca7d3210219"
// } // make a 2nd request and return a promise
// }).then(response => {
// return response.json();
// }).then(data => {
// console.log(data.data[1].city);
// city = data.data[1].city;
// return weatherInfo = fetch("http://api.openweathermap.org/data/2.5/weather?q=" + city + ",tx,us&units=imperial&APPID=8266711937dd0c587290c3b4a86c6b7c", {
// method: 'get',
// }).then(response => {
// return response.json();
// }).then(data => {
// var location = "lat: " + data.coord.lat + " long: " + data.coord.lon;
// $(".location").append(location);
// var weather = data.weather[0].main;
// $(".weather").append(weather);
// var temp = Math.round(data.main.temp) + "F°";
// $(".temp").append(temp);
// })
// })
// });
// function getLatLon(callback) {
// var temp = $.getJSON("https://us1.locationiq.com/v1/search.php?key=7110bd3965f2c9&q=" + address + "&format=json", function(data){
// lati = data[0].lat;
// long = data[0].lon;
// callback(lati + long);
// });
// }
// function findNearbyCities(){
// getLatLon(function(data){
// console.log(data)
// console.log(typeof data);
// // -------This API inputs the lat and long of the users location and finds the nearby cities--------
// var settings = {
// "async": true,
// "crossDomain": true,
// "url": "https://wft-geo-db.p.rapidapi.com/v1/geo/locations/" + data + "/nearbyCities?radius=100",
// "method": "GET",
// "headers": {
// "x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
// "x-rapidapi-key": "5179f5814dmsh5139c561fbe52afp1a5112jsn0ca7d3210219"
// }
// }
// $.ajax(settings).done(function (response) {
// console.log(response);
// console.log(response.data[0].city);
// city = response.data[0].city;
// });
// });
// console.log('i am executed before anything else');
// }
// findNearbyCities();
// console.log(city); //does not work because asynchronous
// -----Promise-----
// let getLatLonPromise = new Promise(function(resolve,reject) {
// function getLatLon() {
// var temp = $.getJSON("https://us1.locationiq.com/v1/search.php?key=7110bd3965f2c9&q=" + address + "&format=json", function(data){
// lati = data[0].lat;
// long = data[0].lon;
// });
// }
// })
// ----Fetch API-----
// fetch("https://us1.locationiq.com/v1/search.php?key=7110bd3965f2c9&q=" + address + "&format=json")
// .then(res => res.json())
// .then(data => latlon = (data[0].lat + data[0].lon))
// .then(citiesnearme => {
// // -------This API inputs the lat and long of the users location and finds the nearby cities--------
// var settings = {
// "async": true,
// "crossDomain": true,
// "url": "https://wft-geo-db.p.rapidapi.com/v1/geo/locations/" + latlon + "/nearbyCities?radius=100",
// "method": "GET",
// "headers": {
// "x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
// "x-rapidapi-key": "5179f5814dmsh5139c561fbe52afp1a5112jsn0ca7d3210219"
// }
// }
// $.ajax(settings).done(function (response) {
// console.log(response);
// console.log(response.data[4].city);
// city = response.data[4].city;
// });
// })
// .then(weatherinfo => {
// $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city + ",tx,us&units=imperial&APPID=8266711937dd0c587290c3b4a86c6b7c", function(data){
// console.log(data);
// var location = "lat: " + data.coord.lat + " long: " + data.coord.lon;
// $(".location").append(location);
// var temp = Math.round(data.main.temp);
// $(".temp").append(temp);
// var weather = data.weather[0].main;
// $(".weather").append(weather);
// })
// })
// ------This API gets the weather data of the nearby cities--------
// $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=Coppell,tx,us&units=imperial&APPID=8266711937dd0c587290c3b4a86c6b7c", function(data){
// console.log(data);
// var location = "lat: " + data.coord.lat + " long: " + data.coord.lon;
// $(".location").append(location);
// var temp = Math.round(data.main.temp);
// $(".temp").append(temp);
// var weather = data.weather[0].main;
// $(".weather").append(weather);
// })
|
import actionTypes from '../actionTypes';
import ActionCreator from ".";
import store from "../store";
export const FetchPurchaseGem = (userid, isNeedSpinner, token, request_data, callbackFunc) => {
const data = new FormData();
data.append('amount', request_data.amount);
data.append('purchase_type', request_data.purchase_type);
if (isNeedSpinner) {
store.dispatch(ActionCreator.ShowDefaultSpinner());
}
fetch(`/gems/${userid}/purchase/`, {
method: "POST",
headers: {
"Authorization": `JWT ${token}`,
},
body: data
})
.then( response => {
if (response.status === 401){
store.dispatch(ActionCreator.Logout());
if (isNeedSpinner) {
store.dispatch(ActionCreator.HideDefaultSpinner());
}
} else {
return response.json();
}
})
.then(json => {
if (isNeedSpinner) {
store.dispatch(ActionCreator.HideDefaultSpinner());
}
if (json === undefined || json.result === undefined || json.result === null) {
store.dispatch(ActionCreator.SaveUserInfo(null));
callbackFunc(false, json);
} else if (json.status === "1") {
store.dispatch(ActionCreator.GetUserInfo(userid, token));
callbackFunc(true, json);
} else {
callbackFunc(false, json);
}
})
.catch(
err => {
callbackFunc(false, null);
if (isNeedSpinner) {
store.dispatch(ActionCreator.HideDefaultSpinner());
}
}
)
return {
type: actionTypes.GEM_PURCHASE,
};
} |
var UnitController = require('../controllers/UnitController');
module.exports = function (app) {
app.post('/unit/getUnitBy', function (req, res) {
console.log('/unit/getUnitBy', req.body)
UnitController.getUnitBy(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
} |
import React from "react";
import { Button, Container, Slide } from "@material-ui/core";
import { Link } from "react-router-dom";
function About() {
return (
<Container>
<Slide direction="up" in={true} timeout={1000}>
<div style={{ marginBottom: 50 }}>
<div>
<h1 style={{ textAlign: "center", margin: 30 }}>WHO ARE WE</h1>
</div>
<div>
<p style={{ textAlign: "justify", margin: 30 }}>
Ispirithalei is Sri Lanka's first small-scale one-stop online health care system. Ispirithalei was established
and maintained with the purpose of decentralizing the online health care systems and bringing online healthcare
to everyone in Sri Lanka.
<br /><br />
We provide services ranging from E-Channeling, online pharmacy, and drug dispensing to online lab test retrieval
and maintenance. Ispirithalei has hired the best doctors, pharmacists, lab technicians, and the best healthcare
professionals in the country to provide you with the best services. We are equipped with the best technology and
the best IT professionals in the industry to back us up in providing you with uninterrupted and reliable service.
Ispirithalei's online healthcare platform enables easy, user-friendly, and simple access to medicare and health
services to your fingertips.
<br /><br />
Join the Ispirithalei family and enjoy healthcare like never before. No interruptions. Secure. No waiting in queue
to book your appointment. Everything at your fingertips from the comfort of your home.
</p>
<p style={{ textAlign: "center" }}><strong>- LEAVE YOUR HEALTHCARE WORRIES WITH US -</strong></p>
<Link to="/patient/inquiry" style={{ textDecoration: "none" }}>
<center><Button size="large" variant="contained" color="primary" style={{ marginTop: 40, width: "50%" }}>
Direct your inquiries at us through here
</Button></center>
</Link>
</div>
</div>
</Slide>
<center><hr style={{ width: "70%" }}></hr></center>
<div style={{ marginBottom: 50 }}>
<div>
<h1 style={{ textAlign: "center", margin: 30 }}>OUR MISSION</h1>
</div>
<div>
<p style={{ textAlign: "center", margin: 30 }}>
To bring uninterrupted, quality healthcare to all Sri Lankans without any exception. We strive to provide consistency in
healthcare. Ispirithalei is on a mission to become the biggest, the most reliable, and quality online healthcare platform in
the country
</p>
</div>
</div>
<center><hr style={{ width: "70%" }}></hr></center>
<div style={{ marginBottom: 50 }}>
<div>
<h1 style={{ textAlign: "center", margin: 30 }}>OUR VISION</h1>
</div>
<div>
<p style={{ textAlign: "center", margin: 30 }}>
Become the most sought after healthcare brand of Sri Lanka which is loved by people all across the country and to provide
the best online healthcare service in the country.
</p>
</div>
</div>
</Container>
);
}
export default About; |
import React from "react"
import { Link } from "gatsby"
import LocalizedLink from "../components/LocalizedLink"
import Layout from "../components/layout"
import SEO from "../components/seo"
import Steps from "../components/Steps"
import { css } from "@emotion/core"
import { useTranslation } from "react-i18next"
import logoGrey from "../images/logoGrey.png"
let requests = [
{
name: { en: "Warehouse inquiry", uk: "Складський запит" },
text: {
en:
"If you want to choose products from warehouse, this option is for you.",
uk: "Якщо бажаєте обрати продукцію зі складу, цей варіант саме для Вас.",
},
img: "/icon/request-basic.png",
id: "products",
},
{
name: { en: "Print inquiry", uk: "Запит друку" },
text: {
en:
"If you want products with your own printing, this option is for you.",
uk: "Якщо бажаєте продукцію з власним друком, цей варіант саме для Вас.",
},
img: "/icon/request-printed.png",
id: "printform",
},
{
name: { en: "Custom inquiry", uk: "Індивідуальний запит" },
text: {
en:
"If you have your own design ideas and need maximum flexibility in envelope design, this option is for you.",
uk:
"Якщо бажаєте продукцію з власними параметрами, цей варіант саме для Вас.",
},
img: "/icon/request-custom.png",
id: "individualform",
},
]
export default props => {
const T = useTranslation()
if (T.i18n.language !== props.pageContext.langKey) {
T.i18n.changeLanguage(props.pageContext.langKey)
}
const t = key => (typeof key === "string" ? T.t(key) : key[T.i18n.language])
const steps = [
t("requestType"),
t("requestOrderCreate"),
t("requestPersonal"),
]
return (
<Layout>
<SEO title={t("seoInquiry")} />
<Link
css={css`
background: url(${logoGrey}) center center no-repeat;
width: 190px;
height: 66px;
background-size: cover;
position: absolute;
top: 20px;
left: 30px;
`}
to="/"
></Link>
<Steps steps={steps} activeStep={0} />
<h1
css={css`
font-size: 36px;
font-weight: 500;
margin-bottom: 50px;
text-align: center;
`}
>
{t("chooseType")}
</h1>
<section
css={css`
position: relative;
`}
>
<div
css={css`
width: 100%;
height: 178px;
background: #b40039;
position: absolute;
top: 120px;
z-index: 1;
@media (max-width: 1024px) {
display: none;
}
`}
/>
<div
className="row"
css={css`
position: absolute;
top: 0px;
z-index: 5;
`}
>
{requests.map(({ name, text, img, id }) => (
<div key={id} className="w-full md:w-1/3 px-2">
<LocalizedLink
to={`/${id}`}
css={css`
height: 60vh;
background: #ffffff;
box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
text-align: center;
cursor: pointer;
text-decoration: none;
color: #000000;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
padding: 100px 40px;
@media (max-width: 1024px) {
height: auto;
flex-direction: row;
margin-bottom: 25px;
padding: 25px 17px;
text-align: left;
justify-content: flex-start;
width: 100%;
}
`}
>
<div>
<img
src={img}
alt={`${img} type`}
css={css`
width: 90px;
`}
/>
</div>
<div
css={css`
@media (max-width: 1024px) {
padding: 0 20px;
}
`}
>
<h4
css={css`
font-weight: 500;
font-size: 36px;
margin: 0;
@media (max-width: 1024px) {
font-size: 18px;
}
`}
>
{t(name)}
</h4>
<p
css={css`
font-size: 18px;
line-height: 27px;
@media (max-width: 1024px) {
font-size: 14px;
margin-bottom: 0;
}
`}
>
{t(text)}
</p>
</div>
</LocalizedLink>
</div>
))}
</div>
</section>
</Layout>
)
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ReviewSchema = require('./review').schema;
// Create a Schema
const ProductSchema = new Schema({
name: {
type: String,
required: true
},
category: {
type: String,
required: true
},
brand: {
type: String
},
price: {
type: Number,
required: true
},
features: {
type: [String]
},
stock: {
type: Number,
default: 10
},
purchases: {
type: Number,
default: 0
},
comments: {
type: [ReviewSchema],
default: []
},
avgRating: {
type: Number,
default: 0,
},
wishlist: {
type: Number,
default: 0
},
productImage:{
type: String,
required: true
}
});
module.exports = Product = mongoose.model('product', ProductSchema); |
var listScrpts;
var current;
var durationtotal;
var player;
// var saudacao;
$(function() {
/*
* listScrpts = new HtmlImport("imports"); listScrpts.addItem("question",
* "question.html"); listScrpts.load();
*
* $('#video').click(function(e) { this.pause(); alert(e.pageX + ' , ' +
* e.pageY); alert(current); this.play(); }).trigger('change');
$('#btnTeste').click(function(e) {
alert(durationtotal);
}).trigger('change');
*/
$('#btnTeste').hide();
player = new Video("video");
player.addSource(new SourceVideo("Scorm_01_Tecnologia-4k.mp4","passaVideo"));
player.addSource(new SourceVideo("Scorm_02_Beneficios-4k.mp4"));
player.addEvento(new ActionMove("5.5626666", "exibeBotao"));
player.addEvento(new ActionMove("10.5626666", "escondeBotao"));
player.addListener(new ListenerVideo("btnTeste"));
player.addActionListener("btnTeste", "teste");
player.intiVideo();
});
function teste(){
alert("teste");
}
function acopanhaVideo(currentTime, duration) {
player.onTrackedVideoFrame(currentTime, duration);
}
function encerraVideo() {
player.finalizaVideo();
}
function passaVideo() {
player.intiVideo(1);
}
function exibeBotao() {
$('#btnTeste').show();
}
function escondeBotao() {
$('#btnTeste').hide();
}
// |
import firebase from 'firebase'
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};
firebase.initializeApp(firebaseConfig);
export default function firebaseService(){
const messaging = firebase.messaging();
Notification.requestPermission().then((permission) => {
console.log(permission)
if(permission === "granted"){
messaging.getToken().then((currentToken) => {
if (currentToken) {
console.log("TOKEN")
console.log(currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
})
} |
export var AppConfig = {
landingPageRestClient: {
baseUrl: 'https://newtoms-landingpage-process-api.us-e1.cloudhub.io/api'
}
}
|
import React, { useState } from 'react'
import FormData from 'form-data'
import qs from 'qs'
const NewsletterForm = () => {
const [emailState, setEmail] = useState(``)
const [errorState, setError] = useState(``)
const [successState, setSuccess] = useState(``)
const [loading, setLoading] = useState(false)
let formData = new FormData()
formData.append(`email`, emailState) // multiple upload
const data = qs.stringify({
email: emailState,
})
const changeEmail = (event) => {
const email = event.target.value
setEmail(email)
}
const subscribeMe = async (event) => {
event.preventDefault()
//console.log(`submitting...`)
setLoading(true)
try {
// eslint-disable-next-line ghost/ember/require-fetch-import
const res = await fetch(`/api/subscribe`, {
headers: {
'Content-Type': `application/x-www-form-urlencoded`,
},
body: data,
method: `POST`,
})
const { error, message } = await res.json()
if (error) {
setError(error)
setLoading(false)
//console.log(error)
} else {
setSuccess(message)
setLoading(false)
//console.log(res)
}
} catch (err) {
console.log(err)
}
}
return (
<div className="newsletter-signup">
<h3 className="text-3xl mb-2 font-black text-wide">
Sign up for the <span className="highlight highlight-right primary">latest updates</span>
</h3>
<p className="text-lg font-light mb-10">
I have a newsletter now! Want to stay up to date on the musings of a burnt-out developer that still wants to do way too much? Enter your email and you'll be added to the list,
of which you can opt out any time.
</p>
<form className="my-4 grid grid-cols-12 mb-8" onSubmit={subscribeMe}>
<div className="col-span-12 lg:col-span-8">
<input
aria-label="Email for newsletter"
placeholder="tyler@underlost.net"
type="email"
autoComplete="email"
required
className="w-full px-4 py-3 text-lg border-2 border-black dark:border-purple focus:outline-none lg:border-r-0 dark:bg-purple-dark dark:text-white"
onChange={changeEmail}
/>
</div>
<div className="col-span-12 lg:col-span-4 mt-3 lg:mt-0">
<button
className="font-bold w-full bg-black dark:bg-purple dark:text-purple-dark text-white px-4 py-3 text-lg hover:bg-blue hover:text-black border-2 border-black dark:border-purple focus:outline-none focus:border-blue focus:bg-blue"
type="submit"
>
{loading ? `Subscribing...` : `Subscribe`}
</button>
</div>
</form>
<p className="text-end">
<a className="btn-underline" href="/tag/newsletter">
<span>View Past Issues</span>
</a>
</p>
{successState ? <span className="text-secondary">{successState}</span> : <span className="text-secondary">{errorState}</span>}
</div>
)
}
export default NewsletterForm
|
//--------------------------------------------------------------------------------;
// SERVER;
//--------------------------------------------------------------------------------;
//------------------------------;
global.REQUIRES = {};
//------------------------------;
global.REQUIRES.http = require('http');
global.REQUIRES.url = require('url');
global.REQUIRES.fs = require('fs');
global.REQUIRES.querystring = require('querystring')
global.REQUIRES.iconv = require('iconv-lite')
global.REQUIRES.child_process = require('child_process');
global.REQUIRES.uglify = require("uglify-js");
global.REQUIRES.redis = require("redis");
global.REQUIRES.websocket = require("websocket").server;
global.REQUIRES.https = require('https');
global.REQUIRES.readline = require('readline');
global.REQUIRES.googleapis = require('googleapis');
//------------------------------;
global.SERVER = {};
//--------------------;
// FUNCTION;
//--------------------;
global.SERVER.make_navi_resource = function(){
var make_resource = function( r ){
var file = "./public/html/thtml/navi.thtml";
var file1 = "./public/html/include/navi.html";
var b0 = global.REQUIRES.fs.readFileSync( file, 'utf8' );
var b1 = b0.replace("<!=data=!>", r)
global.REQUIRES.fs.writeFileSync( file1, b1 ,{ flag : "w" } );
}
var path = "./js/router/web/";
var a0 = global.REQUIRES.fs.readdirSync( path );
var i = 0,iLen = a0.length;
var io, r = "";
for(; i < iLen; ++i )
{
io = a0[ i ]
if( io[ 0 ] != "_" )
{
var a1 = global.REQUIRES.fs.readdirSync( path + io );
//console.log( a1 )
var j = 0, jLen = a1.length;
var jo;
for(; j < jLen; ++j )
{
jo = a1[ j ].split(".")
jo.pop()
var jo1 = jo[ jo.length - 1 ]
var jo2 = jo[ jo.length - 2 ]
var ttt = '<a class="item line_height_small" href="/' + jo2 + "/" + jo1 +'">' + jo1 + '</a>' + "\n"
r += ttt;
}
}
}
make_resource( r )
};
global.SERVER.Initialize_commonJS = function(){
var path = "./public/js/_define/";
var path0 = "./public/js/common/"
var a0 = global.REQUIRES.fs.readdirSync( path );
var ws = global.REQUIRES.fs.createWriteStream( path0 + 'common.min.js' );
ws.on("finish",function(){ /*console.log( 'finish' );*/})
ws.on("close",function(){ /*console.log( 'close' );*/ })
var i =0,iLen = a0.length;
for( ; i < iLen; ++i )
{
console.log( "-[S]- Initialize_commonJS -- " + path + a0[ i ]);
var r = global.REQUIRES.fs.readFileSync(path + a0[ i ],'utf8');
//*/
ws.write( global.REQUIRES.uglify.minify( r ).code,{ flag : "w" });
/*/
ws.write( r,{ flag : "w" });
//*/
console.log( "-[E]- Initialize_commonJS -- " + path + a0[ i ] );
}
ws.end();
};
global.SERVER.Initialize_api = function(){
var path = global.ROOTPath + "/js/api/";
var path___define = global.ROOTPath + "/js/api/__define/"
var a2 = global.REQUIRES.fs.readdirSync( path___define );
var k = 0,kLen = a2.length;
var ko;
for( ; k < kLen; ++k )
{
ko = a2[ k ]
console.log( "-[S]- Initialize_api -- " + path___define + ko );
var t = global.REQUIRES.fs.readFileSync( path___define + ko,"utf8");
var e = function( name ){ return eval( name ) }
e( t );
console.log( "-[E]- Initialize_api -- " + path___define + ko );
}
var a0 = global.REQUIRES.fs.readdirSync( path ).sort();
//debugger;
a0.pop();
var i =0,iLen = a0.length;
var io,a1;
for( ; i < iLen; ++i )
{
io = a0[ i ];
a1 = global.REQUIRES.fs.readdirSync( path + a0[ i ] );
//debugger;
var j = 0
for( ; j < a1.length; ++j )
{
console.log( "-[S]- Initialize_api -- " + path + a0[ i ] + "/" + a1[ j ] );
var t = global.REQUIRES.fs.readFileSync( path + a0[ i ] + "/" + a1[ j ],"utf8");
//debugger;
var e = function( name ){ return eval( name ) }
e( t );
console.log( "-[E]- Initialize_api -- " + path + a0[ i ] + "/" + a1[ j ] );
}
}
};
global.SERVER.serverStart = function( routerControl ) {
global.SERVER.Initialize_commonJS();
global.SERVER.Initialize_api();
// global.ROUTER.Initialize_router();
global.ROUTER.Initialize_router( "web" )
global.ROUTER.Initialize_router( "api" )
//global.SERVER.make_navi_resource();
//------------------------------ Logger Regist - Logic;
global.api.Log.regist_logger( "CSJLog" );
global.api.Log.regist_logger( "_Someone" );
//------------------------------ Logger Test CODE;
var onRequest = function(req, res){
if (req.method == 'OPTIONS') {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
res.end();
}
// res.setHeader("Access-Control-Allow-Origin", "/*");
// res.setHeader("Access-Control-Allow-Credentials", "true");
// res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
// res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
routerControl( req, res );
};
global.server = global.REQUIRES.http.createServer( onRequest ).listen(8888);
global.CSJLog.timeStamp('server has started.');
//----------------------------------------WebSocket;
global.ws = new global.REQUIRES.websocket({
httpServer : global.server
})
global.ws.clients = {};
var getUniqueID = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4();
};
global.ws.on('connect', function(connection){
global.CSJLog.timeStamp("---------- WebSocket connect ----------")
global.CSJLog.timeStamp( connection.remoteAddresses )
global.CSJLog.timeStamp("---------- WebSocket connect ----------")
});
global.ws.on('close', function(webSocketConnection, closeReason, description){
global.CSJLog.timeStamp("---------- WebSocket close ----------")
global.CSJLog.timeStamp(webSocketConnection)
global.CSJLog.timeStamp(closeReason)
global.CSJLog.timeStamp(description)
global.CSJLog.timeStamp("---------- WebSocket close ----------")
});
// WebSocket server
global.ws.on('request', function(request) {
//console.log( request )
global.CSJLog.timeStamp('WebSocket Connection from origin ' + request.origin );
var connection = request.accept(null, request.origin);
var clientID = getUniqueID();
global.ws.clients[ clientID + "_" + request.resourceURL.query.mid ] = connection;
//console.log( request.resourceURL.query.mid )
//---------- Redis;
var _con = {
port : global.REDIS.CONFIG.port
, host : global.REDIS.CONFIG.connect_url
,db : 1
}
var r = global.REQUIRES.redis.createClient( _con );
r.auth( global.REDIS.CONFIG.pass );
r.set( request.resourceURL.query.mid, "{data : ''}", 'EX', 15*60)
r.quit()
//---------- Redis;
connection.on('message', function(message) {
global.CSJLog.timeStamp("---------- WebSocket message ----------" )
global.CSJLog.timeStamp( JSON.stringify( message ) )
global.CSJLog.timeStamp("---------- WebSocket message ----------" )
if (message.type === 'utf8') {
// var i = 0,iLen = global.ws.clients.length,io
// for(;i<iLen; ++i)
// {
// io = global.ws.clients[ i ];
// io.sendUTF( JSON.stringify( message ) )
// }
for(var s in global.ws.clients)
{
io = global.ws.clients[ s ];
// console.log( s +" || "+ "aaa")
// console.log( global.ws.clients[ s ] )
// if(io !== connection )io.sendUTF( JSON.stringify( message ) )
io.sendUTF( JSON.stringify( message ) )
}
}
});
connection.on('close', function(reasonCode, description) {
global.CSJLog.timeStamp("---------- WebSocket close ----------")
global.CSJLog.timeStamp( reasonCode )
global.CSJLog.timeStamp( description )
global.CSJLog.timeStamp("---------- WebSocket close ----------")
});
connection.on('error', function(error) {
global.CSJLog.timeStamp("---------- WebSocket error ----------" )
global.CSJLog.timeStamp(error)
global.CSJLog.timeStamp("---------- WebSocket error ----------" )
});
});
//----------------------------------------WebSocket;
};
|
const path = require('path')
const resolve = dir => path.join(__dirname, dir)
module.exports = {
css: {
loaderOptions: {
less: {
javascriptEnabled: true
}
}
},
chainWebpack: config => {
config.resolve.alias.set('@', resolve('src'))
},
devServer: {
proxy: {
'/api': {
target: 'http://www.cc.com', //要访问的跨域的域名
ws: true, // 是否启用websockets
secure: false, // 使用的是http协议则设置为false,https协议则设置为true
changOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样客户端端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
'^/api': ''
}
}
}
}
}
|
app.filter('trusted', function($sce){
return function(link){
return $sce.trustAsResourceUrl(link);
};
}); |
const exec = require('child_process').execSync;
var paperkey = '';
var keybaseRepoName = '';
var username = '';
var githubRepoURL = '';
var githubRepoName = '';
var githubUsername = '';
var githubRepoIsPrivate = '';
var cmd = '';
var useSSH = false;
function execute(cmd, cwd){
if(cwd == ''){
return exec(cmd);
}
else{
return exec(cmd, { cwd: cwd });
}
}
function setEnvironment(){
const fs = require("fs");
if (!fs.existsSync('/tmp/gopath/')) {
cmd = 'mkdir /tmp/gopath/ && mkdir /tmp/gopath/bin/';
execute(cmd, '');
process.env['PATH'] = process.env['PATH'] + ':' + '/tmp/gopath/bin';
cmd = 'cp /var/task/gopath/bin/* /tmp/gopath/bin/';
execute(cmd, '');
cmd = 'chmod 777 /tmp/gopath/bin/*'
execute(cmd, '');
}
if(githubRepoIsPrivate) {
useSSH = true;
} else {
useSSH = false;
}
if (useSSH && !fs.existsSync('/tmp/.ssh/')) {
cmd = 'mkdir /tmp/.ssh/';
execute(cmd, '');
cmd = 'cp /var/task/.ssh/* /tmp/.ssh/';
execute(cmd, '');
cmd = 'chmod 400 /tmp/.ssh/*'
execute(cmd, '');
}
}
function startKeybase(){
cmd = 'keybase ctl start';
execute(cmd, '');
cmd = `keybase oneshot --username ${username} --paperkey "${paperkey}"`;
execute(cmd, '');
}
function cloneRepo(){
if(useSSH){
cmd = `git clone --mirror git@github.com:${githubUsername}/${githubRepoName}.git _tmp.git`;
}else{
cmd = `git clone --mirror ${githubRepoURL} _tmp.git`;
}
execute(cmd, '/tmp');
cmd = 'git push --mirror keybase://private/' + username + '/' + keybaseRepoName;
execute(cmd, '/tmp/_tmp.git');
cmd = 'cd .. && rm -rf _tmp.git';
execute(cmd, '/tmp/_tmp.git');
}
function main(){
setEnvironment();
startKeybase();
cloneRepo();
}
module.exports.githubtoKeybaseCloner = async function(event) {
const attr = event.Records[0].messageAttributes;
paperkey = attr.paperkey.stringValue;
keybaseRepoName = attr.keybaseRepoName.stringValue;
username = attr.username.stringValue;
githubRepoURL = attr.githubRepoURL.stringValue;
githubRepoName = attr.githubRepoName.stringValue;
githubUsername = attr.githubUsername.stringValue;
githubRepoIsPrivate = attr.githubRepoIsPrivate.stringValue;
if(githubRepoIsPrivate === 'true'){
githubRepoIsPrivate = true;
} else {
githubRepoIsPrivate = false;
}
await require("lambda-git")()
.then(function () {
main();
}).catch(function (error) {
console.log(error);
});
return {};
}
|
exports.handle = function(data) {
console.log("Received data" + data);
var carrotData = JSON.parse(data);
var db = require('nano')('http://localhost:5984/carrot');
console.log("Persisting data");
db.insert(carrotData, '', function(err, body) {
if (!err)
console.log(body);
});
return true;
} |
import React from "react";
import { Image, ListGroupItem } from "react-bootstrap";
import { FaTrash } from "react-icons/fa";
export default function CartProduct({ product, handleRemoveFromCart }) {
const { id, title, image } = product;
return (
<ListGroupItem className="custom-list-group-item">
<Image src={image} alt={title} style={{ width: "100px", border: "1px solid rgba(0,0,0,.125)" }} className="custom-image"/>
<h5>{title}</h5>
<FaTrash
className="remove-icon"
onClick={() => handleRemoveFromCart(id)}
/>
</ListGroupItem>
);
} |
import selectedTeaReducer from './../../reducers/selected-tea-reducer';
import * as a from './../../actions/index';
import initialState from './../../initialState';
const testId = Object.keys(initialState.masterTeaList)[0];
describe ('selectedTea', () => {
test('Should return default state if there is no action type passed into the reducer', () => {
expect(selectedTeaReducer({}, {type:null})).toEqual({});
});
test('Should return specific tea with the specific id', () => {
expect(testId).toEqual(initialState.masterTeaList[testId].id);
});
test('Should unselect tea after selection done', () => {
//const selected = selectedTeaReducer({}, a.selectedTea(testId));
const unselect = selectedTeaReducer(initialState.masterTeaList[testId], a.unselectTea());
expect(unselect).toEqual(null);
});
}); |
/*
================================
Coder: Emily Yu
Date: 02/11/2019 - 02/23/2019
Main Related Files: textAdventureGame.html, textGameStyle.css
Description:
Text adventure game where player types in instructions to forward the story.
Feature within This Javascript File:
This part of the file checks user's input and locates keywords about directions, actions, and items.
Once found a match, the function either changes the mapLocation, adds the item to the backapack, or drops the item from backpack.
Since use item has too many different cases, an individual file is created to accomodate that, and thus is taken out from this file.
====================================
*/
//"use strict";
let happen = document.getElementById("event");//user's input
let outputMap = document.getElementById("mapMessage");
let outputGame = document.getElementById("gameMessage");
let outputItem = document.getElementById("itemMessage");
let mapImage = document.getElementById("background");
/*--Explanation for Blocked Path Messages:--
To get the value for when the player will travel out of bounds, store it to the variable of G.
Since it's 3 rows X 4 columns game area, drawing out the map I know that:
First Row (0,1,2,3) can't go north (less than 4);
Third Row (8,9,10,11) can't go south (equal to or more than 8, which is 4 X 2);
1st Column (0, 4, 8) can't go west ( x % 4 === 0 );
3rd Column (3, 7, 11) can't go east ( x % 4 === 3, which is G-1)
To move north, subtract 4; to move south, add four
All factors have 4 in it and suppose we were to add more rows or columns,
we would only need to change the value of G in the future
*/
let G = 4;
function gameAction(){
let input = happen.value.toLowerCase();
//reset value to empty string
outputItem.innerHTML = "";//reset from switch case "use"
doAction = "";
interactItem = "";
//check for direction and action keywords
for(var act of events){
if(input.indexOf(act) !== -1){
doAction = act;
break;
}
}
//check for item keywords
for(var obj of items){
if(input.indexOf(obj) !== -1){
interactItem = obj;
break;
}
}
switch(doAction){
case "north":
if(mapLocation >= G){
mapLocation -= G;
outputGame.innerHTML = game[mapLocation];
}else{
outputGame.innerHTML = blockedPath[mapLocation];
}
break;
case "south":
if(mapLocation < 2*G){
mapLocation += G;
outputGame.innerHTML = game[mapLocation];
}else{
outputGame.innerHTML = blockedPath[mapLocation];
}
break;
case "east":
if(mapLocation % G !== 3){
mapLocation += 1;
outputGame.innerHTML = game[mapLocation];
}else{
outputGame.innerHTML = blockedPath[mapLocation];
}
break;
case "west":
if(mapLocation % G !== 0){
mapLocation -= 1;
outputGame.innerHTML = game[mapLocation];
}else{
outputGame.innerHTML = blockedPath[mapLocation];
}
break;
case "take":
takeItem();
break;
case "use":
//check whether the player interacts with two items and then store the items in an array
if(input.indexOf("and") !== -1){
interactItem = [];
for(var obj of items){
if(input.indexOf(obj) == -1){
outputItem.innerHTML = "There's no such combination.";
}else{
interactItem.push(obj);
}
}
useItem();
break;
}else{//if there's only one item, call the useItem() method
useItem();
break;
}
case "drop":
dropItem();
break;
default:
outputGame.innerHTML = "I don't understand that.";
}
render();
}
function takeItem(){
let takeIndexNumber = itemsToTake.indexOf(interactItem);
let itemIndexNumber = items.indexOf(interactItem);
console.log(itemsToTake);
//because the case for the item lock is special, check its condition first
//before the player can take the lock, check whether the lock is in current gameplay
if(interactItem === "lock" && items.indexOf("lock") !== -1){
//before the player can take the lock, check whether the book is in backpack or the book is at current location
if(backpack.indexOf(interactItem) === -1 && (backpack.indexOf("book") !== -1 || itemsLocation[items.indexOf("book")] === mapLocation)){
outputItem.innerHTML = "The item lock is now in your backpack.";
backpack.push(interactItem);
itemsToTake.splice(takeIndexNumber, 1);//remove one item from array starting from the position takeIndexNumber
itemsLocation.splice(itemIndexNumber, 1, 100);//remove one value from array starting from the position itemIndexNumber and add the value of "in-transit" in its place(I don't put a string in case javascript later on interprets mapLocation as a string instead of an integer)
//if the book is at current location but not in backpack, add the book to backpack
if(backpack.indexOf("book") === -1 && itemsLocation[items.indexOf("book")] === mapLocation){
outputItem.innerHTML += "<br>The book is also now back in your backpack.";
backpack.push("book");
//take book out from the array and give the mapLocation value of 100 for "in-transit" (I don't put a string in case javascript later on interprets mapLocation as a string instead of an integer)
itemsToTake.splice(itemsToTake.indexOf("book"), 1);
itemsLocation.splice(items.indexOf("book"), 1, 100);
}
}else{
outputItem.innerHTML = "Sorry, you do not have the book with you so you cannot take the lock.";
}
}else if(takeIndexNumber !== -1 && itemsLocation[itemIndexNumber] === mapLocation){//check whether the item is takeable from the game
outputItem.innerHTML = "The item " + interactItem + " is now in your backpack.";
backpack.push(interactItem);
itemsToTake.splice(takeIndexNumber, 1);//remove one item from array starting from the position takeIndexNumber
itemsLocation.splice(itemIndexNumber, 1, 100);//remove one value from array starting from the position itemIndexNumber and add the value of "in-transit" in its place
}else if(takeIndexNumber !== -1 && itemsLocation[itemIndexNumber] !== mapLocation){//for re-taking items that have dropped elsewhere
outputItem.innerHTML = "The item " + interactItem + " can be taken but is not located here.";
}else if((items.indexOf(interactItem) !== -1 && itemsLocation[itemIndexNumber] === mapLocation) || interactItem === "chair" && mapLocation === 4){//in case user decides to take chair in the sunroom
outputItem.innerHTML = "Sorry, you cannot take the " + interactItem + ". It stays here.<br>Or maybe you've already taken the item. Check your backpack.";
}else{
outputItem.innerHTML = "I don't understand that request.<br>Either you have already taken the item<br>or there's no such item here.";
}
//console.log("In-World items: " + items);
//console.log("Items to take: " + itemsToTake);
//console.log("Backpack: " + backpack);
}
function dropItem(){
if(backpack.length !== 0){
let backpackIndexNumber = backpack.indexOf(interactItem);
if(backpackIndexNumber !== -1){
outputItem.innerHTML = "The " + interactItem + " is no longer in your backpack.";
if(interactItem === "book"){
if(backpack.indexOf("lock") !== -1){//drop the lock if the book is dropped, since the lock is attached to the book
backpack.splice(backpack.indexOf("lock"), 1);//remove the lock from backpack, if it's in there
itemsLocation.splice(items.indexOf("lock"), 1, mapLocation);//update the itemLocation for lock with the current mapLocation
outputItem.innerHTML += "<br>The lock with the book is also no longer in your backpack.";
}
}
itemsToTake.push(interactItem);//push the object back to the array
//itemsLocation needs to be updated too
//find the index number from the items array
let itemIndexNumber = items.indexOf(interactItem);
itemsLocation.splice(itemIndexNumber, 1, mapLocation);//remove one value from array starting from the position itemIndexNumber, and adding the value of mapLocation in its place
backpack.splice(backpackIndexNumber, 1);//remove one item from array starting from the position backpackIndexNumber
}else{
outputItem.innerHTML = "You do not have that in your backpack.";
}
}else{
outputItem.innerHTML = "There's nothing in your backpack.";
}
} |
//document.getElementById('theBigTitle').innerText = "Xiangyu Gan";
//document.getElementById('theBigTitle').attributes[1].nodeValue = "Xiangyu Gan"; |
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;mongoose.connect(process.env.MONGO_URL);
var User = require('./../schemas/user_model.js');
var Item = require('./../schemas/shop_model.js');
function isNumeric(value) {
return /^\d+$/.test(value);
}
function buyitem(user, item, message, bot){
var kaef = bot.emojis.find("name", "fallout_kaef");
var newCash = user.retrocoinCash - item.itemPrice;
var user_obj = User.findOne({userID: message.member.id}, function(err, found_user){
if (err)
console.log("WTF there is an error: " + err);
else {
if (!user_obj)
console.log("User not found");
else {
//если у юзера инвентарь старого типа - делаю резет
if (typeof found_user.inv[0] === 'object')
var newinv = [];
else
var newinv = found_user.inv;
newinv.push(item.itemName);
found_user.retrocoinCash = newCash;
found_user.inv = newinv;
found_user.save(function(err, updatedObj){
if (err)
console.log(err);
});
}
}
});
return message.reply("держи, вот тебе " + item.itemName);
}
module.exports.run = async (bot, message, args) => {
var shop_channel = message.guild.channels.find(`name`, "💸основное_экономика");
if (message.channel.name != "💸основное_экономика" && message.channel.name != "🌎general_bots" && message.channel.name != "🕵секретный_чат" && message.channel.name != "🍲комната_отдыха"){
message.delete(3000);
return message.reply(`покупать можно только в ${shop_channel}`).then(msg => msg.delete(10000));
}
var kaef = bot.emojis.find("name", "fallout_kaef");
//message.delete().catch(O_o=>{});
//ищем есть ли человек, который пытается что либо купить, у нас в базе
var user_obj = await User.findOne({userID: message.member.id}, function(err, found_user){});
if (typeof user_obj === 'undefined' || user_obj === null)
return message.reply("пользователь не найден в базе");
//парсим что человек пытается купить
var item = message.content.split(" ").toString();
var to_cut = item.indexOf(",");
item = item.slice(to_cut + 1);
item = item.replace(/,/g, " ");
item = item.replace(/\s\s+/g, ' ');
//ищем этот итем у нас в базе, узнаем цену
var item_obj = await Item.findOne({itemName: item}, function(err, found_item){});
if (typeof item_obj === 'undefined' || item_obj === null)
return message.reply("укажите точное название из магазина");
//чекаем есть ли у человека в инветаре этот предмет или есть ли эта роль
if (item_obj.itemName == "Покупка роли: Азартный игрок 🎲"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Азартный игрок 🎲"].includes(r.name)))
return message.reply(`ты уже Азартный игрок!`);
};
if (item_obj.itemName == "Покупка роли: Шулер 🎱"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Шулер 🎱"].includes(r.name)))
return message.reply(`ты уже Шулер!`);
};
if (item_obj.itemName == "Boost Pack +5% 💰"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Boost Pack +5% 💰"].includes(r.name)))
return message.reply(`у тебя уже есть этот Boost Pack!`);
};
if (item_obj.itemName == "Ключ от номера 🔑"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Ключ от 1-го номера"].includes(r.name)))
return message.reply(`у тебя уже есть этот ключ!`);
};
if (item_obj.itemName == "Пропуск в Убежище 111 💣"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>['Житель убежища "111"'].includes(r.name)))
return message.reply(`ты уже являешься Жителем убежища "111"!`);
};
if (item_obj.itemName == "Покупка роли: **Активист** 🔋"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Активист 🔋"].includes(r.name)))
return message.reply(`ты уже **Активист**!`);
};
if (item_obj.itemName == "Ключ к Клубничному чату 🍓"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["🍓Клубничный клуб🍓"].includes(r.name)))
return message.reply(`у тебя уже есть доступ к Клубничному клубу! ${kaef}`);
};
if (item_obj.itemName == "Покупка роли: **Коренной житель (lv.35)**"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Коренной житель (lv.35)"].includes(r.name)))
return message.reply(`ты уже стал Коренным жителем!`);
};
if (item_obj.itemName == "Boost Pack +25% 💰"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Boost Pack +25% 💰"].includes(r.name)))
return message.reply(`у тебя уже есть этот Boost Pack!`);
};
if (item_obj.itemName == "Покупка роли: **Легенда (lv.50)**"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Легенда [lv.50]"].includes(r.name)))
return message.reply(`ты уже стал Легендой!`);
};
if (item_obj.itemName == "Boost Pack +50% 💰"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Boost Pack +50% 💰"].includes(r.name)))
return message.reply(`у тебя уже есть этот Boost Pack!`);
};
if (item_obj.itemName == "Boost Pack +75% 💰"){
if (user_obj.inv.includes(item_obj.itemName) == true)
return message.reply(`у тебя уже есть ${item_obj.itemName}`);
if(message.member.roles.some(r=>["Boost Pack +75% 💰"].includes(r.name)))
return message.reply(`у тебя уже есть этот Boost Pack!`);
};
//проверяем может ли юзер купить то, что задумал
if (user_obj.retrocoinCash - item_obj.itemPrice >= 0)
buyitem(user_obj, item_obj, message, bot);
else
return message.reply("у тебя не хватает на " + item_obj.itemName);
}
module.exports.help = {
name: "buy"
}
|
const About = () => (
<div className='container'>
<div className='col-5'>
<h3>Arun!</h3>
<p>I am Arun, a product designer and engineer from India. I like to make digital experiences easier and simpler for people. I have worked with multiple teams in roles of design, engineering, product and marketing. </p>
<p> I am passionate about researching problems and solving them through design while providing a pleasant user experiences.</p>
<p>Currently, I'm pursing my Master's degree in Interaction Design from University of Limerick, Ireland</p>
</div>
</div>
)
export default About |
// Gets the schema of the first media type defined in the `content` of the path operation
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#user-content-parameterContent
module.exports = pathOperation => {
try {
if (pathOperation.requestBody.content) {
const type = Object.keys(pathOperation.requestBody.content)[0];
return { type, schema: pathOperation.requestBody.content[type].schema };
}
} catch (e) {} // eslint-disable-line no-empty
return undefined;
};
|
import Link from 'next/link';
import React from 'react';
const contents = {
shapes: [
'bp-chose-5.1.png',
'bp-chose-5.2.png',
'bp-chose-5.3.png',
],
feature_bg: '/assets/img/feature/fea-2.png',
subtitle: 'Why Choose us',
title: 'We provide the best',
highlight_text: 'solution for',
text_1: 'By understanding the client,s condition and leveraging our experience and knowledge. we support reform by recommending the most appropriate methods and sesources.',
text_2: 'At collax we specialize in designing, building, shipping and scaling beautiful, usable products with blazing.',
btn_text: 'About Collax'
}
const { btn_text, feature_bg, highlight_text, shapes, subtitle, text_1, text_2, title } = contents;
const FeatureArea = () => {
return (
<div className="tp-chose-area pt-190 pb-130 p-relative">
{shapes.map((s, i) => (
<div key={i} className={`bp-chose-${i + 1} d-none d-lg-block`}>
<img src={`/assets/img/chose/${s}`} alt="" />
</div>
))}
<div className="container">
<div className="row">
<div className="col-xl-6 col-lg-7 col-md-12">
<div className="tpchosebox-main p-relative">
<div className="tp-chose-bg">
<img src={feature_bg} alt="" />
</div>
<div className="row gx-40 align-items-center tp-chose-space">
<div className="col-xl-6 col-lg-6 col-md-6 col-12 wow tpfadeLeft"
data-wow-duration=".3s" data-wow-delay=".5s">
<div className="tp-chose-item mb-40">
<div className="tpchosebox">
<div className="tpchosebox__icon mb-30">
<a href="#"><i className="flaticon-group"></i></a>
</div>
<div className="tpchosebox__content">
<h4><a href="#">Professional <br /> Team</a></h4>
<p>24+ Team Member</p>
</div>
</div>
</div>
</div>
<div className="col-xl-6 col-lg-6 col-md-6 col-12">
<div className="tp-chose-item">
<ChoseItem item_num={'two'} m={'mb-40'} icon={'flaticon-web'} color="4"
title={<>Cretified <br /> Globally</>} text="65.04 k Reach" />
<ChoseItem item_num={'three'} icon={'fas fa-star'} color="5"
title={<>Competitive <br /> Rate</>} text="100% Client Satisfied" />
</div>
</div>
</div>
</div>
</div>
<div className="col-xl-6 col-lg-5 col-md-10 col-12 wow tpfadeRight" data-wow-duration=".5s" data-wow-delay=".9s">
<div className="tp-feature-section-title-box">
<h5 className="tp-subtitle pb-10">{subtitle}</h5>
<h2 className="tp-title tp-title-sm">{title}
<span className="tp-section-highlight">
{highlight_text}
<svg width="247" height="12" viewBox="0 0 247 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M-0.000488281 0L247 12H-0.000488281V0Z" fill="#FFDC60" />
</svg>
</span>
your business development</h2>
<p className="pb-25">{text_1}</p>
<p className="pb-20">{text_2}</p>
<div className="tp-fea-button-five">
<Link href="/contact">
<a className="tp-btn-sky">{btn_text}</a>
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default FeatureArea;
const ChoseItem = ({ item_num, m, icon, title, text, color }) => {
return (
<div className={`tpchosebox tpchosebox-${item_num} ${m && 'mb-40'} wow tpfadeIn`}
data-wow-duration=".5s" data-wow-delay=".7s">
<div className={`tpchosebox__icon fea-color-${color} mb-30`}>
<a href="#"><i className={icon}></i></a>
</div>
<div className="tpchosebox__content">
<h4><a href="#">{title}</a></h4>
<p>{text}</p>
</div>
</div>
)
} |
//
// Counts the total number of lines in a file - async
//
// Usage:
// nodejs Async_Line_Counter.js file_path
//
//
// We need the file system module
var fs = require("fs");
var logging = false;
if(logging)
console.log(process.argv);
var filePath = process.argv[process.argv.length - 1];
if(logging)
console.log("Filepath: " + filePath);
// Callback for fs.readFile
var calcNewLines = function(err, data) {
if (err) throw err;
var fileBuffer = data;
var count = 0;
if(logging)
console.log("length: " + fileBuffer.length);
// Loop through the characters in the file
for(var i = 0; i < fileBuffer.length; i++){
if(logging)
console.log("i: " + fileBuffer[i]);
// Check if the character is a new line
if(fileBuffer[i] === 10){
if(logging)
console.log("Found One @ position: " + i);
count++;
}
}
console.log(count);
}
fs.readFile(filePath, calcNewLines); |
var assert = require("chai").assert;
var sinon = require("sinon");
var { objToString } = require("../");
describe("objToString()", function () {
it("returns an empty string when given an empty object", function () {
var actual = objToString({}, () => "");
assert.equal(actual, "");
});
it("invokes the toString function once for each key/value pair at the top level of the object", function () {
var toString = sinon.spy(() => "");
var actual = objToString({ foo: "", bar: "" }, toString);
assert.equal(toString.callCount, 2);
});
it("provides the key, value and index arguments to the toString function", function () {
var toString = (k, v, i) => {
assert.equal(k, "foo");
assert.equal(v, "bar");
assert.equal(i, 0);
}
objToString({ foo: "bar" }, toString);
});
it("returns a single string using the returned values from each function in order", function () {
var toString = (k, v) => `[${k}::${v}]`;
var actual = objToString({ foo: "bar", baz: 5 }, toString);
var expected = "[foo::bar][baz::5]";
assert.equal(actual, expected);
});
}); |
<script>
$(document).ready(function () {
$('.mt-toggle-container nav em:contains("No headers")').closest('.mt-toggle-container').css('display', 'none');
$('.noindex .mt-toggle-collapse').trigger('click');
$('ol li.elm-back-to-top a').attr('href', 'javascript:void(0);');
$(document).on('click', 'ol li.elm-back-to-top a', function () {
$("html, body").animate({ scrollTop: 0 }, 500);
});
window.onscroll = function () {
var pageOffset = document.documentElement.scrollTop || document.body.scrollTop;
if (pageOffset >= 500) {
$('.mt-icon-back-to-top').removeClass('back').addClass('move');
} else {
$('.mt-icon-back-to-top').removeClass('move').addClass('back');
}
};
});
</script>
|
import { GET_PROGRAMS, DELETE_PROGRAM, ADD_PROGRAM } from "../actions/types.js";
const initialState = {
programs: []
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_PROGRAMS:
return {
...state, // gets all properties of initialState.
programs: action.payload
};
case DELETE_PROGRAM:
return {
...state, // gets all properties of initialState.
programs: state.programs.filter(
program => program.id !== action.payload
)
};
case ADD_PROGRAM:
return {
...state, // gets all properties of initialState.
programs: [...state.programs, action.payload] // [existing programs, append new payload program]
};
default:
return state;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.