text stringlengths 7 3.69M |
|---|
alert("Chegou aqui");
$(function(){
verificarCliqueMenu();
function verificarCliqueMenu(){
$('a').click(function(){
var href = $(this).attr('href');
$.ajax({
'beforeSend': function(){
console.log("Estamos chamando o beforeSend");
},
'timeout': 10000,
'url':href,
'error': function(){
console.log("ocorreu um erro");
},
'success': function(data){
console.log(data);
}
})
return false;
})
}
});
|
/**
* Created by 国正 on 14-2-19.
*/
var clients = [];
var net = require('net');
net.createServer(function (socket) {
console.log('Conntected ' + socket.remoteAddress + ':' + socket.remotePort);
socket.on('data', function (data) {
console.log(socket.remoteAddress + ' ' + data);
socket.write('Got message. You said: '+ data);
});
socket.on('error', function (err) {
console.log("Error:", err.message);
});
socket.on('close', function () {
console.log('Connection is closed.');
var index = clients.indexOf(socket);
clients.splice(index, 1);
});
/*socket.on('listening',function(){
console.log('Server is listening 5006.');
});*/
}).listen(5006); |
export const actions = {
UPDATE_MY_VAR: 'UPDATE_MY_VAR',
};
|
import React, { useEffect } from 'react';
// , useState
import Product from '../Product/Product';
// import Axios from 'axios';
import {useParams} from "react-router-dom"
import { searchProducts } from '../../actions/Products';
import { useDispatch, useSelector } from 'react-redux';
const Search = () => {
const query = useParams();
// const [products, setProducts]= useState([])
const dispatch = useDispatch();
const products = useSelector(state => state.Product.searchProduct);
useEffect(()=>{
// Axios(`http://localhost:3001/search?query=${query.search}`)
// .then(r => setProducts(r.data))
// .catch(err => {
// console.log(err)
// })
dispatch( searchProducts(query.search) );
// eslint-disable-next-line
},[query.search])
if(!products){
return <p>Cargando...</p>
}
return (
<div className='container'>
{products.length === 0 ? <p>No hay productos encontrados para la busqueda {query.search}</p> : products.map((f) => <Product
f={f}
key={f.name}
/>)}
</div>
);
}
export default Search; |
const model = require('./../model')
exports.tokenCheck = (req, res, next) => {
if (!req.headers['x-access-token']) res.status(500).send('Can\'t find token in header')
else {
model.User.findOne({ where: { access_token: req.headers['x-access-token'] } })
.then(user => {
if (user) {
req.user = user
next()
} else {
res.status(500).send('fail')
}
})
.catch(err => res.send(500))
}
}
|
/* global describe, it, expect */
import webdriver from 'next-webdriver'
import { readFileSync, writeFileSync, renameSync } from 'fs'
import { join } from 'path'
import { waitFor } from 'next-test-utils'
export default (context, render) => {
describe('Hot Module Reloading', () => {
describe('syntax error', () => {
it('should detect the error and recover', async () => {
const browser = await webdriver(context.appPort, '/hmr/about')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPagePath = join(__dirname, '../', 'pages', 'hmr', 'about.js')
const originalContent = readFileSync(aboutPagePath, 'utf8')
const erroredContent = originalContent.replace('</div>', 'div')
// change the content
writeFileSync(aboutPagePath, erroredContent, 'utf8')
const errorMessage = await browser
.waitForElementByCss('pre')
.elementByCss('pre').text()
expect(errorMessage.includes('Unterminated JSX contents')).toBeTruthy()
// add the original content
writeFileSync(aboutPagePath, originalContent, 'utf8')
const newContent = await browser
.waitForElementByCss('.hmr-about-page')
.elementByCss('p').text()
expect(newContent).toBe('This is the about page.')
browser.close()
})
})
describe('delete a page and add it back', () => {
it('should load the page properly', async () => {
const browser = await webdriver(context.appPort, '/hmr/contact')
const text = await browser
.elementByCss('p').text()
expect(text).toBe('This is the contact page.')
const contactPagePath = join(__dirname, '../', 'pages', 'hmr', 'contact.js')
const newContactPagePath = join(__dirname, '../', 'pages', 'hmr', '_contact.js')
// Rename the file to mimic a deleted page
renameSync(contactPagePath, newContactPagePath)
// wait until the 404 page comes
while (true) {
try {
const pageContent = await browser.elementByCss('body').text()
if (/This page could not be found/.test(pageContent)) break
} catch (ex) {}
await waitFor(1000)
}
// Rename the file back to the original filename
renameSync(newContactPagePath, contactPagePath)
// wait until the page comes back
while (true) {
try {
const pageContent = await browser.elementByCss('body').text()
if (/This is the contact page/.test(pageContent)) break
} catch (ex) {}
await waitFor(1000)
}
browser.close()
})
})
})
}
|
export { default } from './DroneInn';
|
import React from 'react';
import ViewSet from '../../components/views/viewSet';
import Form from './_form';
import Fields1 from './_fields1'
export default function Edit({item, afterSubmit}) {
return <Form item={item} afterSubmit={afterSubmit}>
{props => <ViewSet
viewType='plan'
labels={['']}
tabs={[
<Fields1
item={props.item}
values={props.values}
errors={props.errors}
touched={props.touched}
handleChange={props.handleChange}
onDelete={props.onDelete}
submitForm={props.submitForm}
/>
]}
/>
}
</Form>
} |
var searchData=
[
['non_5foption_5fconst_5fiterator_214',['non_option_const_iterator',['../namespaceoptionpp.html#a3d6a15f82589ed4fec9fcdd82eab59d0',1,'optionpp']]],
['non_5foption_5fiterator_215',['non_option_iterator',['../namespaceoptionpp.html#a45602ec8fa92e066f6e2e340d1b7b101',1,'optionpp']]]
];
|
import React, {useEffect} from 'react';
import '../../styles/CustomerOrderStyle.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Container, Image, Button, Row, Col, Table} from 'react-bootstrap'
import WebFont from 'webfontloader';
const CustomerOrderDetailPage = () => {
useEffect(() => {
WebFont.load({
google: {
families: ['Roboto', 'sans-serif']
}
});
}, []);
return (
<div className="background">
<Container>
<div id="header">
<h2>Order Detail</h2>
</div>
<h5>Order Status</h5>
<div id="order-status">
</div>
<h5>Order items list</h5>
<div id="products-order-list">
<div className="product-order">
<h6>Order number</h6>
</div>
<div className="product-order">
<h6>Order number</h6>
</div>
<div className="product-order">
<h6>Order number</h6>
</div>
<div className="product-order">
<h6>Order number</h6>
</div>
<div className="product-order">
<h6>Order number</h6>
</div>
</div>
</Container>
</div>
)
}
export default CustomerOrderDetailPage; |
// var i= 1;
// var factorial = 1;
// while (i<10){
// factorial= factorial*i;
// console.log(i, factorial)
// i++;
// }
function factorial(n){
var i= 1;
var factorial = 1;
while (i<=n){
factorial= factorial*i;
i++;
}
return factorial
}
var result= factorial(4);
console.log(result) |
'use strict'
import winston from 'winston'
import fs from 'fs'
const tsFormat = () => (new Date()).toLocaleTimeString();
const LOG_LEVEL = process.env.LOG_LEVEL
const LOG_DIRECTORY = process.env.LOG_DIRECTORY
let transports = [new (winston.transports.Console)({ colorize: true, timestamp: tsFormat, level: LOG_LEVEL })]
if (LOG_DIRECTORY) {
if (!fs.existsSync(LOG_DIRECTORY)) {
fs.mkdirSync(LOG_DIRECTORY);
}
transports.push(new (winston.transports.File)({
filename: `${LOG_DIRECTORY}/results.log`,
timestamp: tsFormat,
level: LOG_LEVEL
}))
}
const logger = new (winston.Logger)({transports: transports});
logger.level = LOG_LEVEL
export default logger |
searchServiceUrl="http://localhost:8081/jokesearch/api/"
$(document).ready(function () {
$.ajax({
url: window.searchServiceUrl+"getCategories",
datatype: "JSON",
type: "GET",
success: function (data) {
debugger;
for(var i=0;i<data.length;i++)
{
var opt = new Option(data[i]);
$("#op1").append(opt);
}
}
});
});
function UserAction() {
console.log("UserAction Called")
var key=document.getElementById("keysearch").value;
updateDiv();
$.ajax({
url: window.searchServiceUrl+"getJokesByTerm",
type : "GET",
dataType: 'json',
data: {
term : key
}
}).then(function(data) {
for (var x in data) {
document.getElementById('jokesByTerm').innerHTML += '<li>' + data[x].setup +" "+ data[x].punchline + '</li>'+ "<br>";
console.log(data[x].punchline);
}
});
}
function UserActionDownloadJoke() {
console.log("UserActionDownloadJoke Called")
var key=document.getElementById("keysearch").value;
if(key != null && key != '') {
var url=window.searchServiceUrl+"downloadJoke?term="+key;
window.location.href=url;
}
else{
alert("search field is empty");
}
}
function UserActionAdvSearch() {
console.log("UserActionAdvSearch Called")
updateDiv();
var key=document.getElementById("advsearch").value;
var type=document.getElementById("op1").value;
$.ajax({
url: window.searchServiceUrl+"getJokesByTerm",
type : "GET",
dataType: 'json',
data: {
term : key
}
}).then(function(data) {
for (var x in data) {
document.getElementById('jokesByTerm').innerHTML += '<li>' + data[x].setup +" "+ data[x].punchline + '</li>'+ "<br>";
console.log(data[x].punchline);
}
});
//document.getElementById("keysearch").value=key;
document.getElementById('keysearch').value=key;
}
function updateDiv()
{
$( "#jokesByTerm" ).load(window.location.href + " #jokesByTerm" );
$( "#searchedTerms" ).load(window.location.href + " #searchedTerms" );
termNavigation();
}
function termNavigation() {
console.log("termNavigation Called")
$.ajax({
url: window.searchServiceUrl+"getRecentSearchedTerms",
type : "GET",
dataType: 'json',
}).then(function(data) {
for (var x in data) {
document.getElementById('searchedTerms').innerHTML += '<li>' + data[x].term +" "+ data[x].termCount + '</li>'+ "<br>";
console.log(data[x].term +" "+ data[x].termcount );
}
});
}
|
import React from 'react'
import Radium from '@instacart/radium'
import PropTypes from 'prop-types'
import { colors } from '../../styles'
// Not using `margin` or `padding` shorthand to avoid any future
// Radium warnings with combining shorthand/longhand properties.
const baseStyles = {
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
marginTop: 0,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
color: colors.GRAY_13,
}
// Matches the Open Sans font weights
// https://fonts.google.com/specimen/Open+Sans?selection.family=Open+Sans
const fontWeights = {
light: 300,
regular: 400,
semiBold: 600,
bold: 700,
}
const variantStyles = {
'T.92': {
fontSize: '92px',
lineHeight: '138px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.82': {
fontSize: '82px',
lineHeight: '123px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.72': {
fontSize: '72px',
lineHeight: '108px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.64': {
fontSize: '64px',
lineHeight: '96px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.58': {
fontSize: '58px',
lineHeight: '87px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.46': {
fontSize: '46px',
lineHeight: '69px',
letterSpacing: '0',
fontWeight: fontWeights.regular,
},
'T.36': {
fontSize: '36px',
lineHeight: '54px',
letterSpacing: '0.03em',
fontWeight: fontWeights.regular,
},
'T.28': {
fontSize: '28px',
lineHeight: '42px',
letterSpacing: '0.05em',
fontWeight: fontWeights.bold,
},
'T.22': {
fontSize: '22px',
lineHeight: '32px',
letterSpacing: '0.03em',
fontWeight: fontWeights.regular,
},
'T.18': {
fontSize: '18px',
lineHeight: '32px',
letterSpacing: '0.03em',
fontWeight: fontWeights.regular,
},
'T.16': {
fontSize: '16px',
lineHeight: '24px',
letterSpacing: '0.03em',
fontWeight: fontWeights.regular,
},
'T.14': {
fontSize: '14px',
lineHeight: '21px',
letterSpacing: '0.03em',
fontWeight: fontWeights.regular,
},
'T.12': {
fontSize: '12px',
lineHeight: '18px',
letterSpacing: '0.05em',
fontWeight: fontWeights.regular,
},
'T.11': {
fontSize: '11px',
lineHeight: '16px',
letterSpacing: '0.05em',
fontWeight: fontWeights.regular,
},
}
const htmlTagMapping = {
'T.92': 'h1',
'T.82': 'h1',
'T.72': 'h1',
'T.64': 'h1',
'T.58': 'h1',
'T.46': 'h1',
'T.36': 'h2',
'T.28': 'h2',
'T.22': 'h2',
'T.18': 'p',
'T.16': 'p',
'T.14': 'p',
'T.12': 'p',
'T.11': 'p',
}
function Text({ variant, style, children, elementType, fontWeight, ...restProps }) {
const ElementType = elementType || htmlTagMapping[variant]
const finalStyles = {
...baseStyles,
...variantStyles[variant],
...(fontWeight && { fontWeight: fontWeights[fontWeight] }),
...style,
}
return (
<ElementType style={finalStyles} {...restProps}>
{children}
</ElementType>
)
}
Text.propTypes = {
/** Typography variant to be used. */
variant: PropTypes.oneOf(Object.keys(variantStyles)).isRequired,
/** Text content to be rendered. */
children: PropTypes.node.isRequired,
/** Overrides the default HTML element type. Each typography variant has a default HTML element (e.g. h1, p),
* but this is only a best guess. Always ensure you're using the correct header markup -- element
* types with Snacks typography should be used to describe document structure, not visual style. */
elementType: PropTypes.string,
/** Overrides the variant's default font weight. */
fontWeight: PropTypes.oneOf(Object.keys(fontWeights)),
/** Any custom inline styles. Useful for things like gutters and responsive styles. */
style: PropTypes.shape({}),
}
export default Radium(Text)
|
import 'bootstrap/dist/css/bootstrap.min.css';
import Navbar from "react-bootstrap/Navbar";
import Container from "react-bootstrap/Container"
import Nav from "react-bootstrap/Nav"
import NavDropdown from "react-bootstrap/NavDropDown"
import { useDispatch, useSelector } from "react-redux";
import { logoutUser } from "../store/actions/userActions"
import React, { useEffect, useState } from "react";
import { Link, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { getUserCart } from '../store/actions/cartActions';
function NavbarComponent() {
//we need to draw data from store, so that we can access isLoggedIn and user cart info
const userData = useSelector(state => state.user);
const userCart = useSelector(state => state.usercart)
//count is to determine how many products does user have
const [count, setCount] = useState(0);
const { usercart } = userCart;
const { isLoggedIn, user } = userData
const history = useHistory();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getUserCart(user[0]?.id))
}, [user[0]?.id])
useEffect(() => {
//when usercart changes (if user adds product), count should change
//but this feature needs arrangement since it doesn't work properly
{ usercart != undefined ? setCount(usercart.length) : setCount(0) }
}, [usercart]);
//Log out makes isLoggedIn = false and redirects to login page
const handleLogout = (event) => {
event.preventDefault();
dispatch(logoutUser());
history.push("/login")
}
return (
<Navbar collapseOnSelect expand="lg" bg="light" variant="dark">
<Link to="/"><i class="fab fa-shopware fa-3x" style={{ color: "#7C203A" }}></i></Link>
<Navbar.Brand href="/" style={{ color: "#7C203A", fontWeight: "bold" }}>MeShop!</Navbar.Brand>
<Container>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="me-auto">
<Nav.Link href="#features" className="text-muted">Fırsat Ürünleri</Nav.Link>
<Nav.Link href="#pricing" className="text-muted">Favori Ürünler</Nav.Link>
<NavDropdown title={<span className="text-muted">Kategoriler</span>} id="collasible-nav-dropdown" style={{ color: "#777" }}>
<NavDropdown.Item href="/products/womenwear">Kadın Giyim</NavDropdown.Item>
<NavDropdown.Item href="/products/menwear">Erkek Giyim</NavDropdown.Item>
<NavDropdown.Item href="/products/electronics">Elektronik</NavDropdown.Item>
<NavDropdown.Item href="/products/jewelery">Hediyelik Eşya</NavDropdown.Item>
</NavDropdown>
</Nav>
<Nav>
{isLoggedIn ? <NavDropdown title={<span className="text-muted">Kullanıcı</span>} id="collasible-nav-dropdown">
<NavDropdown.Item href="/">Profil</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="/" onClick={handleLogout}>Çıkış yap</NavDropdown.Item>
</NavDropdown> : <NavDropdown title={<span className="text-muted">Kullanıcı</span>} id="collasible-nav-dropdown">
<NavDropdown.Item href="/login">Giriş yap</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="/signup" >Üye ol</NavDropdown.Item>
</NavDropdown>}
<Nav.Link href="/usercart" className="text-muted">Sepetim</Nav.Link>
</Nav>
</Navbar.Collapse>
<Navbar.Brand href="/">
<a href="/usercart"><i class="fas fa-shopping-cart text-muted" style={{ color: "#f2f2f2" }}></i>
{count > 0 ? <small><span class="badge rounded-pill badge-notification bg-danger">{count}</span></small> : null}
</a>
</Navbar.Brand>
</Container>
</Navbar>
);
}
export default NavbarComponent;
|
exports.askForBathroomEnglish = function(){
console.log("May I please use your restroom?");
}
exports.askForDirectionsEnglish = function(){
console.log("Could you please tell me how to get to <insert destination here>?");
}
exports.askForBathroomJapanese = function(){
console.log("toire wa doko desu ka");
}
exports.askForDirectionsJapanese = function(){
console.log("Michijun ni tsuite");
}
exports.askForBathroomIcelandic = function(){
console.log("Hvar er klósettið?");
}
exports.askForDirectionsIcelandic = function(){
console.log("fyrir leiðbeiningar");
}
exports.askForBathroomSpanish = function(){
console.log("¿dónde están los baños?,");
}
exports.askForDirectionsSpanish = function(){
console.log("Cómo puedo llegar a?");
}
|
import Link from 'next/link';
import PropTypes from 'prop-types';
import { Col, Row } from 'reactstrap';
import s from './footerColumn.scss';
const FooterColumn = (props) => {
const { title, list } = props;
return (
<Col xs={12} sm={3}>
<div className="footerColumn">
<Row>
<div className="leftbar" />
<div>
<h4>{title}</h4>
<ul>
{list.map(item => (
<li key={item.name}>
<Link href={item.link}>
<a className="footerColumn__link" href={item.link}>{item.name}</a>
</Link>
</li>
))}
</ul>
</div>
</Row>
<style jsx>{s}</style>
</div>
</Col>
);
};
FooterColumn.propTypes = {
title: PropTypes.string,
list: PropTypes.array,
width: PropTypes.number,
};
FooterColumn.defaultProps = {
title: '',
list: [],
width: 273,
};
export default FooterColumn;
|
// Learn more about this file at:
// https://victorzhou.com/blog/build-an-io-game-part-1/#6-client-input-%EF%B8%8F
import { updateDirection, fire } from './networking';
const upTurn = Math.atan2(0, 0);
const rightTurn = Math.atan2(1, 0);
const downTurn = Math.atan2(0, -1);
const leftTurn = Math.atan2(-1, 0);
let inputNumbers = '';
function onMouseInput(e) {
handleInput(e.clientX, e.clientY);
}
export function getCurrentInput() {
return inputNumbers;
}
function onTouchInput(e) {
const touch = e.touches[0];
handleInput(touch.clientX, touch.clientY);
}
function numberInput(newnum) {
inputNumbers += newnum;
if (inputNumbers.length === 5) {
inputNumbers = inputNumbers.substring(1, 5);
}
}
function backspaceInput() {
inputNumbers = inputNumbers.substring(0,inputNumbers.length - 1);
}
function useNumber() {
fire(Number(inputNumbers));
inputNumbers = '';
}
function onKeyDown(e) {
if (e.code === 'ArrowUp') updateDirection(upTurn);
if (e.code === 'ArrowRight') updateDirection(rightTurn);
if (e.code === 'ArrowLeft') updateDirection(leftTurn);
if (e.code === 'ArrowDown') updateDirection(downTurn);
if (e.code === 'KeyW') updateDirection(upTurn);
if (e.code === 'KeyD') updateDirection(rightTurn);
if (e.code === 'KeyA') updateDirection(leftTurn);
if (e.code === 'KeyS') updateDirection(downTurn);
if (e.code === 'Digit1') numberInput(1);
if (e.code === 'Digit2') numberInput(2);
if (e.code === 'Digit3') numberInput(3);
if (e.code === 'Digit4') numberInput(4);
if (e.code === 'Digit5') numberInput(5);
if (e.code === 'Digit6') numberInput(6);
if (e.code === 'Digit7') numberInput(7);
if (e.code === 'Digit8') numberInput(8);
if (e.code === 'Digit9') numberInput(9);
if (e.code === 'Digit0') numberInput(0);
if (e.code === 'Minus') numberInput('-');
if (e.code === 'Numpad1') numberInput(1);
if (e.code === 'Numpad2') numberInput(2);
if (e.code === 'Numpad3') numberInput(3);
if (e.code === 'Numpad4') numberInput(4);
if (e.code === 'Numpad5') numberInput(5);
if (e.code === 'Numpad6') numberInput(6);
if (e.code === 'Numpad7') numberInput(7);
if (e.code === 'Numpad8') numberInput(8);
if (e.code === 'Numpad9') numberInput(9);
if (e.code === 'Numpad0') numberInput(0);
if (e.code === 'Enter') useNumber();
if (e.code === 'Space') useNumber();
if (e.code === 'NumpadEnter') useNumber();
if (e.code === 'Backspace') backspaceInput();
}
function handleInput(x, y) {
const dir = Math.atan2(x - window.innerWidth / 2, window.innerHeight / 2 - y);
updateDirection(dir);
}
export function startCapturingInput() {
// window.addEventListener('mousemove', onMouseInput);
window.addEventListener('mousemove', onMouseInput);
window.addEventListener('click', onMouseInput);
window.addEventListener('touchstart', onTouchInput);
window.addEventListener('touchmove', onTouchInput);
window.addEventListener('keydown', onKeyDown);
}
export function stopCapturingInput() {
window.removeEventListener('mousemove', onMouseInput);
window.removeEventListener('click', onMouseInput);
window.removeEventListener('touchstart', onTouchInput);
window.removeEventListener('touchmove', onTouchInput);
window.removeEventListener('keydown', onKeyDown);
}
|
//import items from '../data'
import itemData from '../../../../documents.json'
import CardList from './CardList.vue'
import areaData from '../areas.json'
import R from 'ramda'
let uid = 1
const items = itemData.map(item => ({
...item,
hidden: false,
comment: null,
approved: false,
departments: [],
title: item.gegenstand || item.url,
uid: uid++,
}))
export default {
data() {
return {
items,
query: '',
areaData,
}
},
computed: {
visibleItems() {
return this.items.filter(item => item.hidden !== true)
},
filteredItems() {
return this.visibleItems.filter(item => this.matchTitle(this.query, item) || this.matchId(this.query, item) || this.matchTag(this.query, item))
},
areas() {
return this.areaData.map(area => {
return {
...area,
items: this.visibleItems.filter(item => this.matchTags(area.tags, item.tags))
}
}).sort((a,b) => a.name > b.name)
}
},
methods: {
matchTitle(query, item) {
return item.title.toLowerCase().indexOf(query.trim().toLowerCase()) !== -1
},
matchId(query, item) {
return item.id.toLowerCase().indexOf(query.trim().toLowerCase()) !== -1
},
matchTag(query, item) {
return item.tags.filter(tag => tag.toLowerCase().indexOf(query.trim().toLowerCase()) !== -1).length > 0
},
matchTags(areaTags, itemTags) {
return R.intersection(
areaTags.map(tag => tag.toLowerCase()),
itemTags.map(tag => tag.toLowerCase()),
).length > 0
},
},
components: {
CardList
}
} |
/**
* @param {Array} data -Array of products
* @param {Object} product - {title, price}
*/
const addItem = (data, product) => {
data.push(product);
};
export default addItem;
|
import { useState, useEffect } from "react";
import { useHistory, useParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { selectUser } from "../../../redux/reducers/userReducer";
import { editPostAsync } from "../../../redux/reducers/postReducer";
import { getOnePost } from "../../../WebAPI";
import {
Root,
Container,
InputTitle,
InputContent,
InputBlock,
} from "../../BlogStyle";
function Article() {
let { id } = useParams();
const [isLoading, setIsLoading] = useState(true);
const [post, setPost] = useState([]);
const history = useHistory();
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const userState = useSelector(selectUser);
const dispatch = useDispatch();
useEffect(() => {
if (!isLoading) return;
getOnePost(id)
.then((data) => {
setPost(data);
setTitle(data[0].title);
setContent(data[0].body);
})
.then(() => {
setIsLoading(false);
});
}, []);
const handleTitleChange = (e) => {
setTitle(e.target.value);
};
const handleContentChange = (e) => {
setContent(e.target.value);
};
const handleSubmit = (e) => {
if (!userState.data || !userState.data.ok) return;
const postData = {
id: post[0].id,
title,
content,
};
dispatch(editPostAsync(postData))
.then(() => {
history.push(`/posts/${post[0].id}`);
})
.catch((err) => {
console.log(err);
});
};
return (
<Container>
{!isLoading && (
<form onSubmit={handleSubmit}>
<InputTitle>
<label>
<div>Title</div>
<input type="text" value={title} onChange={handleTitleChange} />
</label>
</InputTitle>
<InputContent>
<label>
<div>Content</div>
<textarea
cols="30"
rows="30"
value={content}
onChange={handleContentChange}
></textarea>
</label>
</InputContent>
<InputBlock>
<button type="submit" value="submit">
submit
</button>
</InputBlock>
</form>
)}
</Container>
);
}
export default function EditArticlePage() {
return (
<Root>
<Article />
</Root>
);
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Form, Button, Progress, Row, Col } from 'antd';
import TitleBar from '../../components/TitleBar';
import './index.scss';
const FormItem = Form.Item;
class NetworkTesting extends React.Component {
constructor(props) {
super(props);
this.state = {
networkQuality: 2
};
this.$rtc = props.adapter.$rtc;
}
componentDidMount() {
this.$rtc.on('lastmilequality', (quality) => {
// console.log(quality)
this.setState({
networkQuality: quality
});
});
this.$rtc.enableLastmileTest();
}
componentWillUnmount() {
this.$rtc.disableLastmileTest();
}
componentDidCatch(err, info) {
console.error(err);
window.location.hash = '';
}
render() {
return (
<div className="wrapper" id="networkTesting">
<header className="title">
<TitleBar />
</header>
<main className="main">
<section className="content">
<header>
<img src={require('../../assets/images/logo.png')} alt="" />
</header>
<main>
<Form>
<FormItem
label={(
<img style={{ width: '24px' }} src={require('../../assets/images/connection.png')} alt="" />
)}
labelCol={{ span: 4 }}
wrapperCol={{ span: 20 }}
colon={false}
>
<Progress percent={30} showInfo={false} />
</FormItem>
</Form>
<Row>
<Col span={12}>
<header className="stats-title">Packet Loss</header>
<main className="stats-body">
0%
</main>
</Col>
<Col span={12}>
<header className="stats-title">Delay Time</header>
<main className="stats-body">
29 ms
</main>
</Col>
<Col span={12}>
{/* <header className="stats-title">Network Status</header>
<main className="stats-body">
<div className="network-status">
Good
</div>
</main> */}
<NetworkStatus quality={this.state.networkQuality} />
</Col>
</Row>
</main>
</section>
<section className="illustration">
<h3 className="title">Network Testing</h3>
<div className="button-group">
<Button size="large" id="nextBtn" type="primary">
<Link to="/classroom">Next Step -></Link>
</Button>
</div>
</section>
</main>
</div>
);
}
}
function NetworkStatus(props) {
const profile = {
0: {
text: 'unknown', color: '#000', bgColor: '#FFF'
},
1: {
text: 'excellent', color: '', bgColor: ''
},
2: {
text: 'good', color: '#7ED321', bgColor: '#B8E986'
},
3: {
text: 'poor', color: '#F5A623', bgColor: '#F8E71C'
},
4: {
text: 'bad', color: '#FF4D89', bgColor: '#FF9EBF'
},
5: {
text: 'vbad', color: '', bgColor: ''
},
6: {
text: 'down', color: '#4A90E2', bgColor: '#86D9E9'
}
};
const quality = (function () {
switch (props.quality) {
default:
case 0:
return profile[0];
case 1:
case 2:
return profile[2];
case 3:
return profile[3];
case 4:
case 5:
return profile[4];
case 6:
return profile[6];
}
}());
return (
<section>
<header className="stats-title">Network Status</header>
<main className="stats-body">
<div
className="network-status"
style={{
color: quality.color,
backgroudColor: quality.bgColor
}}
>
{ quality.text }
</div>
</main>
</section>
);
}
export default NetworkTesting;
|
module.exports = function(app,path) {
app.get('/login', function (req, res) {
let filepath = path.resolve('www/index.html');
res.sendFile(filepath);
});
} |
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
function preload()
{
}
function setup() {
createCanvas(1200, 700);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
ground = new Ground(600,height,1200,20);
box1 = new Box(800,680,200,25)
box2 = new Box(700,680,25,200)
box3 = new Box(900,680,25,200)
ball = new Ball(100,680,40,40)
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(255);
ball.display();
ground.display();
box1.display();
box2.display();
box3.display();
}
function keyPressed(){
if(keyCode===UP_ARROW){
Matter.Body.applyForce(ball.body,ball.body.position,{x:158, y:-158})
}
}
|
//jshint esversion:6
const mongoose = require ('mongoose');
// Create fruitsDB
mongoose.connect('mongodb://localhost:27017/fruitsDB', { useNewUrlParser: true });
const fruitSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please check your data entry, no name is specified!"]
},
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
// Creates a new collection Fruits
const Fruit = mongoose.model('Fruit', fruitSchema);
// Adds a fruit named Apple to the Fruits collection and follows the fruitSchema model
const fruit = new Fruit ({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit."
});
// Inserts new Fruit into fruitsDB Fruits collection
// fruit.save();
const personSchema = new mongoose.Schema({
name: String,
age: Number,
favoriteFruit: fruitSchema
});
const Person = mongoose.model('Person', personSchema );
// const person = new Person ({
// name: "John",
// age: 37,
// });
// person.save();
// const kiwi = new Fruit ({
// name: "Kiwi",
// rating: 10,
// review: "The best fruit!"
// });
//
// const orange = new Fruit ({
// name: "Orange",
// rating: 4,
// review: "Too sour for me"
// });
//
// const banana = new Fruit ({
// name: "Banana",
// rating: 3,
// review: "Weird texture"
// });
// const peach = new Fruit ({
// name: "Peach",
// rating: 8,
// review: "They are just so sweet!"
// });
//
// peach.save();
// const pineapple = new Fruit ({
// name: "Pineapple",
// rating: 10,
// review: "Nobody can hate Pineapple!"
// });
//
// // pineapple.save();
// const person = new Person ({
// name: "Amy",
// age: 12,
// favoriteFruit: pineapple
// });
// person.save();
const pear = new Fruit ({
name: "Pear",
rating: 4,
review: "ehhh..."
});
// pear.save();
// Insert many documents into a collection
// Fruit.insertMany([kiwi, orange, banana], function(err) {
// if (err) {
// console.log(err);
// } else {
// console.log("Successfully saved all the fruits to fruitsDB");
// }
// });
// How to update a document in a collection
Fruit.updateOne({name: "Banana"}, {rating: 9}, function(err){
if (err) {
console.log(err);
} else {
console.log("The document Banana has been Successfully Updated!");
}
});
Person.updateOne({name: "John"}, {favoriteFruit: pear}, function(err){
if (err) {
console.log(err);
} else {
console.log("The document John was Successfully Updated");
}
});
// How to delete a document in a collection
// Fruit.deleteOne({name: "Pineapple"}, function(err){
// if (err) {
// console.log(err);
// } else {
// console.log("Document has been Successfully Deleted!");
// }
// });
Fruit.find(function(err, fruits){
if (err) {
console.log(err);
} else {
// Close connection that way you don't have to close it manually through the terminal
mongoose.connection.close();
fruits.forEach(function(fruit){
console.log(fruit.name);
});
}
});
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('fruits');
// Find some documents
collection.find({}).toArray(function(err, fruits) {
assert.equal(err, null);
console.log("Found the following records");
console.log(fruits);
callback(fruits);
});
};
|
(function() {
const qs = ((selector, scope=document) => {
return scope.querySelector(selector);
});
const qsa = ((selector, scope=document) => {
return scope.querySelectorAll(selector);
});
const getParentNode = ((child, className) => {
let parentNode = child.parentNode;
while(!parentNode.classList.contains(className)){
parentNode = parentNode.parentNode;
}
return parentNode;
});
function AddToCart() {
const getBtnParentElement = ((button) => {
return getParentNode(button, "card");
});
Array.from(qsa("button.add__to__cart__btn"))
.map((button) => {
return {parent: getBtnParentElement(button), button};
})
.filter(data => !!data.parent)
.forEach(({button, parent}) => {
const img = (qs("img", parent));
button
.addEventListener("click", ()=>app.Animate(img.parentNode, parent));
});
};
const matchWindowSize = ((size="600") => {
const media = window.matchMedia(`(max-width: ${size}px)`);
return media.matches;
})
window.app = window.app || {};
window.app.AddToCart = AddToCart;
window.app.getParentNode = getParentNode;
window.app.matchWindowSize = matchWindowSize;
window.qs = qs;
window.qsa = qsa;
})();
|
import React from 'react';
import { useMyContext } from '../Provider';
import './Forms.css';
const AboutYou = () => {
const [myState, dispatch] = useMyContext();
const onChange = (event) => {
dispatch({
type: 'ADD_INFORMATION',
field: event.target.name,
value: event.target.value,
});
};
return (
<div>
<div className="icon-title">
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M14.2875 0.3375L17.6625 3.7125C18.1125 4.1625 18.1125 4.8375 17.6625 5.2875L15.6375 7.3125L10.6875 2.3625L12.7125 0.3375C13.1625 -0.1125 13.8375 -0.1125 14.2875 0.3375ZM0.3375 12.7125L9.1125 3.9375L14.0625 8.88751L5.2875 17.6625C5.0625 17.8875 4.8375 18 4.5 18H1.125C0.45 18 0 17.55 0 16.875V13.5C0 13.1625 0.1125 12.9375 0.3375 12.7125Z" fill="black"/>
</svg>
<p className="titleComponent">Sobre Tí</p>
</div>
<p className="labelComponent">Haz una pequeña descripción de ti, tus intereses y tu experiencia.</p>
<input
type="text"
name="aboutMe"
className="textComponent-aboutme col-8"
onChange={onChange}
/>
<p className="labelComponent">Situación laboral Actual</p>
<select name="actualJob" className="selectComponent col-4">
<option>Estudiante</option>
<option>Empleado</option>
<option>Independiente</option>
</select>
</div>
);
};
export default AboutYou;
|
import React, { Component } from 'react';
import { AuthToken } from 'Auth';
import AdminTitlebar from 'admin/common/AdminTitlebar';
class DashboardLayout extends Component {
constructor (props) {
super(props);
}
componentWillMount () {
let {router} = this.props;
let token = localStorage.getItem('admintoken');
if (!token) { router.push('/admin/login'); }
else { AuthToken(token); }
}
render () {
let {children} = this.props;
return (
<div>
<AdminTitlebar />
<div className="container-fluid">
<div className="row">
<div className="col-md-12">
{children}
</div>
</div>
</div>
</div>
);
}
}
export default DashboardLayout;
|
// My Global variables
var count = 60;
var correct = 0;
var wrong = 0;
var unanswered = 0;
var panel = $("#main-container");
$("#main-container").hide();
$("#end-container").hide();
//Game Functions
var game = {
// Counts down and displays the time to the user
countdown: function(){
count--;
$('#timer_number').html(count + " seconds");
// Finish the game after the timer reaches 0
if(count === 0){
game.timeUp();
// Hide the game Div from the user
$("#main-container").hide();
}
},
// Show the countdown
startCountdown: function() {
$("#main-container").show();
timer = setInterval(game.countdown, 1000);
$('#directions').remove();
panel.append("<br><button type='submit' id='done_button'>Done</button>");
},
// Function to be run after the timer is up
timeUp: function() {
// Checked values of Radio Buttons
var Q1 = $('input:radio[name="q1"]:checked').val();
var Q2 = $('input:radio[name="q2"]:checked').val();
var Q3 = $('input:radio[name="q3"]:checked').val();
var Q4 = $('input:radio[name="q4"]:checked').val();
var Q5 = $('input:radio[name="q5"]:checked').val();
var Q6 = $('input:radio[name="q6"]:checked').val();
var Q7 = $('input:radio[name="q7"]:checked').val();
var Q8 = $('input:radio[name="q8"]:checked').val();
var Q9 = $('input:radio[name="q9"]:checked').val();
var Q10 = $('input:radio[name="q10"]:checked').val();
// Determine the right/wrong/unanswered counts
if(Q1 == undefined){
unanswered++;
}
else if(Q1 == "Clark Kent"){
correct++;
}
else{
wrong++;
}
if(Q2 == undefined){
unanswered++;
}
else if(Q2 == "Steve Trevor"){
correct++;
}
else{
wrong++;
}
if(Q3 == undefined){
unanswered++;
}
else if(Q3 == "The Flash"){
correct++;
}
else{
wrong++;
}
if(Q4 == undefined){
unanswered++;
}
else if(Q4 == "Hal Jordan"){
correct++;
}
else{
wrong++;
}
if(Q5 == undefined){
unanswered++;
}
else if(Q5 == "Atlantis"){
correct++;
}
else{
wrong++;
}
if(Q6 == undefined){
unanswered++;
}
else if(Q6 == "Green Arrow"){
correct++;
}
else{
wrong++;
}
if(Q7 == undefined){
unanswered++;
}
else if(Q7 == "Joe Chill"){
correct++;
}
else{
wrong++;
}
if(Q8 == undefined){
unanswered++;
}
else if(Q8 == "All of the Above"){
correct++;
}
else{
wrong++;
}
if(Q9 == undefined){
unanswered++;
}
else if(Q9 == "Black Widow"){
correct++;
}
else{
wrong++;
}
if(Q10 == undefined){
unanswered++;
}
else if(Q10 == "Teen Titans"){
correct++;
}
else{
wrong++;
}
this.results();
},
results: function(){
clearInterval(timer);
// Show the completed Score Div
$("#end-container").show();
//show final results
$('#correct-answers').html(correct);
$('#wrong-answers').html(wrong);
$('#unanswered').html(unanswered);
}
};
//Click Events
$(document).on("click", "#start_button", function () {
game.startCountdown();
$("#main-container").show();
});
$(document).on("click", "#done_button", function () {
game.timeUp();
$("#main-container").hide();
}); |
import types from "./types"
const takeTurn = (squares, currentIcon) => {
return {
type: types.TAKE_TURN,
squares: squares,
currentIcon: currentIcon
}
}
const reset = () => {
return {
type: types.RESET
}
}
const setGameState = (payload) => {
return {
type: types.SET_GAME_STATE,
payload
}
}
export default {
takeTurn,
reset,
setGameState
} |
// Importando o React
import React, { Component } from "react";
import { Row} from 'react-materialize';
import { Link } from 'react-router-dom';
class TopNavigation extends Component{
render (){
return (
<Row>
<nav>
<div class="nav-wrapper container">
<Link to="/ideas" class="brand-logo">Ideaboard</Link>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><Link to="/signup">Signup</Link></li>
<li><Link to="/">Login</Link></li>
</ul>
</div>
</nav>
</Row>
);
}
}
export default TopNavigation;
|
/*global ODSA */
// Written by Mohammed Farghally and Cliff Shaffer
// Problem, Algorithm, and program definitions
$(document).ready(function() {
"use strict";
var av_name = "AnalCasesSameCON";
// Load the config object with interpreter and code created by odsaUtils.js
var config = ODSA.UTILS.loadConfig({av_name: av_name}),
interpret = config.interpreter, // get the interpreter
code = config.code; // get the code object
var av = new JSAV(av_name);
var pseudo = av.code(code[0]).hide();
var arr1, arr2, arr3;
var topAlign = 60;
var leftAlign = 10;
var rectWidth = 180;
var rectHeight = 225;
// Slide 1
av.umsg(interpret("sc1"));
var rect = av.g.rect(leftAlign + 380, topAlign - 25, rectWidth, rectHeight);
var mainLabel = av.label(interpret("lab1"), {top: topAlign - 20, left: leftAlign + 400});
mainLabel.addClass("codeLabel");
av.displayInit();
// Slide 2
av.umsg(interpret("sc2"));
var lineInput = av.g.line(leftAlign + 320, topAlign + 95, leftAlign + 380, topAlign + 95);
var labelInput = av.label("$n$", {top: topAlign + 62, left: leftAlign + 285}).addClass("largeLabel");
var lineOutput = av.g.line(leftAlign + rectWidth + 380, topAlign + 95, leftAlign + rectWidth + 440, topAlign + 95);
var labelOutput = av.label("$n!$", {top: topAlign + 62, left: leftAlign + rectWidth + 460}).addClass("largeLabel");
av.step();
// Slide 3
av.umsg(interpret("sc3"));
lineInput.hide();
labelInput.hide();
lineOutput.hide();
labelOutput.hide();
var lineInput1 = av.g.line(leftAlign + 320, topAlign + 30, leftAlign + 380, topAlign + 30);
var labelInput1 = av.label("$n = 2$", {top: topAlign + 0, left: leftAlign + 250}).addClass("largeLabel");
var lineOutput1 = av.g.line(leftAlign + rectWidth + 380, topAlign + 30, leftAlign + rectWidth + 440, topAlign + 30);
var labelOutput1 = av.label("$n! = 2$", {top: topAlign + 0, left: leftAlign + rectWidth + 460}).addClass("largeLabel");
av.step();
// Slide 4
av.umsg(interpret("sc4"), {preserve: true});
var lineInput2 = av.g.line(leftAlign + 320, topAlign + 95, leftAlign + 380, topAlign + 95);
var labelInput2 = av.label("$n = 3$", {top: topAlign + 62, left: leftAlign + 250}).addClass("largeLabel");
var lineOutput2 = av.g.line(leftAlign + rectWidth + 380, topAlign + 95, leftAlign + rectWidth + 440, topAlign + 95);
var labelOutput2 = av.label("$n! = 6$", {top: topAlign + 62, left: leftAlign + rectWidth + 460}).addClass("largeLabel");
av.step();
// Slide 5
av.umsg(interpret("sc5"), {preserve: true});
var lineInput3 = av.g.line(leftAlign + 320, topAlign + 155, leftAlign + 380, topAlign + 155);
var labelInput3 = av.label("$n = 4$", {top: topAlign + 124, left: leftAlign + 250}).addClass("largeLabel");
var lineOutput3 = av.g.line(leftAlign + rectWidth + 380, topAlign + 155, leftAlign + rectWidth + 440, topAlign + 155);
var labelOutput3 = av.label("$n! = 24$", {top: topAlign + 124, left: leftAlign + rectWidth + 460}).addClass("largeLabel");
av.step();
// Slide 6
av.umsg(interpret("sc6"));
lineInput1.hide();
labelInput1.hide();
lineInput2.hide();
labelInput2.hide();
lineInput3.hide();
labelInput3.hide();
lineOutput1.hide();
labelOutput1.hide();
lineOutput2.hide();
labelOutput2.hide();
lineOutput3.hide();
labelOutput3.hide();
pseudo.show();
mainLabel.text(interpret("lab2"));
rect.css({width: rectWidth + 50});
mainLabel.css({left: "+=20"});
av.step();
// Slide 7
av.umsg(interpret("sc7"));
av.step();
// Slide 8
av.umsg(interpret("sc8"), {preserve: true});
arr1 = av.ds.array(["Key1", "Key2", "Key3"],
{left: leftAlign + 118, top: topAlign - 2, indexed: false});
lineInput1 = av.g.line(leftAlign + 273, topAlign + 30, leftAlign + 380, topAlign + 30);
av.step();
//Slide 9
av.umsg(interpret("sc9"), {preserve: true});
arr2 = av.ds.array(["Key1", "Key2", "Key3", "Key4"],
{left: leftAlign + 105, top: topAlign + 73, indexed: false});
lineInput2 = av.g.line(leftAlign + 310, topAlign + 105, leftAlign + 380, topAlign + 105);
av.step();
//Slide 10
av.umsg(interpret("sc10"), {preserve: true});
arr3 = av.ds.array(["Key1", "Key2", "Key3", "Key4", "key5"],
{left: leftAlign + 103, top: topAlign + 148, indexed: false});
lineInput3 = av.g.line(leftAlign + 360, topAlign + 180, leftAlign + 380, topAlign + 180);
av.step();
//Slide 11
av.umsg(interpret("sc11"));
arr1.highlight();
arr2.highlight();
arr3.highlight();
av.step();
av.recorded();
});
|
var constraints;
var imageCapture;
var mediaStream;
var takePhotoButton = document.querySelector('button#takePhoto');
var canvas = document.querySelector('canvas');
var img = document.querySelector('img');
var video = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
takePhotoButton.onclick = takePhoto;
videoSelect.onchange = getStream;
// Get a list of available media input (and output) devices
// then get a MediaStream for the currently selected input device
navigator.mediaDevices.getUserMedia()
.then(getStream)
.catch(error => {
console.log('enumerateDevices() error: ', error);
})
// Get a video stream from the currently selected camera source.
function getStream() {
if (mediaStream) {
mediaStream.getTracks().forEach(track => {
track.stop();
});
}
var videoSource = videoSelect.value;
constraints = {
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints)
.then(stream)
.catch(error => {
console.log('getUserMedia error: ', error);
});
}
// Display the stream from the currently selected camera source, and then
// create an ImageCapture object, using the video from the stream.
function gotStream(stream) {
console.log('getUserMedia() got stream: ', stream);
mediaStream = stream;
video.srcObject = stream;
video.classList.remove('hidden');
imageCapture = new ImageCapture(stream.getVideoTracks()[0]);
getCapabilities();
}
// Get the PhotoCapabilities for the currently selected camera source.
function getCapabilities() {
imageCapture.getPhotoCapabilities().then(function(capabilities) {
console.log('Camera capabilities:', capabilities);
if (capabilities.zoom.max > 0) {
zoomInput.min = capabilities.zoom.min;
zoomInput.max = capabilities.zoom.max;
zoomInput.value = capabilities.zoom.current;
zoomInput.classList.remove('hidden');
}
}).catch(function(error) {
console.log('getCapabilities() error: ', error);
});
}
// Get a Blob from the currently selected camera source and
// display this with an img element.
function takePhoto() {
imageCapture.takePhoto().then(function(blob) {
console.log('Took photo:', blob);
img.classList.remove('hidden');
img.src = URL.createObjectURL(blob);
}).catch(function(error) {
console.log('takePhoto() error: ', error);
});
} |
var assert = require('assert');
var spaceit = require('../support/simple_spaceit');
var simple_m = require('../support/simple_module');
// EXERCISE: implement the following module, using the previous two
var combo = require('../impl/simple_combo');
//// Test module simple_spaceit
assert.strictEqual(spaceit('hello'), 'h e l l o');
assert.strictEqual(spaceit('x'), 'x');
//// Test module simple_module
assert.strictEqual(simple_m.reverse('hello'), 'olleh');
//// Test module simple_combo
// reverseSpace() combines the above two functions
assert.strictEqual(combo.reverseSpace('hello'), 'o l l e h');
|
import express from 'express';
import cors from 'cors';
import api from './src';
import * as config from './env/default/app-config.json';
const app = express();
const { port, basePath } = config.api;
app.use(express.json());
// Configure cors
app.use(cors());
// Default route
app.use(basePath, api);
// Start API
app.listen(port, () => {
console.log(`API listening on port ${port}`);
});
|
// Code solution part 1
// declare PizzaSingle class
class PizzaSingle {
constructor () {
this.posX = 0
this.posY = 0
this.positionTracker = ['posX 0 posY 0'] // always deliver to starting house
}
moveOnce (direction) {
if (direction === '^') {
this.posY += 1
} else if (direction === 'v') {
this.posY -= 1
} else if (direction === '>') {
this.posX += 1
} else if (direction === '<') {
this.posX -= 1
}
if (!this.positionTracker.includes(`posX ${this.posX} posY ${this.posY}`)) { // check if house has been visited
this.positionTracker.push(`posX ${this.posX} posY ${this.posY}`) // if not, push visited house to positionTracker array
}
}
processMove (moveString) {
const moveArray = moveString.split('')
moveArray.forEach(element => { // iterate through string array
this.moveOnce(element)
})
return this.positionTracker.length // total houses visited is the length of the positionTracker array
}
}
// Part 2
// extend the class declared above
class PizzaSquad extends PizzaSingle {
constructor () {
super()
this.onePosX = 0 // declare positions for both delivery people
this.onePosY = 0 //
this.twoPosX = 0 //
this.twoPosY = 0 //
this.turnCounter = 1 // declare a turn counter
}
// alternate between turns, moving positions for each respective delivery person
// uses similar logic to above, taking into account whose turn it is
processSquadSingleMove (direction) {
if (this.turnCounter === 1) {
if (direction === '^') {
this.onePosY += 1
} else if (direction === 'v') {
this.onePosY -= 1
} else if (direction === '>') {
this.onePosX += 1
} else if (direction === '<') {
this.onePosX -= 1
}
if (!this.positionTracker.includes(`posX ${this.onePosX} posY ${this.onePosY}`)) {
this.positionTracker.push(`posX ${this.onePosX} posY ${this.onePosY}`)
}
this.turnCounter = 2
} else {
if (direction === '^') {
this.twoPosY += 1
} else if (direction === 'v') {
this.twoPosY -= 1
} else if (direction === '>') {
this.twoPosX += 1
} else if (direction === '<') {
this.twoPosX -= 1
}
if (!this.positionTracker.includes(`posX ${this.twoPosX} posY ${this.twoPosY}`)) {
this.positionTracker.push(`posX ${this.twoPosX} posY ${this.twoPosY}`)
}
this.turnCounter = 1
}
}
processSquadMove (moveString) {
const moveArray = moveString.split('')
moveArray.forEach(element => {
this.processSquadSingleMove(element)
})
return this.positionTracker.length
}
}
module.exports = {
PizzaSquad,
PizzaSingle
}
|
import Joi from 'joi';
import Country from './countries.model';
import logger from '../utils/logger';
// GET -> /countries
export function getCountries(req, res) {
Country.find()
.populate('leagues')
.exec()
.then(countries => {
if (countries) {
logger.info('All countries have been got');
res.status(200).json({ data: { countries } });
} else {
logger.error('All countries not found');
res.status(404).json({ message: 'Not found' });
}
})
.catch(error => {
logger.error(error.message);
res.status(404).json({ message: 'Not found' });
});
}
// GET -> /countries/:id
export function getCountry(req, res) {
const { id } = req.params;
Country.findOne({ _id: id })
.populate('leagues')
.exec()
.then(country => {
if (country) {
logger.info('A country has been got');
res.status(200).json({ data: { country } });
} else {
logger.error('A country not found');
res.status(404).json({ message: 'Not found' });
}
})
.catch(error => {
logger.error(error.message);
res.status(404).json({ message: 'Not found' });
});
}
// POST -> /countries
export function addCountry(req, res) {
const result = validateCountry(req.body);
if (result.error) {
logger.error(result.error.details[0].message);
res.status(404).json({ message: 'Wrong parameters' });
return;
}
const { name, leagues } = result.value;
new Country({
name,
leagues
})
.save()
.then(() => {
logger.info('A country has been created');
res.status(201).json({ message: 'A country has been created' });
})
.catch(error => {
logger.error(error.message);
res.status(404).json({ message: 'Not found' });
});
}
// PUT -> /countries/:id
export function updateCountry(req, res) {
const { id } = req.params;
const result = validateCountry(req.body);
if (result.error) {
logger.error(result.error.details[0].message);
res.status(404).json({ message: 'Wrong parameters' });
return;
}
const { name } = result.value;
Country.findOneAndUpdate({ _id: id }, { name: name })
.then(() => {
logger.info('A country has been updated');
res.status(200).json({ message: 'A country has been updated' });
})
.catch(error => {
logger.error(error.message);
res.status(404).json({ message: 'Not found' });
});
}
// DELETE -> /countries/:id
export function removeCountry(req, res) {
const { id } = req.params;
Country.findOneAndRemove({ _id: id })
.then(() => {
logger.info('A country has been removed');
res.status(200).json({ message: 'A country has been removed' });
})
.catch(error => {
logger.error(error.message);
res.status(404).json({ message: 'Not found' });
});
}
function validateCountry(country) {
const countrySchema = {
name: Joi.string()
.min(3)
.required(),
leagues: Joi.array().items(Joi.number())
};
return Joi.validate(country, countrySchema);
}
|
function solution(N, users) {
let probArr = [];
let devider = users.length;
let answer = [];
// checking the probability
for(let i = 0; i < N; i++) {
if (!users.includes(i+1)) { // first time element and not available in probArr
probArr.push({
stage : i + 1,
probability : 0
})
} else {
count = 0;
// calculate the probability
users.forEach(item => (item === i+1) ? count += 1 : count += 0);
probArr.push({
stage : i + 1,
probability : (count/devider).toFixed(3)
});
devider -= count;
}
}
// sort decending
probArr.sort(function(a, b) {return b.probability - a.probability})
// update the answer
probArr.forEach(item => answer.push(item.stage))
return answer;
}
// let j = solution(5, [2,1,2,6,2,4,3,3]);
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EspecialidadesSchema = Schema({
codigo: String,
nombre: String,
ingrediente: String,
precio: String,
detalle: String,
foto: String
});
module.exports = mongoose.model("Especialidades", EspecialidadesSchema); |
import fs from 'fs'
const makeFriendlyName = (name) => {
return name.replace(/[^a-z0-9]/gi, '')
}
const spreadProps = (element) => {
return element.replace('>', ' {...props}>')
}
const write = (outputDir, svg, name) => {
const friendlyName = makeFriendlyName(name)
const filePath = `${outputDir}/${friendlyName}.js`
const svgWithSpreadProps = spreadProps(svg)
const template =
`/* eslint-disable */
import React from 'react'
const ${friendlyName} = (props) =>
${svgWithSpreadProps}
export default ${friendlyName}
`
console.log(`${name}.svg -> ${friendlyName}.js`)
if (fs.existsSync(filePath)) {
// We generated a non-unique name. :(
throw new Error('That dog won\'t hunt.')
} else {
fs.writeFileSync(filePath, template)
}
}
export default write
|
import React, { Component } from 'react';
class Form extends Component {
render() {
return (
<div className = "countryForm">
<form onSubmit = { this.props.getSongs }>
<select name = "country">
<option value="india">India</option>
<option value="canada">Canada</option>
<option value="france">France</option>
<option value="china">China</option>
<option value="greece">Greece</option>
<option value="japan">Japan</option>
</select>
<button>Search</button>
</form>
</div>
)
}
}
export default Form;
|
'use strict';
function el(tagName, attributes, children) {
const element = document
.createElement(tagName);
if (typeof attributes === 'object') {
Object.keys(attributes).forEach(i => element
.setAttribute(i, attributes[i]));
}
if (typeof children === 'string') {
element.textContent = children;
} else if (children instanceof Array) {
children.forEach(child => element
.appendChild(child));
}
return element;
}
const btnSeatMap = document.getElementById('btnSeatMap');
const acSelect = document.getElementById('acSelect');
acSelect.addEventListener('change', function(event) {
let id = event.currentTarget.value;
fetch(`https://neto-api.herokuapp.com/plane/${id}`)
.then((res) => res.json())
.then((data) => btnSeatMap.addEventListener('click', function() {
el('div', {class: 'row seating-row text-center'}, [
el('div', {class: 'col-xs-1 row-number'},
el('h2', {class: ''}, 1))
el('div', {class: 'col-xs-5'}, [
el('div', {class: 'col-xs-4 seat'},
el('span', {class: 'seat-label'}, 'A'))
])])
}))
})
|
// INSTANTIATION
var APP = require("/core");
var args = arguments[0] || {};
// ADDITIONS
// FUNCTIONS
function loadData(){
if(args._type == 3){
//Ti.API.info(JSON.stringify(args._data));
APP.openCloseOptions();
APP.currentController.getMessages({lat:0,lon:0,faname:args._data.ogGroup,pkorgGroups:args._data.pkorgGroups,ogfAdmin:args._data.ogfAdmin});
}else if(args._type == 4){
APP.openCloseOptions();
APP.currentController.getMessages({lat:0,lon:0,faname:args._data.ogGroup,pkorgGroups:args._data.pkorgGroups,ogfAdmin:args._data.ogfAdmin});
}
}
function editAddress(){
var notificationDialog = Ti.UI.createAlertDialog({
title : 'Remove Group',
message : 'Do you want to remove this group?',
buttonNames : ['Yes', 'No']
});
notificationDialog.addEventListener('click', function(e) {
if(e.index === 0) {
var dataTemp = {
url : L("ws_groupremove"),
type : 'GET',
format : 'JSON',
data : {
atoken : APP.getToken({openLogin:false}),
pkorggroups : args._data.pkorgGroups
}
};
APP.http.request(dataTemp,function(_result){
if(_result._result == 1){
if(_result._data.errorcode == 0){
APP.optionbar.changeView(5);
alert("You have removed a group.");
}else{
alert(_result._data.message);
}
}else{
alert("Internet connection error, please try again.");
}
});
}
});
notificationDialog.show();
}
// CODE
$.groupTitle.text = args._data.ogGroup; |
// src/DisplayMapClass.js
import * as React from 'react';
import{Link} from 'react-router-dom';
class DisplayMapClass extends React.Component {
mapRef = React.createRef();
state = {
map: null
};
componentDidMount() {
const H = window.H;
const platform = new H.service.Platform({
apikey: "gQ2xoeeDN1C0vXBT6A8Us08CLQj1wsQMAgfQeqlz1oY"
});
const defaultLayers = platform.createDefaultLayers();
const map = new H.Map(
this.mapRef.current,
defaultLayers.vector.normal.map, {
center: {
lat: -33.4282564,
lng: -70.6194612,
startingPoint: null,
endingPoint: null,
},
zoom: 18,
pixelRatio: window.devicePixelRatio || 1
}
);
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
// This variable is unused and is present for explanatory purposes
new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components to allow the user to interact with them
// This variable is unused
H.ui.UI.createDefault(map, defaultLayers);
this.setState({ map });
}
componentWillUnmount() {
this.state.map.dispose();
}
render() {
return (
<div className="container-fluid square">
<div className="row">
<nav className="navbar navbar-light bg-light">
<form className="form-inline d-flex justify-content-between">
<Link to= "/Home">
<i className="arrow fas fa-arrow-left"></i>
</Link>
<p className="col-2 pt-3 weel">Farmacias</p>
<input className="form-control col-6 ml-4" type="search" placeholder="Buscar" aria-label="Search"/>
<button className="btn btn-outline col-2" type="submit"><i className="fas fa-search"></i></button>
</form>
</nav>
</div>
<div ref = { this.mapRef }
style = { { height: "700px" }}/>
<div className="row d-flex justify-content-around mt-3 mb-2 menu pt-3 pr-4">
<Link to="/Home">
<div className="icons">
<i className="icono_menu fas fa-map-marker-alt"></i>
<p className="titulo_menu">Explorar</p>
</div>
</Link>
<div className="icons">
<i className="icono_menu fas fa-star"></i>
<p className="titulo_menu">Favoritos</p>
</div>
<Link to="/Ajustes">
<div className="icons">
<i className="icono_menu fas fa-cog"></i>
<p className="titulo_menu">Ajustes</p>
</div>
</Link>
</div>
</div>
)
}
}
export default DisplayMapClass; |
/*global PIFRAMES */
/* Written by Mostafa Mohammed and Cliff Shaffer */
$(document).ready(function() {
"use strict";
var av_name = "LanguagesFS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("A :term:`language` is simply a collection (that is, a set) of strings. More precisely, a language is a subset of the strings that can be generated from some :term:`alphabet`. A fundamental thing to be able to do with a string is to determine whether or not it is part of a given language. We will talk later about ways to formally define a particular language. But first we need some notation to help express ourselves.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("alpha"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("char"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("strings"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("stringnotset"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("badchar"));
av.step();
// Frame 7
av.umsg(Frames.addQuestion("examplelang"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("notset"));
av.step();
// Frame 9
av.umsg(Frames.addQuestion("isset"));
av.step();
// Frame 10
av.umsg("For $\\Sigma$={$a,b,c\\}$, $L=\\{ab,ac,cabb\\}$ is an example of a <b>finite</b> language, because there are only three strings in the language.");
av.step();
// Frame 11
av.umsg(Frames.addQuestion("infinite"));
av.step();
// Frame 12
av.umsg("For $\\Sigma$={$0,1,2,3,4,5,6,7,8, 9\\}$, $L=\\{all\\ even\\ numbers\\}$ is a somewhat informal way to describe a language.");
av.step();
// Frame 13
av.umsg(Frames.addQuestion("empty"));
av.step();
// Frame 14
av.umsg(Frames.addQuestion("emptysymbol"));
av.step();
// Frame 15
av.umsg(Frames.addQuestion("stringname"));
av.step();
// Frame 16
av.umsg(Frames.addQuestion("charname"));
av.step();
// Frame 17
av.umsg(Frames.addQuestion("size"));
av.step();
// Frame 18
av.umsg(Frames.addQuestion("concat"));
av.step();
// Frame 19
av.umsg(Frames.addQuestion("nocirc"));
av.step();
// Frame 20
av.umsg("Sometimes we want to talk about the string that has no characters. If we literally wrote a string with no characters, it would be hard for you to understand what we wrote! So we have a special symbol to use for the empty string: $\\lambda$. This is the Greek letter <b>lambda</b>.");
av.step();
// Frame 21
av.umsg(Frames.addQuestion("emptystring"));
av.step();
// Frame 22
av.umsg("Note the difference. $L_1 = \\{\\}$ is the language with no strings in it. But $L_2 = \\{ \\lambda \\}$ is the language that has just one string in it: the empty string. The empty string is a perfectly fine string, and a language with the empty string is different from a language with no strings at all.");
av.step();
// Frame 23
av.umsg(Frames.addQuestion("selfconcat"));
av.step();
// Frame 24
av.umsg(Frames.addQuestion("identity"));
av.step();
// Frame 25
av.umsg(Frames.addQuestion("reverse"));
av.step();
// Frame 26
av.umsg(Frames.addQuestion("revlength"));
av.step();
// Frame 27
av.umsg(Frames.addQuestion("closure"));
av.step();
// Frame 28
av.umsg(Frames.addQuestion("closurex"));
av.step();
// Frame 29
av.umsg(Frames.addQuestion("plus"));
av.step();
// Frame 30
av.umsg(Frames.addQuestion("union"));
av.step();
// Frame 31
av.umsg(Frames.addQuestion("intersect"));
av.step();
// Frame 32
av.umsg(Frames.addQuestion("comp"));
av.step();
// Frame 33
av.umsg(Frames.addQuestion("concatsets"));
av.step();
// Frame 34
av.umsg(Frames.addQuestion("selfconset"));
av.step();
// Frame 35
av.umsg(Frames.addQuestion("setconx"));
av.step();
// Frame 36
av.umsg(Frames.addQuestion("setcon3"));
av.step();
// Frame 37
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
var http = require('http');
var msg = [
'Hello',
'Hi',
'Good bye',
]
http.createServer(function(req, res){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><head><title>simple_get</title></head>');
res.write('<body>');
for(var idx in msg){
res.write('\n<h1>' + msg[idx] + '</h1>');
}
res.end('\n</body></html>');
}).listen(8080); |
const AWS = require('aws-sdk')
const fs = require('fs')
const ini = require('ini')
function assumeRole (clb) {
// compatibility with aws-cli
let awsProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE
if (!awsProfile) return clb()
try {
let configIni = ini.parse(fs.readFileSync(
`${process.env.HOME}/.aws/config`,
'utf-8'
))
let awsProfileConfig = configIni[`profile ${awsProfile}`]
if (awsProfileConfig.source_profile) {
try {
let credentialsIni = ini.parse(fs.readFileSync(
`${process.env.HOME}/.aws/credentials`,
'utf-8'
))
if (credentialsIni && credentialsIni[awsProfileConfig.source_profile] && credentialsIni[awsProfileConfig.source_profile].aws_access_key_id) {
AWS.config.update({
accessKeyId: credentialsIni[awsProfileConfig.source_profile].aws_access_key_id,
secretAccessKey: credentialsIni[awsProfileConfig.source_profile].aws_secret_access_key
})
}
} catch (e) {}
}
var sts = new AWS.STS()
sts.assumeRole({
RoleArn: awsProfileConfig.role_arn,
RoleSessionName: awsProfile
}, (err, data) => {
if (err) {
console.error('Cannot assume role')
console.error(err.stack)
return process.exit(1)
}
AWS.config.update({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
})
clb()
})
} catch (_err) {
clb(_err)
}
}
module.exports = assumeRole
assumeRole.sync = function () {
const deasync = require('deasync')
const assumeRoleSync = deasync(assumeRole)
assumeRoleSync()
}
if (!require.main) {
assumeRole.sync()
}
|
({
selectCode: function(component, event, helper) {
/* Event to pass the selected zip code to customLookUpCmp*/
var getselectedcode = component.get("v.zipcode");
var compEvent = component.getEvent("zipcodeEvt");
compEvent.setParams({
"codeByEvent": getselectedcode
});
compEvent.fire();
},
}) |
/**
*
* ProductsList
*
* Products.List page content scripts. Initialized from scripts.js file.
*
*
*/
class ProductsList {
constructor() {
// Initialization of the page plugins
if (typeof Checkall !== 'undefined') {
this._initCheckAll();
} else {
console.error('[CS] Checkall is undefined.');
}
}
// Check all button initialization
_initCheckAll() {
new Checkall(document.querySelector('.check-all-container-checkbox-click .btn-custom-control'), {clickSelector: '.form-check'});
}
}
|
app.controller("CategoryController", [
'$scope',
'$location',
'$route',
'$routeParams',
'Journey',
'Category',
'Note',
'Snippet',
'UnassignedSnippet',
'Owner',
'$sce',
function($scope, $location, $route, $routeParams, Journey, Category, Note, Snippet, UnassignedSnippet, Owner, $sce ) {
var regex = /users\/(\d+)#/;
var user_id = regex.exec($location.absUrl());
$scope.fullPath = $location.absUrl();
var owner = Owner.check( {id: user_id[1]} );
owner.$promise.then( function(response) {
$scope.isOwner = response.isOwner;
});
$scope.journey = Journey.get({id: $routeParams.journey_id});
$scope.category = Category.get({journey_id: $routeParams.journey_id, id: $routeParams.id});
$scope.notes = Note.index( { journey_id: $routeParams.journey_id, category_id: $routeParams.id } );
UnassignedSnippet.index({user_id: user_id[1]}).$promise.then( function(response) {
$scope.unassignedSnippets = response;
});
$scope.notes.$promise.then( function() {
angular.forEach($scope.notes,function(note,index){
$scope.notes[index].snippets = Snippet.index( { journey_id: $routeParams.journey_id, category_id: $routeParams.id, note_id: note.id } );
});
});
$scope.showForm = false;
$scope.visibleSnipForm = [];
$scope.editNoteFlag = [];
var menuOpen = false;
var rightMenuOpen = false;
$scope.displayForm = function() {
hideForm();
function hideForm(){
$(".note-list").css("animation", "menuSlideUp ease-out .3s");
$(".cat-new-button").css("animation", "menuSlideUp ease-out .3s");
$(".note-list").css("animation-fill-mode", "forwards");
$(".cat-new-button").css("animation-fill-mode", "forwards");
}
$(".note-list").css("height", "0");
$(".cat-new-button").css("display", "none");
$scope.showForm = true;
$scope.note = {};
};
$scope.toggleMenu = function(noteId) {
var noteAsString = "#context" + noteId.toString();
if (menuOpen === false) {
$(noteAsString).css("animation", "toggle_context_menu_open ease-in-out .3s");
$(noteAsString).css("animation-fill-mode", "forwards");
$(noteAsString).css("box-shadow", "-5px 0px 16px 6px rgba(0, 0, 0, .1)");
menuOpen = true;
}else {
$(noteAsString).css("animation", "toggle_context_menu_closed ease-in-out .3s");
$(noteAsString).css("animation-fill-mode", "forwards");
$(noteAsString).css("box-shadow", "none");
menuOpen = false;
}
};
$scope.slideLeft = function(className) {
};
$scope.createNote = function() {
Note.create( {journey_id: $scope.journey.id, category_id: $scope.category.id}, $scope.note )
.$promise.then( function(response) {
//Add note title to sidebar
// liTitle = "<li id=id" +response.id+ ">" +response.title+ "</li>";
// $(".note-list").append(liTitle)
// $scope.showForm = false;
//Add note to bottom of notes div
$route.reload();
});
};
$scope.deleteNote = function(note) {
var msg = "Are you sure you want to delete this Note and all included snippets?";
// $scope.toggleMenu(note.id);
if (confirm(msg)) {
Note.destroy( {journey_id: $scope.journey.id}, note).$promise.then( function() {
$(".note-list").find("#id" +note.id).remove();
$(".notes").find("#note-" +note.id).remove();
} );
}
};
$scope.showNoteForm = function(note) {
$scope.editNoteFlag[note.id] = true;
$scope.editingNote = note;
};
$scope.hideNoteForm = function(note) {
$scope.editNoteFlag[note.id] = false;
}
$scope.editNote = function(note) {
Note.update( {journey_id: $scope.journey.id, category_id: $scope.category.id, note_id: note.id}, $scope.editingNote).$promise.then( function() {
$scope.editNoteFlag[note.id] = false;
} );
};
$scope.togglePublic = function(note) {
$scope.toggleMenu(note.id);
if (note.public_bool) { note.public_bool = false }
else { note.public_bool = true }
Note.update( {journey_id: $scope.journey.id, category_id: $scope.category.id}, note);
}
$scope.showSnipForm = function(note) {
$scope.toggleMenu(note.id);
$scope.visibleSnipForm[note.id] = true;
$scope.snippet = {};
};
$scope.hideSnipForm = function(note) {
$scope.visibleSnipForm[note.id] = false;
};
$scope.saveSnip = function(note) {
Snippet.create( {journey_id: $scope.journey.id, category_id: $scope.category.id, note_id: note.id}, $scope.snippet )
.$promise.then( function(response) {
//add the snips in here with DOM manipulation
$route.reload();
});
};
$scope.saveSnipEdit = function(note, snippet) {
Snippet.update( {journey_id: $scope.journey.id, category_id: $scope.category.id, note_id: note.id, snippet_id: snippet.id}, snippet );
};
$scope.deleteSnippet = function(snippet) {
var msg = "Are you sure you want to delete this snippet?";
if (confirm(msg)) {
Snippet.destroy( {journey_id: $scope.journey.id, category_id: $scope.category.id}, snippet).$promise.then( function() {
$(".show-snippets-container").find("#snip" + snippet.id).remove();
});
}
};
$scope.addToNote = function(note, snippet) {
snippet.note_id = note.id;
Snippet.update( {journey_id: $scope.journey.id, category_id: $scope.category.id, note_id: note.id, snippet_id: snippet.id}, snippet )
.$promise.then( function(response){
// console.log("We give a shit. Improve on this.");
$route.reload();
});
};
$scope.display = function(item)
{
return ($scope.isOwner || item.public_bool);
};
$scope.validUrl = function(snippet) {
if (snippet.cached_url) {
return true;
}
else {
return false;
}
};
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
};
}
]);
|
'use strict';
/* jshint node: true */
/* globals browser, describe, it, beforeAll, EC, expect, protractor, xit, afterAll */
var dpage = require('../pages/personalDetailsPage.js');
var homeP = require('../../../common/pages/homePage.js');
afterAll(function(done) {
process.nextTick(done);
});
describe('UIDS-718 Confirm Personal Details Page ----- ', function() {
browser.ignoreSynchronization = false;
it(browser.tc_desc('UIDS-1367 Story TC1 (1) check Menu Link is clickable on confirm details page'), function() {
if ( !browser.mobile ) {
browser.wait(EC.visibilityOf(homeP.openfooterLink), 12000, 'Menu link is not displayed');
expect(homeP.openfooterLink.isDisplayed()).toBeTruthy();
browser.indirectClick(homeP.openfooterLink);
browser.sleep(1000);
}
else {
console.log('This functionality is not for mobile devices');
}
});
it(browser.tc_desc('UIDS-1367 Story TC2 (1) check Menu Items are available on confirm details page'), function() {
if ( !browser.mobile ) {
expect(homeP.footer.header.isDisplayed()).toBeTruthy();
expect(homeP.footer.aboutLink.isDisplayed()).toBeTruthy();
// expect(homeP.footer.fagsLink.isDisplayed()).toBeTruthy();
// expect(homeP.footer.supportLink.isDisplayed()).toBeTruthy();
expect(homeP.footer.privacyLink.isDisplayed()).toBeTruthy();
// expect(homeP.footer.securityLink.isDisplayed()).toBeTruthy();
// expect(homeP.footer.accessibilityLink.isDisplayed()).toBeTruthy();
expect(homeP.footer.language.isDisplayed()).toBeTruthy();
expect(homeP.footer.login.isDisplayed()).toBeTruthy();
}
else{
console.log('This functionality is not for mobile devices');
}
});
it(browser.tc_desc('UIDS-1367 Story TC3 (1) check Menu can be closed on confirm details page'), function() {
if ( !browser.mobile ) {
browser.wait(EC.visibilityOf(homeP.closefooterLink), 12000, 'Close menu button is not displayed');
expect(homeP.closefooterLink.isDisplayed()).toBeTruthy();
homeP.closefooterLink.click();
//browser.indirectClick(homeP.closefooterLink);
}
else
{
console.log('This functionality is not for mobile devices');
}
});
it(browser.tc_desc('UIDS-502 TC 4b (1) check header, description, copyright and confirm button text on name page'), function() {
if ( !browser.mobile ) {
dpage.confirmation.confirmTitleWeb.getText().then(function(text)
{
expect(text.toUpperCase()).toBe(browser.params.user.authentication.language.confirm.stmtConfirmYourDetails.toUpperCase());
});
expect(homeP.headerLabelOne.getText()).toEqual(browser.params.user.authentication.language.header.universalId);
}
else {
dpage.confirmation.confirmTitleMob.getText().then(function(text)
{
expect((text.trim()).toUpperCase()).toBe(browser.params.user.authentication.language.confirm.stmtConfirmYourDetails.toUpperCase());
});
}
expect(dpage.confirmation.ConfirmSubTitle.getText()).toEqual(browser.params.user.authentication.language.confirm.stmtInstruction);
dpage.confirmation.submit.getText().then(function(text)
{
expect((text.trim()).toUpperCase()).toBe(browser.params.user.authentication.language.confirm.btnConfirm.toUpperCase());
});
if (browser.params.langOption === 'es') {
homeP.footer.copyrightMsgOne.getText().then(function (text) {
var abc = text.toString().replace("\n", " ");
expect(abc).toEqual("Copyright Ⓒ 2017 Zentry Proprietary and Confidential _Español");
});
}
else if (browser.params.langOption === 'ja') {
homeP.footer.copyrightMsgOne.getText().then(function (text) {
var abc = text.toString().replace("\n", " ");
expect(abc).toEqual("著作権 Ⓒ 2017年 Zentry独自および機密");
});
}
else if (browser.params.langOption === 'en') {
homeP.footer.copyrightMsgOne.getText().then(function (text) {
var abc = text.toString().replace("\n", " ");
expect(abc).toEqual("Copyright Ⓒ 2017 Zentry Proprietary and Confidential");
});
}
});
it(browser.tc_desc('UIDS-1488 TC1 Verify Zentry Logo on confirm page'), function() {
//expect(homeP.footer.copyrightMsgOne.isDisplayed()).toBeTruthy();
if ( !browser.mobile ) {
expect(homeP.footer.zentryLogo.isDisplayed()).toBeTruthy();
}
else {
console.log("This functionality is not for mobile devices");
}
});
it(browser.tc_desc('UIDS-895 TC1 (1) Check presence of Help Button on confirm details page'), function() {
browser.wait(EC.visibilityOf(dpage.confirmation.helpLink), 120000, 'Help Link is not displayed');
if ( browser.deviceName === 'Edge'){
dpage.confirmation.helpLink.getText().then(function(text)
{
expect( text.trim().toUpperCase()).toBe(browser.params.user.authentication.language.mobnav.help);
});
}
else {
expect(dpage.confirmation.helpLink.getText()).toEqual(browser.params.user.authentication.language.mobnav.help);
}
});
it(browser.tc_desc('UIDS-895 TC2 (1) Click on help button on confirm details page(2) Check the content'), function() {
dpage.confirmation.helpLink.click();
browser.wait(EC.visibilityOf(dpage.confirmation.helpLinkContent), 120000, 'help content is not displayed');
expect(dpage.confirmation.helpLinkContent.isDisplayed()).toBeTruthy();
});
it(browser.tc_desc('UIDS-895 TC3 (1) Verify help menu is closed on confirm details page(2) clicking on close button'), function() {
dpage.confirmation.helpLinkClose.click();
expect(dpage.confirmation.helpLinkContent.isPresent()).toEqual(false);
});
/* Commenting out this code as SSN, DOB page is out of scope in MVP and this code used to redirect to SSN/DOB page clicking on back button*/
// it(browser.tc_desc('UIDS-1677 TC 4a (1) Click on back button (2) Verify information added in personal information page is retained'), function() {
// browser.wait(EC.visibilityOf(dpage.confirmation.backbtn), 120000, 'Back button on confirmation page is not displayed');
// dpage.confirmation.backbtn.click();
// browser.wait(EC.visibilityOf(dpage.personalInfo.ssn), 120000, 'SSN field is not visible');
// expect(dpage.personalInfo.ssn.getAttribute("value")).toBe('123-45-6789');
// expect(dpage.personalInfo.cob.getAttribute("value")).toBe(browser.params.user.personalInfo.cob);
// expect(dpage.personalInfo.dob.getAttribute("value")).toBe('01-01-1981');
//
// });
// it(browser.tc_desc('UIDS-1677 TC 4b (1) Click on continue button (2) Verify user is redirected to confirmation page'), function() {
//
// dpage.personalInfo.continueBtn.click();
// browser.wait(EC.visibilityOf(dpage.confirmation.ConfirmSubTitle), 120000, 'confirm subtext is missing, or the App is down!');
// expect(dpage.confirmation.ConfirmSubTitle.isDisplayed()).toBeTruthy();
//
// });
// Commenting out as clicking on back button is having issues in retrieving the information//
// it(browser.tc_desc('UIDS-1677 TC 4a (1) Click on back button (2) Verify information added in address page is retained'), function() {
// browser.wait(EC.visibilityOf(dpage.confirmation.backbtn), 120000, 'Back button on confirmation page is not displayed');
// dpage.confirmation.backbtn.click();
// browser.wait(EC.visibilityOf(dpage.address.country), 120000, 'Country field is not visible');
// expect(dpage.address.country.getAttribute("value")).toBe('USA');
// expect(dpage.address.street.getAttribute("value")).toBe('151 W 34th St');
// expect(dpage.address.zipcode.getAttribute("value")).toBe('10001');
// expect(dpage.address.city.getAttribute("value")).toBe('New York');
// expect(dpage.address.state.getAttribute("value")).toBe('NY');
// expect(dpage.address.extendedAddress.getAttribute("value")).toBe('152 S 37th St');
// });
//
// it(browser.tc_desc('UIDS-1677 TC 4b (1) Click on continue button (2) Verify user is redirected to confirmation page'), function() {
//
// dpage.address.continueBtn.click();
// browser.wait(EC.visibilityOf(dpage.confirmation.ConfirmSubTitle), 120000, 'confirm subtext is missing, or the App is down!');
// expect(dpage.confirmation.ConfirmSubTitle.isDisplayed()).toBeTruthy();
//
// });
it(browser.tc_desc('UIDS-502 TC7 Verify label of name field'), function() {
expect(dpage.confirmation.nameLabel.getText()).toEqual(browser.params.user.authentication.language.confirm.stmtName);
});
it(browser.tc_desc('UIDS-502 TC24 Verify label of address field'), function() {
expect(dpage.confirmation.addressLabel.getText()).toEqual(browser.params.user.authentication.language.confirm.stmtAddress);
});
// it(browser.tc_desc('UIDS-502 TC12 Verify label of SSN field'), function() {
//
// expect(dpage.personalInfo.ssnLabel.getText()).toEqual(browser.params.user.authentication.language.confirm.stmtSocialSecurityNumber);
// });
// it(browser.tc_desc('UIDS-502 TC16 Verify label of DOB field'), function() {
//
// expect(dpage.confirmation.dobLabel.getText()).toEqual(browser.params.user.authentication.language.confirm.stmtDateofbirth);
// });
// it(browser.tc_desc('UIDS-502 TC22 Verify label of COB field'), function() {
//
// expect(dpage.personalInfo.cobLabel.getText()).toEqual(browser.params.user.authentication.language.confirm.stmCirtyOfBirth);
// });
it(browser.tc_desc('UIDS-502 TC3a Verify Edit Text of name field'), function() {
dpage.confirmation.nameEditText.getText().then(function(text)
{
expect( text.toUpperCase().trim()).toBe(browser.params.user.authentication.language.general.edit.toUpperCase());
});
});
it(browser.tc_desc('UIDS-502 TC3b Verify Edit Text of address field'), function() {
dpage.confirmation.AddressEditText.getText().then(function(text)
{
expect( text.toUpperCase().trim()).toBe(browser.params.user.authentication.language.general.edit.toUpperCase());
});
});
// it(browser.tc_desc('UIDS-502 TC3c Verify Edit Text of ssn field'), function() {
//
// dpage.confirmation.ssnEditText.getText().then(function(text)
// {
// expect( text.toUpperCase().trim()).toBe(browser.params.user.authentication.language.general.edit.toUpperCase());
// });
// });
// it(browser.tc_desc('UIDS-502 TC3d Verify Edit Text of dob field'), function() {
//
// dpage.confirmation.dobEditText.getText().then(function(text)
// {
// expect( text.toUpperCase().trim()).toBe(browser.params.user.authentication.language.general.edit.toUpperCase());
// });
// });
// it(browser.tc_desc('UIDS-502 TC3e Verify Edit Text of cob field'), function() {
//
// dpage.confirmation.cobEditText.getText().then(function(text)
// {
// expect( text.toUpperCase().trim()).toBe(browser.params.user.authentication.language.general.edit.toUpperCase());
// });
// });
it(browser.tc_desc('UIDS-502 TC3 confirm (1) Name (2) SSN (3) D.O.B'), function() {
browser.wait(EC.visibilityOf(dpage.confirmation.ConfirmSubTitle), 120000, 'confirm subtext is missing, or the App is down!');
/* Commenting below lines because of SSN, DOB page not in scope*/
// dpage.confirmation.dob.getText().then(function(text)
// {
// expect( text.replace(/-/g,"")).toBe(browser.params.user.personalInfo.dob);
// });
//
// dpage.confirmation.ssn.getText().then(function(text)
// {
// expect( text.replace(/-/g,"")).toBe(browser.params.user.personalInfo.ssn);
// });
//
// expect(dpage.confirmation.cob.getText()).toBe(browser.params.user.personalInfo.cob);
expect(dpage.confirmation.name.getText()).toEqual("Mr. FirstName Middle LastName Su");
expect(dpage.confirmation.address.getText()).toEqual('151 W 34th St'+"\n"+'152 S 37th St'+"\n"+'New York, New York 10001'+"\n"+'United States');
//dpage.confirmation.submit.click();
browser.indirectClick(dpage.confirmation.submit);
browser.waitForAngular();
});
});
|
import React from 'react';
import CssBaseline from '@material-ui/core/CssBaseline';
import { AppBar, Toolbar, IconButton, Typography } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import { useStyles } from '../static/MiniDrawerStyles';
import clsx from 'clsx';
function AppBarComponent() {
const { appBar, appBarShift, menuButton, hide } = useStyles();
const [open, setOpen] = React.useState(false);
function handleDrawerOpen() {
setOpen(true);
}
return (
<React.Fragment>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(appBar, {
[appBarShift]: open,
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(menuButton, {
[hide]: open,
})}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap>
Cogent Health
</Typography>
</Toolbar>
</AppBar>
</React.Fragment>
);
}
export default AppBarComponent; |
import React from "react";
import styled from "styled-components";
import { CSSTransition } from "react-transition-group";
import { StyledButton } from "./ButtonStyles";
import { ref, storageRef } from "../../Firebase/FBConfig";
import formCloseBtn from "../../assets/form-close.svg";
import uuidv4 from "uuid/v4";
const StyledInlineFormBtn = styled(StyledButton)`
padding: 0;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
width: 35%;
@media (min-width: 768px) {
max-height: 52px;
padding: 0;
}
`;
const CloseIcon = styled.img`
position: absolute;
height: 35px;
width: 35px;
top: 15px;
right: 15px;
z-index: 100;
cursor: pointer;
`;
const FormValidation = styled.h3`
position: absolute;
height: 100%;
width: 100%;
top: 0;
right: 0;
z-index: 99;
color: #fff;
background: rgba(237, 169, 136, 1);
display: ${props => (props.formSubmitted ? "flex" : "none")};
align-items: center;
justify-content: center;
font-weight: 700;
text-align: center;
font-size: 20px;
@media (min-width: 768px) {
font-size: 30px;
}
`;
const StyledInlineForm = styled.form`
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
transform: translateY(0px);
display: ${props => (props.display ? props.display : "flex")};
grid-gap: 15px;
grid-template-columns: 1fr;
grid-gap: 15px;
background-color: ${props => (props.color ? props.color : "#a3d8ce")};
flex-direction: column;
padding-right: 8%;
flex-wrap: nowrap;
height: 100vh;
padding-top: ${props => (props.formHeader ? "70px;" : "30px")};
padding-left: 8%;
width: 100%;
margin-top: ${props => (props.projectForm ? "100px" : "")};
z-index: 501;
h1 {
font-size: 35px;
font-family: theinhardt_medium;
}
.spacer {
height: 40px;
}
@media (min-width: 768px) {
grid-gap: 30px;
grid-template-columns: 1fr 1fr;
height: 600;
height: ${props => (props.size ? props.size : "550px")};
z-index: 1;
flex-wrap: wrap;
padding-bottom: ${props => (props.display ? "5vh" : "0")};
grid-template-areas: ${props => (props.gridArea ? props.gridArea : "none")};
width: 100%;
position: absolute;
height: ${props => (props.sizeTablet ? props.sizeTablet : "550px")};
}
@media (min-width: 992px) {
height: ${props => (props.sizeDesktopSM ? props.sizeDesktopSM : "550px")};
}
@media (min-width: 1040px) {
height: ${props => (props.sizeDesktopMD ? props.sizeDesktopMD : "550px")};
}
@media (min-width: 992px) {
height: ${props => (props.sizeDesktopSM ? props.sizeDesktopSM : "550px")};
}
@media (min-width: 1040px) {
height: ${props => (props.sizeDesktopMD ? props.sizeDesktopMD : "550px")};
}
&.slide-enter {
animation: formslipins 0.4s ease-in;
}
&.slide-exit {
animation: formslipouts 0.5s ease-out;
}
.input-group {
display: flex;
justify-content: ${props => (props.display ? "flex-end" : "flex-start")};
margin-bottom: ${props => (props.display ? "0" : "40px")};
margin-right: ${props => (props.display ? "0" : "3vw")};
width: ${props => (props.inputWidth ? props.inputWidth : "80%")};
flex-direction: column;
&:last-of-type {
margin-bottom: 0;
button {
margin-bottom: 0;
}
}
@media (min-width: 768px) {
width: ${props => (props.gridArea ? "100%" : "40%")};
}
label {
font-family: theinhardt_regular;
font-size: 15px;
@media (min-width: 768px) {
font-size: 18px;
}
}
.orange {
color: orange;
}
input {
background: none;
height: 4vh;
}
textarea {
margin-top: 2vh;
background: none;
resize: none;
@media (max-width: 767px) {
border: none;
border-bottom: 1px solid #000;
height: 35px;
font-size: 15px;
}
@media (min-width: 768px) {
max-height: ${props =>
props.maxHeightTablet ? props.maxHeightTablet : "100%"};
}
@media (min-width: 1040px) {
max-height: ${props =>
props.maxHeightDesktop ? props.maxHeightDesktop : "100%"};
}
}
}
.input-group.name {
@media (min-width: 768px) {
grid-area: ${props => (props.gridArea ? "name" : "auto")};
}
}
.input-group.email {
@media (min-width: 768px) {
grid-area: ${props => (props.gridArea ? "email" : "auto")};
}
}
.input-group.info {
@media (min-width: 768px) {
grid-area: ${props => (props.gridArea ? "info" : "auto")};
}
}
.input-group.styledformbtn {
@media (min-width: 768px) {
grid-area: ${props => (props.gridArea ? "btn" : "auto")};
display: inline-block;
}
button {
width: auto;
}
}
p {
font-size: 1.5vw;
}
button {
color: black;
font-size: 18px;
@media (min-width: 768px) {
font-size: 20px;
padding: 8px 20px;
}
@media (min-width: 992px) {
font-size: 23px;
padding: 10px 22px;
}
@media (min-width: 1200px) {
padding: 12px 24px;
font-size: 25px;
}
}
@keyframes formslipins {
from {
transform: ${props =>
props.projectForm ? "translate(0, -700px)" : "translate(0, 500px)"};
}
to {
transform: translate(0, 0px);
}
}
@keyframes formslipouts {
from {
transform: translateY(0, 0px);
}
to {
transform: ${props =>
props.projectForm ? "translate(0, -700px)" : "translate(0, 500px)"};
}
}
@keyframes formslidesUp {
from {
transform: ${props =>
props.projectForm ? "translateY(-700px)" : "translateY(500px)"};
}
to {
transform: translateY(0px);
}
}
@keyframes formslidesDown {
from {
transform: translateY(0px);
}
to {
transform: ${props =>
props.projectForm ? "translateY(-700px)" : "translateY(500px)"};
}
}
`;
export class InlinePublicForm extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
let newState = {};
for (let i = 0; i < this.props.form.fields.length; i++) {
newState[this.props.form.fields[i].value] = "";
}
newState["message"] = "please fill out the required fields";
newState["showMessage"] = false;
if (newState) {
this.setState(newState);
}
}
componentDidUpdate(prevProps) {
if (this.props.form.fields !== prevProps.form.fields) {
let newState = {};
for (let i = 0; i < this.props.form.fields.length; i++) {
newState[this.props.form.fields[i].value] = "";
}
newState["message"] = "please fill out the required fields";
newState["showMessage"] = false;
if (newState) {
this.setState(newState);
}
}
}
handleSubmit = event => {
event.preventDefault();
let form = this.state;
form["timestamp"] = Date.now();
form["submitted"] = Date.now();
if (!this.props.projectForm) {
form["spaceName"] = this.props.currentSpace;
form["spaceUrl"] = this.props.currentUrl;
}
if (!this.checkRequiredFields()) {
let newItemRef = ref
.child(
this.props.firebasePath ? this.props.firebasePath : "requests/spaces"
)
.push();
form.key = newItemRef.key;
form.message = this.props.removeMessage ? "" : form.message;
try {
newItemRef
.update(form)
.then(() => {
this.props.deactivateForm();
this.props.activateResponse();
this.clearState();
})
.catch(e => {
console.log("Error uploading object to requests " + e);
window.alert(e);
});
} catch (err) {
console.log(err);
}
}
};
handleCustomSubmit = e => {
e.preventDefault();
if (this.props.submitArgs) {
let args = [...this.props.submitArgs, this.state];
this.props.customFormSubmission.apply(null, args);
} else {
this.props.customFormSubmission(e);
}
this.props.deactivateForm();
};
clearState = () => {
const keys = Object.keys(this.state);
for (let key in keys) {
this.setState({ [keys[key]]: "" });
}
this.setState({ showMessage: false });
};
checkRequiredFields = () => {
let fields = this.props.form.fields;
let isNotComplete = false;
for (var i = 0; i < fields.length; i++) {
if (fields[i].label.charAt(0) === "*" && !this.state[fields[i].value]) {
isNotComplete = true;
}
}
this.setState({ showMessage: isNotComplete });
return isNotComplete;
};
handleChange = event => {
// event.preventDefault();
let value = event.target.value;
let name = event.target.name;
this.setState({ [`${name}`]: value });
};
handleFile = event => {
// console.log("activeInput " + activeInput);
let storeKey = uuidv4();
const file = event.target.files[0];
if (!file) {
return;
}
const filename = event.target.files[0].name;
const profileTypeStorageRef = storageRef.child(
"requests/projectSubmissionStorage"
);
const heroImgStorageRef = profileTypeStorageRef.child(storeKey);
const fileURL = heroImgStorageRef.child(filename);
fileURL.put(file).then(() => {
heroImgStorageRef
.child(filename)
.getDownloadURL()
.then(url => this.setState({ file: url }))
.catch(function(error) {
window.alert("Error uploading the image " + error);
});
});
};
renderInputs = values => {
return values.map(value => (
<div
data-test="InlinePublicForm-inputs"
className={`input-group ${value.value}`}
key={value.label}
>
<label
className={
this.state.showMessage &&
!this.state[value.value] &&
value.label.charAt(0) === "*"
? "orange"
: ""
}
>
{value.label}
</label>
{this.determineInputType(value)}
</div>
));
};
determineInputType = value => {
switch (value.type) {
case "textarea":
return (
<textarea
data-test="InlinePublicForm-inputfield-textarea"
name={value.value}
label={value.label}
value={this.state[value.value]}
rows="6"
onChange={e => this.handleChange(e)}
/>
);
case "email":
return (
<input
data-test="InlinePublicForm-inputfield-email"
name={value.value}
label={value.label}
type={"email"}
value={this.state[value.value]}
onChange={e => this.handleChange(e)}
/>
);
case "file":
return (
<input
data-test="InlinePublicForm-inputfield-file"
name={value.value}
label={value.label}
type="file"
onChange={e => this.handleFile(e)}
/>
);
default:
return (
<input
data-test="InlinePublicForm-inputfield-default"
name={value.value}
label={value.label}
value={this.state[value.value]}
onChange={e => this.handleChange(e)}
/>
);
}
};
render() {
return (
<CSSTransition
in={this.props.formActive}
classNames={
this.props.animationClass ? this.props.animationClass : "slide"
}
timeout={450}
mountOnEnter
unmountOnExit
>
<React.Fragment>
<StyledInlineForm
data-test="component-InlinePublicForm"
gridArea={this.props.gridArea}
sizeTablet={this.props.sizeTablet}
sizeDesktopMD={this.props.sizeDesktopMD}
sizeDesktopSM={this.props.sizeDesktopSM}
display={this.props.display}
projectForm={this.props.projectForm ? true : false}
inputWidth={this.props.inputWidth}
maxHeightDesktop={this.props.maxHeightDesktop}
maxHeightTablet={this.props.maxHeightTablet}
color={this.props.color}
>
{this.props.formHeader ? <div className="spacer" /> : null}
{this.renderInputs(this.props.form.fields)}
<div
data-test="InlinePublicForm-button-submit"
className="input-group styledformbtn"
>
{this.props.display ? (
<StyledInlineFormBtn
onClick={e =>
this.props.customFormSubmission
? this.props.customFormSubmission(e)
: this.handleSubmit(e)
}
type="submit"
>
submit
</StyledInlineFormBtn>
) : (
<StyledButton
onClick={e =>
this.props.customFormSubmission
? this.handleCustomSubmit(e)
: this.handleSubmit(e)
}
type="submit"
>
submit
</StyledButton>
)}
</div>
<CloseIcon
src={formCloseBtn}
onClick={e => this.props.deactivateForm(e)}
/>
<FormValidation formSubmitted={this.props.formSubmitted}>
{" "}
your request was received! <br /> we’ll be in touch soon :){" "}
</FormValidation>
<p>{this.state.showMessage ? this.state.message : ""}</p>
</StyledInlineForm>
</React.Fragment>
</CSSTransition>
);
}
}
|
const ModelTask = require('../models/task');
const ModelProject = require('../models/project');
const ModelUserStory = require('../models/userStory');
const moment = require('moment');
//Display create task form
function displayCreateTask(req, res) {
ModelProject.findOne({ _id: req.params.projectId }).then(project => {
res.render('createTask', {
project: project,
user: req.user
});
}).catch(err => console.log(err));
}
// Display modify task
function displayModifyTask(req, res) {
ModelProject.findOne({ _id: req.params.projectId }).then(project => {
ModelTask.findOne({ _id: req.params.taskId }).then(task => {
res.render('modifyTask', {
task: task,
project: project,
user: req.user
});
}).catch(err => console.log(err));
})
}
//Modify an existing task
function modifyTask(req, res) {
const description = req.body.description;
const developerId = req.body.developerId;
const taskId = req.params.taskId;
const projectId = req.params.projectId;
const state = req.body.state;
let errors = [];
if (!state || !description || !developerId) {
errors.push({ msg: "Champ requis non remplis" })
}
if (state > 3 || state < 1) {
errors.push({ msg: "valeur non possible" });
}
if (description.length > 3000) {
errors.push({ msg: "Description trop longue" });
}
if (errors.length === 0) {
ModelTask.updateOne({ _id: taskId }, {
description: description,
developerId: developerId,
state: state
}).then(() => {
renderProjectPage(res, projectId);
}).catch(err => console.log(err));
}
else {
ModelProject.findOne({ _id: projectId }).then(project => {
ModelTask.findOne({ _id: taskId }).then(task => {
res.render('modifyTask', {
errors: errors,
task: task,
project: project,
user: req.user
});
}).catch(err => console.log(err));
})
}
}
//Create a new Task
function createTask(req, res) {
const dev = req.body.developerId;
const description = req.body.description;
const state = req.body.state;
let errors = [];
if (!description || !dev || !state) {
errors.push({ msg: "champs requis non remplis" });
}
if (state > 3 || state < 1) {
errors.push({ msg: "valeur non possible" });
}
if (description.length > 3000) {
errors.push({ msg: "Description trop longue" });
}
if (errors.length == 0) {
const newTask = new ModelTask({
projectId: req.params.projectId,
description,
developerId: dev,
state
});
newTask.save().then(() => {
renderProjectPage(res, req.params.projectId);
}).catch(err => console.log(err));
} else {
ModelProject.findOne({ _id: req.params.projectId }).then(project => {
res.render('createTask', {
errors,
project
});
})
}
}
//Delete an existing task
function deleteTask(req, res) {
ModelTask.deleteOne({ _id: req.params.taskId }).then(() => {
renderProjectPage(res, req.params.projectId);
}).catch(err => console.log(err));
}
function linkTask(req, res) {
const projectId = req.params.projectId;
const taskId = req.params.taskId;
const selectedUsJSON = req.body.selectedUs;
// Translate the US in JSON format into objects and add them into the list of US that will be added in the sprint
let selectedUs;
if (selectedUsJSON !== undefined) {
// If the user selected only one user story
if (!Array.isArray(selectedUsJSON)) {
selectedUs = JSON.parse(selectedUsJSON);
const selectedUsId = selectedUs._id;
// Get the selected us's sprint id
ModelUserStory.findOne({ _id: selectedUsId }).then(us => {
const sprintId = us.sprintId;
ModelTask.findOne({ _id: taskId }).then(task => {
selectedUs.tasks.push(task);
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$pull": { "sprints.$.userStories": { _id: selectedUsId } } },
function (err) {
if (err) {
console.log("Couldn't update the sprint: " + err)
}
else {
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$push": { "sprints.$.userStories": selectedUs } },
function (err) {
if (err) {
console.log("Couldn't update the sprint: " + err)
}
else {
renderProjectPage(res, projectId);
}
}
);
}
}
);
});
})
.catch(err => console.log(err));
}
// Else ...
else if (selectedUsJSON.length > 1) {
selectedUs = [];
let myTask;
ModelTask.findOne({ _id: taskId }).then(task => {
myTask = task;
for (let i = 0; i < selectedUsJSON.length; i++) {
let us = JSON.parse(selectedUsJSON[i]);
us.tasks.push(myTask);
selectedUs.push(us);
const selectedUsId = selectedUs[i]._id;
ModelUserStory.findOne({ _id: selectedUsId }).then(us => {
const sprintId = us.sprintId;
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$pull": { "sprints.$.userStories": { _id: selectedUsId } } }).then(() => {
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$push": { "sprints.$.userStories": selectedUs[i] } }
).then(() => {
if (i === selectedUsJSON.length - 1) {
renderProjectPage(res, projectId);
}
})
.catch(err => console.log(err));
});
});
}
});
}
}
}
function unlinkTask(req, res) {
const projectId = req.params.projectId;
const sprintId = req.params.sprintId;
const taskId = req.params.taskId;
const userStoryId = req.params.userStoryId;
let unlinkedUserstory = JSON.parse(req.body.linkedUserstory);
const taskIndex = unlinkedUserstory.tasks.findIndex(t => t._id === taskId);
if (taskIndex !== undefined) unlinkedUserstory.tasks.splice(taskIndex, 1);
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$pull": { "sprints.$.userStories": { _id: userStoryId } } },
function (err) {
if (err) {
console.log("Couldn't update the sprint: " + err)
}
else {
ModelProject.updateOne(
{ 'sprints._id': sprintId },
{ "$push": { "sprints.$.userStories": unlinkedUserstory } },
function (err) {
if (err) {
console.log("Couldn't update the sprint: " + err)
}
else {
renderProjectPage(res, projectId);
}
}
);
}
}
);
}
function renderProjectPage(res, projectId) {
let noOrphanUs = false;
ModelUserStory.countDocuments({ projectId: projectId, isOrphan: true })
.then(numberOfOrphanUs => {
noOrphanUs = (numberOfOrphanUs === 0);
});
ModelProject.findOne({ _id: projectId })
.then(project => {
ModelUserStory.find({ projectId: projectId })
.then(userStorys => {
ModelTask.find({ projectId: projectId }).then(task => {
res.render('project', {
project: project,
moment: moment,
orphanUs: userStorys,
tasks: task,
noOrphanUs: noOrphanUs
});
})
})
.catch(err => console.log("Couldn't find orphan user stories: " + err));
})
.catch(err => console.log("Couldn't find user stories: " + err));
}
module.exports = {
displayCreateTask,
displayModifyTask,
modifyTask,
createTask,
deleteTask,
linkTask,
unlinkTask
}
|
import Device from "../core/device";
import Port from "../library/port";
import Anode from "../library/anode"; //new from CK
import Cathode from "../library/cathode"; //new from CK
import Channel from "../library/channel";
import BetterMixer from "../library/betterMixer";
import RotaryMixer from "../library/rotaryMixer";
import AlignmentMarks from "../library/alignmentMarks";
import CellTrapL from "../library/celltrapL";
import Gelchannel from "../library/gelchannel"; //CK
import Chamber from "../library/chamber";
import Connection from "../library/connection";
import CurvedMixer from "../library/curvedMixer";
import DiamondReactionChamber from "../library/diamondReactionChamber";
import DropletGenerator from "../library/dropletGenerator";
import GradientGenerator from "../library/gradientGenerator";
import Mux from "../library/mux";
import Pump from "../library/pump";
import Pump3D from "../library/pump3D";
import RoundedChannel from "../library/roundedChannel";
import thermoCycler from "../library/thermoCycler";
import Transition from "../library/transition";
import Transposer from "../library/transposer";
import Valve from "../library/valve";
import Valve3D from "../library/valve3D";
import Tree from "../library/tree";
import YTree from "../library/ytree";
import LLChamber from "../library/llChamber";
import ThreeDMixer from "../library/threeDMixer";
import Via from "../library/via";
//new
import Filter from "../library/filter";
import CellTrapS from "../library/celltrapS";
import ThreeDMux from "../library/threeDMux";
import ChemostatRing from "../library/chemostatring";
import Incubation from "../library/incubation";
import Merger from "../library/merger";
import PicoInjection from "../library/picoinjection";
import Sorter from "../library/sorter";
import CapacitanceSensor from "../library/capacitancesensor";
import Splitter from "../library/splitter";
import Node from "../library/node";
import DropletGeneratorT from "../library/dropletGeneratorT";
import DropletGeneratorFlowFocus from "../library/dropletGeneratorFlowFocus";
import LogicArray from "../library/logicArray";
export default class FeatureSet {
constructor(definitions, tools, render2D, render3D, setString) {
this.__definitions = definitions;
this.__setString = setString;
this.__tools = tools;
this.__render2D = render2D;
this.__render3D = render3D;
//TODO: Replace this cumbersome mechanism for generating different feature variants, etc.
this.__library = {
Port: { object: new Port(), key: null },
Anode: { object: new Anode(), key: null }, //ck addition
Cathode: { object: new Cathode(), key: null }, //ck addition
Channel: { object: new Channel(), key: null },
BetterMixer: { object: new BetterMixer(), key: "FLOW" },
RotaryMixer: { object: new RotaryMixer(), key: "FLOW" },
RotaryMixer_control: { object: new RotaryMixer(), key: "CONTROL" },
AlignmentMarks: { object: new AlignmentMarks(), key: "FLOW" },
AlignmentMarks_control: {
object: new AlignmentMarks(),
key: "CONTROL"
},
CellTrapL: { object: new CellTrapL(), key: "FLOW" },
CellTrapL_cell: { object: new CellTrapL(), key: "CELL" },
Gelchannel: { object: new Gelchannel(), key: "FLOW" }, //CK
Gelchannel_cell: { object: new Gelchannel(), key: "CELL" }, //CK
Chamber: { object: new Chamber(), key: null },
Connection: { object: new Connection(), key: null },
CurvedMixer: { object: new CurvedMixer(), key: null },
DiamondReactionChamber: {
object: new DiamondReactionChamber(),
key: null
},
DropletGen: { object: new DropletGenerator(), key: null },
GradientGenerator: { object: new GradientGenerator(), key: null },
Mux: { object: new Mux(), key: "FLOW" },
Mux_control: { object: new Mux(), key: "CONTROL" },
Pump: { object: new Pump(), key: "FLOW" },
Pump_control: { object: new Pump(), key: "CONTROL" },
Pump3D: { object: new Pump3D(), key: "FLOW" },
Pump3D_control: { object: new Pump3D(), key: "CONTROL" },
RoundedChannel: { object: new RoundedChannel(), key: null },
thermoCycler: { object: new thermoCycler(), key: "FLOW" },
Transition: { object: new Transition(), key: null },
Transposer: { object: new Transposer(), key: "FLOW" },
Transposer_control: { object: new Transposer(), key: "CONTROL" },
Tree: { object: new Tree(), key: null },
YTree: { object: new YTree(), key: null },
Valve: { object: new Valve(), key: null },
Valve3D: { object: new Valve3D(), key: "FLOW" },
Valve3D_control: { object: new Valve3D(), key: "CONTROL" },
LLChamber: { object: new LLChamber(), key: "FLOW" },
LLChamber_control: { object: new LLChamber(), key: "CONTROL" },
"3DMixer": { object: new ThreeDMixer(), key: "FLOW" },
"3DMixer_control": { object: new ThreeDMixer(), key: "CONTROL" },
Via: { object: new Via(), key: "FLOW" },
//new
Filter: { object: new Filter(), key: "Flow" },
CellTrapS: { object: new CellTrapS(), key: "FLOW" },
CellTrapS_cell: { object: new CellTrapS(), key: "CELL" },
"3DMux": { object: new ThreeDMux(), key: "FLOW" },
"3DMux_control": { object: new ThreeDMux(), key: "CONTROL" },
ChemostatRing: { object: new ChemostatRing(), key: "FLOW" },
ChemostatRing_control: { object: new ChemostatRing(), key: "CONTROL" },
Incubation: { object: new Incubation(), key: "FLOW" },
Merger: { object: new Merger(), key: "FLOW" },
PicoInjection: { object: new PicoInjection(), key: "FLOW" },
Sorter: { object: new Sorter(), key: "FLOW" },
Splitter: { object: new Splitter(), key: "FLOW" },
CapacitanceSensor: { object: new CapacitanceSensor(), key: "FLOW" },
Node: { object: new Node(), key: "FLOW" },
DropletGenT: { object: new DropletGeneratorT(), key: null },
DropletGenFlow: { object: new DropletGeneratorFlowFocus(), key: null },
LogicArray: { object: new LogicArray(), key: "FLOW" },
LogicArray_control: { object: new LogicArray(), key: "CONTROL" },
LogicArray_cell: { object: new LogicArray(), key: "CELL" }
};
// this.__checkDefinitions();
console.warn("Skipping definition check over here ");
}
containsDefinition(featureTypeString) {
if (this.__definitions.hasOwnProperty(featureTypeString)) return true;
else return false;
}
/**
* Returns the 3DuF type for MINT syntax (need to get rid of this in the future)
* @param minttype
* @return {string|null}
*/
getTypeForMINT(minttype) {
let checkmint = minttype;
for (let key in this.__library) {
if (checkmint === this.__library[key].object.mint) {
return key;
}
}
return null;
}
/**
* Returns the default params and values for the entire library
*/
getDefaults() {
let output = {};
for (let key in this.__library) {
output[key] = this.__library[key].object.defaults;
}
return output;
}
getFeatureType(typeString) {
let setString = this.name;
let defaultName = "New " + setString + "." + typeString;
return function(values, name = defaultName) {
return Device.makeFeature(typeString, setString, values, name);
};
}
getSetString() {
return this.setString;
}
/**
* Returns the definition of the given typestring
* @param typeString
* @return {null|{mint: *, defaults: *, unique: *, maximum: *, units: *, heritable: *, minimum: *}}
*/
getDefinition(typeString) {
// console.log("Called", typeString);
//TODO:Clean up this hacky code and shift everything to use MINT convention
if (!this.__library.hasOwnProperty(typeString)) {
typeString = this.getTypeForMINT(typeString);
}
if (!this.__library.hasOwnProperty(typeString)) {
console.error("Could not find the type in featureset definition !: " + typeString);
return null;
}
let definition = this.__library[typeString].object;
let ret = {
unique: definition.unique,
heritable: definition.heritable,
units: definition.units,
defaults: definition.defaults,
minimum: definition.minimum,
maximum: definition.maximum,
mint: definition.mint
};
return ret;
}
getRender3D(typeString) {
return this.__render3D[typeString];
}
/**
* Returns the library/technology description instead of the function pointer as it was doing before
* @param typeString
* @return {*}
*/
getRender2D(typeString) {
return this.__library[typeString];
}
/**
* Returns the Tool that is being used by the definition
* @param typeString
* @return {Document.tool|null}
*/
getTool(typeString) {
return this.__definitions[typeString].tool;
}
/**
* Creates a Feature (Outdated, I think)
* @param typeString
* @param setString
* @param values
* @param name
* @return {*}
*/
makeFeature(typeString, setString, values, name) {
throw new Error("MAke featre in feature set is being called");
console.log(setString);
let set = getSet(setString);
let featureType = getFeatureType(typeString);
return featureType(values, name);
}
/**
* Returns the component ports for a given component
* @param params
* @param typestring
* @return {void|Array}
*/
getComponentPorts(params, typestring) {
let definition = this.__library[typestring].object;
return definition.getPorts(params);
}
/**
* Checks if the component definition in the library has the Inverse Render generation support
* @param typestring
* @return {*|boolean}
*/
hasInverseRenderLayer(typestring) {
let definition = this.__library[typestring].object;
// Go through the renderkeys and check if inverse is available
let renderkeys = definition.renderKeys;
return renderkeys.includes("INVERSE");
}
__checkDefinitions() {
for (let key in this.__definitions) {
if (!this.__tools.hasOwnProperty(key) || !this.__render2D.hasOwnProperty(key) || !this.__render3D.hasOwnProperty(key)) {
throw new Error("Feature set does not contain a renderer or tool definition for: " + key);
}
}
}
}
|
import { createAction } from '@reduxjs/toolkit';
import { v4 as uuidv4 } from 'uuid';
const createContact = createAction('CREATE_CONTACTS', (name, number) => {
return {
payload: {
name,
number,
id: uuidv4(),
},
};
});
const removeContacts = createAction('REMOVE_CONTACTS');
const changeFilter = createAction('CHANGE_FILTER');
const getFiltredContacts = createAction('GET_FILTRED_CONTACTS');
const actions = {
createContact,
removeContacts,
changeFilter,
getFiltredContacts,
};
export default actions;
|
Ext.define('Admin.view.main.MainModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.main',
data: {
currentView: null,
mainTree: {
fields: [{
name: 'text'
}],
root: {
expanded: true,
children: [{
text: '首页',
iconCls: 'x-fa fa-desktop',
rowCls: 'nav-tree-badge nav-tree-badge-new',
url: 'dashboard',
leaf: true
}, {
text: '订单记录',
iconCls: 'x-fa fa-send',
rowCls: 'nav-tree-badge nav-tree-badge-hot',
url: 'trades',
leaf: true,
checked: false
}, {
text: '系统管理',
iconCls: 'x-fa fa-plus-square',
rowCls: 'nav-tree-badge',
expanded: false,
selectable: false,
children: [{
text: '用户管理',
iconCls: 'x-fa fa-user',
rowCls: 'nav-tree-badge',
url: 'user',
leaf: true
}, {
text: '角色管理',
iconCls: 'x-fa fa-users',
rowCls: 'nav-tree-badge',
url: 'role',
leaf: true
}]
}
]
}
}
}
});
|
// var a = [];
// for (let i=0 ;i<10;i++){
// a[i]=function(){
// console.log(i);
// };
// }
// a[6]();
// console.log(i);//变量提升
// var a = [];
// for (var i=0 ;i<10;i++){
// a[i]=function(){
// console.log(i);
// };
// }
// a[6]();
// console.log(i);
// var tmp = new Date();
// console.log(tmp);
// function f(){
// console.log(tmp);
// if(false){
// var tmp = 'hello world';
// }
// }
// f();//变量提升了 tmp被覆盖了 所以不再是Date();
// console.log(typeof tmp);
// function f1(){
// let n =5;
// if(true){
// let n = 10;
// }
// console.log(n);
// }
// f1();
// var o = {
// x:1,
// y:2,
// z:3,
// c:4
// }
// var result=[];
// for(var prop in o)
// {
// result.push(prop);
// }
// console.log(result);
// var a=o.hasOwnProperty("x");
// var b=o.hasOwnProperty("y");
// var c=o.hasOwnProperty("toString");
// console.log(a,b,c);
// var p = {
// x:1.0,
// y:1.0,
// get r(){
// return Math.sqrt(this.x*this.x+this.y*this.y);
// },
// set r(newvalue){
// var oldvalue = Math.sqrt(this.x*this.x+this.y*this.y);
// var ratio = newvalue/oldvalue;
// this.x*=ratio;
// this.y*=ratio;
// },
// get theta(){return Math.atan2(this.y,this.x);}
// };
// console.log(p.theta);
// console.log(p.r);
// p.r=20;
// console.log(p.theta);
// console.log(p.r);
function constfuncs(){
var funcs =[];
for (var i=0;i<10;i++)
{
funcs[i]=function(){return i;};
}
return funcs;
};
var funcs = constfuncs();
console.log(funcs[5]());//10 |
var gulp = require("gulp"),
less = require("gulp-less"),
concat = require("gulp-concat"),
uglify = require("gulp-uglify"),
rename = require("gulp-rename"),
minify = require("gulp-minify-css"),
runSequence = require("run-sequence");
/*
* LESS/CSS tasks.
*/
gulp.task("buildLess", function() {
return gulp.src(["./Less/Site.less",
"./Less/Rtl.less"])
.pipe(less())
.pipe(gulp.dest("Styles"));
});
gulp.task("minifyStyles", function() {
return gulp.src(["./Styles/Site.css",
"./Styles/Rtl.css"])
.pipe(minify())
.pipe(rename({
extname: ".min.css"
}))
.pipe(gulp.dest("Styles"));
});
gulp.task("buildColorSchemeLess", function() {
return gulp.src(["./Less/ColorSchemes/*.less"])
.pipe(less())
.pipe(gulp.dest("Styles/ColorSchemes"));
});
gulp.task("minifyColorSchemeStyles", function () {
return gulp.src(["./Styles/ColorSchemes/Black.css",
"./Styles/ColorSchemes/Blue.css",
"./Styles/ColorSchemes/Green.css",
"./Styles/ColorSchemes/Grey.css",
"./Styles/ColorSchemes/White.css"])
.pipe(minify())
.pipe(rename({
extname: ".min.css"
}))
.pipe(gulp.dest("Styles/ColorSchemes"));
});
/*
* JavaScript tasks.
*/
gulp.task("concatScripts", function() {
return gulp.src(["./Vendor/DoubletapToGo/doubletaptogo.js",
"./Scripts/Theme.js"])
.pipe(concat("Site.js"))
.pipe(gulp.dest("Scripts"));
});
gulp.task("minifyScripts", function() {
return gulp.src("./Scripts/Site.js")
.pipe(uglify())
.pipe(rename({
extname: ".min.js"
}))
.pipe(gulp.dest("Scripts"));
});
/*
* General tasks.
*/
gulp.task("default", function(callback) {
runSequence("buildLess",
"minifyStyles",
"concatScripts",
"minifyScripts");
});
gulp.task("colorSchemes", function(callback) {
runSequence("buildColorSchemeLess",
"minifyColorSchemeStyles");
}); |
import React from 'react';
import styled from 'styled-components';
const Author = styled.div`
font-size: 0.8rem;
color: #666;
`;
export default ({ author }) => <Author>Author: {author}</Author>;
|
$(document).ready(function () {
$("#js_AddCode").click(function () {
var GetCode = $("#textbit").text();
// Validate GetCode Value
if (GetCode === "") {
alert("Please Select a BarCode");
}else {
// Add the scaned code to code list.
$(".js_BarCodeList").append("<tr> <td>"+GetCode+"</td> </tr>");
console.log(GetCode);
}
}); //End click
}); // End Scope
|
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require('fs');
const token = "MzI2MTE2NzQ2MzcxMTM3NTM4.DDaanw.YhjNiWCl87lpqtxVP6YeTDzBQ_E";
var mention = "<@326116746371137538>";
module.exports = {
login: function () {
client.on("ready", () => {
console.log("Client Ready !");
});
client.on('message', message => {
if (message.mentions.users.array() !== undefined && message.mentions.users.array()[0] !== undefined && message.mentions.users.array()[0].username === 'SoundBoard') {
let command = message.content.substring(22);
if (command === 'join') {
if (message.member.voiceChannel) {
message.member.voiceChannel.join()
.then(connection => {
})
.catch(console.log);
} else {
message.reply('You need to join a voice channel first!');
}
}
else if (command.substring(0, 4) === "play") {
this.play(command.substring(5));
}
else if (command === "stop" || command === "quit") {
this.quit();
}
else {
message.reply('Invalid command !');
}
}
});
client.login(token)
},
play: function (song) {
if (client.voiceConnections.size != 0) {
var filepath = './server/songs/' + song + '.mp3';
fs.stat(filepath, function (err, stats) {
if (stats !== undefined) {
for (connection of client.voiceConnections.array()) {
connection.playFile(filepath);
}
console.log('Song "' + song + '" played !');
}
else {
console.log('No such song !');
}
});
}
else {
console.log('No connection !');
}
},
quit: function () {
for (connection of client.voiceConnections.array()) {
connection.disconnect();
}
}
} |
import React from 'react';
import "../styles/website.css"
const CustomerCard = ({author}) => {
return (
<>
<div className="customerCard">
<div className="review">
<p>— Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum cillum dolore eu fugiat.</p>
</div>
<div className="line"></div>
<div className="author">
<h3>{author}/<span>AppName</span></h3>
</div>
</div>
</>
);
}
export default CustomerCard;
|
import React from 'react';
import { Menu, Grid, Dropdown } from 'semantic-ui-react';
export default class MiddleMenu extends React.Component {
render() {
return (
<Menu borderless className="middleMenu">
<Grid centered container>
<Dropdown item text="MEN">
<Dropdown.Menu>
<Dropdown.Item>Tank Tops</Dropdown.Item>
<Dropdown.Item>Shirts</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Dropdown item text="WOMEN">
<Dropdown.Menu>
<Dropdown.Item>Tank Tops</Dropdown.Item>
<Dropdown.Item>Shirts</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Item>KIDS</Menu.Item>
<Dropdown item text="BRANDS">
<Dropdown.Menu>
<Dropdown.Item>Tank Tops</Dropdown.Item>
<Dropdown.Item>Shirts</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Item>Search</Menu.Item>
</Grid>
</Menu>
);
}
} |
import React from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Link as RouterLink } from 'react-router-dom';
import {
Link,
Typography,
Fab,
Grid,
} from '@material-ui/core/';
// Themes
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import { cyan, green } from '@material-ui/core/colors/';
// Components
import Register from './users/Register';
import Login from './users/Login';
const theme = createMuiTheme({
palette: {
type: 'dark',
primary: cyan,
secondary: green,
},
typography: {
useNextVariants: true,
},
});
function Navigation() {
return (
<nav>
<Grid container spacing={16}>
<Grid item xs={6}>
<Link component={RouterLink} to="/login">
<Fab color="secondary" variant="extended">
Login
</Fab>
</Link>
</Grid>
<Grid item xs={6}>
<Link component={RouterLink} to="/register">
<Fab color="secondary" variant="extended">
Register
</Fab>
</Link>
</Grid>
</Grid>
</nav>
);
}
function App() {
return (
<MuiThemeProvider theme={theme}>
<Router>
<div className="App">
<header className="App-header">
<Typography component="h2" variant="h1" gutterBottom>
Reforest
</Typography>
</header>
<Route path="/" exact component={Navigation} />
<Route path="/register" exact component={Register} />
<Route path="/login" exact component={Login} />
</div>
</Router>
</MuiThemeProvider>
);
}
export default App;
|
import React, { useState } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Text from "../BaseComponents/Text";
import RadioInput from "./RadioInput";
import { whiteBackground } from "../themes";
const Container = styled.div`
padding: 14px 9px;
${whiteBackground}
`;
const TitleWrapper = styled.div`
padding: 9px 0 5px 0;
`;
function RadioGroup({ title, subTitle, radios }) {
const [value, setValue] = useState();
return (
<Container>
<TitleWrapper>
<Text bold>{title}</Text>
</TitleWrapper>
<Text small secondary>
{subTitle}
</Text>
{/* radio buttons */}
{radios.map(r => (
<RadioInput
key={r.key}
title={r.title}
name={title}
checked={value === r.title}
onChange={() => setValue(r.title)}
/>
))}
</Container>
);
}
const radioType = PropTypes.shape({
title: PropTypes.string.isRequired
});
const propTypes = {
title: PropTypes.string.isRequired,
subTitle: PropTypes.string,
radios: PropTypes.arrayOf(radioType).isRequired
};
RadioGroup.propTypes = propTypes;
RadioGroup.defaultProps = {
subTitle: null
};
export const RadioGroupType = PropTypes.shape(propTypes);
export default RadioGroup;
|
// ================================================================================
//
// Copyright: M.Nelson - technische Informatik
// Die Software darf unter den Bedingungen
// der APGL ( Affero Gnu Public Licence ) genutzt werden
//
// datei: js/menu/mne_amenu.js
//================================================================================
window.MneAjaxMenu = function(win, frame, param)
{
this.loadCss("menu.css");
MneAjaxData.call(this, win);
if ( typeof frame == 'string' ) this.frame = this.doc.getElementById(frame); else this.frame = frame;
if ( typeof param.name != 'undefined' && param.name != null ) this.name = param.name; else this.name = 'main';
if ( typeof param.classname != 'undefined' && param.classname != null ) this.classname = param.classname; else this.classname = 'menu';
if ( typeof param.parentid != 'undefined' && param.parentid != null ) this.parentid = param.parentid; else this.parentid = '';
if ( typeof param.weblet != 'undefined' && param.weblet != null ) this.weblet = param.weblet; else this.weblet;
if ( typeof param.lastquery != 'undefined' && param.lastquery != null ) this.lastquery = param.lastquery; else this.lastquery = "";
if ( typeof param.debug != 'undefined' && param.debug != null ) this.pdebug = 1;
if ( typeof param.pdebug != 'undefined' && param.pdebug != null ) this.pdebug = 1;
if ( typeof param.cols != 'undefined' && param.cols != null && typeof param.showcols != 'undefined' && param.showcols != null )
{
this.cols = param.cols.split(',');
this.showcols = param.showcols.split(',');
if ( typeof param.action != 'undefined' && param.action != null ) this.readaction = param.action; else this.readaction = null;
if ( typeof param.table != 'undefined' && param.table != null ) this.table = param.table; else this.table = null;
if ( typeof param.schema != 'undefined' && param.schema != null ) this.schema = param.schema; else this.schema = 'mne_application';
if ( typeof param.query != 'undefined' && param.query != null ) this.query = param.query ; else this.query = null;
if ( typeof param.wcol != 'undefined' && param.wcol != null ) this.wcol = param.wcol; else this.wcol = "";
if ( typeof param.wop != 'undefined' && param.wop != null ) this.wop = param.wop; else this.wop = "";
if ( typeof param.wval != 'undefined' && param.wval != null ) this.wval = param.wval; else this.wval = "";
if ( typeof param.scols != 'undefined' && param.scols != null ) this.scols = param.scols; else this.scols = "";
this.read = MneAjaxMenu.prototype.read_fix;
}
else if ( typeof param.readaction != 'undefined' && param.readaction != null )
{
this.readaction = param.readaction;
this.readparam = param.readparam;
this.read = MneAjaxMenu.prototype.read_action;
if ( typeof param.noleaf != 'undefined' && param.noleaf != null ) this.noleaf = param.noleaf;
if ( typeof param.showleaf != 'undefined' && param.showleaf != null ) this.showleaf = param.showleaf;
if ( typeof param.showsubmenu != 'undefined' && param.showsubmenu != null ) this.showsubmenu = param.showsubmenu;
if ( typeof param.name != 'undefined' && param.name != null ) this.name = param.name; else this.name = '';
if ( typeof this.weblet != 'undefined' && this.weblet.scrollframe != null )
this.weblet.scrollframe.action = { "menu" : this, "menuid" : '', name : '', action : "root", "frame" : this.frame, timeout : null, "classname" : this.classname };
}
else
{
if ( typeof param.action != 'undefined' && param.action != null ) this.readaction = param.action; else this.readaction = null;
if ( typeof param.table != 'undefined' && param.table != null ) this.table = param.table; else this.table = null;
if ( typeof param.schema != 'undefined' && param.schema != null ) this.schema = param.schema; else this.schema = 'mne_application';
if ( typeof param.query != 'undefined' && param.query != null ) this.query = param.query ; else this.query = 'menu';
if ( param.name == 'all' )
{
if ( typeof param.wcol != 'undefined' && param.wcol != null ) this.wcol = "parentid," + param.wcol; else this.wcol = "parentid";
if ( typeof param.wop != 'undefined' && param.wop != null ) this.wop = "=," + param.wop; else this.wop = "=";
if ( typeof param.wval != 'undefined' && param.wval != null ) this.wval = param.wval; else this.wval = "";
}
else
{
if ( typeof param.wcol != 'undefined' && param.wcol != null ) this.wcol = "menuname,parentid," + param.wcol; else this.wcol = "menuname,parentid";
if ( typeof param.wop != 'undefined' && param.wop != null ) this.wop = "=,=," + param.wop; else this.wop = "=,=";
if ( typeof param.wval != 'undefined' && param.wval != null ) this.wval = param.wval; else this.wval = "";
}
if ( typeof param.noleaf != 'undefined' && param.noleaf != null ) this.noleaf = param.noleaf;
if ( typeof param.showsubmenu != 'undefined' && param.showsubmenu != null ) this.showsubmenu = param.showsubmenu;
this.read = MneAjaxMenu.prototype.read_recursive;
this.oid = this.id = "menu";
}
this.frame.innerHTML = '';
this.frame.className = this.frame.className + " " + this.classname + "main";
this.actions = {};
this.last_action = null;
this.act_action = null;
this.mkElement = function(menuid, iname, classname, action )
{
var name = iname;
if ( name == '' ) name = " ";
var div = this.doc.createElement("div");
var e;
var ra = action.rootaction;
var path = action.name;
var parentpath = "";
while ( typeof ra != 'undefined' )
{
parentpath = ra.name + "➔" + parentpath;
path = ra.name + "➔" + path;
ra = ra.rootaction;
}
action.path = path;
action.parentpath = parentpath.substr(0, parentpath.length - 1);
div.id = this.name + 'frame' + menuid;
div.className = classname;
div.action = action;
if ( typeof action.status != 'undefined' && action.status != '' )
div.className = div.className + " " + div.className + action.status;
if ( this.navigator.mobile || this.navigator.tablet )
{
div.onclick = function() {};
div.addEventListener ('touchstart', window.MneAjaxMenu.prototype.touchstart, false);
div.addEventListener ('touchend', window.MneAjaxMenu.prototype.touchend, false);
}
e = this.doc.createElement("div");
e.className = this.classname + "link";
div.appendChild(e);
e.innerHTML = name;
e.action = action;
if ( typeof action.status != 'undefined' && action.status != '' )
e.className = e.className + " " + e.className + action.status;
action.root = div;
action.frame = this.doc.createElement('div');
action.frame.className = this.classname + 'main';
action.root.appendChild(action.frame);
return div;
};
this.submenu = function(menuid, refresh)
{
var action = this.actions[menuid];
var parent = action.root;
var frame;
var a;
var i;
try
{
if ( refresh == true )
{
this.eleMkClass(action.root, "menuopen", false);
if ( typeof action.status != 'undefined')
this.eleMkClass(action.root, "menuopen" + action.status, false);
}
if ( action.root.className.indexOf('menuopen') == -1 )
{
action.frame.innerHTML = "";
this.read(menuid, action.frame, this.classname);
action.frame.child_count = this.child_count;
}
this.eleMkClass(action.root, 'menuopen', ( action.root.className.indexOf('menuopen') == -1 ));
}
catch(e)
{
this.exception("MneAjaxMenu::submenu:",e);
}
};
this.click_real = function(action, evt)
{
var menu = this;
action.timeout = null;
if ( typeof this.weblet != 'undefined' )
this.weblet.showwait();
window.setTimeout(function() {
try
{
if ( typeof action != 'undefined' && action.menu == menu ) menu.action.call(menu, action);
if ( typeof menu.weblet != 'undefined' && typeof menu.weblet.click == 'function' )
menu.weblet.click(evt);
}
catch ( e )
{
menu.exception("MneAjaxMenu::click_real:",e);
menu.weblet.hidewait();
}
menu.weblet.hidewait();
}, 0);
};
this.dblclick = function(evt)
{
if ( this.classname == 'register' )
{
if ( typeof evt.target.action != 'undefined' && evt.target.action.menu == this )
{
evt.target.action.menu.weblet.reload = true;
evt.target.action.menu.last_action = null;
}
this.click_real(evt.target.action);
}
else if ( this.classname.substr(0,4) == 'tree' && evt.target.action.action != 'root' )
{
this.click_real(evt.target.action);
if ( typeof this.weblet.dblclick == 'function' )
this.weblet.dblclick(evt);
}
return true;
};
this.click = function(evt)
{
try
{
if ( typeof evt.target.action != 'undefined' && evt.target.action.action != 'submenu' )
this.close(evt.target.action);
else if ( typeof evt.target.action == 'undefined' || evt.target.action.menu != this || evt.target.action.rootaction != this.last_action )
this.close(null);
if ( typeof evt.target.action != 'undefined' && evt.target.action.menu == this )
{
if ( evt.button == 0 )
{
if ( evt.ctrlKey != true )
{
if ( evt.target.action.timeout == null )
{
var self = this;
var e = evt;
var timeout = function() { self.click_real.call(self, evt.target.action, e); };
evt.target.action.timeout = window.setTimeout(timeout, 200);
}
else
{
window.clearTimeout(evt.target.action.timeout);
evt.target.action.timeout = null;
this.dblclick(evt);
}
}
else if ( typeof this.weblet.click_right == 'function' )
this.weblet.click_right(evt);
}
if ( evt.button != 0 && typeof this.weblet.click_right == 'function' )
this.weblet.click_right(evt);
}
}
catch ( e )
{
this.exception("MneAjaxMenu::click:",e);
}
return true;
};
this.mousedown = function(evt)
{
if ( typeof evt.target.action != 'undefined' && evt.target.action.menu == this )
{
if ( evt.button != 0 && typeof this.weblet.click_right == 'function' )
this.weblet.click_right(evt);
}
}
this.reload = function()
{
this.actions = new Array();
this.last_action = null;
this.act_action = null;
this.frame.innerHTML = '';
this.read(this.parentid, this.frame, this.classname);
};
this.win.mneDocevents.addInterest("click", this);
if ( param.noread != true )
this.read(this.parentid, this.frame, this.classname);
};
MneAjaxMenu.prototype = new MneAjaxData(window);
MneAjaxMenu.prototype.release = function()
{
this.win.mneDocevents.remove(this);
}
MneAjaxMenu.prototype.action = function(a)
{
var action = a.action;
var closeit = ( typeof this.frame.mne_slider != 'undefined' );
this.act_action = a;
this.weblet.obj.act_menuid = a.menuid;
try
{
var str;
str = action.split("(")[0].replace(/ *$/, "");
action = action.replace(/\\'/g, "\\\\'");
switch(str)
{
case "root":
break;
case "submenu" :
closeit = false;
a.menu.submenu(a.menuid);
if ( this.noleaf == true || this.showsubmenu == true )
{
var param =
{
menuparentid : typeof a.rootaction == 'undefined' ? null : a.rootaction.menuid,
menuid : a.menuid,
name : a.name,
path : a.path,
parentpath : a.parentpath,
submenu : true
};
this.weblet.setValue(param);
}
break;
case "show" : eval("this.weblet." + action); break;
case "load" : eval("this.weblet." + action); break;
case "setValue" : eval("this.weblet." + action); break;
default : eval(action);
}
if ( typeof this.weblet.resize == 'function')
this.weblet.resize();
if ( closeit )
this.frame.mne_slider.hide();
}
catch(e)
{
if ( typeof e.stack == 'undefined' ) e.stack = "no stack";
this.exception("MneAjaxMenu::action:" + action, e);
}
this.act_action = null;
this.last_action = a;
};
MneAjaxMenu.prototype.refresh = function(menuid)
{
if ( menuid == '' ) { this.reload(); return; }
if ( typeof this.actions[menuid] == 'undefined' ) return;
if ( this.actions[menuid].action.split("(")[0].replace(/ *$/, "") == 'submenu' && this.actions[menuid].frame != null )
this.actions[menuid].menu.submenu(menuid, true);
};
MneAjaxMenu.prototype.close = function(a)
{
var i = null;
if ( this.classname.substr(0,4) == 'tree' ) return;
for ( i in this.actions )
{
var action = this.actions[i];
if ( typeof a != 'undefined' && a != null && a.menu == this )
this.eleMkClass(action.root, this.classname + "active", action == a );
}
};
MneAjaxMenu.prototype.read_setval = function(p)
{
var param = p;
if ( typeof param == 'string' )
eval("param = { " + param + "}");
return param;
};
MneAjaxMenu.prototype.check_width = function(f)
{
var frame = ( typeof f != 'undefined' ) ? f : this.frame;
var w = 0;
if ( this.classname == 'register' )
{
for ( ele = frame.firstChild; ele != null; ele = ele.nextSibling )
if ( w < ele.scrollWidth ) w = ele.scrollWidth;
for ( ele = frame.firstChild; ele != null; ele = ele.nextSibling )
ele.style.minWidth = ( w + 4 ) + "px";
}
}
MneAjaxMenu.prototype.read_recursive = function(parentid, frame, classname)
{
var val;
if ( this.name == 'all' )
val = parentid.replace(/\,/, "\\,");
else
val = this.name + "," + parentid.replace(/\,/, "\\,");
if ( this.wval != "" ) val = val + "," + this.wval;
var param =
{
"schema" : this.schema,
"query" : this.query,
"cols" : "menuid,item,action,typ,pos",
"scols" : "pos",
"wcol" : this.wcol,
"wop" : this.wop,
"wval" : val,
"distinct" : 1,
"lastquery" : this.lastquery,
"sqlend" : 1
};
if ( this.noleaf == true ) param.cols += ",typnoleaf";
MneAjaxData.prototype.read.call(this, "/db/utils/query/data.xml", param);
var ele;
var menuid = this.ids['menuid'];
var name = this.ids['item'];
var action = this.ids['action'];
var typ = this.ids['typ'];
var typnoleaf = this.ids['typnoleaf'];
var i;
this.child_count = 0;
for ( i = 0; i<this.values.length; i++ )
{
var v = this.values[i][action];
var str = v.split("(")[0].replace(/ *$/, "");
var setvals = {};
if ( str == 'setValue' )
{
v = v.replace(/setValue/, 'this.read_setval');
v = v.replace(/\\'/g, "\\\\'");
setvals = eval(v);
}
if ( this.noleaf != true || this.values[i][typ] != 'leaf' )
{
this.actions[this.values[i][menuid]] =
{
menu : this,
menuid : this.values[i][menuid],
name : this.values[i][name],
action : this.values[i][action],
setvals : setvals,
frame : null,
rootaction : this.actions[parentid],
timeout : null,
classname : classname,
leaf : this.values[i][typ]
};
ele = this.mkElement( this.values[i][menuid], this.txtFormat.call(this, this.values[i][name], this.typs[name]), classname + this.values[i][typ], this.actions[this.values[i][menuid]]);
frame.appendChild(ele);
this.child_count++;
}
}
this.check_width(frame) ;
};
MneAjaxMenu.prototype.read_fix = function(parentid, frame, classname)
{
var wcol = this.wcol;
var wop = this.wop;
var wval = this.wval;
var deep = 0;
var komma = '';
var menuid = '';
var typ = '';
var action = '';
var setvals = new Array();
if ( parentid != '' )
{
wcol = this.actions[parentid].wcol;
wop = this.actions[parentid].wop;
wval = this.actions[parentid].wval;
deep = this.actions[parentid].deep;
menuid = this.actions[parentid].menuid;
}
if ( wcol != '' )
komma = ',';
var colarray = this.cols[deep].split(':');
var cols = colarray[0];
if ( colarray.length > 1 ) cols = cols + "," + colarray[1];
var scols = ( colarray.length > 1 ) ? colarray[1] : colarray[0];
if ( this.scols != '' )
{
var s = this.scols.split(',');
var i;
for ( i =0; i< s.length; i++ )
{
if ( s[i].substring(0,1) == '!' )
{
cols += ',' + s[i].substr(1);
}
else
{
cols += ',' + s[i];
}
scols = this.scols + "," + scols;
}
}
if ( deep == this.cols.length - 1 )
{
typ = 'leaf';
cols = cols + ',' + this.showcols.join(',');
}
var param =
{
"query" : this.query,
"schema" : this.schema,
"table" : this.table,
"cols" : cols,
"scols" : scols,
"wcol" : wcol,
"wop" : wop,
"wval" : wval,
"lastquery" : this.lastquery,
"distinct" : 1,
"sqlend" : 1
};
if ( typeof this.readaction != 'undefined' && this.readaction != null )
MneAjaxData.prototype.read.call(this, this.readaction, param);
else if ( typeof this.query != 'undefined' && this.query != null )
MneAjaxData.prototype.read.call(this, "/db/utils/query/data.xml", param);
else
MneAjaxData.prototype.read.call(this, "/db/utils/table/data.xml", param);
var ele;
for ( i = 0; i<this.values.length; i++ )
{
setvals = {};
if ( typ == 'leaf' )
{
var j;
action = "setValue('";
for ( j=0; j<this.showcols.length; j++ )
{
action += this.showcols[j] + ': "' + this.values[i][this.ids[this.showcols[j]]] + '",';
setvals[this.showcols[j]] = this.values[i][this.ids[this.showcols[j]]];
}
action = action.substring(0,action.length - 1);
action += "')";
}
else
{
action = "submenu";
}
this.actions[menuid + '@@@@' + this.values[i][this.ids[colarray[0]]]] =
{
menu : this,
menuid : menuid + '@@@@' + this.values[i][this.ids[colarray[0]]],
action : action,
setvals : setvals,
frame : null,
rootaction : this.actions[parentid],
deep : deep + 1,
wcol : wcol + komma + colarray[0],
wval : wval + komma + this.values[i][this.ids[colarray[0]]].replace(/\,/, "\\,"),
wop : wop + komma + "=",
leaf : typ
};
ele = this.mkElement( menuid + this.values[i][this.ids[colarray[0]]], this.txtFormat.call(this, this.values[i][this.ids[colarray[0]]], this.typs[this.ids[colarray[0]]]), classname + typ, this.actions[menuid + '@@@@' + this.values[i][this.ids[colarray[0]]]]);
frame.appendChild(ele);
}
};
MneAjaxMenu.prototype.read_action = function(parentid, frame, classname)
{
var i = null;
var param = {};
for ( i in this.readparam )
{
param[i] = eval(this.readparam[i]);
}
if ( this.noleaf == true )
param['noleaf'] = "1";
MneAjaxData.prototype.read.call(this, this.readaction, param);
var ele;
var menuid = this.ids['menuid'];
var name = this.ids['item'];
var action = this.ids['action'];
var typ = this.ids['typ'];
var status = this.ids['status'];
var i;
this.child_count = 0;
for ( i = 0; i<this.values.length; i++ )
{
var menuidvalue = this.values[i][menuid];
if ( this.name != '' )
menuidvalue = menuidvalue.substr(this.name.length + 1);
this.actions[menuidvalue] = { "menu" : this, "menuid" : menuidvalue, name : this.values[i][name], action : this.values[i][action], "frame" : null, "rootaction" : this.actions[parentid], timeout : null, "classname" : classname, leaf : this.values[i][typ] };
if ( status != 'undefined' )
this.actions[menuidvalue].status = this.values[i][status];
ele = this.mkElement( menuidvalue, this.txtFormat.call(this, this.values[i][name], this.typs[name]), classname + this.values[i][typ], this.actions[menuidvalue]);
frame.appendChild(ele);
this.child_count++;
}
};
MneAjaxMenu.prototype.touchstart = function(e)
{
this.touch = 0;
var s = this;
window.setTimeout(function() { s.touch = 1; }, 1000);
};
MneAjaxMenu.prototype.touchend = function(evt)
{
this.action.menu.close.call(this.action.menu, this.action);
if ( this.touch == 1 )
{
if ( this.action.menu.classname == 'register')
{
this.action.menu.weblet.reload = true;
this.action.menu.last_action = null;
this.action.menu.click_real.call(this.action.menu, this.action);
}
else
{
this.action.menu.mousedown({ target : evt.target, button : 1 });
return;
}
}
};
|
import express from "express";
import cors from "cors";
import products from "./routes/product";
import user from "./routes/user";
import cart from "./routes/cart";
import order from "./routes/order";
const app = express();
app.use(express.json());
/**
* For local testing only! Enables CORS for all domains
*/
app.use(cors());
// ADD ROUTES
app.use("/api/products", products);
app.use("/api/user", user);
app.use("/api/cart", cart);
app.use("/api/order", order);
app.listen(8000, () => {
console.log(`Resource Server Ready on port 8000`);
});
|
import React from 'react';
import {View, FlatList, StyleSheet} from 'react-native';
import ShowListItem from '../../../common/ShowListItem';
export const ShowList = ({tvShows, onPress, itemNumbersByLine}) => {
const renderListItem = ({item}) => (
<ShowListItem
onPress={onPress}
itemNumbersByLine={itemNumbersByLine}
{...item}
/>
);
return (
<View style={styles.wrapperStyle}>
<FlatList
key={itemNumbersByLine}
data={tvShows}
renderItem={renderListItem}
keyExtractor={item => `${item.id}`}
numColumns={itemNumbersByLine}
/>
</View>
)
};
const styles = StyleSheet.create({
wrapperStyle: {
flex: 1
}
})
|
import QbProgressBar from './QbProgressBar';
export default QbProgressBar;
|
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import toJson from 'enzyme-to-json';
import {AddProduct} from '../../components/AddProduct.js';
describe('test productCards component',()=>{
let wrapper;
// let state;
beforeEach(()=>{
// state ={
// category: "Tshirt"
// }
wrapper = shallow(<AddProduct />)
});
afterEach(()=>{
wrapper.unmount();
});
it('should not crash AddProduct',()=>{
expect(toJson(wrapper)).toMatchSnapshot();
})
it('input fileds in AddProduct',()=>{
expect(wrapper.find('input').length).toEqual(5);
})
it('Input fileds in AddProduct',()=>{
expect(wrapper.find('Input').length).toEqual(7);
})
it('Dropdown fileds in AddProduct without tshirt',()=>{
expect(wrapper.find('Dropdown').length).toEqual(2);
})
}) |
/**
* Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/ssr-apis/
*/
import React from "react"
import { AuthProvider } from "./src/context/AuthContext"
import { StoreProvider } from "./src/state/StoreWrapper"
export const wrapRootElement = ({ element }) => (
<StoreProvider>
<AuthProvider>{element}</AuthProvider>
</StoreProvider>
)
// You can delete this file if you're not using it
|
const BankingHistory = require('../models').BankingHistory;
const phoneService = require('./../services/PhoneService');
const User = require('../models').User;
const SendNotification = require('./NotificationFCMController');
const Notification = require('../models').Notification;
const constants = require('../constants');
const uploadServices = require('./../services/UploadServices');
const multiparty = require('multiparty');
const doctorWithdrawal = async function (req, res) {
res.setHeader('Content-Type', 'application/json');
try {
const body = req.body;
if (!body) {
return ReE(res, 'Bad request', 400);
}
else {
const code = Math.floor(10000 + 89999 * Math.random());
let bankingHistory = new BankingHistory({
userId: body.userId,
amount: body.amount,
remainMoney: body.remainMoney,
type: constants.BANKKING_TYPE_Withdrawal,
nameBank: body.nameBank,
accountNumber: body.accountNumber,
code: code,
});
let objBankingHistoryReturn = await bankingHistory.save();
if (objBankingHistoryReturn) {
// update remain money for doctor
//get doctor
let objDoctor = await User.findById({ _id: body.userId });
// update remain
await objDoctor.set({ remainMoney: body.remainMoney });
let objSuccess = await objDoctor.save();
// check update success - send notification
if (objSuccess) {
let errors;
let codeVerify;
[errors, codeVerify] = await to(phoneService.sendSMSVerifyBanking(objDoctor.phoneNumber, code));
if (errors) {
return ReE(res, {
status: false,
message: 'Có lỗi khi gửi message!',
}, 400);
} else {
return ReS(res, {
status: true,
message: 'Code xác minh giao dịch đã được gửi tới số điện thoại của bạn!'
, bankingId: objBankingHistoryReturn.id,
}, 200);
}
}
else {
return ReE(res, {
status: false,
message: 'Có lỗi khi tạo giao dịch!',
}, 400);
}
}
}
} catch (e) {
return ReE(res, 'Tạo yêu cầu rút tiền không thành công', 503);
}
};
module.exports.doctorWithdrawal = doctorWithdrawal;
const checkCodeVerify = async function (req, res) {
res.setHeader('Content-Type', 'application/json');
try {
let body = req.body;
if (body) {
let objAdmin = await User.findOne({ role: constants.ROLE_ADMIN });
let fullNameAdmin = objAdmin.firstName + ' ' + objAdmin.middleName + ' ' + objAdmin.lastName;
let objBanking = await BankingHistory.findById({ _id: body.id });
if ('2' === objBanking.status + '') {
return ReE(res, { message: 'Giao dịch đã được xác mminh.' }, 503);
}
if (objBanking) {
if (body.code === objBanking.code + '') {
objBanking.set({ status: constants.BANKING_HISTORY_VERIFIED });
let objBankingReturn = await objBanking.save();
if (objBankingReturn) {
// save
let notificationDoctor = {
senderId: objAdmin.id,
nameSender: fullNameAdmin,
receiverId: objBanking.userId,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objBanking.id,
message: 'Tạo yêu cầu rút tiền thành công. Yêu cầu của bạn đang trong quá trình kiểm tra và xử lí.',
};
await createNotification(notificationDoctor);
//send notification to doctor
let payLoadDoctor = {
data: {
senderId: objAdmin.id,
nameSender: fullNameAdmin,
receiverId: objBanking.userId,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objBanking.id,
message: 'Tạo yêu cầu rút tiền thành công. Yêu cầu của bạn đang trong quá trình kiểm tra và xử lí.',
createTime: Date.now().toString(),
},
};
// send
await SendNotification.sendNotification(objBanking.userId, payLoadDoctor);
/// get list admin
let listAdmin = await User.find({ role: '3' }).select('id');
//send notification to Admin
let fullNameDoctor = await getUser(objBanking.userId);
for (let objStaff of listAdmin) {
// save
let notificationAdmin = {
senderId: objBanking.userId,
nameSender: fullNameDoctor,
receiverId: objStaff.id,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objBanking.id,
message: 'Bác sỹ ' + fullNameDoctor + ' đã tạo yêu cầu rút tiền qua tài khoản ngân hàng - Chờ xử lí',
};
await createNotification(notificationAdmin);
/// send noti admin
let payLoadAdmin = {
data: {
senderId: objBanking.userId,
nameSender: fullNameDoctor,
receiverId: objStaff.id,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objBanking.id,
message: 'Bác sỹ ' + fullNameDoctor + ' đã tạo yêu cầu rút tiền qua tài khoản ngân hàng - Chờ xử lí',
createTime: Date.now().toString(),
},
};
// send
await SendNotification.sendNotification(objStaff.id, payLoadAdmin);
}
return ReS(res, { status: true, message: 'Giao dịch thành công. Chờ xử lí từ hệ thống' }, 200);
}
}
else {
let timeInputCode = objBanking.timeInputCode + 1;
objBanking.set({ timeInputCode: timeInputCode });
let objBankingReturn = await objBanking.save();
if ('4' === objBankingReturn.timeInputCode + '') {
let objUser = await User.findById({ _id: objBanking.userId });
let oldRemainMoney = objBanking.amount + objBanking.remainMoney;
objUser.set({ remainMoney: oldRemainMoney });
let objUserReturn = await objUser.save();
if (objUserReturn) {
// xóa giao dịch
BankingHistory.findByIdAndRemove({ _id: objBanking.id }, function (err, success) {
if (err) {
return ReE(res, { message: 'Có lỗi xảy ra khi xóa giao dịch' }, 503);
}
});
return ReS(res, {
status: false,
message: 'Giao dịch đã bị hủy',
oldRemainMoney: oldRemainMoney,
}, 200);
}
}
else {
return ReS(res, { message: 'Bạn đã nhập sai code' }, 503);
}
}
}
else {
return ReE(res, { message: 'Giao dịch không tồn tại.' }, 503);
}
}
else {
return ReE(res, { message: 'BAD REQUEST' }, 400);
}
}
catch (e) {
}
};
module.exports.checkCodeVerify = checkCodeVerify;
const patientRecharge = async function (req, res) {
};
module.exports.patientRecharge = patientRecharge;
const getHistoryBanking = async function (req, res) {
try {
if (req.query.pageSize && req.query.page) {
let pageSize = 0;
let page = 0;
if (req.query.pageSize) {
pageSize = req.query.pageSize * 1;
}
if (req.query.page) {
page = req.query.page * 1;
}
if (req.params.userId) {
let listBankingHistory = await BankingHistory.find({
userId: req.params.userId,
deletionFlag: false,
})
.select('-timeInputCode -code')
.sort([['updatedAt', -1]])
.limit(pageSize)
.skip(pageSize * page);
if (listBankingHistory) {
return ReS(res, {
status: true,
message: 'Danh sách giao dịch ngân hàng.',
listBankingHistory: listBankingHistory,
}, 200);
}
else {
return ReE(res, { message: 'Không tìm thấy lịch sử giao dịch' }, 400);
}
}
else {
return ReE(res, { message: 'BAD REQUEST' }, 400);
}
}
else {
if (req.params.userId) {
let listBankingHistory = await BankingHistory.find({
userId: req.params.userId,
deletionFlag: false,
})
.select('-timeInputCode -code')
.sort([['createdAt', -1]]);
if (listBankingHistory) {
return ReS(res, {
status: true,
message: 'Danh sách giao dịch ngân hàng.',
listBankingHistory: listBankingHistory,
}, 200);
}
else {
return ReE(res, { message: 'Không tìm thấy lịch sử giao dịch' }, 400);
}
}
else {
return ReE(res, { message: 'BAD REQUEST' }, 400);
}
}
}
catch (e) {
return ReE(res, { message: 'ERROR' }, 400);
}
};
module.exports.getHistoryBanking = getHistoryBanking;
const getListBankingPendingVerify = async function (req, res) {
try {
let objListPending = await BankingHistory.find({
status: constants.BANKING_HISTORY_VERIFIED,
}).sort([['createdAt', 1]]);
if (objListPending) {
return ReS(res, {
status: true,
message: 'Danh sách giao dịch chờ xử lí.',
objListPending: objListPending,
}, 200);
}
else {
return ReE(res, { message: 'ERROR' }, 503);
}
}
catch (e) {
return ReE(res, { message: 'ERROR' }, 400);
}
};
module.exports.getListBankingPendingVerify = getListBankingPendingVerify;
const getDetailHistoryById = async function (req, res) {
try {
if (req.params.id) {
let objDetail = await BankingHistory.findById({ _id: req.params.id }).populate(
{
path: 'userId',
select: 'firstName middleName lastName avatar remainMoney role',
});
if (objDetail) {
return ReS(res, {
status: true,
message: 'Chi tiết giao dịch.',
objDetail: objDetail,
}, 200);
}
else {
return ReE(res, { message: 'NOT FOUND' }, 404);
}
}
else {
return ReE(res, { message: 'BAD REQUEST' }, 400);
}
}
catch (e) {
return ReE(res, { message: 'ERROR' }, 503);
}
};
module.exports.getDetailHistoryById = getDetailHistoryById;
const handleBankingHistory = async function (req, res) {
try {
let imageEvidence = 'http://dnr-live.ru/wp-content/uploads/2017/03/noavatar.png';
const form = new multiparty.Form();
form.parse(req, async (error, fields, files) => {
let body = JSON.parse(fields.body[0]);
if (error) throw new Error(error);
// get id Admin
let handler = req.user.id;
// get id Banking
let idBanking = req.params.id;
// get note
let note = body.note;
//get status
let status = body.status;
// get object Admin
let objAdminHandler = await User.findById({ _id: handler });
// get full name admin
let fullNameAdmin = objAdminHandler.firstName + ' ' + objAdminHandler.middleName + ' ' + objAdminHandler.lastName;
// get object Banking
let objDetail = await BankingHistory.findById({ _id: idBanking });
// upload image
if (files && files.evidence) {
let [error, imageURL] = await to(uploadServices.uploadService(files.evidence[0]));
if (error) {
return ReE(res, 'Xử lí yêu cầu không thành công, vui lòng thử lại.', 400);
}
// get link image
imageEvidence = imageURL;
}
if (objDetail) {
if (status === constants.BANKING_HISTORY_DONE) {
// set data to update banking
objDetail.set({
status: constants.BANKING_HISTORY_DONE,
evidence: imageEvidence,
handler: handler,
note: note,
});
// save banking
let objDetailReturn = await objDetail.save();
if (objDetailReturn) {
// save notification
let notificationDoctor = {
senderId: objAdminHandler.id,
nameSender: fullNameAdmin,
receiverId: objDetailReturn.userId,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objDetailReturn.id,
message: 'Yêu cầu rút tiền đã được xử lí. Số tiền: ' + objDetailReturn.amount + ' VND đã được chuyển tới STK: ' + objDetailReturn.accountNumber,
};
await createNotification(notificationDoctor);
//send notification to doctor
let payLoadDoctor = {
data: {
senderId: objAdminHandler.id,
nameSender: fullNameAdmin + '',
receiverId: objDetailReturn.userId,
type: constants.NOTIFICATION_TYPE_BANKING + '',
storageId: objDetailReturn.id,
message: 'Yêu cầu rút tiền đã được xử lí. Số tiền: ' + objDetailReturn.amount + ' VND đã được chuyển tới STK: ' + objDetailReturn.accountNumber,
createTime: Date.now().toString(),
},
};
// send
await SendNotification.sendNotification(objDetailReturn.userId, payLoadDoctor);
return ReS(res, {
success: true,
message: 'Update trạng thái giao dịch thành công.',
}, 200);
}
else {
return ReE(res, { message: 'ERROR SAVE' }, 503);
}
}
else if (status === constants.BANKING_HISTORY_FAILED) {
// set data to update banking
objDetail.set({
status: constants.BANKING_HISTORY_FAILED,
evidence: imageEvidence,
handler: handler,
note: note,
});
// save banking
let objDetailReturn = await objDetail.save();
// trả lại tiền cho bác sỹ
let amountAdmin = objDetail.amount;
User.findByIdAndUpdate({ _id: objDetail.userId }, { $inc: { remainMoney: amountAdmin } }, { lean: true }, function (err, resUser) {
if (err) {
return ReE(res, {message: 'ERROR SAVE'}, 503);
}
//send notification to doctor
let payLoadDoctor = {
data: {
senderId: objAdminHandler.id,
nameSender: fullNameAdmin + '',
receiverId: objDetailReturn.userId,
type: constants.NOTIFICATION_TYPE_BANKING + '',
storageId: objDetailReturn.id,
message: 'Yêu cầu rút tiền thất bại.Hoàn trả: '+objDetail.amount+'VND. Lý do: '+note,
remainMoney: resUser.remainMoney+'',
createTime: Date.now().toString(),
},
};
// send
SendNotification.sendNotification(objDetailReturn.userId, payLoadDoctor);
});
if (objDetailReturn) {
// save notification
let notificationDoctor = {
senderId: objAdminHandler.id,
nameSender: fullNameAdmin,
receiverId: objDetailReturn.userId,
type: constants.NOTIFICATION_TYPE_BANKING,
storageId: objDetailReturn.id,
message: 'Yêu cầu rút tiền thất bại.Hoàn trả: '+objDetail.amount+'VND. Lý do: '+note,
};
await createNotification(notificationDoctor);
return ReS(res, {
success: true,
message: 'Update trạng thái giao dịch thành công.',
}, 200);
}
else {
return ReE(res, {message: 'ERROR SAVE'}, 503);
}
}
}
else {
return ReE(res, {message: 'NOT FOUND BANKING REQUEST'}, 404);
}
});
}
catch (e) {
return ReE(res, {message: 'ERROR'}, 503);
}
};
module.exports.handleBankingHistory = handleBankingHistory;
const removeLogic = async function (req, res) {
BankingHistory.findByIdAndUpdate(req.params.id, { $set: { deletionFlag: '1' } }, function (err, removeLogic) {
res.send(removeLogic);
});
};
module.exports.removeLogic = removeLogic;
async function getUser (userId) {
let fullName;
let objUser = await User.findById({ _id: userId });
if (objUser) {
fullName = ' ' + objUser.firstName + ' ' + objUser.middleName + ' ' + objUser.lastName + '';
}
return fullName;
}
const createNotification = async function (body) {
try {
let notification = Notification({
senderId: body.senderId,
nameSender: body.nameSender,
receiverId: body.receiverId,
type: body.type,
storageId: body.storageId,
message: body.message,
});
await notification.save();
}
catch (e) {
}
};
const getAllBanking = async function (req, res) {
try {
const bankHistories = await BankingHistory.find({ deletionFlag: { $ne: true } }).populate(
{
path: 'userId',
select: 'firstName middleName lastName avatar remainMoney role',
},
);
if (bankHistories) {
return ReS(res, { message: 'Lấy danh sách banking thành công', listBanking: bankHistories }, 200);
}
else {
return ReE(res, { message: 'Lấy danh sách banking không thành công' }, 404);
}
} catch (e) {
return ReE(res, { message: 'Lấy danh sách banking không thành công' }, 404);
}
};
module.exports.getAllBanking = getAllBanking;
|
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const QuestionSchema = Schema({
number: {
type: Number,
required: true
},
type: {
type: String,
required: true
},
question: {
type: String,
required: true
},
audio_url: {
type: String
},
reading: {
type: String
},
time: {
type: Number
},
created: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Task', QuestionSchema);
|
var Intent = require('../lib/im/im').Intent,
intent = new Intent('imIntent', 'this is a test');
intent.send('imReciver', process.argv[2]); |
/**
* @fileoverview Appears elements while scrolling.
*/
goog.provide('morning.ui.AppearEffect');
goog.require('goog.async.Delay');
goog.require('goog.async.Throttle');
goog.require('goog.dom.dataset');
goog.require('goog.ui.Component');
/**
* Appear effect
*
* @constructor
* @extends {goog.ui.Component}
*/
morning.ui.AppearEffect = function()
{
goog.base(this);
/**
* Scroll offset after which elements is appears
* (Element Position + Scroll Offset = Visible).
*
* @type {number}
* @private
*/
this.offset_ = 100;
/**
* @type {number}
* @private
*/
this.offsetRatio_ = 0;
/**
* Defines whether element is appeared.
*
* @type {boolean}
* @private
*/
this.isVisible_ = false;
/**
* Position and size of the element in the document
* @type {goog.math.Rect}
* @protected
*/
this.bounds = null;
/**
* Size of the screen.
*
* @type {goog.math.Size}
* @protected
*/
this.viewportSize = goog.dom.getViewportSize();
/**
* Defines whether element should appear once.
*
* @type {boolean}
* @private
*/
this.isOnce_ = false;
/**
* @type {boolean}
* @private
*/
this.isOnceAppeared_ = false;
/**
* @type {goog.async.Delay}
* @protected
*/
this.updatePositionDelay = new goog.async.Delay(this.updatePosition,
300, this);
this.registerDisposable(this.updatePositionDelay);
/**
* Update css class with a certain delay.
*
* @type {goog.async.Delay}
* @private
*/
this.updateClsDelay_ = null;
this.registerDisposable(this.updateClsDelay_);
};
goog.inherits(morning.ui.AppearEffect, goog.ui.Component);
/**
* @inheritDoc
*/
morning.ui.AppearEffect.prototype.decorateInternal = function(el)
{
goog.base(this, 'decorateInternal', el);
var offset = goog.dom.dataset.get(el, 'offset');
if (offset)
{
this.offset_ = parseFloat(offset);
if (this.offset_ < 1 && this.offset_ > 0)
{
this.offsetRatio_ = this.offset_;
this.offset_ *= goog.dom.getViewportSize().height;
}
}
var delay = goog.dom.dataset.get(el, 'delay');
if (delay)
{
goog.dispose(this.updateClsDelay_);
this.updateClsDelay_ = new goog.async.Delay(this.updateVisibility,
Number(delay), this);
this.registerDisposable(this.updateClsDelay_);
}
this.isOnce_ = goog.dom.classlist.contains(el, 'once');
};
/** @inheritDoc */
morning.ui.AppearEffect.prototype.enterDocument = function()
{
goog.base(this, 'enterDocument');
this.getHandler().
listen(window, goog.events.EventType.SCROLL, this.handleScroll).
listen(window, goog.events.EventType.RESIZE, this.handleResize_);
this.updatePosition();
this.updatePositionDelay.start();
goog.Timer.callOnce(this.updatePosition, 2000, this);
this.handleScroll(null);
};
/**
* Handles browser scroll events.
*
* @param {goog.events.Event} e
* @protected
*/
morning.ui.AppearEffect.prototype.handleScroll = function(e)
{
if (this.isOnceAppeared_ && this.isOnce_)
{
return;
}
var docScroll = goog.dom.getDocumentScroll();
var viewportSize = this.viewportSize;
var isVisible = this.bounds.top < docScroll.y + viewportSize.height - this.offset_;
this.setVisible(isVisible);
};
/**
* @param {goog.events.Event} e
* @private
*/
morning.ui.AppearEffect.prototype.handleResize_ = function(e)
{
if (this.offsetRatio_ > 0)
{
this.offset_ = goog.dom.getViewportSize().height * this.offsetRatio_;
}
this.updatePositionDelay.start();
};
/**
* Returns true if element is visible currently.
*
* @return {boolean}
*/
morning.ui.AppearEffect.prototype.isVisible = function()
{
return this.isVisible_;
};
/**
* Sets whether element is visible.
*
* @param {boolean} isVisible
*/
morning.ui.AppearEffect.prototype.setVisible = function(isVisible)
{
if (isVisible != this.isVisible_)
{
this.isVisible_ = isVisible;
if (this.updateClsDelay_ && !this.updateClsDelay_.isActive())
{
this.updateClsDelay_.start();
}
else
{
this.updateVisibility();
}
}
};
/**
*/
morning.ui.AppearEffect.prototype.updatePosition = function()
{
if (this.getElement())
{
this.bounds = goog.style.getBounds(this.getElement());
}
this.viewportSize = goog.dom.getViewportSize();
};
/**
* Updates class depending on visibility of the element.
*/
morning.ui.AppearEffect.prototype.updateVisibility = function()
{
goog.dom.classlist.enable(this.getElement(), 'appear', this.isVisible_);
if (this.isVisible_ && this.isOnce_)
{
this.isOnceAppeared_ = true;
}
};
/**
* Register this control so it can be created from markup.
*/
goog.ui.registry.setDecoratorByClassName(
'appear-effect',
function() {
return new morning.ui.AppearEffect();
}
);
|
/*Creacion del controller para las publicaciones*/
var publicationN = require('../models/PublicationModel').Publication;
var imagesP = require('../models/PublicationModel').imgpublic;
exports.Publications = function(req, res, next){
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
try{
/*Public.find({}, function(err, docs){
if(err){
console.log('error' + err);
}else{
res.json(docs);
}
});*/
res.json('funciona');
}catch(err){
console.log('error' + err);
}
}
exports.load = function(req, res, next){
try{
}catch(err){
}
}
exports.save = function(req, res, next){
/*res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);*/
try{
var publication = new publicationN({
user: req.body.idUsr,
asunto: req.body.asunto,
nombreMascota: req.body.petName,
edad : req.body.edad,
DuenioActual: req.body.dueno,
Descripcion: req.body.descripcion
});
console.log(publication);
//console.log(req.body.imgP);
/*console.log(publication.idUsr);
console.log(publication.asunto);
console.log(publication.nombreMascota);
console.log(publication.edad);
console.log(publication.DuenioActual);
console.log(publication.Descripcion);
console.log('============================');
/*console.log(req.body.imgP);*/
res.json('si');
/*publication.save(function(err){
if(err){
console.log('error' + err);
}else{
res.json(true);
}
});*/
}catch(err){
}
}
function upload_img(){
} |
const tobuyItemController = require("../controllers/tobuyitem.controller");
const router = require("express").Router();
const verify = require("../auth/verifiedToken");
router.get(
"/api/tobuys/:uniqueId",
verify,
tobuyItemController.getAllTobuyItems
);
router.post("/api/tobuy", verify, tobuyItemController.addTobuyitem);
router.delete(
"/api/tobuy/:uniqueId",
verify,
tobuyItemController.deleteTobuyItem
);
module.exports = router;
|
const { CONFLICT } = require('http-status');
const PublicError = require('./PublicError');
class ConflictError extends PublicError {
constructor(type = 'conflict', message = 'Conflict') {
super(CONFLICT, type, message);
}
}
module.exports = ConflictError;
|
export function imgUrl(id) {
return 'http://y.gtimg.cn/music/photo_new/T002R300x300M000' + id+ '.jpg?max_age=2592000'
}
|
var s,
CandidateSkills = {
settings: {
updateSkill_cb: $(".candidate_skill"),
},
init: function () {
console.log("_init");
s = this.settings;
this.bindUIActions();
this.datatableActions();
this.datetimePickerActions();
},
bindUIActions: function () {
s.updateSkill_cb.on("click", function (e) {
var element = $(this);
console.log(element);
var candidateId = element.attr('candidate');
var skillId = element.attr('id');
var data = JSON.stringify({
'candidateId': candidateId,
'skillId': skillId
});
console.log(data);
$.ajax({
type: "POST",
url: "/api/candidates/addskill",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
},
datatableActions: function () {
$('.search-skill').on('click', function () {
var search = $('input[type=search]');
search.focusin();
console.log();
var temp = search.val() + $('.search-skill').data('value') + ' ';
search.val(temp);
search.focus();
search.keypress();
});
},
datetimePickerActions: function () {
}
};
(function () {
CandidateSkills.init();
})(); |
// components/hot-list/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
hotlist:Object
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
ToThemeE(event){
wx.navigateTo({
url: `/pages/theme/index?tName=t-5`
})
},
GotoDetail(event){
const pid = event.currentTarget.dataset.pid
wx.navigateTo({
url: `/pages/detail/index?pid=${pid}`
})
}
}
})
|
'use strict';
const config =require("./config");
const AppSession=require('./appsessdbschema');
const utils={
fillWebSession:function(request,userData) {
request.session.user=userData;
if(userData.rememberMe==true){
var thirtyDays = 30*24*60*60*1000;
request.session.cookie.expires = new Date(Date.now() + thirtyDays);
}
},
fillAppSession:function(userData,responseObject,response){
userData._id=undefined; //prevent duplicate record error
userData=userData.toObject();
userData.sessionid=responseObject.sessionid;
AppSession.create(userData,function(error,result){
if(error){
console.log("Error Occured",error);
}
else{
response.send(responseObject);
}
});
},
fillSession:function(request,response,result,responseObject){
//data is freezed object so no issue till not adding any new property
var userData=result;
userData.password1=undefined;
userData.salt=undefined;
userData.passwordtokenstamp=undefined;
userData.emailactivationtoken=undefined;
userData.forgotpasswordtoken=undefined;
userData.mobileverificationcode=undefined;
userData.updated=undefined;
userData.facebookAccessToken=undefined;
if(request.body.appCall===true){
if(request.body.sessionid!=undefined){
AppSession.find({sessionid:request.body.sessionid}).remove(function(error,result){
if(error){
console.log(error);
}
});
}
var randomString=this.randomStringGenerate(32);
responseObject.sessionid=randomString+userData.username;
responseObject.userData=userData;
this.fillAppSession(userData,responseObject,response);
}
else{
this.fillWebSession(request,userData);
responseObject.userData=userData;
response.send(responseObject);
}
},
webSessionDestroy:function(request,response){
request.session.destroy(function(error) {
if(error){
console.log(error);
}
else{
response.json({message:"success"});
}
});
},
appSessionDestroy:function(id,response){
AppSession.find({sessionid:id}).remove(function(error,result){
if(error){
console.log(error);
}
else{
response.json({message:"success"});
}
});
},
sendMail:function(To,Subject,EmailText,Html_Body){
const nodeMailer = require("nodemailer");
var URL="smtps://"+config.SMTPS_EMAIL+":"+config.SMTPS_PASSWORD+"@"+config.SMTPS_URL;
var transporter = nodeMailer.createTransport(URL);
// setup e-mail data with unicode symbols
var mailOptions = {
from: config.COMPANY_NAME+ '<h='+config.SMTPS_EMAIL+'>' , // sender address
to: To, // list of receivers
subject: Subject, // Subject line
text: EmailText, // plaintext body
html: Html_Body // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
},
randomStringGenerate:function(x){
const randomString = require("randomstring");
return randomString.generate(x);
},
sendSms:function(number,body){
const twilio = require("twilio");
var accountSid = config.TWILIO_ACCOUNT_SID;
var authToken = config.TWILIO_AUTH_TOKEN;
var client = new twilio.RestClient(accountSid, authToken);
client.messages.create({
body: body,
to: number, // Text this number
from: config.VALID_TWILIO_NUMBER, // From a valid Twilio number
}, function(err, message) {
if(err){
console.log(err);
}
else{
console.log(message.sid);
}
});
},
};
module.exports=utils; |
/*
* @Author: Waylon
* @Date: 2019-05-25 20:24:13
* @Last Modified by: Waylon
* @Last Modified time: 2019-05-26 14:47:18
*/
// Set数据结构
// 添加元素
{
// 声明一个set
let list = new Set();
// add方法向Set集合中添加数据
list.add(5);
list.add(7);
//size 相当于数组中的length
console.log('size',list.size);//size 2
}
{
let arr = [1,2,3,4,5];
//set将arr数组转换成list Set 集合
let list = new Set(arr);
console.log('size',list.size);//size 5
}
// Set数据结构中的数据必须为唯一的
{
let list = new Set();
list.add(1);
list.add(2);
list.add(1);//不会报错,但是不会生效,常用于组去重
console.log(list);//Set(2) {1, 2}
// 数组去重
// 但是在进行的时候不会做数据类型的转换
// 因此在进行转换时一定要注意数据类型一致
let arr=[1,2,3,1,2];
let list2=new Set(arr);
console.log('unique',list2);//unique Set(3) {1, 2, 3}
}
// Set数据结构中常用的方法
{
let arr = ['add','delete','clear','has'];
let list = new Set(arr);
// 判断是否有
console.log('has',list.has('add'));//has true
// 删除
console.log('delete',list.delete('add'),list);//delete true Set(3) {"delete", "clear", "has"}
// 清空
list.clear();
console.log('list',list);//list Set(0) {}
}
// Set的遍历
{
let arr = ['add','delete','clear','has'];
let list = new Set(arr);
// 遍历key
for(let key of list.keys()){
console.log('keys',key);
/*
keys add
keys delete
keys clear
keys has
*/
}
// 变量值
for(let value of list.values()){
console.log('value',value);
/*
value add
value delete
value clear
value has
*/
}
// 变量值
for(let value of list){
console.log('value',value);
/*
value add
value delete
value clear
value has
*/
}
// 遍历值和key
for(let [key,value] of list.entries()){
console.log('entries',key,value);
/*
entries add add
entries delete delete
entries clear clear
entries has has
*/
}
// forEach
list.forEach(function(item){console.log(item);})
/*
add
delete
clear
has
*/
}
// WeakSet数据类型只能是对象
// 是一个弱引用
{
let weakList = new WeakSet();
let arg={};
weakList.add(arg);
// weakList.add(2);报错,不支持的类型,只支持对象类型
//没有clear方法,没有size属性,不能遍历,其他方法与Set相似
console.log('weakList',weakList);//weakList WeakSet {{…}}
}
// Map对象
// 第一种定义方法
{
let map = new Map();
let arr = ['123'];
// map添加元素,是一个key,value
map.set(arr,456);
// map.get()获取值
console.log('map',map,map.get(arr));//map Map(1) {Array(1) => 456} 456
}
// 第二种定义方法
{
let map = new Map([['a',123],['b',456]]);
console.log('map args',map);//map args Map(2) {"a" => 123, "b" => 456}
//常用的方法,与Set相似
console.log('size',map.size);//size 2
console.log('delete',map.delete('a'),map);//delete true Map(1) {"b" => 456}
console.log('clear',map.clear(),map);///clear undefined Map(0) {}
// 遍历与Set相似
}
//WeakMap的key只能是对象
//没有clear方法,没有size属性,不能遍历,其他方法与Set相似
{
let weakmap = new WeakMap();
let o={};
weakmap.set(o,123);
console.log(weakmap.get(o));//123
}
// map与数组比较
{
// 数据结构横向对比,增删改查
let map=new Map();
let array=[];
// 增
map.set('t',1);
array.push({t:1});
console.log('map-array',map,array);//map-array Map(1) {"t" => 1} [{…0: {t: 1}}]
// 查
// map返回布尔值,array返回当前对象
let map_exist=map.has('t');
let array_exist=array.find(item=>item.t);
console.log('map-array',map_exist,array_exist);//map-array true {t: 1}
// 改
map.set('t',2);
array.forEach(item=>item.t?item.t=2:'');
console.log('map-array-modify',map,array);
//map-array-modify Map(1) {"t" => 2} [{0: {t: 2}}]
// 删除
map.delete('t');
let index=array.findIndex(item=>item.t);
array.splice(index,1);
console.log('map-array-empty',map,array);//map-array-empty Map(0) {} []
}
// set与数组的比较
{
let set = new Set();
let array=[]
// 增
set.add({t:1});
array.push({t:1});
console.log('set-array',set,array);//set-array Set(1) {{…}}size: (...)__proto__: Set[[Entries]]: Array(1)0: Objectlength: 1 [{…}]
// 查
let set_exist=set.has({t:1});
let array_exist=array.find(item=>item.t);
console.log('set-array',set_exist,array_exist);//set-array false {t: 1}
// 改
set.forEach(item=>item.t?item.t=2:'');
array.forEach(item=>item.t?item.t=2:'');
console.log('set-array-modify',set,array);///set-array-modify Set(1) {{…}} [{…}]
// 删除
set.forEach(item=>item.t?set.delete(item):'');
let index=array.findIndex(item=>item.t);
array.splice(index,1);
console.log('set-array-empty',set,array);//set-array-empty Set(0) {} []
}
{
// map,set,object对比
let item={t:1};
let map=new Map();
let set=new Set();
let obj={};
// 增
map.set('t',1);
set.add(item);
obj['t']=1;
console.info('map-set-obj',obj,map,set);//map-set-obj {t: 1} Map(1) {"t" => 1} Set(1) {{…}}
// 查
console.info({
map_exist:map.has('t'),
set_exist:set.has(item),
obj_exist:'t' in obj
})//{map_exist: true, set_exist: true, obj_exist: true}
// 改
map.set('t',2);
item.t=2;
obj['t']=2;
console.info('map-set-obj-modify',obj,map,set);//map-set-obj-modify {t: 2} Map(1) {"t" => 2} Set(1) {{…}}
// 删除
map.delete('t');
set.delete(item);
delete obj['t'];
console.info('map-set-obj-empty',obj,map,set);//map-set-obj-empty {} Map(0) {} Set(0) {}
}
// 总结:
// 在涉及数据结构,优先使用map,如果考虑唯一用set,放弃传统的obj和数组 |
const express = require('express');
const pool = require('../modules/pool');
const router = express.Router();
const moment = require('moment');
// get all tasks
router.get('/', (req, res) => {
const queryText = `SELECT * FROM "task"`;
pool.query(queryText)
.then((result) => {
res.send(result.rows);
console.log(`recieved tasks `, result.rows);
})
.catch((err) => {
console.log('Error completing SELECT task query', err);
res.sendStatus(500);
});
});
// insert a new task
router.post('/', async (req, res) => {
const client = await pool.connect()
let newTask = req.body;
let targetList = req.body.targetList;
let constraintList = req.body.constraintList;
console.log(`newTask `, newTask);
let queryText = `INSERT INTO "task" ("task_name", "description", "create_date", "active", "creator")
VALUES ($1, $2, $3, $4, $5) RETURNING "task_id";`;
let queryValues = [newTask.name, newTask.description, moment(), true, 1];
try {
await client.query('BEGIN');
let result = await pool.query(queryText, queryValues);
let task_id = result.rows[0].task_id;
console.log(`returned id `, task_id);
res.sendStatus(201);
console.log(`targetList`, targetList);
console.log(`constraintLIst`, constraintList);
queryText = `INSERT INTO "constraint" ("task_id", "constraint_table", "constraint_column", "constraint_comparison")
VALUES ($1, $2, $3, $4);`
for(constraint of constraintList){
queryValues = [task_id, constraint.constraint_table, constraint.constraint_column, constraint.constraint_comparison];
await pool.query(queryText, queryValues);
}
queryText = `INSERT INTO "target" ("task_id", "target_table", "target_column", "modification_value", "modification")
VALUES ($1, $2, $3, $4, $5);`
for(target of targetList){
queryValues = [task_id, target.target_table, target.target_column, target.modification_value, target.modification];
await pool.query(queryText, queryValues);
}
} catch(error){
await client.query('ROLLBACK')
throw error
} finally{
client.release()
}
});
// get all targets
router.get('/target', (req, res) => {
const queryText = `SELECT * FROM "target"`;
pool.query(queryText)
.then((result) => {
res.send(result.rows);
console.log(`recieved targets `, result.rows);
})
.catch((err) => {
console.log('Error completing SELECT target query', err);
res.sendStatus(500);
});
});
// update target modificaiton_value
router.put('/target/value', (req, res) => {
const target = req.body;
console.log(`target`, target);
const queryText = `UPDATE "target" SET "modification_value" = $1 WHERE "target_id"=$2`;
const queryValue = [target.modification_value, target.target_id];
pool.query(queryText, queryValue)
.then((result) => {
res.sendStatus(200);
console.log(`updated target modificaiton_value `, queryValue);
})
.catch((err) => {
console.log('Error completing UPDATE target query', err);
res.sendStatus(500);
});
});
// get all constraints
router.get('/constraint', (req, res) => {
const queryText = `SELECT * FROM "constraint"`;
pool.query(queryText)
.then((result) => {
res.send(result.rows);
console.log(`recieved constraints `, result.rows);
})
.catch((err) => {
console.log('Error completing SELECT constraint query', err);
res.sendStatus(500);
});
});
router.delete('/:id', (req, res) => {
let queryText = `DELETE FROM "task" WHERE "task_id"=$1;`;
let queryValues = [req.params.id];
pool.query(queryText, queryValues)
.then((result) => {
res.sendStatus(200);
console.log(`DELETE task`, queryValues);
})
.catch((err) => {
console.log('Error completing DELETE task query', err);
res.sendStatus(500);
});
})
router.put('/:id', (req, res) => {
let queryText = `UPDATE "task" SET "active"='false' WHERE "task_id"=$1;`;
let queryValues = [req.params.id];
pool.query(queryText, queryValues)
.then((result) => {
res.sendStatus(200);
console.log(`update task`, queryValues);
})
.catch((err) => {
console.log('Error completing update task query', err);
res.sendStatus(500);
});
})
module.exports = router; |
import React from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import colors from '../../Constants/colors';
import AppButton from './AppButton';
const CommonCell = ({
style,
Title,
Description,
onPressAccept,
onLongPress,
isPending,
onPressDecline,
State,
onPress,
}) => {
return (
<TouchableOpacity
onPress={onPress}
style={{...styles.container, ...style}}
onLongPress={onLongPress}
>
<View style={styles.containerText}>
<Text style={styles.text}>{Title}</Text>
</View>
<View style={{...styles.bottomContainer, width: isPending ? '40%' : '100%'}}>
<View style={{...styles.descriptionContainer, width: State ? '50%' : '100%'}}>
<Text style={styles.descriptionLabel}>Описание</Text>
<Text style={styles.description}>{Description || '-'}</Text>
</View>
{State &&
<View style={styles.stateContainer}>
<Text style={{...styles.descriptionLabel, marginLeft: 5}}>Состояние</Text>
<View style={styles.tagView}>
<Text style={{...styles.description, color: '#fff'}}>{State.Title}</Text>
</View>
</View>}
</View>
{isPending &&
<View>
<AppButton
textStyle={{marginVertical: 10, marginHorizontal: 10}}
onPress={onPressAccept}
style={{position: 'absolute', right: 105, bottom: 5}}
text="Принять"
/>
<AppButton
textStyle={{marginVertical: 10, marginHorizontal: 10}}
isDestructive={true}
style={{position: 'absolute', right: 0, bottom: 5}}
onPress={onPressDecline}
text="Отклонить"
/>
</View>}
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
titleCard: {
marginBottom: 10,
backgroundColor: '#FFF',
elevation: 3,
marginHorizontal: 10,
borderRadius: 5,
flexDirection: 'column',
justifyContent: 'center',
},
tagView: {
marginLeft: 5,
marginTop: 5,
paddingHorizontal: 5,
width: '100%',
backgroundColor: '#03bafc',
borderRadius: 6,
alignItems: 'center',
},
descriptionLabel: {
color: colors.brownGrey,
fontSize: 12,
marginTop: 5,
},
bottomContainer: {
flexDirection: 'row',
},
buttonContainer: {
position: 'absolute',
flexDirection: 'row',
right: 10,
bottom: 0,
},
container: {
marginBottom: 10,
backgroundColor: '#FFF',
elevation: 3,
marginHorizontal: 10,
paddingHorizontal: 10,
borderRadius: 5,
flexDirection: 'column',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
},
text: {
fontSize: 18,
fontWeight: 'bold',
marginTop: 10,
marginBottom: 10,
},
containerText: {
borderColor: colors.charcoalGrey10,
borderBottomWidth: 1,
},
descriptionContainer: {
marginBottom: 10,
},
description: {
fontSize: 16,
},
icon: {
position: 'absolute',
bottom: 5,
right: 5,
},
stateContainer: {
borderLeftWidth: 1,
borderColor: colors.charcoalGrey10,
},
stateDescription: {
marginLeft: 5,
},
});
export default CommonCell;
|
/**
* 화면 초기화 - 화면 로드시 자동 호출 됨
*/
function _Initialize() {
// 단위화면에서 사용될 일반 전역 변수 정의
// $NC.setGlobalVar({ });
// 그리드 초기화
grdMasterInitialize();
grdDetailInitialize();
// 조회조건 - 물류센터 세팅
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CSUSERCENTER",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_CENTER_CD: "%"
})
}, {
selector: "#cboQCenter_Cd",
codeField: "CENTER_CD",
nameField: "CENTER_NM",
onComplete: function() {
$NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD);
}
});
$("#btnQBu_Cd").click(showUserBuPopup);
$("#btnConfirm").click(procClosing);
// 사업부코드/명에 초기값 설정
$NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD);
$NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM);
$NC.setInitMonthPicker("#dtpClose_Month", $NC.addMonth($NC.G_USERINFO.LOGIN_DATE, -1));
$NC.setInitDatePicker("#dtpProtect_date", $NC.addMonth($NC.G_USERINFO.LOGIN_DATE, -1), "L");
}
function _OnLoaded() {
// 스플리터 초기화
$NC.setInitSplitter("#divMasterView", "h", 350, 250);
}
function _SetResizeOffset() {
// 화면 리사이즈 Offset 계산
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight;
$NC.G_OFFSET.closeProcHeight = $("#divProc").outerHeight() + $NC.G_LAYOUT.header;
}
/**
* Window Resize Event - Window Size 조정시 호출 됨
*/
function _OnResize(parent) {
var clientWidth = parent.width() - $NC.G_LAYOUT.border1;
var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight;
// Splitter 컨테이너 크기 조정
var container = $("#divMasterView");
$NC.resizeContainer(container, clientWidth, clientHeight);
var splitTopHeight = $("#grdMaster").parent().height();
var height = splitTopHeight - $NC.G_LAYOUT.header - $NC.G_OFFSET.closeProcHeight;
// Grid 사이즈 조정
$NC.resizeGrid("#grdMaster", clientWidth, height);
var splitBottomHeight = $("#grdDetail").parent().height();
height = splitBottomHeight - $NC.G_LAYOUT.header;
// Grid 사이즈 조정
$NC.resizeGrid("#grdDetail", clientWidth, height);
}
/**
* 검색항목 값 변경시 화면 클리어
*/
function onChangingCondition() {
// 전역 변수 값 초기화
$NC.clearGridData(G_GRDMASTER);
$NC.clearGridData(G_GRDDETAIL);
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
function _OnConditionChange(e, view, val) {
var id = view.prop("id").substr(4).toUpperCase();
// 사업부 Key 입력
switch (id) {
case "BU_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: val
};
O_RESULT_DATA = $NP.getUserBuInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onUserBuPopup(O_RESULT_DATA[0]);
} else {
$NP.showUserBuPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onUserBuPopup, onUserBuPopup);
}
return;
}
onChangingCondition();
}
function _OnInputChange(e, view, val) {
var id = view.prop("id").substr(3).toUpperCase();
switch (id) {
case "CLOSE_MONTH":
$NC.setValueMonthPicker(view, val, "마감월을 정확히 입력하십시오.");
break;
case "PROTECT_DATE":
$NC.setValueDatePicker(view, val, "보안설정일자를 정확히 입력하십시오.", "L");
break;
}
}
/**
* Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨
*/
function _Inquiry() {
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDMASTER);
$NC.setInitGridVar(G_GRDDETAIL);
// 조회조건 체크
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(CENTER_CD)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var BU_CD = $NC.getValue("#edtQBu_Cd", true);
BU_CD = $NC.isNull(BU_CD) ? "%" : BU_CD;
// 파라메터 세팅
G_GRDMASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_USER_ID: $NC.G_USERINFO.USER_ID
});
// 데이터 조회
$NC.serviceCall("/LF01020E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster);
$NC.setValue("#all_check_yn", "N"); // 하단그리드 헤더의 전체선택 체크 박스 선택해제
}
/**
* New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨
*/
function _New() {
}
/**
* Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨
*/
function _Save() {
}
/**
* Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨
*/
function _Delete() {
}
/**
* Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨
*/
function _Cancel() {
}
/**
* Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨
*
* @param printIndex
* 선택한 출력물 Index
*/
function _Print(printIndex, printName) {
}
function grdMasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "CHECK_YN",
field: "CHECK_YN",
minWidth: 30,
width: 30,
sortable: false,
cssClass: "align-center",
formatter: Slick.Formatters.CheckBox,
editor: Slick.Editors.CheckBox,
editorOptions: {
valueChecked: "Y",
valueUnChecked: "N"
}
});
$NC.setGridColumn(columns, {
id: "CUST_NM",
field: "CUST_NM",
name: "위탁사명",
minWidth: 150
});
$NC.setGridColumn(columns, {
id: "BU_CD",
field: "BU_CD",
name: "사업부",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_NM",
field: "BU_NM",
name: "사업부명",
minWidth: 100,
});
$NC.setGridColumn(columns, {
id: "CLOSE_LEVEL_D",
field: "CLOSE_LEVEL_D",
name: "정산레벨",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "CLOSE_DAY",
field: "CLOSE_DAY",
name: "정산마감일",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "PROTECT_DATE",
field: "PROTECT_DATE",
name: "보안설정일자",
minWidth: 120,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BASE_DATE",
field: "BASE_DATE",
name: "최종이월수불일자",
minWidth: 150,
cssClass: "align-center"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 상단그리드 초기화
*/
function grdMasterInitialize() {
var options = {
editable: false,
autoEdit: false,
frozenColumn: 3
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdMaster", {
columns: grdMasterOnGetColumns(),
queryId: "LF01020E.RS_MASTER",
sortCol: "BU_CD",
gridOptions: options
});
G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll);
G_GRDMASTER.view.onHeaderClick.subscribe(grdMasterOnHeaderClick);
G_GRDMASTER.view.onClick.subscribe(grdMasterOnClick);
$NC.setGridColumnHeaderCheckBox(G_GRDMASTER, "CHECK_YN");
}
function grdMasterOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDMASTER.lastRow != null) {
if (row == G_GRDMASTER.lastRow) {
e.stopImmediatePropagation();
return;
}
}
var rowData = G_GRDMASTER.data.getItem(row);
// 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDDETAIL);
onGetDetail({
data: null
});
// 파라메터 세팅
G_GRDDETAIL.queryParams = $NC.getParams({
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_CLOSE_MONTH: $NC.getValue("#dtpClose_Month")
});
// 데이터 조회
$NC.serviceCall("/LF01020E/getDataSet.do", $NC.getGridParams(G_GRDDETAIL), onGetDetail);
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdMaster", row + 1);
}
function grdMasterOnHeaderClick(e, args) {
G_GRDMASTER.view.getCanvasNode().focus();
if (args.column.id == "CHECK_YN") {
if ($(e.target).is(":checkbox")) {
if (G_GRDMASTER.data.getLength() == 0) {
e.preventDefault();
e.stopImmediatePropagation();
return;
}
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowCount = G_GRDMASTER.data.getLength();
var rowData;
G_GRDMASTER.data.beginUpdate();
for (var row = 0; row < rowCount; row++) {
rowData = G_GRDMASTER.data.getItem(row);
if (rowData.CHECK_YN !== checkVal) {
rowData.CHECK_YN = checkVal;
G_GRDMASTER.data.updateItem(rowData.id, rowData);
}
}
G_GRDMASTER.data.endUpdate();
e.stopPropagation();
e.stopImmediatePropagation();
}
}
}
function grdMasterOnClick(e, args) {
G_GRDMASTER.view.getCanvasNode().focus();
if (args.cell === G_GRDMASTER.view.getColumnIndex("CHECK_YN")) {
if ($(e.target).is(":checkbox")) {
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowData = G_GRDMASTER.data.getItem(args.row);
if (rowData.CHECK_YN !== checkVal) {
rowData.CHECK_YN = checkVal;
G_GRDMASTER.data.updateItem(rowData.id, rowData);
}
}
}
}
/**
* Grid에서 CheckBox Formatter를 사용할 경우 CheckBox Click 이벤트 처리
*
* @param e *
* @param view
* 대상 Object
* @param args
* row, cell, value
*/
function _OnGridCheckBoxFormatterClick(e, view, args) {
if (G_GRDMASTER.view.getEditorLock().isActive()) {
G_GRDMASTER.view.getEditorLock().commitCurrentEdit();
}
$NC.setGridSelectRow(G_GRDMASTER, args.row);
var rowData = G_GRDMASTER.data.getItem(args.row);
if (args.cell == G_GRDMASTER.view.getColumnIndex("CHECK_YN")) {
rowData.CHECK_YN = args.val === "Y" ? "N" : "Y";
}
G_GRDMASTER.data.updateItem(rowData.id, rowData);
}
function grdDetailOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "INOUT_DATE",
field: "INOUT_DATE",
name: "수불일자",
minWidth: 80,
cssClass: "align-center",
});
$NC.setGridColumn(columns, {
id: "INOUT_CD",
field: "INOUT_CD",
name: "입출고구분",
minWidth: 100,
cssClass: "align-center",
});
$NC.setGridColumn(columns, {
id: "INOUT_NM",
field: "INOUT_NM",
name: "입출고구분명",
minWidth: 140
});
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "상품코드",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "상품명",
minWidth: 160
});
$NC.setGridColumn(columns, {
id: "ITEM_SPEC",
field: "ITEM_SPEC",
name: "상품규격",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "BRAND_NM",
field: "BRAND_NM",
name: "브랜드명",
minWidth: 100
});
$NC.setGridColumn(columns, {
id: "ITEM_STATE_F",
field: "ITEM_STATE_F",
name: "상품상태",
minWidth: 60,
cssClass: "align-center",
});
$NC.setGridColumn(columns, {
id: "ITEM_LOT",
field: "ITEM_LOT",
name: "LOT번호",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "NOTE_QTY",
field: "NOTE_QTY",
name: "전표수량",
minWidth: 80,
cssClass: "align-right",
});
$NC.setGridColumn(columns, {
id: "INOUT_QTY",
field: "INOUT_QTY",
name: "수불수량",
minWidth: 80,
cssClass: "align-right",
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 하단그리드 초기화
*/
function grdDetailInitialize() {
var options = {
editable: false,
autoEdit: false,
frozenColumn: 3
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdDetail", {
columns: grdDetailOnGetColumns(),
queryId: "LF01020E.RS_DETAIL",
sortCol: "INOUT_DATE",
gridOptions: options
});
G_GRDDETAIL.view.onSelectedRowsChanged.subscribe(grdDetailOnAfterScroll);
}
function grdDetailOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDDETAIL.lastRow != null) {
if (row == G_GRDDETAIL.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdDetail", row + 1, G_GRDDETAIL.data.getLength());
}
/**
* 검색조건의 사업부 검색 이미지 클릭
*/
function showUserBuPopup() {
$NP.showUserBuPopup({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: "%"
}, onUserBuPopup, function() {
$NC.setFocus("#edtQBu_Cd", true);
});
}
function onUserBuPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQBu_Cd", resultInfo.BU_CD);
$NC.setValue("#edtQBu_Nm", resultInfo.BU_NM);
} else {
$NC.setValue("#edtQBu_Cd");
$NC.setValue("#edtQBu_Nm");
$NC.setFocus("#edtQBu_Cd", true);
}
onChangingCondition();
}
/**
* 조회버튼 클릭후 상단 그리드에 데이터 표시처리
*/
function onGetMaster(ajaxData) {
$NC.setInitGridData(G_GRDMASTER, ajaxData);
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.isNull(G_GRDMASTER.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridSelectRow(G_GRDMASTER, {
selectKey: "BU_CD",
selectVal: G_GRDMASTER.lastKeyVal
});
}
} else {
// 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDDETAIL);
onGetDetail({
data: null
});
$NC.setGridDisplayRows("#grdMaster", 0, 0);
}
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/**
* 조회버튼 클릭후 하단 그리드에 데이터 표시처리
*/
function onGetDetail(ajaxData) {
$NC.setInitGridData(G_GRDDETAIL, ajaxData);
if (G_GRDDETAIL.data.getLength() > 0) {
if ($NC.isNull(G_GRDDETAIL.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDDETAIL, 0);
} else {
$NC.setGridSelectRow(G_GRDDETAIL, {
selectKey: "INOUT_DATE",
selectVal: G_GRDDETAIL.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdDetail", 0, 0);
}
}
/*
* 마감처리
*/
function procClosing() {
var CLOSE_MONTH = $NC.getValue("#dtpClose_Month");
var PROTECT_DATE = $NC.getValue("#dtpProtect_date");
var rowCount = G_GRDMASTER.data.getLength();
if (rowCount === 0) {
alert("조회 후 처리하십시오.");
return;
}
var result = confirm("월마감을 처리하시겠습니까?");
if (!result) {
return;
}
var CLOSING_LEVEL1_YN = $NC.getValue("#chkQClosing_Level1") === "Y" ? "Y" : "N";
var CLOSING_LEVEL2_YN = $NC.getValue("#chkQClosing_Level2") === "Y" ? "Y" : "N";
var CLOSING_LEVEL3_YN = $NC.getValue("#chkQClosing_Level3") === "Y" ? "Y" : "N";
if (CLOSING_LEVEL1_YN === "N" && CLOSING_LEVEL2_YN === "N" && CLOSING_LEVEL3_YN === "N") {
alert("선택된 마감처리 대상 작업이 없습니다.");
return;
}
var closingDS = [ ];
var chkCnt = 0;
for (var row = 0; row < rowCount; row++) {
var rowData = G_GRDMASTER.data.getItem(row);
if (rowData.CHECK_YN == "Y") {
chkCnt++;
var closingData = {
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_CLOSE_MONTH: CLOSE_MONTH,
P_PROTECT_DATE: PROTECT_DATE,
P_CLOSING_LEVEL1_YN: CLOSING_LEVEL1_YN,
P_CLOSING_LEVEL2_YN: CLOSING_LEVEL2_YN,
P_CLOSING_LEVEL3_YN: CLOSING_LEVEL3_YN,
};
closingDS.push(closingData);
}
}
if (chkCnt == 0) {
alert("월마감 처리할 사업부를 선택하십시오.");
return;
}
$NC.serviceCall("/LF01020E/callProcessingClossing.do", {
P_DS_MASTER: $NC.getParams(closingDS),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, onSave, onSaveError);
}
function onSave(ajaxData) {
var resultData = $NC.toArray(ajaxData);
if (!$NC.isNull(resultData)) {
if (resultData.RESULT_DATA !== "OK") {
alert(resultData.RESULT_DATA);
}
}
var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, {
selectKey: "BU_CD"
});
_Inquiry();
G_GRDMASTER.lastKeyVal = lastKeyVal;
}
function onSaveError(ajaxData) {
$NC.onError(ajaxData);
}
|
'use strict';
const fs = require('fs');
const gulp = require('gulp');
const karma = require('karma');
const rimraf = require('rimraf');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const runSequence = require('run-sequence');
const webpack = require('webpack-stream');
const webpackConfig = require('./webpack.config');
const testEnvironment = require('./test/test-environment');
gulp.task('lint', function () {
return gulp.src(['*.js', 'src/**/*.js', 'test/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('clean', function (done) {
rimraf('lib', done);
});
gulp.task('build', function (done) {
runSequence('clean', ['build:node', 'build:browser'], 'minify', done);
});
gulp.task('build:node', function () {
return gulp.src('src/**/*.js')
.pipe(babel({ presets: ['es2015'] }))
.pipe(gulp.dest('lib'));
});
gulp.task('build:browser', function () {
return gulp.src('src/index.js')
.pipe(webpack(webpackConfig))
.pipe(rename('browser.js'))
.pipe(gulp.dest('lib'));
});
gulp.task('minify', function () {
return gulp.src('lib/browser.js')
.pipe(uglify())
.pipe(rename('browser.min.js'))
.pipe(gulp.dest('lib'));
});
gulp.task('start-test-environment', function (done) {
testEnvironment.start().then(() => done(), done);
});
gulp.task('stop-test-environment', function (done) {
testEnvironment.stop().then(() => done(), done);
});
gulp.task('test', function (done) {
runSequence('start-test-environment', 'test:node', 'test:browser', 'stop-test-environment', done);
});
gulp.task('test:node', function () {
return gulp.src('test/**/*.specs.js')
.pipe(mocha())
.on('error', function (err) {
console.error(err.toString());
this.emit('end');
});
});
gulp.task('test:browser', function (done) {
new karma.Server({ configFile: `${__dirname}/karma.conf.js` }, () => done()).start();
});
gulp.task('watch', function () {
return gulp.watch(['src/**/*.js', 'test/**/*.js'], ['test']);
});
gulp.task('default', ['watch']);
|
import {SERVICE_URLS} from '../constants/serviceUrl';
import * as types from '../constants/actiontypes';
import axios from 'axios';
import toastr from 'toastr';
let createEvents=(formData, token)=>{
const url=SERVICE_URLS.CREATEEVENT_API;
var config = {headers: {'Authorization':'Token '+token}};
const apiCreateEventRequest = axios.post(url, formData, config);
return(dispatch)=>{
return apiCreateEventRequest.then(({data})=>{
toastr.success("Event created successfully");
}).catch((error)=>{
toastr.error(error);
throw(error);
});
}
};
let getStates=(token)=>{
const url=SERVICE_URLS.CREATEEVENT_API;
var config = {headers: {'Authorization':'Token '+token}};
const apiCreateEventRequest = axios.get(url, config);
return(dispatch)=>{
return apiCreateEventRequest.then(({data})=>{
///return data;
dispatch({type:types.EVENT_STATES, apiResult:data});
}).catch((error)=>{
if(error != "Error: Request failed with status code 401"){
toastr.error(error);
}
throw(error);
});
}
}
let editEvents=(formData, id, token)=>{
const url=SERVICE_URLS.EDITEVENT_API + id + '/' ;
var config = {headers: {'Authorization':'Token '+token}};
const apiCreateEventRequest = axios.put(url, formData, config);
return(dispatch)=>{
return apiCreateEventRequest.then(({data})=>{
toastr.success("Event updated successfully");
}).catch((error)=>{
toastr.error(error);
if (error.response) {
} else {
}
throw(error);
});
}
};
let RequestInvite = (token, eventId) =>{
const url = SERVICE_URLS.REQUEST_INVITE+eventId+'/request-access';
var config = {
headers: {'Authorization':'Token '+token}
};
const apiGroupRequest = axios.get(url, config);
return(dispatch) => {
return apiGroupRequest.then(({data})=>{
if(data.request_status){
toastr.success(data.response_message);
return data;
}
else{
toastr.error(data.response_message);
return data;
}
}).catch((error)=>{
toastr.error(error);
throw(error);
});
}
}
export {createEvents, editEvents, RequestInvite, getStates};
|
/*
* Copyright
*/
/*
* declaration of used JS files
*/
jQuery.sap.declare("com.slb.mobile.util.Helper");
//jQuery.sap.require("sap.m.MessageToast");
//jQuery.sap.require("sap.m.MessageBox");
//*****************************************************************************************************************************************
// Helper.js
// It contains all the Gloabl methods
//*****************************************************************************************************************************************
/*
This method handles all failed request after getting error message from server. It closes the dialog and try to reauthenticate the user if it needs to be
*/
/*function handleRequestFailed(){
busyDialog.close();
sap.m.MessageBox.alert(i18nModel.getResourceBundle().getText("LoadingError"));
}
*/
/*
* This method performs the logoff function from the app. After confirmation user will be logged off from JBC
*/
/*function logoff(){
sap.m.MessageBox.confirm(i18nModel.getResourceBundle().getText("LogoffConfirm"),function (oAction){
if(oAction == sap.m.MessageBox.Action.OK){
//log off the user
busyDialog.open();
logoffHelper();
//Clear model data
clearAppData();
busyDialog.close();
}
});
} */
/*
* Helper method to logoff and terminate user sessions.
*/
/*function logoffHelper(){
var req = new XMLHttpRequest();
try{
req.open('GET', getDataEndPoint('logout'), false);
req.send();
sap.m.MessageToast.show(i18nModel.getResourceBundle().getText("LogoffSuccess"));
//after logoff display the login page
var nav=oCore.byId("Login").getController().nav;
nav.to("Login");
}catch(exception){
return 0;
}
} */
/*
This method is authentication handler for Line Clearance app it checks if a valid user session is available and show login screen if required
*/
/*function authenticate(firstTime){
var nav = oCore.byId('Login').getController().nav;
if(firstTime){
nav.to("Login");
}else {
switch(isUserSessionAvailable()){
case 200 : break;
case 401 :{
nav.to("Login");
if(busyDialog !=null){
busyDialog.close();
}
break;
}
case 404 : showMessage(i18nModel.getResourceBundle().getText("Error"),"Error",i18nModel.getResourceBundle().getText("ServerError")); break;
default : {
nav.to("Login");
if(busyDialog !=null){
busyDialog.close();
}
break;
}
}
}
} */
/*
* This method checks if user session is available in the app.
*/
function isUserSessionAvailable(){
var req = new XMLHttpRequest();
try{
req.open('GET', getDataEndPoint(), false);
req.send();
return req.status;
}catch(exception){
return 0;
}
}
/*
* This method is used for getting the data end points for various calls to backend system .
It prepares the backend service call
*/
function getDataEndPoint(datapoint){
switch(datapoint){
case "logout" : return gwHost+"/sap/public/bc/icf/logoff?sap-client=020";
case "WorkOrders" : return serverEndpoint+"/WOLIST?sap-client=330";
case "HdrOperations" : return serverEndpoint;
case "lchdrs": authenticate(false); return serverEndpoint+"/LCHDRS?sap-client=020";
default: return serverEndpoint;
}
}
function getOperations(workorder) {
gwLogin();
// var url = getDataEndPoint('HdrOperations')+"WORKORDER(Number='000001000000')/GetOP";
// var username= "05173240";
//var pass= "Maryam@2011";
//var odatamodel = new sap.ui.model.odata.ODataModel("http://sapf1sdi10.dir.slb.com:8010/sap/opu/odata/sap/Z_THIN_SLB_MOB_SRV",username,pass);
//odatamodel.setHeaders({"Content-Type" : "application/json"});//Setting the Headers "Content Type"
//fetch XSRF token as part of request
// odatamodel.setHeaders({"X-CSRF-Token" : "Fetch"});
// var lcTypeData=oCore.getModel("lcTypeModel").getData();
/* odatamodel.read("/WOLIST", null,
function fnSuccess(oData,response)
{
alert("s");
},
function fnError(response)
{
alert("f");
}
);
*/
/*
var req = $.ajax({
url: getDataEndPoint(),
async: false,
dataType: 'json',
cache: false,
beforeSend:function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + Base64.encode(username + ':' + pass));
}
});
req.success(function(oData,status, xhr) {
alert("success");
});
req.fail(function(xhr){
alert("failed");
}); */
}
function getWorkOrders()
{
var req = $.ajax({
url: getDataEndPoint('WorkOrders'),
async: false,
dataType: 'json',
cache: false,
beforeSend:function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + Base64.encode("05173240" + ':' + "Maryam@2011"));
}
});
req.success(function(oData,status, xhr) {
if(xhr.status==200){
var woList=[];
var woModel = new sap.ui.model.json.JSONModel();
$(oData.d.results).each(function( i, val ) {
woList.push({ "WOId" : val.Orderid,
"Plant" : val.OrderType,
"WOText" :val.ShortText,
"RigId": "R2322",
"JobId": "J87799",
"StartDate": "23-Nov-2014"
});
woModel.setData(woList);
});
//oCore.setModel(woModel,"WorkOrderModel");
// alert("ss");
//handleLoginSuccess(xhr);
return woModel;
}else{
//handleLoginFail(xhr);
}
});
req.fail(function(xhr){
alert("error");
});
}
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
}
|
import PropTypes from 'prop-types';
import styles from '../styles/Preview.module.css';
function Preview({ html, setHtml }) {
return (
<div className={styles.container}>
<iframe
className={styles.iframe}
src={'data:text/html,' + encodeURIComponent(html)}
/>
<button className={styles.button} onClick={() => setHtml('')}>
Close
</button>
</div>
);
}
Preview.propTypes = {
html: PropTypes.string,
setHtml: PropTypes.func,
};
export default Preview;
|
import React, { useState } from "react";
import {
Table,
Container,
Button,
ModalHeader,
ModalBody,
Modal
} from "reactstrap";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import StripeCheckout from "react-stripe-checkout";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import "./cart.css";
import {
increaseProd,
decreaseProd,
remove_from_cart,
make_payment_start
} from "../../store/actions/cartAction";
const Cart = props => {
const [modalStatus, toggleModal] = useState(false);
const onToken = token => {
const body = {
amount: props.total,
products: props.ordered,
token
};
props.pay(body);
};
const toggle = event => {
//console.log("toggle");
toggleModal(!modalStatus);
};
const checkAuth = event => {
if (!props.auth) {
event.stopPropagation(); //this is to stop the event bubble up to the parent StripeCheckout component
toggle(event);
}
//return props.history.push("/login");
};
let paymentForm = (
<StripeCheckout
token={onToken}
name="Framework Inc"
stripeKey="pk_test_rOnIUC7hbo7ElO2ZOTW2mbDZ"
panelLabel="Make Payment"
currency="USD"
amount={props.total * 100}
>
<div style={{ textAlign: "right" }}>
<Button
onClick={checkAuth}
disabled={props.total > 0 ? false : true}
color="success"
>
Place Order
</Button>
</div>
</StripeCheckout>
);
const prePayment = (
<Container className="page">
<Modal isOpen={modalStatus} toggle={toggle}>
<ModalHeader toggle={toggle}>Please Login before purchase</ModalHeader>
<ModalBody>
<Link to="/login">Go Back to Login</Link>
</ModalBody>
</Modal>
<Table>
<thead>
<tr>
<th>Framework</th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<TransitionGroup component={null}>
{props.ordered.map(item => {
return (
<CSSTransition key={item._id} timeout={500} classNames="fade">
<tr>
<td>{item.title}</td>
<td>{item.price}</td>
<td>
<div>
<div>
<i
style={{ marginRight: "1rem", cursor: "pointer" }}
className="fas fa-plus-square"
onClick={() => props.increase(item)}
/>
<input
style={{
width: "2rem",
height: "1rem",
textAlign: "right"
}}
readOnly
disbaled="true"
value={item.quantity}
/>
<i
style={{ marginLeft: "1rem", cursor: "pointer" }}
className="fas fa-minus-square"
onClick={() => props.decrease(item)}
/>
</div>
<Button
onClick={() => props.remove(item)}
color="danger"
>
Remove
</Button>
</div>
</td>
</tr>
</CSSTransition>
);
})}
</TransitionGroup>
</tbody>
</Table>
<h1 style={{ marginTop: "3rem", textAlign: "right" }}>
Total: {props.total}
</h1>
{paymentForm}
</Container>
);
return prePayment;
};
const mapStateToProps = state => {
return {
ordered: state.cart.orderedProducts,
total: state.cart.totalPrice,
auth: state.auth.isAuth
};
};
const mapDispatchToProps = dispatch => {
return {
increase: productInfo => dispatch(increaseProd(productInfo)),
decrease: productInfo => dispatch(decreaseProd(productInfo)),
remove: productInfo => dispatch(remove_from_cart(productInfo)),
pay: paymentInfo => dispatch(make_payment_start(paymentInfo))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Cart);
|
import React from "../React/index"
// 该方法用于初始挂在渲染
export function render(virtualNode,container,callback) {
const realNode = _render(undefined,virtualNode,container); // 统一diffRender进行渲染,这里的dom为undefined,在diffrender中就是直接添加
callback && callback()
return realNode;
}
function _render( dom, vnode, container ) {
const ret = diffNode( dom, vnode );
if ( container && ret.parentNode !== container ) {
container.appendChild( ret );
}
return ret;
}
// 注意更新节点的本质就是对节点的更新或对内部节点内容的更新
// diffNode函数基本上不修改节点,他会返回一个新的diffNode,用来操作
// 但是如果文本节点的更改都是发生在diffNode中
function diffNode(realNode,virtualNode) {
let diffRes = realNode;
if (virtualNode === undefined || virtualNode === null || typeof virtualNode === "boolean") virtualNode = "";
// virtualNode属于文本节点时
if (typeof virtualNode === "string" || typeof virtualNode === "number"){
if(realNode && realNode.nodeType === 3) {
// 节点内容发生变化
if (realNode.textContent !== virtualNode) {
realNode.textContent = virtualNode;
}
} else { // 替换的节点不是文本类型,或者不存在时
// 创建一个新的节点
diffRes = document.createTextNode(String( virtualNode ));
if(realNode && realNode.parentNode){ // 如果是文本更新场景,则将新建的节点替换
realNode.parentNode.replaceChild(diffRes,realNode)
}
}
return diffRes
}
// virtualNode属于function组件
if ( typeof virtualNode.type === 'function' ) {
// 之前的组件更新,你会发现效率不高,这里做一下判断
return diffComponent( realNode, virtualNode );
}
if ( !realNode || !isSameNodeType( realNode, virtualNode ) ) {
diffRes = document.createElement( virtualNode.type );
if ( realNode ) {
[ ...realNode.childNodes ].forEach(item => diffRes.appendChild(item) ); // 将原来的子节点移到新节点下
if ( realNode.parentNode ) {
realNode.parentNode.replaceChild( diffRes, realNode ); // 移除掉原来的DOM对象
}
}
}
// virtualNode属于由createElment生成的虚拟节点
// // 创造组件对象
// realNode = document.createElement(virtualNode.type);
// // 添加属性
// virtualNode.props && Object.keys(virtualNode.props).forEach(key => setAttribute(realNode,key,virtualNode.props[key]));
// // 开始套娃,套子节点
// virtualNode.children.forEach(child => render(child,realNode));
// 以上过程是虚拟节点的更换过程但是不具有diff比对效果,所以重新修改
// 添加属性
diffAttributes(diffRes,virtualNode)
// virtualNode.props && Object.keys(virtualNode.props).forEach(key => setAttribute(diffRes,key, virtualNode.props[key]));
// 开始套娃,套子节点
if ( virtualNode.children && virtualNode.children.length > 0 || ( diffRes.childNodes && diffRes.childNodes.length > 0 ) ) {
diffChildrenRender(diffRes,virtualNode.children)
}
// virtualNode.children.forEach(child => render(child,diffRes));
return diffRes;
}
function diffChildrenRender(dom,vChildren) {
const rChildren = dom.childNodes;
vChildren.forEach((vChild,index) => {
let rChild = rChildren[index];
const diffChild = diffNode( rChild, vChild );
if ( diffChild && diffChild !== dom && diffChild !== rChild ) {
if ( !rChild ) {
dom.appendChild( diffChild );
} else if ( diffChild === rChild.nextSibling ) {
removeNode( rChild );
} else {
dom.insertBefore( diffChild, rChildren[index] );
}
}
})
}
function diffComponent( dom, vnode ) {
let c = dom && dom._component;
let oldDom = dom;
// 如果组件类型没有变化,则重新set props
if ( c && c.constructor === vnode.type ) {
setComponentProps( c, vnode.props );
renderComponent(c)
return c.base;
// 如果组件类型变化,则移除掉原来组件,并渲染新的组件
} else {
if ( c ) {
unmountComponent( c );
oldDom = null;
}
c = createComponent( vnode.type, vnode.props );
setComponentProps( c, vnode.props );
renderComponent(c)
return c.base;
// if ( oldDom && dom !== oldDom ) {
// oldDom._component = null;
// removeNode( oldDom );
// }
}
}
/**
* react DOM属性是自己独有的,需要单独拿出来设置
*/
function setAttribute(dom,key,value) {
if(key === "className") {
key = "class";
if(value instanceof Array) value = value.join(" ");
} else if (key === "class") {
console.error("Use the className attribute name");
return;
}
if (/on\w+/.test( key )){
// react 中监听事件的名称是驼峰,这里统一转换成小写
key = key.toLowerCase();
// 动态给DOM元素绑定事件
dom[key] = value;
} else if(key === "style"){
// style样式属性,在对象和字符串两种类型下的操作
if(value && typeof value === "object"){
Object.keys(value).forEach(styleKey => dom.style[styleKey] = typeof value[styleKey] === "number"?value[styleKey]+"px":value[styleKey])
} else{
dom.style.cssText = value || ""
}
} else{
if ( value ) {
dom.setAttribute( key, value );
} else {
dom.removeAttribute( key );
}
}
}
/**
* react组件渲染周期部分
*/
// 创建组件的时候
function createComponent(component, props){
let inst;
// 如果是类定义组件,直接返回实例
if (component.prototype && component.prototype.render) {
inst = new component(props);
} else {
inst = new React.Component(props);
inst.constructor = component;
inst.render = function() {
return this.constructor(props);
}
}
return inst
}
// 组件数据初始化
function setComponentProps( component, props ) {
if ( !component.base ) {
// 组件将要挂载的时候,也就是组件第一次生成
if ( component.componentWillMount ) component.componentWillMount();
} else if ( component.componentWillReceiveProps ) {
// 这里指的是,组件props的值发生变化,从而更新组件
component.componentWillReceiveProps( props );
}
component.props = props;
}
export function renderComponent( component ) {
let base = {};
const renderer = component.render();
if ( component.base && component.componentWillUpdate ) {
// 组件将要更新
component.componentWillUpdate();
}
const replaceNode = diffNode(component.base,renderer);
// const replaceNode = _render( renderer );
// 组件没有挂载更新之前,但已经通过render生成真实DOM元素
if ( component.base ) {
if ( component.componentDidUpdate ) component.componentDidUpdate();
} else if ( component.componentDidMount ) {
component.componentDidMount();
}
// // 找到父节点,通过父节点更新节点
// if ( component.base && component.base.parentNode ) {
// component.base.parentNode.replaceChild( replaceNode, component.base );
// }
// 用 component.base 保存已经更新的节点元素
component.base = replaceNode;
// 形成闭环
base._component = component;
}
function isSameNodeType( dom, vnode ) {
if ( typeof vnode === 'string' || typeof vnode === 'number' ) {
return dom.nodeType === 3;
}
if ( typeof vnode.type === 'string' ) {
return dom.nodeName.toLowerCase() === vnode.type.toLowerCase();
}
return dom && dom._component && dom._component.constructor === vnode.type;
}
//
function diffAttributes( dom, vnode ) {
const old = {}; // 当前DOM的属性
const attrs = vnode.props; // 虚拟DOM的属性
for ( let i = 0; i < dom.attributes.length; i++ ) {
const attr = dom.attributes[ i ];
old[ attr.name ] = attr.value;
}
// 如果原来的属性不在新的属性当中,则将其移除掉(属性值设为undefined)
for ( const name in old ) {
if ( !( name in attrs ) ) {
setAttribute( dom, name, undefined );
}
}
// 更新新的属性值
for ( const name in attrs ) {
if ( old[ name ] !== attrs[ name ] ) {
setAttribute( dom, name, attrs[ name ] );
}
}
}
document.addEventListener("DOMSubtreeModified", function(e){
console.log(`本次修改位置:${e.srcElement},修改内容:${e.target}`);
}, false); |
import React, { forwardRef } from 'react';
import moment from 'moment';
import styles from './textMessage.module.scss';
export default forwardRef(({ me, text, time }, ref) => {
return (
<li
ref={ref}
className={styles[me ? 'me' : '']}
>
{text}
<div className='time'>{moment(time).format('hh:mm')}</div>
</li>
)
}); |
Ext.define('JSONExtJS.view.startpage.View', {
extend: 'Ext.Panel',
xtype: 'startPage',
title: 'Start Page',
layout: {
type: 'vbox',
pack: 'center',
align: 'middle',
},
controller: 'startPage',
items: [{
xtype: 'button',
text: 'Start Using Application',
handler: 'onStartPressed'
}],
}); |
const express = require("express");
const { v4: uuid } = require("uuid");
const app = express();
app.use(express.json());
// Lista de respositorios
const repositories = [];
// listar repositorios
app.get("/repositories", (request, response) => {
return response.json(repositories);
});
// cadastrar repositorio
app.post("/repositories", (request, response) => {
// dados da requisicao
const { title, url, techs } = request.body
// criando objeto que sera cadastrado
const repository = {
id: uuid(),
title,
url,
techs,
likes: 0
};
// adicionando novo repositorio
repositories.push(repository);
return response.status(201).json(repository);
});
// atualizar repositorio
app.put("/repositories/:id", (request, response) => {
// dados da requisicao
const { id } = request.params;
const updatedRepository = request.body;
// remover a propriedade likes caso tenha sido passada
if (updatedRepository.likes){
delete updatedRepository.likes;
}
// verificar se repositorio existe
repositoryIndex = repositories.findIndex(repository => repository.id === id);
if (repositoryIndex < 0) {
return response.status(404).json({ error: "Repository not found" });
}
// merge dos objetos (atual e novo para atualizar)
const repository = { ...repositories[repositoryIndex], ...updatedRepository };
repositories[repositoryIndex] = repository; // atualizando repositorio na lista
return response.json(repository);
});
// deletar repositorio
app.delete("/repositories/:id", (request, response) => {
// dados da requisicao
const { id } = request.params;
// verifica se repositorio existe
repositoryIndex = repositories.findIndex(repository => repository.id === id);
if (repositoryIndex < 0) {
return response.status(404).json({ error: "Repository not found" });
}
// remove repositorio
repositories.splice(repositoryIndex, 1);
return response.status(204).send();
});
// para adicionar likes ao repositorio
app.post("/repositories/:id/like", (request, response) => {
// dados da requisição
const { id } = request.params;
// verifica se repositório existe
repositoryIndex = repositories.findIndex(repository => repository.id === id);
if (repositoryIndex < 0) {
return response.status(404).json({ error: "Repository not found" });
}
// incrementando like
repositories[repositoryIndex].likes++;
return response.json({ message: "Like add" });
});
module.exports = app;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Alert
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { Root } from "native-base";
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import LandingScreen from './src/containers/landing';
import SearchOrganization from './src/containers/searchOrganization';
import LoginScreen from './src/containers/login';
import ForgetPasswordScreen from './src/containers/forgotPassword';
import HomeScreen from './src/containers/home';
import DashboardScreen from './src/containers/dashboard';
import ShareSurvey from './src/containers/shareSurvey';
import FeedDetailsScreen from './src/containers/feedDetails';
import AskQuestion from './src/containers/askQuestion';
import CreatePostScreen from './src/containers/createPost';
import CreateScreen from './src/containers/create';
import NewPostsScreen from './src/containers/newPost';
import ReplyVideoScreen from './src/containers/replyVideo';
import ReplyAudioScreen from './src/containers/replyAudio';
import WatchVideoComments from './src/containers/watchVideosComm';
import ListenAudioComments from './src/containers/listenAudiosComments';
import ShareDmScreen from './src/containers/shareDm';
import UploadPhoto from './src/containers/uploadPhoto';
import UploadVideo from './src/containers/uploadVideo';
import UploadReply from './src/containers/uploadReply';
import PlayVideoScreen from './src/containers/playVideo';
import FeedDetailsNotif from './src/containers/feedDetailsNotif';
import LoginScreenStudent from './src/containers/loginStudent';
import SignupScreenStudent from './src/containers/signup';
import SelectCourseScreen from './src/containers/selectCourse';
import ChangePasswordScreen from './src/containers/changePassword';
import CoursesDetailsScreen from './src/containers/coursesDetails';
import DocViewerScreen from './src/containers/docViewer';
import SignupScreenInstructor from './src/containers/signupInstructor';
import SelectCourseInstructorScreen from './src/containers/selectCourseInstructor';
import AddNewCourse from './src/containers/addNewCourse';
import PrivacyPolicyScreen from './src/containers/privacyPolicy';
import AddCoursesScreen from './src/containers/addCourses';
import NotificationScreen from './src/containers/notification';
import VerifyAccessCode from './src/containers/verifyAccessCode';
import SignupScreenAccess from './src/containers/signUpAccess';
import LoginAccessCode from './src/containers/loginAccessCode'
import AddNewInstitution from './src/containers/addNewInstitution';
import AskUser from './src/containers/AskUser';
import AddAccessCode from './src/containers/addAccessCode';
const AppNavigator = createStackNavigator({
LandingScreen: { screen: LandingScreen , navigationOptions:{
gesturesEnabled: false
}},
SearchOrganization: { screen: SearchOrganization, navigationOptions:{
gesturesEnabled: false
}},
LoginScreen: {screen: LoginScreen, navigationOptions:{
gesturesEnabled: false
}},
ForgetPasswordScreen: {screen: ForgetPasswordScreen, navigationOptions:{
gesturesEnabled: false
}},
FeedDetailsNotif: {screen: FeedDetailsNotif, navigationOptions:{
gesturesEnabled: false
}},
HomeScreen: {screen: HomeScreen, navigationOptions:{
gesturesEnabled: false
}},
DashboardScreen: {screen: DashboardScreen, navigationOptions:{
gesturesEnabled: false
}},
ShareSurvey: {screen: ShareSurvey, navigationOptions:{
gesturesEnabled: false
}},
FeedDetailsScreen: {screen: FeedDetailsScreen, navigationOptions:{
gesturesEnabled: false
}},
AskQuestion: {screen: AskQuestion, navigationOptions:{
gesturesEnabled: false
}},
CreatePostScreen: {screen: CreatePostScreen, navigationOptions:{
gesturesEnabled: false
}},
CreateScreen: {screen: CreateScreen, navigationOptions:{
gesturesEnabled: false
}},
NewPostsScreen: {screen: NewPostsScreen, navigationOptions:{
gesturesEnabled: false
}},
ReplyVideoScreen: {screen: ReplyVideoScreen, navigationOptions:{
gesturesEnabled: false
}},
ReplyAudioScreen: {screen: ReplyAudioScreen, navigationOptions:{
gesturesEnabled: false
}},
WatchVideoComments: {screen : WatchVideoComments, navigationOptions:{
gesturesEnabled: false
}},
ListenAudioComments: {screen : ListenAudioComments, navigationOptions:{
gesturesEnabled: false
}},
ShareDmScreen: {screen : ShareDmScreen, navigationOptions:{
gesturesEnabled: false
}},
UploadPhoto: {screen: UploadPhoto, navigationOptions:{
gesturesEnabled: false
}},
UploadVideo: {screen: UploadVideo, navigationOptions:{
gesturesEnabled: false
}},
UploadReply: {screen: UploadReply, navigationOptions:{
gesturesEnabled: false
}},
PlayVideoScreen: {screen: PlayVideoScreen, navigationOptions:{
gesturesEnabled: false
}},
LoginScreenStudent: {screen: LoginScreenStudent, navigationOptions:{
gesturesEnabled: false
}},
SignupScreenStudent: {screen: SignupScreenStudent, navigationOptions:{
gestureEnabled: false
}},
SelectCourseScreen: {screen: SelectCourseScreen, navigationOptions:{
gestureEnabled: false
}},
ChangePasswordScreen: {screen: ChangePasswordScreen, navigationOptions:{
gestureEnabled: false
}},
CoursesDetailsScreen: {screen: CoursesDetailsScreen, navigationOptions:{
gestureEnabled: false
}},
DocViewerScreen: {screen: DocViewerScreen, navigationOptions:{
gestureEnabled: false
}},
SignupScreenInstructor: {screen: SignupScreenInstructor, navigationOptions:{
gestureEnabled: false
}},
SelectCourseInstructorScreen: {screen: SelectCourseInstructorScreen, navigationOptions:{
gestureEnabled: false
}},
AddNewCourse: {screen: AddNewCourse, navigationOptions:{
gestureEnabled: false
}},
AddNewInstitution: {screen: AddNewInstitution, navigationOptions:{
gestureEnabled: false
}},
PrivacyPolicyScreen: {screen: PrivacyPolicyScreen, navigationOptions:{
gestureEnabled: false
}},
AddCoursesScreen: {screen: AddCoursesScreen, navigationOptions:{
gestureEnabled: false
}},
NotificationScreen: {screen: NotificationScreen, navigationOptions:{
gestureEnabled: false
}},
VerifyAccessCode: {screen: VerifyAccessCode, navigationOptions:{
gestureEnabled: false
}},
SignupScreenAccess: {screen: SignupScreenAccess, navigationOptions:{
gestureEnabled: false
}},
LoginAccessCode: {screen: LoginAccessCode, navigationOptions:{
gestureEnabled: false
}},
AskUser: {screen: AskUser, navigationOptions:{
gestureEnabled: false
}},
AddAccessCode: {screen: AddAccessCode, navigationOptions:{
gestureEnabled: false
}}
},
{
initialRouteName: 'LandingScreen',
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
});
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
componentDidMount() {
global.heightSafe = 0
}
render() {
return (
<Root>
<AppContainer />
</Root> )
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
}); |
const sqlConnection = require('../configs/mysql_configs.js');
const getLocationHistory = (req, res) => {
const tableName = req.body.tableName;
const first_date = req.body.first_date;
const last_date = req.body.last_date;
const sql = 'CALL GetCarLocationHistory(?,?,?);';
let locationList = [];
sqlConnection.query(sql, [tableName, first_date, last_date], (err, result) => {
if (err) {
console.log('Error : ', err);
res.status(400).json({ message: err });
}
for(let index = 0;index<result[0].length;index++){
// let value = Object.values(result[0][index]);
let element = result[0][index];
locationList.push(element.value);
}
console.log('');
});
res.end();
}
module.exports = { getLocationHistory }; |
import React from "react";
import Topbar from "./components/wrap/Topbar";
import RegisterPage from "./pages/Signup";
import LoginPage from "./pages/Signin";
import LogoutPage from "./pages/Logout";
import ResetPasswordPage from "./pages/ResetPassword";
import HomePage from "./pages/Home";
import ProfileEditPage from "./pages/ProfileEdit";
const routes = [
{
path: "/",
exact: true,
topbar: () => <Topbar />,
sidebar: () => <div></div>,
main: () => <HomePage />
},
{
path: "/profile",
exact: true,
topbar: () => <Topbar />,
sidebar: () => <div></div>,
main: () => <ProfileEditPage />
},
{
path: "/signup",
topbar: () => <div></div>,
sidebar: () => <div></div>,
main: () => <RegisterPage />
},
{
path: "/signin",
topbar: () => <div></div>,
sidebar: () => <div></div>,
main: () => <LoginPage />
},
{
path: "/logout",
topbar: () => <div></div>,
sidebar: () => <div></div>,
main: () => <LogoutPage />
},
{
path: "/password/reset",
topbar: () => <div></div>,
sidebar: () => <div></div>,
main: () => <ResetPasswordPage />
}
];
export default routes;
|
/*
** This proposal model is an expedient to hand 2 problems
** The proposal details are in private collection.
** problem 1: There are to many private collections and it is hard search them one by one,
** So I could record all proposal id and private collection name, and serach them when need
** problem 2: This proposal model can help to record whether user has read the event notification
*/
const mongoose = require('mongoose');
// eventName is the private collection name
const proposalSchema = new mongoose.Schema({
proposalId: String,
eventName: String,
eventType: String,
sender: String,
receiver: String,
read: Boolean // should be set false when new event comes, and set true when read
});
const Proposal = mongoose.model('Proposal', proposalSchema, 'Proposals');
module.exports = Proposal; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.